Sometimes tests need to invoke functionality which depends on global settings or which invokes code which cannot be easily tested such as network access. The monkeypatch fixture helps you to safely set/delete an attribute, dictionary item or environment variable, or to modify sys.path for importing.
The monkeypatch fixture provides these helper methods for safely patching and mocking functionality in tests:
- monkeypatch.setattr(obj, name, value, raising=True)
- monkeypatch.delattr(obj, name, raising=True)
- monkeypatch.setitem(mapping, name, value)
- monkeypatch.delitem(obj, name, raising=True)
- monkeypatch.setenv(name, value, prepend=None)
- monkeypatch.delenv(name, raising=True)
- monkeypatch.syspath_prepend(path)
- monkeypatch.chdir(path)
- monkeypatch.context()
All modifications will be undone after the requesting test function or fixture has finished. The raising parameter determines if a KeyError or AttributeError will be raised if the target of the set/deletion operation does not exist.
The pytest framework makes it easy to write small, readable tests, and can scale to support complex functional testing for applications and libraries.
pytest requires: Python 3.8+ or PyPy3.
PyPI package name: pytest
pip install pytest
Testing applications has become a standard skill set required for any competent developer today. The Python community embraces testing, and even the Python standard library has good inbuilt tools to support testing. In the larger Python ecosystem, there are a lot of testing tools. Pytest stands out among them due to its ease of use and its ability to handle increasingly complex testing needs.

Expand your automation to a virtually unlimited set of use cases.
The pytest framework makes it easy to write small, readable tests, and can scale to support complex functional testing for applications and libraries.
pytest requires: Python 3.7+ or PyPy3.