Mocking Python modules across multiple test scripts

Viewed 769

In my implementation script I have a line which logs a metric:

from datadog import statsd

def some_function:
    statsd.increment('some_metric')

From my test script, I assert that statsd.increment() is called by mocking out the datadog module:

datadog = Mock()
sys.modules['datadog'] = datadog

def test():
    some_function()
    datadog.statsd.increment.assert_called()

This works fine and passes. But as soon as I add ANOTHER script which calls some_function() without mocking datadog, that script runs beforehand and loads the real datadog module into the cache. The above test then fails because some_function() is no longer using the mock datadog, it uses the real (cached) datadog.

How can I address this? Is it possible to remove the module from the cache?

2 Answers

Have you tried to mock the datalog module inside your function test? As long as your other scripts are not running concurrently with your test, this may work. That way the mock itself will be set only when the function is called, instead of being set in your script scope.

You could use unittest.mock.patch. If you are using pytest you can do the same with the monkeypatch fixture.

from datadog import statsd
from unittest.mock import Mock, patch

def some_function():
    statsd.increment()

def test_some_function():
    with patch('datadog.statsd', Mock()) as mock_statsd:
        some_function()
    mock_statsd.increment.assert_called()

test_some_function()
Related