Tips and Tricks - Monkeypatch Global Variables in Pytest

When writing code it is always a good idea to write testable code or easy to test code. However, sometimes you need to test code, which is not as easy to test as wanted. A useful trick that can assist you while testing code is monkeypatching global variables.

Suppose you have the following script.py:

from pathlib import Path

data_directory = Path(__file__).parent / "data"
print(data_directory)

The data_directory may be used for finding data resources or saving new files. However, when testing this code, you do not want to modify the documents in the data directory. Instead, a temporary directory should be used, where additional temporary files can be created. To do so, the data_directoryvariable needs to be overwritten in tests.

Fortunately, we can utilise pytest's monkeypatch fixture:

# test.py
import script


def test_overwrite_data_dir(tmp_path, monkeypatch) -> None:
    data_directory = tmp_path / "data"
    monkeypatch.setattr(script, "data_directory", data_directory)

    assert data_directory == script.data_directory

Groups: pytest