| 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 :option:`--tb=native`, :option:`--assert=plain` and :option:`--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. Prefer patching the reference that your code uses |
| 245 |
instead of patching the original object in the standard library. For example, |
| 246 |
if your module does ``from os import getcwd``, patch ``mymodule.getcwd`` |
| 247 |
rather than ``os.getcwd``. |
| 248 |
|
| 249 |
For code that you control, a safer long-term pattern is to make dependencies |
| 250 |
explicit so they can be passed into the code under test instead of patched |
| 251 |
globally. When patching a stdlib object is unavoidable, use |
| 252 |
:meth:`MonkeyPatch.context` to limit the patching to the block you want tested: |
| 253 |
|
| 254 |
.. code-block:: python |
| 255 |
|
| 256 |
import functools |
| 257 |
|
| 258 |
|
| 259 |
def test_partial(monkeypatch): |
| 260 |
with monkeypatch.context() as m: |
| 261 |
m.setattr(functools, "partial", 3) |
| 262 |
assert functools.partial == 3 |
| 263 |
|
| 264 |
See :issue:`3290` for details. |
| 265 |
|
| 266 |
|
| 267 |
Monkeypatching environment variables |
| 268 |
------------------------------------ |
| 269 |
|
| 270 |
If you are working with environment variables you often need to safely change the values |
| 271 |
or delete them from the system for testing purposes. ``monkeypatch`` provides a mechanism |
| 272 |
to do this using the ``setenv`` and ``delenv`` method. Our example code to test: |
| 273 |
|
| 274 |
.. code-block:: python |
| 275 |
|
| 276 |
# contents of our original code file e.g. code.py |
| 277 |
import os |
| 278 |
|
| 279 |
|
| 280 |
def get_os_user_lower(): |
| 281 |
"""Simple retrieval function. |
| 282 |
Returns lowercase USER or raises OSError.""" |
| 283 |
username = os.getenv("USER") |
| 284 |
|
| 285 |
if username is None: |
| 286 |
raise OSError("USER environment is not set.") |
| 287 |
|
| 288 |
return username.lower() |
| 289 |
|
| 290 |
There are two potential paths. First, the ``USER`` environment variable is set to a |
| 291 |
value. Second, the ``USER`` environment variable does not exist. Using ``monkeypatch`` |
| 292 |
both paths can be safely tested without impacting the running environment: |
| 293 |
|
| 294 |
.. code-block:: python |
| 295 |
|
| 296 |
# contents of our test file e.g. test_code.py |
| 297 |
import pytest |
| 298 |
|
| 299 |
|
| 300 |
def test_upper_to_lower(monkeypatch): |
| 301 |
"""Set the USER env var to assert the behavior.""" |
| 302 |
monkeypatch.setenv("USER", "TestingUser") |
| 303 |
assert get_os_user_lower() == "testinguser" |
| 304 |
|
| 305 |
|
| 306 |
def test_raise_exception(monkeypatch): |
| 307 |
"""Remove the USER env var and assert OSError is raised.""" |
| 308 |
monkeypatch.delenv("USER", raising=False) |
| 309 |
|
| 310 |
with pytest.raises(OSError): |
| 311 |
_ = get_os_user_lower() |
| 312 |
|
| 313 |
This behavior can be moved into ``fixture`` structures and shared across tests: |
| 314 |
|
| 315 |
.. code-block:: python |
| 316 |
|
| 317 |
# contents of our test file e.g. test_code.py |
| 318 |
import pytest |
| 319 |
|
| 320 |
|
| 321 |
@pytest.fixture |
| 322 |
def mock_env_user(monkeypatch): |
| 323 |
monkeypatch.setenv("USER", "TestingUser") |
| 324 |
|
| 325 |
|
| 326 |
@pytest.fixture |
| 327 |
def mock_env_missing(monkeypatch): |
| 328 |
monkeypatch.delenv("USER", raising=False) |
| 329 |
|
| 330 |
|
| 331 |
# notice the tests reference the fixtures for mocks |
| 332 |
def test_upper_to_lower(mock_env_user): |
| 333 |
assert get_os_user_lower() == "testinguser" |
| 334 |
|
| 335 |
|
| 336 |
def test_raise_exception(mock_env_missing): |
| 337 |
with pytest.raises(OSError): |
| 338 |
_ = get_os_user_lower() |
| 339 |
|
| 340 |
|
| 341 |
Monkeypatching dictionaries |
| 342 |
--------------------------- |
| 343 |
|
| 344 |
:py:meth:`monkeypatch.setitem <MonkeyPatch.setitem>` can be used to safely set the values of dictionaries |
| 345 |
to specific values during tests. Take this simplified connection string example: |
| 346 |
|
| 347 |
.. code-block:: python |
| 348 |
|
| 349 |
# contents of app.py to generate a simple connection string |
| 350 |
DEFAULT_CONFIG = {"user": "user1", "database": "db1"} |
| 351 |
|
| 352 |
|
| 353 |
def create_connection_string(config=None): |
| 354 |
"""Creates a connection string from input or defaults.""" |
| 355 |
config = config or DEFAULT_CONFIG |
| 356 |
return f"User Id={config['user']}; Location={config['database']};" |
| 357 |
|
| 358 |
For testing purposes we can patch the ``DEFAULT_CONFIG`` dictionary to specific values. |
| 359 |
|
| 360 |
.. code-block:: python |
| 361 |
|
| 362 |
# contents of test_app.py |
| 363 |
# app.py with the connection string function (prior code block) |
| 364 |
import app |
| 365 |
|
| 366 |
|
| 367 |
def test_connection(monkeypatch): |
| 368 |
# Patch the values of DEFAULT_CONFIG to specific |
| 369 |
# testing values only for this test. |
| 370 |
monkeypatch.setitem(app.DEFAULT_CONFIG, "user", "test_user") |
| 371 |
monkeypatch.setitem(app.DEFAULT_CONFIG, "database", "test_db") |
| 372 |
|
| 373 |
# expected result based on the mocks |
| 374 |
expected = "User Id=test_user; Location=test_db;" |
| 375 |
|
| 376 |
# the test uses the monkeypatched dictionary settings |
| 377 |
result = app.create_connection_string() |
| 378 |
assert result == expected |
| 379 |
|
| 380 |
You can use the :py:meth:`monkeypatch.delitem <MonkeyPatch.delitem>` to remove values. |
| 381 |
|
| 382 |
.. code-block:: python |
| 383 |
|
| 384 |
# contents of test_app.py |
| 385 |
import pytest |
| 386 |
|
| 387 |
# app.py with the connection string function |
| 388 |
import app |
| 389 |
|
| 390 |
|
| 391 |
def test_missing_user(monkeypatch): |
| 392 |
# patch the DEFAULT_CONFIG to be missing the 'user' key |
| 393 |
monkeypatch.delitem(app.DEFAULT_CONFIG, "user", raising=False) |
| 394 |
|
| 395 |
# Key error expected because a config is not passed, and the |
| 396 |
# default is now missing the 'user' entry. |
| 397 |
with pytest.raises(KeyError): |
| 398 |
_ = app.create_connection_string() |
| 399 |
|
| 400 |
|
| 401 |
The modularity of fixtures gives you the flexibility to define |
| 402 |
separate fixtures for each potential mock and reference them in the needed tests. |
| 403 |
|
| 404 |
.. code-block:: python |
| 405 |
|
| 406 |
# contents of test_app.py |
| 407 |
import pytest |
| 408 |
|
| 409 |
# app.py with the connection string function |
| 410 |
import app |
| 411 |
|
| 412 |
|
| 413 |
# all of the mocks are moved into separated fixtures |
| 414 |
@pytest.fixture |
| 415 |
def mock_test_user(monkeypatch): |
| 416 |
"""Set the DEFAULT_CONFIG user to test_user.""" |
| 417 |
monkeypatch.setitem(app.DEFAULT_CONFIG, "user", "test_user") |
| 418 |
|
| 419 |
|
| 420 |
@pytest.fixture |
| 421 |
def mock_test_database(monkeypatch): |
| 422 |
"""Set the DEFAULT_CONFIG database to test_db.""" |
| 423 |
monkeypatch.setitem(app.DEFAULT_CONFIG, "database", "test_db") |
| 424 |
|
| 425 |
|
| 426 |
@pytest.fixture |
| 427 |
def mock_missing_default_user(monkeypatch): |
| 428 |
"""Remove the user key from DEFAULT_CONFIG""" |
| 429 |
monkeypatch.delitem(app.DEFAULT_CONFIG, "user", raising=False) |
| 430 |
|
| 431 |
|
| 432 |
# tests reference only the fixture mocks that are needed |
| 433 |
def test_connection(mock_test_user, mock_test_database): |
| 434 |
expected = "User Id=test_user; Location=test_db;" |
| 435 |
|
| 436 |
result = app.create_connection_string() |
| 437 |
assert result == expected |
| 438 |
|
| 439 |
|
| 440 |
def test_missing_user(mock_missing_default_user): |
| 441 |
with pytest.raises(KeyError): |
| 442 |
_ = app.create_connection_string() |
| 443 |
|
| 444 |
|
| 445 |
.. currentmodule:: pytest |
| 446 |
|
| 447 |
API Reference |
| 448 |
------------- |
| 449 |
|
| 450 |
Consult the docs for the :class:`MonkeyPatch` class. |