我可以在python unittests中伪造/模拟我的模拟对象的类型吗 [英] Can I fake/mock the type of my mock objects in python unittests
问题描述
在我的python代码中,我检查了其中一个参数的类型,以确保它属于我期望的类型.例如:
def myfunction(dbConnection):
if (type(dbConnection)<>bpgsql.Connection):
r['error'] += ' invalid database connection'
我想通过模拟连接来进行测试.有没有办法使模拟对象假装为正确的类型?
以所有应有的尊重,看来你们不太正确!
我可以使用鸭子输入,但是首先有一种方法可以完成我打算做的事情:
来自 http://docs.python.org/dev/library/unittest .mock.html
使用类或实例作为spec
或spec_set
的模拟对象能够通过isintance测试:
>>>
>>> mock = Mock(spec=SomeClass)
>>> isinstance(mock, SomeClass)
True
>>> mock = Mock(spec_set=SomeClass())
>>> isinstance(mock, SomeClass)
True
所以我的示例代码如下:
m = mock.MagicMock(spec=bpgsql.Connection)
isinstance(m, bpgsql.Connection)
这将返回True
所有这些,我并不是说要在python中进行严格的类型检查,我说如果您需要检查它就可以做到,它也可以与测试和模拟一起工作.
In my python code I check the type of one of the parameters to make sure it is of the type I expect. For instance:
def myfunction(dbConnection):
if (type(dbConnection)<>bpgsql.Connection):
r['error'] += ' invalid database connection'
I want to pass a mock connection for testing purposes. Is there a way to make the mock object pretend to be of the correct type?
With all due respect, It looks like you guys are not quite right!
I can use duck typing as said, but there is a way to do what I intended to do in the first place:
from http://docs.python.org/dev/library/unittest.mock.html
Mock objects that use a class or an instance as a spec
or spec_set
are able to pass isintance tests:
>>>
>>> mock = Mock(spec=SomeClass)
>>> isinstance(mock, SomeClass)
True
>>> mock = Mock(spec_set=SomeClass())
>>> isinstance(mock, SomeClass)
True
so my example code would be like:
m = mock.MagicMock(spec=bpgsql.Connection)
isinstance(m, bpgsql.Connection)
this returns True
All that said, I am not arguing for strict type checking in python, I say if you need to check it you can do it and it works with testing and mocking too.
这篇关于我可以在python unittests中伪造/模拟我的模拟对象的类型吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!