unit testing - Getting return value problems with unittest patch() in python -
i trying use mock.patch unittest code, getting strange result. important part of code:
@mock.patch('benchmark.scenarios.networking.feature.ssh') @mock.patch('benchmark.scenarios.networking.feature.subprocess.call') def test_run_for_success(self, mock_subprocess, mock_ssh): mock_ssh.ssh().execute.return_value = (0, '100', '') mock_subprocess.call().return_value = 'mocked!' result = {} self.feature.run(result)
when run ssh in code, returned value: (0, '100', '')
, good! however, when run subprocess.call()
returned value:
<magicmock name='subprocess.call()' id='139806699670096'>
what doing wrong? 'mocked!' returned value.
you using mock.return_value
wrong, , on wrong object; whenever want set return value foo()
, use foo.return_value
, not foo().return_value
. moreover, mock_subprocess
points subprocess.call
already, don't call
attribute on that!
in other words, don't call mock object when setting return_value
, , use mock_subprocess
directly:
mock_subprocess.return_value = 'mocked!'
you may want rename mock_subprocess
mock_subprocess_call
or similar make obvious patched.
you setting return value subprocess.call.call()()
, not subprocess.call()
.
demo:
>>> import subprocess >>> unittest.mock import patch >>> patch('subprocess.call') mock_subprocess: ... mock_subprocess.call().return_value = 'mocked!' ... print(subprocess.call(), subprocess.call.call()()) ... mock_subprocess.return_value = 'mocked!' ... print(subprocess.call()) ... <magicmock name='call()' id='4557171960'> mocked! mocked!
Comments
Post a Comment