如何解决修补数据类属性,该属性将在单元测试中根据其依赖关系动态生成
我是单元测试的新手。我过去曾使用过模拟和修补程序,但是创建单元测试对我来说有点复杂。
所以我有一个文件:parent.py
,具有以下数据类
import multiprocessing
from dataclasses import dataclass
@dataclass
class ParentClass:
cpu_count: int = multiprocessing.cpu_count()
我还有另一个模块child.py
,具有以下数据类
from stackoverflow.parent import ParentClass
from dataclasses import dataclass
@dataclass
class ChildClass(ParentClass):
some_attribute_1: int = 1
some_attribute_2: int = 2
....
最后,我有了使用这些数据类的第三个模块actual_function.py
。
from stack_overflow.child import ChildClass
def get_cpu_count_and_attributes(cc: ChildClass):
return cc.cpu_count,cc.some_attribute_1
在这里,我想对print_cpu_count_and_attributes
函数进行单元测试。修补在这里如何工作?我创建了以下测试用例,但失败了。我系统中的cpu_count是16,但是我想用返回值8来模拟它,以便它可以在具有不同内核数的其他机器上使用
from unittest import mock
from stack_overflow.actual_function import *
from stack_overflow.child import ChildClass
@mock.patch('stack_overflow.parent.multiprocessing.cpu_count',return_value=8)
def test_print_cpu_count_and_attributes():
cc = ChildClass()
assert get_cpu_count_and_attributes(cc) == (8,1)
这是文件夹结构。
stackoverflow
├── __init__.py
├── actual_function.py
├── child.py
├── parent.py
└── test_function.py
解决方法
如果您要测试ChildClass
,则应设置其路径,而不是其他模块中的父路径。
嘲笑的Heuristincs:
- 修补测试内容
- 尽可能贴近目标函数
您的补丁无法正常工作的原因是,在补丁之后python不会重新评估模块和类层次结构。而且由于python是动态的,所以正在发生
- 父级评估
- 参照父类对象评估子类
- 您在父模块中修补了父类,但是在
actual_function
和ChildClass
中测试代码引用了旧的原始Parent
,因为mock
实际上正在更改Parent
名称空间中的parent.py
。
另外,看看mock documentation on patching point
您的案例示例:
with mock.patch.object(ChildClass,'cpu_count',new_callable=mock.PropertyMock) as m:
m.return_value = 42
get_cpu_count_and_attributes(ChildClass())
您不应更改继承的属性/属性,应将补丁放在目标的顶部(因此为名称))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。