[英]python mock: configure spec of a mock object
I have an instance method which initiates an object of another class.我有一个实例方法,它启动另一个类的对象。 For ex,
例如,
import module_two
class One:
def start(self):
self.two = module_two.Two()
I am patching One class in my test cases我正在我的测试用例中修补一个类
@patch('module_one.One', autospec=True)
def test_one(patched_one):
two = patched_one.return_value
# Following method should raise error, but doesn't
two.any_random_non_existing_method()
As mentioned, two.any_random_non_existing_method()
does not raise any error because two
Mock object does not have any spec assigned.如前所述,
two.any_random_non_existing_method()
不会引发任何错误,因为two
Mock 对象没有分配任何规范。
How can I assign spec to the two
object.?如何将规范分配给
two
对象。? I am looking for something like following snippet.我正在寻找类似以下代码段的内容。
# note: configure_spec actually doesn't exist.!
two.configure_spec(module_two.Two)
two.any_random_non_existing_method() # Error.!
After some comments, looks like mock_add_spec
would work for you:经过一些评论,看起来
mock_add_spec
对你mock_add_spec
:
Add a spec to a mock.
向模拟添加规范。 spec can either be an object or a list of strings.
spec 可以是一个对象或一个字符串列表。 Only attributes on the spec can be fetched as attributes from the mock.
只有规范上的属性可以作为属性从模拟中获取。
https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.mock_add_spec https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.mock_add_spec
Here's how it should look:这是它的外观:
# Add specifications on existing mock object
two.mock_add_spec(module_two.Two)
two.any_random_non_existing_method() # Error.!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.