safely patch object attributes, dicts and environment variables.
Use the monkeypatch funcarg to safely patch environment variables, object attributes or dictionaries. For example, if you want to set the environment variable ENV1 and patch the os.path.abspath function to return a particular value during a test function execution you can write it down like this:
def test_mytest(monkeypatch):
monkeypatch.setenv('ENV1', 'myval')
monkeypatch.setattr(os.path, 'abspath', lambda x: '/')
... # your test code
The function argument will do the modifications and memorize the old state. After the test function finished execution all modifications will be reverted. See the monkeypatch blog post for an extensive discussion.
To add to a possibly existing environment parameter you can use this example:
def test_mypath_finding(monkeypatch):
monkeypatch.setenv('PATH', 'x/y', prepend=":")
# x/y will be at the beginning of $PATH
The returned monkeypatch funcarg provides three helper methods to modify objects, dictionaries or os.environ:
monkeypatch.setattr(obj, name, value) monkeypatch.setitem(mapping, name, value) monkeypatch.setenv(name, value)
All such modifications will be undone when the requesting test function finished its execution.
Checkout customize, other plugins or get in contact.