Search code examples
pythonunit-testingpytestmonkeypatching

monkey patch not working properly


So I'm running py.test and trying to use monkeypatch. I understand that monkeypatch's intended purpose is to replace attributes in a module so that they can be tested. And I get that we can substitute in mock functions in order to do this.

Currently I am trying to run essentially the following block of code.

from src.module.submodule import *

def mock_function(parameter = None):
    return 0

def test_function_works(monkeypatch):
    monkeypatch.setattr("src.module.submodule.function",mock_function ]
   assert function(parameter = None) == 0

When the test runs, instead of swapping in mock_function, it just runs function . Could there be a reason why monkeypatch isn't activating

I have got monkey patch running succesfully with other code before. So I don't see why this isn't working.


Solution

  • I haven't used pytest for this stuff, but I know that with the mock library, functions are patched in the namespace where they're called. i.e. from src.module.submodule import * imports src.module.submodule.function into your namespace, but you then patch it in its original namespace, so your local name for the function still accesses the original, unpatched code.

    If you change this to

    import src.module.submodule
    
    def mock_function(parameter = None):
        return 0
    
    def test_function_works(monkeypatch):
        monkeypatch.setattr("src.module.submodule.function",mock_function ]
        assert src.module.submodule.function(parameter = None) == 0
    

    does it succeed?