我是單元測試的新手。我過去使用過模擬、修補(bǔ),但我的情況對(duì)我來說創(chuàng)建單元測試有點(diǎn)復(fù)雜。所以我有一個(gè)文件:parent.py具有以下數(shù)據(jù)類import multiprocessingfrom dataclasses import dataclass@dataclassclass ParentClass: cpu_count: int = multiprocessing.cpu_count() 我有另一個(gè)child.py具有以下數(shù)據(jù)類的模塊from stackoverflow.parent import ParentClassfrom dataclasses import dataclass@dataclassclass ChildClass(ParentClass): some_attribute_1: int = 1 some_attribute_2: int = 2 ....最后,我有第三個(gè)actual_function.py使用這些數(shù)據(jù)類的模塊。from stack_overflow.child import ChildClassdef get_cpu_count_and_attributes(cc: ChildClass): return cc.cpu_count, cc.some_attribute_1 在這里,我想對(duì)print_cpu_count_and_attributes功能進(jìn)行單元測試。這里的補(bǔ)丁是如何工作的?我創(chuàng)建了以下測試用例,但它失敗了。我系統(tǒng)中的 cpu_count 是 16,但我想用返回值 8 來模擬它,以便它可以在具有不同核心數(shù)量的其他機(jī)器上工作from unittest import mockfrom 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)這是文件夾結(jié)構(gòu)。stackoverflow├── __init__.py ├── actual_function.py ├── child.py ├── parent.py └── test_function.py
1 回答

慕神8447489
TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超1個(gè)贊
如果您嘗試測試ChildClass
,您應(yīng)該對(duì)其進(jìn)行路徑,而不是不同模塊中的父級(jí)。
帶有嘲笑的啟發(fā)式:
修補(bǔ)您測試的內(nèi)容
盡可能接近目標(biāo)函數(shù)的補(bǔ)丁
你的情況下的補(bǔ)丁不起作用的原因是 python 在補(bǔ)丁之后不會(huì)重新評(píng)估模塊和類層次結(jié)構(gòu)。由于 python 是動(dòng)態(tài)的,所以正在發(fā)生的事情是
家長班級(jí)評(píng)估
子類參考父類對(duì)象進(jìn)行評(píng)估
您在父模塊中修補(bǔ)父類,但在 中測試代碼
actual_function
,并且ChildClass
引用舊的原始Parent
,因?yàn)?code>mock實(shí)際上正在更改命名空間Parent
中的對(duì)象屬性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())
您不應(yīng)該更改繼承的屬性/屬性,您應(yīng)該將補(bǔ)丁放在目標(biāo)之上(因此得名;))
添加回答
舉報(bào)
0/150
提交
取消