我正在尝试测试调用subprocess.run
的函数。我想:
subprocess.run
使用以下代码:
import subprocess
from unittest import mock
def test_foo(monkeypatch):
m = mock.Mock(spec=['run'], **{
'run.return_value.returncode': 0,
})
monkeypatch.setattr(subprocess, 'run', m)
assert subprocess.run is m
assert subprocess.run(['ls']).returncode == m.run(['ls']).returncode
运行pytest
显示:
assert subprocess.run is m
> assert subprocess.run(['ls']).returncode == m.run(['ls']).returncode
E AssertionError: assert <Mock name='mock().returncode' id='140293943645408'> == 0
E + where <Mock name='mock().returncode' id='140293943645408'> = <Mock name='mock()' id='140293943645352'>.returncode
E + where <Mock name='mock()' id='140293943645352'> = <Mock id='140293943644792'>(['ls'])
E + where <Mock id='140293943644792'> = subprocess.run
E + and 0 = <Mock name='mock.run()' id='140293943645184'>.returncode
E + where <Mock name='mock.run()' id='140293943645184'> = <Mock name='mock.run' id='140293943645128'>(['ls'])
E + where <Mock name='mock.run' id='140293943645128'> = <Mock id='140293943644792'>.run
第一个断言表明m
和subprocess.run
是相同的模拟,而前者的returncode
为0
,而后者的returncode
是另一个嘲笑。为什么会这样?