我是單元測試的新手。我過去使用過模擬、修補,但我的情況對我來說創建單元測試有點復雜。所以我有一個文件:parent.py具有以下數據類import multiprocessingfrom dataclasses import dataclass@dataclassclass ParentClass: cpu_count: int = multiprocessing.cpu_count() 我有另一個child.py具有以下數據類的模塊from stackoverflow.parent import ParentClassfrom dataclasses import dataclass@dataclassclass ChildClass(ParentClass): some_attribute_1: int = 1 some_attribute_2: int = 2 ....最后,我有第三個actual_function.py使用這些數據類的模塊。from stack_overflow.child import ChildClassdef 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 mockfrom stack_overflow.actual_function import *from stack_overflow.child import [email protected]('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
1 回答

慕神8447489
TA貢獻1780條經驗 獲得超1個贊
如果您嘗試測試ChildClass
,您應該對其進行路徑,而不是不同模塊中的父級。
帶有嘲笑的啟發式:
修補您測試的內容
盡可能接近目標函數的補丁
你的情況下的補丁不起作用的原因是 python 在補丁之后不會重新評估模塊和類層次結構。由于 python 是動態的,所以正在發生的事情是
家長班級評估
子類參考父類對象進行評估
您在父模塊中修補父類,但在 中測試代碼
actual_function
,并且ChildClass
引用舊的原始Parent
,因為mock
實際上正在更改命名空間Parent
中的對象屬性parent.py
。
您的案例示例:
with?mock.patch.object(ChildClass,?'cpu_count',?new_callable=mock.PropertyMock)?as?m: ????m.return_value?=?42 ????get_cpu_count_and_attributes(ChildClass())
您不應該更改繼承的屬性/屬性,您應該將補丁放在目標之上(因此得名;))
添加回答
舉報
0/150
提交
取消