[英]MagicMock return value based on input
I am trying to refactor my tests from flexmock to mock. 我试图将我的测试从flexmock重构为模拟。 Given the following syntax from flexmock: 从flexmock获得以下语法:
flexmock(subprocess).should_receive('check_output').with_args('ls /').and_return(output)
How can I rewrite this using Mock? 如何使用Mock重写它? In particular, how do I pin a return value to a spesific input using Mock? 特别是,如何使用Mock将返回值固定到特殊输入?
You can use side_effect
patch
attribute to do it: 您可以使用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'
>>>
I'm quite sure that you can find it little bit harder compared to flexmock
's syntax, but what you need is more a stub than a mock. 我很确定,与flexmock
的语法相比,您会发现它有点困难,但是您需要的是存根而不是模拟。 If you can design your test to be isolated and configure your mock/stub in some setup stage maybe you will find this syntax good and all mock
asserts and patch
options very powerful. 如果您可以将测试设计为隔离的,并在某个设置阶段配置模拟/存根,那么您可能会发现此语法很好,并且所有mock
断言和patch
选项都非常强大。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.