I am trying to mock
an existing object from another library's class for unit tests with pytest
. However, the attributes (not methods) from the other library are mostly set during runtime.
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. 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%]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.