Why use monkeypatch.setenv instead of os.putenv

Question:

pytest’s monkeypatch module provides a setenv function which will Set environment variable name to value. Why does monkeypatch provide this? It sounds the same as os.putenv? It provides prepend argument as a convenience, but that seems like a weak reason to have a new function for setting an environment variable.

Asked By: rcorre

||

Answers:

This is about tearing down the changes that the test makes in the environment. If you only use os.putenv, or modify the os.environ directly, then your modifications will stay in place even after the end of the test. That means the next test that runs will have the change applied, too! Since the tests are not necessarily ordered, it means you no longer have a repeatable and reliable test execution.

It’s undesirable for a individual tests to change some global mutable state, therefore either use a context manager or the fixture provided when you need to configure environment variables during tests.

Answered By: wim