Monkeypatch with Code Examples

What Is Monkeypatching?

Monkeypatching is a term for mocking or patching a piece of code (class, function, module, variable or object) as part of a Unit Test.

def test_cat_fact_w_monkeypatch(monkeypatch):
    class MockResponse(object):
        def __init__(self):
            self.status_code = 200
            self.url = "www.testurl.com"
 
        def json(self):
            return {'data': ['Mother cats teach their '
                             'kittens to use the litter box.']}
 
    def mock_get(*args, **kwargs):
        return MockResponse()
 
    monkeypatch.setattr(requests, 'get', mock_get)
    assert get_cat_fact() == (200, {'data': ['Mother cats '
                                             'teach their kittens '
                                             'to use the litter box.']})

In this case, we define a class MockResponse and force it to return a JSON response, essentially simulating the Requests.GET method.

Is MonkeyPatch The Same As Mocking or Patching?

The two are very similar and have subtle differences.

Monkeypatching is the act of replacing a function, method, class or variable at runtime.

Mock actually uses Monkeypatch under the hood to mock or change certain objects being evaluated at run time as part of your test.