如何使用模拟猴子进行修补并设置返回值

时间:2018-09-17 16:45:19

标签: python python-3.x mocking pytest monkeypatching

我正在尝试测试调用subprocess.run的函数。我想:

  1. 检查是否已使用期望的参数调用了subprocess.run
  2. 将退出代码设为零

使用以下代码:

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

第一个断言表明msubprocess.run是相同的模拟,而前者的returncode0,而后者的returncode是另一个嘲笑。为什么会这样?

0 个答案:

没有答案