37

I installed pytest-mock and using a mocker I am trying to function as patch does, but I get "Type Error: Need a valid target to patch. You supplied 'return a + b'"

# test_capitalize.py
import time


def sum(a, b):
    time.sleep(10)
    return a + b

def test_sum(mocker):
    mocker.patch('return a + b');
    assertEqual(sum(2, 3), 9)
1
  • You can't patch a string. I assume you want to patch the sum function? mocker.patch(__name__ + '.sum', return_value=9) or, if you want to patch with a custom function, use side_effect: mocker.patch(__name__ + '.sum', side_effect=lambda a, b: a - b) etc.
    – hoefling
    Commented Nov 22, 2018 at 16:47

1 Answer 1

58

patch requires a path to the function being patched. You could do something like this:

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

Result:

$ 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 ===========
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.