pythonpytestmonkeypatching

how to mock a function in pytest monkeypatch?


I am trying to mock a simple function but I get an AttributeError and have no clue on how to fix it.

def my_function():
    return "original"

def mock_my_function():
    return "mocked"

def test_my_function(monkeypatch):
    monkeypatch.setattr(__name__, 'my_function', mock_my_function)
    assert my_function() == "mocked"

What should I put in __name__'s place to make it work?


Solution

  • The solution is to put your function that you want to test in a different file so that it can behave as a module.

    file with functions you want to test (named original_code.py);

    def my_function():
        return "original"
    

    file with test (named test_set.py):

    import pytest
    import original_code
    
    def test_my_function(monkeypatch):
        
        def mock_my_function():
            return "mocked"
        monkeypatch.setattr(original_code, 'my_function', mock_my_function)
        assert original_code.my_function() == "mocked"
    

    structure of the files

    |_ original_code.py
    |_ test_set.py
    

    this should mock the function named "my_function" with "mock_my_function" defined inside the test