使用嘲笑者用pytest修补

时间:2018-11-22 16:25:41

标签: python mocking pytest

我安装了pytest-mock,并尝试尝试使用模仿程序来充当补丁程序,但是我收到“类型错误:需要有效的目标补丁程序。您提供了'return a + b'”

for (let element of array){
    storage.push( ... el )
}

1 个答案:

答案 0 :(得分:2)

patch需要修补的功能的路径。您可以执行以下操作:

import pytest


def sum(a, b):
    return a + b


def test_sum1(mocker):
    mocker.patch(__name__ + ".sum", return_value=9)
    assert sum(2, 3) == 9


def test_sum2(mocker):
    def crazy_sum(a, b):
        return b + b

    mocker.patch(__name__ + ".sum", side_effect=crazy_sum)
    assert sum(2, 3) == 6

结果:

$ pytest -v patch_test.py
============= test session starts ==============
platform cygwin -- Python 3.6.4, pytest-3.10.1, py-1.7.0, pluggy-0.8.0 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: /home/xyz/temp, inifile:
plugins: mock-1.10.0, cov-2.6.0
collected 2 items

patch_test.py::test_sum1 PASSED          [ 50%]
patch_test.py::test_sum2 PASSED          [100%]

=========== 2 passed in 0.02 seconds ===========