问题描述
我是单元测试的新手。我过去曾使用过模拟和修补程序,但是创建单元测试对我来说有点复杂。
所以我有一个文件: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
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)