@@ -6,14 +6,17 @@ Monkeypatching/mocking modules and environments
6
6
7
7
Sometimes tests need to invoke functionality which depends
8
8
on global settings or which invokes code which cannot be easily
9
- tested such as network access. The ``monkeypatch `` function argument
9
+ tested such as network access. The ``monkeypatch `` fixture
10
10
helps you to safely set/delete an attribute, dictionary item or
11
11
environment variable or to modify ``sys.path `` for importing.
12
12
See the `monkeypatch blog post `_ for some introduction material
13
13
and a discussion of its motivation.
14
14
15
15
.. _`monkeypatch blog post` : http://tetamap.wordpress.com/2009/03/03/monkeypatching-in-unit-tests-done-right/
16
16
17
+ As of pytest-3.0, the ``monkeypatch `` fixture is :ref: `invocation-scoped <invocation_scoped_fixture >`
18
+ meaning it can be requested from fixtures of any scope.
19
+
17
20
Simple example: monkeypatching functions
18
21
---------------------------------------------------
19
22
@@ -53,27 +56,31 @@ This autouse fixture will be executed for each test function and it
53
56
will delete the method ``request.session.Session.request ``
54
57
so that any attempts within tests to create http requests will fail.
55
58
56
- example: setting an attribute on some class
57
- ------------------------------------------------------
59
+ example: setting an environment variable for the test session
60
+ -------------------------------------------------------------
58
61
59
- If you need to patch out ``os.getcwd() `` to return an artificial
60
- value::
62
+ If you would like for an environment variable to be
63
+ configured for the entire test session, you can add this to your
64
+ top-level ``conftest.py `` file:
61
65
62
- def test_some_interaction(monkeypatch):
63
- monkeypatch.setattr("os.getcwd", lambda: "/")
66
+ .. code-block :: python
67
+
68
+ # content of conftest.py
69
+ @pytest.fixture (scope = ' session' , autouse = True )
70
+ def enable_debugging (monkeypatch ):
71
+ monkeypatch.setenv(" DEBUGGING_VERBOSITY" , " 4" )
64
72
65
- which is equivalent to the long form::
73
+ This auto-use fixture will set the ``DEBUGGING_VERBOSITY `` environment variable for
74
+ the entire test session.
66
75
67
- def test_some_interaction(monkeypatch):
68
- import os
69
- monkeypatch.setattr(os, "getcwd", lambda: "/")
70
-
76
+ Note that the ability to use a ``monkeypatch `` fixture from a ``session ``-scoped
77
+ fixture was added in pytest-3.0.
71
78
72
79
73
- Method reference of the monkeypatch function argument
74
- -----------------------------------------------------
80
+ Method reference of the monkeypatch fixture
81
+ -------------------------------------------
75
82
76
- .. autoclass :: monkeypatch
83
+ .. autoclass :: MonkeyPatch
77
84
:members: setattr, replace, delattr, setitem, delitem, setenv, delenv, syspath_prepend, chdir, undo
78
85
79
86
``monkeypatch.setattr/delattr/delitem/delenv() `` all
0 commit comments