Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Pytest: Hard-coded path - monkeypatch attribute

We can also use the setattr method of the monkeypatch fixture.

The path is still rather fixed, but now it is fixed in the test. So we could prepare a few config file and use them in the tests.

import app

def test_app_1(monkeypatch):
    monkeypatch.setattr(app, 'data_file', 'test_1.json')

    res = app.do_something()    # It is now test_1.json
    ...

def test_app_2():
    res = app.do_something() # back to the original value
    ...

When running all the tests the first one will have the mocked filename the second one will have the hard-coded one.

$ pytest -s -q test_app_monkeypatch.py
test_1.json
./corporate/fixed/path/data.json
.
2 passed in 0.04s

When running the tests separately each one of them will have the same filename as they had when we ran them together.

$ pytest -s -q test_app_monkeypatch.py::test_app_1
test_1.json
.
1 passed in 0.04s
$ pytest -s -q test_app_monkeypatch.py::test_app_2
/corporate/fixed/path/data.json
.
1 passed in 0.04s