0
我想重構我的測試從flexmock到模擬。從flexmock給出以下語法:基於輸入的MagicMock返回值
flexmock(subprocess).should_receive('check_output').with_args('ls /').and_return(output)
我該如何使用模擬來重寫?特別是,如何使用Mock將返回值固定爲特定輸入?
我想重構我的測試從flexmock到模擬。從flexmock給出以下語法:基於輸入的MagicMock返回值
flexmock(subprocess).should_receive('check_output').with_args('ls /').and_return(output)
我該如何使用模擬來重寫?特別是,如何使用Mock將返回值固定爲特定輸入?
您可以使用side_effect
patch
屬性做到這一點:
>>> from unittest.mock import *
>>> root = '''bin cdrom etc initrd.img lib32 libx32 media opt root sbin sys usr vmlinuz
... boot dev home lib lib64 lost+found mnt proc run srv tmp var'''
>>> answer = {'ls /': root}
>>> import subprocess
>>> with patch('subprocess.check_output', side_effect=lambda arg, *args, **kwargs: answer[arg]) as mock_check_output :
... assert root == subprocess.check_output('ls /')
... mock_check_output.assert_called_with('ls /')
... subprocess.check_output('something else')
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "/usr/lib/python3.4/unittest/mock.py", line 896, in __call__
return _mock_self._mock_call(*args, **kwargs)
File "/usr/lib/python3.4/unittest/mock.py", line 962, in _mock_call
ret_val = effect(*args, **kwargs)
File "<stdin>", line 1, in <lambda>
KeyError: 'something else'
>>>
我敢肯定,你可以找到它有點困難相比flexmock
的語法,但你需要的是多了一個存根一個模擬。如果你可以設計你的測試被隔離,並在某個設置階段配置你的模擬/存根,也許你會發現這個語法很好,並且所有mock
聲明和patch
選項都非常強大。