我可以在 python 单元测试中伪造/模拟我的模拟对象的类型吗
问题描述
在我的 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:
来自 http://docs.python.org/dev/library/unittest.mock.html
使用类或实例作为 spec
或 spec_set
的模拟对象能够通过 isintance 测试:
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)
返回真
话虽如此,我并不是在争论在 python 中进行严格的类型检查,我说如果你需要检查它你可以做到,它也适用于测试和模拟.
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.
相关文章