Patching a method of a class that is already patched

  pytest, pytest-mock, python

I’m trying to patch a class and its method, this is an example that what I’m trying to do:

class Car:
    def __init__(self, color):
        self.color = color

    def show_color(self):
        return self.color

I have this class and I want to patch the class, and its method separately, I didn’t create a fake class, because in my case the class is complex, so I want the class to be created and then just test a method of some that has the class, I’m trying to do this:

import example

def test_example(
    mocker
):
    mocker.patch("example.Car")
    mocker.patch("example.Car.show_color").return_value = "red"
    c = example.Car("blue")
    assert c.show_color() == "red"

Also, I tried to do something like this:

import example

def test_example(
    mocker
):
    mocker.patch("example.Car").return_value = mocker.create_autospec(
        example.Car,
        show_color = "red"
    )
    c = example.Car("blue")
    assert c.show_color() == "red"

In the two cases, I got this error:

========================================================================================== FAILURES ==========================================================================================
________________________________________________________________________________________ test_example ________________________________________________________________________________________

mocker = <pytest_mock.plugin.MockerFixture object at 0x102281bb0>

    def test_example(
        mocker
    ):
        mocker.patch("example.Car")
        mocker.patch("example.Car.show_color").return_value = "red"
        c = example.Car("blue")
>       assert c.show_color() == "red"
E       AssertionError: assert <MagicMock name='Car().show_color()' id='4331364896'> == 'red'
E        +  where <MagicMock name='Car().show_color()' id='4331364896'> = <MagicMock name='Car().show_color' id='4331344512'>()
E        +    where <MagicMock name='Car().show_color' id='4331344512'> = <MagicMock name='Car()' id='4331304944'>.show_color

test_mocking.py:21: AssertionError
================================================================================== short test summary info ===================================================================================
FAILED test_mocking.py::test_example - AssertionError: assert <MagicMock name='Car().show_color()' id='4331364896'> == 'red'
===================================================================================== 1 failed in 0.06s ======================================================================================

I’m patching the method, because I have another method that I want to test, and this method I’d like to just patch the result

Source: Python Questions

LEAVE A COMMENT