Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/doc/en/how-to/monkeypatch.rst

raw
1 .. _monkeypatching:
2
3 How to monkeypatch/mock modules and environments
4 ================================================================
5
6 .. currentmodule:: pytest
7
8 Sometimes tests need to invoke functionality which depends
9 on global settings or which invokes code which cannot be easily
10 tested such as network access. The ``monkeypatch`` fixture
11 helps you to safely set/delete an attribute, dictionary item or
12 environment variable, or to modify ``sys.path`` for importing.
13
14 The ``monkeypatch`` fixture provides these helper methods for safely patching and mocking
15 functionality in tests:
16
17 * :meth:`monkeypatch.setattr(obj, name, value, raising=True) <pytest.MonkeyPatch.setattr>`
18 * :meth:`monkeypatch.delattr(obj, name, raising=True) <pytest.MonkeyPatch.delattr>`
19 * :meth:`monkeypatch.setitem(mapping, name, value) <pytest.MonkeyPatch.setitem>`
20 * :meth:`monkeypatch.delitem(obj, name, raising=True) <pytest.MonkeyPatch.delitem>`
21 * :meth:`monkeypatch.setenv(name, value, prepend=None) <pytest.MonkeyPatch.setenv>`
22 * :meth:`monkeypatch.delenv(name, raising=True) <pytest.MonkeyPatch.delenv>`
23 * :meth:`monkeypatch.syspath_prepend(path) <pytest.MonkeyPatch.syspath_prepend>`
24 * :meth:`monkeypatch.chdir(path) <pytest.MonkeyPatch.chdir>`
25 * :meth:`monkeypatch.context() <pytest.MonkeyPatch.context>`
26
27
28 All modifications will be undone after the requesting
29 test function or fixture has finished. The ``raising``
30 parameter determines if a ``KeyError`` or ``AttributeError``
31 will be raised if the target of the set/deletion operation does not exist.
32
33 Consider the following scenarios:
34
35 1. Modifying the behavior of a function or the property of a class for a test e.g.
36 there is an API call or database connection you will not make for a test but you know
37 what the expected output should be. Use :py:meth:`monkeypatch.setattr <MonkeyPatch.setattr>` to patch the
38 function or property with your desired testing behavior. This can include your own functions.
39 Use :py:meth:`monkeypatch.delattr <MonkeyPatch.delattr>` to remove the function or property for the test.
40
41 2. Modifying the values of dictionaries e.g. you have a global configuration that
42 you want to modify for certain test cases. Use :py:meth:`monkeypatch.setitem <MonkeyPatch.setitem>` to patch the
43 dictionary for the test. :py:meth:`monkeypatch.delitem <MonkeyPatch.delitem>` can be used to remove items.
44
45 3. Modifying environment variables for a test e.g. to test program behavior if an
46 environment variable is missing, or to set multiple values to a known variable.
47 :py:meth:`monkeypatch.setenv <MonkeyPatch.setenv>` and :py:meth:`monkeypatch.delenv <MonkeyPatch.delenv>` can be used for
48 these patches.
49
50 4. Use ``monkeypatch.setenv("PATH", value, prepend=os.pathsep)`` to modify ``$PATH``, and
51 :py:meth:`monkeypatch.chdir <MonkeyPatch.chdir>` to change the context of the current working directory
52 during a test.
53
54 5. Use :py:meth:`monkeypatch.syspath_prepend <MonkeyPatch.syspath_prepend>` to modify ``sys.path`` which will also
55 call ``pkg_resources.fixup_namespace_packages`` and :py:func:`importlib.invalidate_caches`.
56
57 6. Use :py:meth:`monkeypatch.context <MonkeyPatch.context>` to apply patches only in a specific scope, which can help
58 control teardown of complex fixtures or patches to the stdlib.
59
60 See the `monkeypatch blog post`_ for some introduction material
61 and a discussion of its motivation.
62
63 .. _`monkeypatch blog post`: https://tetamap.wordpress.com//2009/03/03/monkeypatching-in-unit-tests-done-right/
64
65 Monkeypatching functions
66 ------------------------
67
68 Consider a scenario where you are working with user directories. In the context of
69 testing, you do not want your test to depend on the running user. ``monkeypatch``
70 can be used to patch functions dependent on the user to always return a
71 specific value.
72
73 In this example, :py:meth:`monkeypatch.setattr <MonkeyPatch.setattr>` is used to patch ``Path.home``
74 so that the known testing path ``Path("/abc")`` is always used when the test is run.
75 This removes any dependency on the running user for testing purposes.
76 :py:meth:`monkeypatch.setattr <MonkeyPatch.setattr>` must be called before the function which will use
77 the patched function is called.
78 After the test function finishes the ``Path.home`` modification will be undone.
79
80 .. code-block:: python
81
82 # contents of test_module.py with source code and the test
83 from pathlib import Path
84
85
86 def getssh():
87 """Simple function to return expanded homedir ssh path."""
88 return Path.home() / ".ssh"
89
90
91 def test_getssh(monkeypatch):
92 # mocked return function to replace Path.home
93 # always return '/abc'
94 def mockreturn():
95 return Path("/abc")
96
97 # Application of the monkeypatch to replace Path.home
98 # with the behavior of mockreturn defined above.
99 monkeypatch.setattr(Path, "home", mockreturn)
100
101 # Calling getssh() will use mockreturn in place of Path.home
102 # for this test with the monkeypatch.
103 x = getssh()
104 assert x == Path("/abc/.ssh")
105
106 Monkeypatching returned objects: building mock classes
107 ------------------------------------------------------
108
109 :py:meth:`monkeypatch.setattr <MonkeyPatch.setattr>` can be used in conjunction with classes to mock returned
110 objects from functions instead of values.
111 Imagine a simple function to take an API url and return the json response.
112
113 .. code-block:: python
114
115 # contents of app.py, a simple API retrieval example
116 import requests
117
118
119 def get_json(url):
120 """Takes a URL, and returns the JSON."""
121 r = requests.get(url)
122 return r.json()
123
124 We need to mock ``r``, the returned response object for testing purposes.
125 The mock of ``r`` needs a ``.json()`` method which returns a dictionary.
126 This can be done in our test file by defining a class to represent ``r``.
127
128 .. code-block:: python
129
130 # contents of test_app.py, a simple test for our API retrieval
131 # import requests for the purposes of monkeypatching
132 import requests
133
134 # our app.py that includes the get_json() function
135 # this is the previous code block example
136 import app
137
138
139 # custom class to be the mock return value
140 # will override the requests.Response returned from requests.get
141 class MockResponse:
142 # mock json() method always returns a specific testing dictionary
143 @staticmethod
144 def json():
145 return {"mock_key": "mock_response"}
146
147
148 def test_get_json(monkeypatch):
149 # Any arguments may be passed and mock_get() will always return our
150 # mocked object, which only has the .json() method.
151 def mock_get(*args, **kwargs):
152 return MockResponse()
153
154 # apply the monkeypatch for requests.get to mock_get
155 monkeypatch.setattr(requests, "get", mock_get)
156
157 # app.get_json, which contains requests.get, uses the monkeypatch
158 result = app.get_json("https://fakeurl")
159 assert result["mock_key"] == "mock_response"
160
161
162 ``monkeypatch`` applies the mock for ``requests.get`` with our ``mock_get`` function.
163 The ``mock_get`` function returns an instance of the ``MockResponse`` class, which
164 has a ``json()`` method defined to return a known testing dictionary and does not
165 require any outside API connection.
166
167 You can build the ``MockResponse`` class with the appropriate degree of complexity for
168 the scenario you are testing. For instance, it could include an ``ok`` property that
169 always returns ``True``, or return different values from the ``json()`` mocked method
170 based on input strings.
171
172 This mock can be shared across tests using a ``fixture``:
173
174 .. code-block:: python
175
176 # contents of test_app.py, a simple test for our API retrieval
177 import pytest
178 import requests
179
180 # app.py that includes the get_json() function
181 import app
182
183
184 # custom class to be the mock return value of requests.get()
185 class MockResponse:
186 @staticmethod
187 def json():
188 return {"mock_key": "mock_response"}
189
190
191 # monkeypatched requests.get moved to a fixture
192 @pytest.fixture
193 def mock_response(monkeypatch):
194 """Requests.get() mocked to return {'mock_key':'mock_response'}."""
195
196 def mock_get(*args, **kwargs):
197 return MockResponse()
198
199 monkeypatch.setattr(requests, "get", mock_get)
200
201
202 # notice our test uses the custom fixture instead of monkeypatch directly
203 def test_get_json(mock_response):
204 result = app.get_json("https://fakeurl")
205 assert result["mock_key"] == "mock_response"
206
207
208 Furthermore, if the mock was designed to be applied to all tests, the ``fixture`` could
209 be moved to a ``conftest.py`` file and use the with ``autouse=True`` option.
210
211
212 Global patch example: preventing "requests" from remote operations
213 ------------------------------------------------------------------
214
215 If you want to prevent the "requests" library from performing http
216 requests in all your tests, you can do:
217
218 .. code-block:: python
219
220 # contents of conftest.py
221 import pytest
222
223
224 @pytest.fixture(autouse=True)
225 def no_requests(monkeypatch):
226 """Remove requests.sessions.Session.request for all tests."""
227 monkeypatch.delattr("requests.sessions.Session.request")
228
229 This autouse fixture will be executed for each test function and it
230 will delete the method ``request.session.Session.request``
231 so that any attempts within tests to create http requests will fail.
232
233
234 .. note::
235
236 Be advised that it is not recommended to patch builtin functions such as ``open``,
237 ``compile``, etc., because it might break pytest's internals. If that's
238 unavoidable, passing ``--tb=native``, ``--assert=plain`` and ``--capture=no`` might
239 help although there's no guarantee.
240
241 .. note::
242
243 Mind that patching ``stdlib`` functions and some third-party libraries used by pytest
244 might break pytest itself, therefore in those cases it is recommended to use
245 :meth:`MonkeyPatch.context` to limit the patching to the block you want tested:
246
247 .. code-block:: python
248
249 import functools
250
251
252 def test_partial(monkeypatch):
253 with monkeypatch.context() as m:
254 m.setattr(functools, "partial", 3)
255 assert functools.partial == 3
256
257 See :issue:`3290` for details.
258
259
260 Monkeypatching environment variables
261 ------------------------------------
262
263 If you are working with environment variables you often need to safely change the values
264 or delete them from the system for testing purposes. ``monkeypatch`` provides a mechanism
265 to do this using the ``setenv`` and ``delenv`` method. Our example code to test:
266
267 .. code-block:: python
268
269 # contents of our original code file e.g. code.py
270 import os
271
272
273 def get_os_user_lower():
274 """Simple retrieval function.
275 Returns lowercase USER or raises OSError."""
276 username = os.getenv("USER")
277
278 if username is None:
279 raise OSError("USER environment is not set.")
280
281 return username.lower()
282
283 There are two potential paths. First, the ``USER`` environment variable is set to a
284 value. Second, the ``USER`` environment variable does not exist. Using ``monkeypatch``
285 both paths can be safely tested without impacting the running environment:
286
287 .. code-block:: python
288
289 # contents of our test file e.g. test_code.py
290 import pytest
291
292
293 def test_upper_to_lower(monkeypatch):
294 """Set the USER env var to assert the behavior."""
295 monkeypatch.setenv("USER", "TestingUser")
296 assert get_os_user_lower() == "testinguser"
297
298
299 def test_raise_exception(monkeypatch):
300 """Remove the USER env var and assert OSError is raised."""
301 monkeypatch.delenv("USER", raising=False)
302
303 with pytest.raises(OSError):
304 _ = get_os_user_lower()
305
306 This behavior can be moved into ``fixture`` structures and shared across tests:
307
308 .. code-block:: python
309
310 # contents of our test file e.g. test_code.py
311 import pytest
312
313
314 @pytest.fixture
315 def mock_env_user(monkeypatch):
316 monkeypatch.setenv("USER", "TestingUser")
317
318
319 @pytest.fixture
320 def mock_env_missing(monkeypatch):
321 monkeypatch.delenv("USER", raising=False)
322
323
324 # notice the tests reference the fixtures for mocks
325 def test_upper_to_lower(mock_env_user):
326 assert get_os_user_lower() == "testinguser"
327
328
329 def test_raise_exception(mock_env_missing):
330 with pytest.raises(OSError):
331 _ = get_os_user_lower()
332
333
334 Monkeypatching dictionaries
335 ---------------------------
336
337 :py:meth:`monkeypatch.setitem <MonkeyPatch.setitem>` can be used to safely set the values of dictionaries
338 to specific values during tests. Take this simplified connection string example:
339
340 .. code-block:: python
341
342 # contents of app.py to generate a simple connection string
343 DEFAULT_CONFIG = {"user": "user1", "database": "db1"}
344
345
346 def create_connection_string(config=None):
347 """Creates a connection string from input or defaults."""
348 config = config or DEFAULT_CONFIG
349 return f"User Id={config['user']}; Location={config['database']};"
350
351 For testing purposes we can patch the ``DEFAULT_CONFIG`` dictionary to specific values.
352
353 .. code-block:: python
354
355 # contents of test_app.py
356 # app.py with the connection string function (prior code block)
357 import app
358
359
360 def test_connection(monkeypatch):
361 # Patch the values of DEFAULT_CONFIG to specific
362 # testing values only for this test.
363 monkeypatch.setitem(app.DEFAULT_CONFIG, "user", "test_user")
364 monkeypatch.setitem(app.DEFAULT_CONFIG, "database", "test_db")
365
366 # expected result based on the mocks
367 expected = "User Id=test_user; Location=test_db;"
368
369 # the test uses the monkeypatched dictionary settings
370 result = app.create_connection_string()
371 assert result == expected
372
373 You can use the :py:meth:`monkeypatch.delitem <MonkeyPatch.delitem>` to remove values.
374
375 .. code-block:: python
376
377 # contents of test_app.py
378 import pytest
379
380 # app.py with the connection string function
381 import app
382
383
384 def test_missing_user(monkeypatch):
385 # patch the DEFAULT_CONFIG t be missing the 'user' key
386 monkeypatch.delitem(app.DEFAULT_CONFIG, "user", raising=False)
387
388 # Key error expected because a config is not passed, and the
389 # default is now missing the 'user' entry.
390 with pytest.raises(KeyError):
391 _ = app.create_connection_string()
392
393
394 The modularity of fixtures gives you the flexibility to define
395 separate fixtures for each potential mock and reference them in the needed tests.
396
397 .. code-block:: python
398
399 # contents of test_app.py
400 import pytest
401
402 # app.py with the connection string function
403 import app
404
405
406 # all of the mocks are moved into separated fixtures
407 @pytest.fixture
408 def mock_test_user(monkeypatch):
409 """Set the DEFAULT_CONFIG user to test_user."""
410 monkeypatch.setitem(app.DEFAULT_CONFIG, "user", "test_user")
411
412
413 @pytest.fixture
414 def mock_test_database(monkeypatch):
415 """Set the DEFAULT_CONFIG database to test_db."""
416 monkeypatch.setitem(app.DEFAULT_CONFIG, "database", "test_db")
417
418
419 @pytest.fixture
420 def mock_missing_default_user(monkeypatch):
421 """Remove the user key from DEFAULT_CONFIG"""
422 monkeypatch.delitem(app.DEFAULT_CONFIG, "user", raising=False)
423
424
425 # tests reference only the fixture mocks that are needed
426 def test_connection(mock_test_user, mock_test_database):
427 expected = "User Id=test_user; Location=test_db;"
428
429 result = app.create_connection_string()
430 assert result == expected
431
432
433 def test_missing_user(mock_missing_default_user):
434 with pytest.raises(KeyError):
435 _ = app.create_connection_string()
436
437
438 .. currentmodule:: pytest
439
440 API Reference
441 -------------
442
443 Consult the docs for the :class:`MonkeyPatch` class.