python - 模拟 attr.ib() 的默认值

标签 python pytest python-unittest python-attrs

我有类似下面的情况

@attrs(auto_attribs=True)
class ExampleClass:
  _prop: OtherClass = attrib(init=False, default=OtherClass())
  def some_func(self):
    test_var = OtherClass()
    test_var.some_func()
    self._prop.some_func()

class OtherClass:
  def some_func(self):
    raise NotImplementedException

def test_example(mocker):
  mocker.patch("path.to.example_class.OtherClass")
  sut = ExampleClass()
  sut.some_func()

所有的类和测试都在不同的文件中,模拟器是由 pytest_mock 提供的固定装置,它只是 unittest.mock 的包装器,可以更轻松地进行清理。

我遇到的问题是,在运行单元测试时,test_var 被正确分配为补丁函数中的 MagicMock。因此,当返回 test_var.some_func() 时,一切都很好。

self._prop.some_func() 被调用时,NotImplementedException 被引发,因为补丁似乎没有影响它。

在我的单元测试中,我可以设置 sut._prop = MagicMock() 但这是一个内部实现细节,使其成为一个脆弱的测试。

如何模拟属性中的默认变量来避免这种情况?

最佳答案

我在功能上错误地使用了库,因为我每次都需要一个新实例时将默认值设置为一个实例。将 ExampleClass 更改为以下修复了我的问题

@attrs(auto_attribs=True)
class ExampleClass:
  _prop: OtherClass = attrib(init=False, factory=lambda: OtherClass())
  def some_func(self):
    test_var = OtherClass()
    test_var.some_func()
    self._prop.some_func()

关于python - 模拟 attr.ib() 的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50425811/

相关文章:

python - 不能将 attach_mock 与 autospec 函数模拟一起使用

python - 如何使用 pytest-cov 生成覆盖报告并打印到终端?

python - 如何在我的测试套件中使用单击来获取命令/子命令列表?

python - 单元测试 - ImportError : Start directory is not importable

python-unittest - 类型错误 : assertEqual() missing 1 required positional argument: 'second'

python - 测试发现: list all tests in a format suitable for copy/paste

python - 重新匹配无 : Differences in Python implementation of regex?

python - 我可以使用单个文件作为缓冲区吗? IE。同时写入和读取

python - 如何删除不是数字的列表项?

python - 用点替换逗号并转换 float 中的值(python 字典)