Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using mocker to patch with pytest

Tags:

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)
like image 551
Kevin Avatar asked Nov 22 '18 16:11

Kevin


People also ask

Can you use mock with Pytest?

Advanced: Mocking in Unit Test In pytest , mocking can replace the return value of a function within a function. This is useful for testing the desired function and replacing the return value of a nested function within that desired function we are testing.

What is Mocker in Python?

mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. unittest. mock provides a core Mock class removing the need to create a host of stubs throughout your test suite.

What is mock patch?

mock provides a powerful mechanism for mocking objects, called patch() , which looks up an object in a given module and replaces that object with a Mock . Usually, you use patch() as a decorator or a context manager to provide a scope in which you will mock the target object.

What is the difference between mock and patch?

Mock is a type, and patch is a context. So you are going to pass or receive Mock instances as parameters, and apply patch contexts to blocks of code. (Lowercase 'mock' is just the name of the package.)


1 Answers

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 ===========
like image 176
ivavid Avatar answered Sep 20 '22 15:09

ivavid