[英]unittest.mock: Set custom attribute (variable) on specced mock object
I am trying to mock
an existing object from another library's class for unit tests with pytest
.我正在尝试从另一个库的 class
mock
现有的 object ,以使用pytest
进行单元测试。 However, the attributes (not methods) from the other library are mostly set during runtime.但是,来自其他库的属性(不是方法)大多是在运行时设置的。
spec
spec
的所有好处from unittest.mock import Mock
from otherlib import ClassName
def test_stuff():
mock_object = Mock(spec=ClassName)
mock_object.data.outward.key = 12345
assert mock_object.data.outward.key == 12345 # AttributeError: Mock object has no attribute 'data'
...
def test_stuff():
mock_object = Mock(spec=ClassName, **{'data.outward.key': 12345})
assert mock_object.data.outward.key == 12345
...
def test_stuff():
mock_object = Mock(spec=ClassName)
attrs = {'data.outward.key': 12345}
mock_object.configure_mock(**attrs)
assert mock_object.data.outward.key == 12345
The best I came up with is using another Mock object
to use when setting the main mock object's
attributes.我想出的最好的方法是使用另一个
Mock object
来设置main mock object's
属性。 It works, but I guess there is a better solution for this...?它有效,但我想有一个更好的解决方案......?
from unittest.mock import Mock
from otherlib import ClassName
def test_stuff():
mock_data = Mock(spec=["outward"], key=12345)
mock_object = Mock(spec=ClassName, data=mock_data)
mock_object.data.outward.key = 12345
assert mock_object.data.outward.key == 12345 # tests.py::test_stuff PASSED [100%]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.