setattr in monkeypatching of a function throws attribute error

Viewed 1068

I have the following code

/tests/test_fixme.py

def make_my_patch():
    name = "Dinesh"
    return name


def test_make_patch(monkeypatch):

    monkeypatch.setattr(make_my_patch,"name","DineshKumar")

Using setattr to set name throws an attribute error.

Note : I have placed both the functions in the same file as a stop gap solution to avoid module/import errors for now.

Here is the traceback.

================================================================== FAILURES ==================================================================
______________________________________________________________ test_make_patch _______________________________________________________________

monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x7fddd5675630>

    def test_make_patch(monkeypatch):

>       monkeypatch.setattr(make_my_patch,"name","DineshKumar")
E       AttributeError: <function make_my_patch at 0x7fddd5676048> has no attribute 'name'

tests/test_fixme.py:16: AttributeError
========================================================== short test summary info ===========================================================
FAILED tests/test_fixme.py::test_make_patch - AttributeError: <function make_my_patch at 0x7fddd5676048> has no attribute 'name'
============================================================= 1 failed in 0.02s ==============================================================
(testenv) user@user:~/MyGitHub/MyLearning/Python/MyUnitTests/Testing10$ 

How do I patch the name attribute correctly? However if I place my code inside a class, the setattr for class variable works just fine? Could you please explain why doesnt it work for functions?

1 Answers

In case someone ends up here.

You need to return a mock object that has a return value so your code will be something like:

from unittest.mock import Mock

def make_my_patch():
    name = "Dinesh"
    return name


def test_make_patch(monkeypatch):
    monkeypatch.setattr(
        make_my_patch,
        Mock(return_value="DineshKumar")
    )
Related