![](/img/trans.png)
[英]How to use more than 20 nested for loops in python3 program without any exception of too many statically nested blocks?
[英]Python, using more than 20 times mock.patch.object() and too many statically nested blocks error
我需要為一個非常胖的方法編寫單元測試代碼。 並且該方法多次調用其他方法,因此我需要對所有調用方法使用mock。 但是當我使用 mock.patch.object 超過 20 次時,我得到了錯誤,太多的靜態嵌套塊。
我的代碼看起來像這樣,
test_fat_method(self):
instance = FatClass()
with mock.patch.object(instance, '_method_1', return_value=1), \
...
with mock.patch.object(instance, '_method_22', return_value=1):
result = instance.test_method()
assert result
有什么辦法可以避免錯誤嗎?
除了上下文切換之外,還有 2 種替代方法可以使用mock.patch
。
作為裝飾者
當我們在方法中綁定裝飾器時,我們在方法的*args
上附加項目。
這個實現的不好的部分是處理一個沒有名字的模擬列表。
from unittest.mock import patch
class Class:
def func_1():
return True
def func_2():
return True
def func_3():
return True
@patch.object(Class, 'func_1')
@patch.object(Class, 'func_2')
@patch.object(Class, 'func_3')
def test_class(*args):
args[0].return_value = 3 # This is the last object patched.
args[1].return_value = 2 # This is the second object patched.
args[2].return_value = 1 # This is the first object patched.
assert len(args) == 3 # Quantity of items in args (3 decorators.)
assert Class().func_1() == 1
assert Class().func_2() == 2
assert Class().func_3() == 3
如果您對裝飾器的順序有任何疑問,請查看此答案
作為對象
此解決方案更冗長,但更易於維護。 但是,我會選擇這種方法。
def test_class_alternative():
mock_func_1 = patch('Class.func_1', return_value=1)
mock_func_2 = patch('Class.func_2', return_value=2)
mock_func_3 = patch('Class.func_3', return_value=3)
assert Class().func_1() == 1
assert Class().func_2() == 2
assert Class().func_3() == 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.