简体   繁体   English

unittest.mock:在指定的模拟 object 上设置自定义属性(变量)

[英]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.但是,来自其他库的属性(不是方法)大多是在运行时设置的。

What I want to achieve我想要达到的目标

  • Get all the benefits of mocking the object with spec获得 mocking 和 object spec的所有好处
  • Set the (nested) attributes (not methods) needed for my unittests to simulate as if they were set during object creation设置我的单元测试所需的(嵌套)属性(不是方法),以模拟它们是在 object 创建期间设置的
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'

I made these attempts in code changes but with no success我在代码更改中进行了这些尝试,但没有成功

...
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM