Table Of Contents

Previous topic

Capturing of stdout/stderr output

Next topic

xdist: pytest distributed testing plugin

This Page

monkeypatching/mocking modules and environments

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 function argument helps you to safely set/delete an attribute, dictionary item or environment variable or to modify sys.path for importing. See the monkeypatch blog post one some introduction material and motivation.

Simple example: patching os.path.expanduser

If you e.g. want to pretend that os.expanduser returns a certain directory, you can use the monkeypatch.setattr() method to patch this function before calling into a function which uses it:

import os.path
def getssh(): # pseudo application code
    return os.path.join(os.expanduser("~admin"), '.ssh')

def test_mytest(monkeypatch):
    def mockreturn(path):
        return '/abc'
    monkeypatch.setattr(os.path, 'expanduser', mockreturn)
    x = getssh()
    assert x == '/abc'

After the test function finishes the os.path.expanduser modification will be undone.

Method reference of the monkeypatch function argument

class _pytest.monkeypatch.monkeypatch[source]

object keeping a record of setattr/item/env/syspath changes.

setattr(obj, name, value, raising=True)[source]

set attribute name on obj to value, by default raise AttributeEror if the attribute did not exist.

delattr(obj, name, raising=True)[source]

delete attribute name from obj, by default raise AttributeError it the attribute did not previously exist.

setitem(dic, name, value)[source]

set dictionary entry name to value.

delitem(dic, name, raising=True)[source]

delete name from dict, raise KeyError if it doesn’t exist.

setenv(name, value, prepend=None)[source]

set environment variable name to value. if prepend is a character, read the current environment variable value and prepend the value adjoined with the prepend character.

delenv(name, raising=True)[source]

delete name from environment, raise KeyError it not exists.

syspath_prepend(path)[source]

prepend path to sys.path list of import locations.

undo()[source]

undo previous changes. This call consumes the undo stack. Calling it a second time has no effect unless you do more monkeypatching after the undo call.

monkeypatch.setattr/delattr/delitem/delenv() all by default raise an Exception if the target does not exist. Pass raising=False if you want to skip this check.