Skip to content

Commit 7fa0e04

Browse files
committed
apply review changes
1 parent 7ff8e1b commit 7fa0e04

File tree

1 file changed

+51
-51
lines changed

1 file changed

+51
-51
lines changed

doc/en/monkeypatch.rst

Lines changed: 51 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ functionality in tests:
2727
All modifications will be undone after the requesting
2828
test function or fixture has finished. The ``raising``
2929
parameter determines if a ``KeyError`` or ``AttributeError``
30-
will be raised if the set/deletion operation has no target.
30+
will be raised if the target of the set/deletion operation does not exist.
3131

3232
Consider the following scenarios:
3333

@@ -46,7 +46,7 @@ environment variable is missing, or to set multiple values to a known variable.
4646
:py:meth:`monkeypatch.setenv` and :py:meth:`monkeypatch.delenv` can be used for
4747
these patches.
4848

49-
4. Use :py:meth:`monkeypatch.syspath_prepend` to add to the system ``$PATH`` and
49+
4. Use :py:meth:`monkeypatch.syspath_prepend` to modify the system ``$PATH`` and
5050
:py:meth:`monkeypatch.chdir` to change the context of the current working directory
5151
during a test.
5252

@@ -59,33 +59,32 @@ Simple example: monkeypatching functions
5959
----------------------------------------
6060

6161
Consider a scenario where you are working with user directories. In the context of
62-
testing, you do not want your test to depend on the running user. ``Monkeypatch``
62+
testing, you do not want your test to depend on the running user. ``monkeypatch``
6363
can be used to patch functions dependent on the user to always return a
6464
specific value.
6565

6666
In this example, :py:meth:`monkeypatch.setattr` is used to patch ``os.path.expanduser``
6767
so that the known testing string ``"/abc"`` is always used when the test is run.
68-
This removes any dependency on the ``$USER`` environment variable for testing purposes.
68+
This removes any dependency on the running user for testing purposes.
6969
:py:meth:`monkeypatch.setattr` must be called before the function which will use
7070
the patched function is called.
7171
After the test function finishes the ``os.path.expanduser`` modification will be undone.
7272

7373
.. code-block:: python
7474
75-
# Content of test_module.py with source code and the test.
76-
# os.path is imported for reference in monkeypatch.setattr().
75+
# Contents of test_module.py with source code and the test
76+
# os.path is imported for reference in monkeypatch.setattr()
7777
import os.path
7878
7979
8080
def getssh():
8181
"""Simple function to return expanded homedir ssh path from $USER"""
82-
user = os.getenv("$USER")
83-
return os.path.join(os.path.expanduser(f"~{user}"), ".ssh")
82+
return os.path.expanduser("~/.ssh")
8483
8584
8685
def test_getssh(monkeypatch):
87-
# The mocked return function to replace os.path.expanduser.
88-
# Given a path, always return '/abc'.
86+
# The mocked return function to replace os.path.expanduser
87+
# Given a path, always return '/abc'
8988
def mockreturn(path):
9089
return "/abc"
9190
@@ -108,7 +107,7 @@ Imagine a simple function to take an API url and return the json response.
108107

109108
.. code-block:: python
110109
111-
# Contents of app.py, a simple API retrieval example.
110+
# Contents of app.py, a simple API retrieval example
112111
import requests
113112
114113
@@ -123,44 +122,44 @@ This can be done in our test file by defining a class to represent ``r``.
123122

124123
.. code-block:: python
125124
126-
# Contents of test_app.py, a simple test for our API retrieval.
127-
# Import requests for the purposes of monkeypatching.
125+
# Contents of test_app.py, a simple test for our API retrieval
126+
# Import requests for the purposes of monkeypatching
128127
import requests
129128
130-
# Our app.py that includes the get_json() function.
131-
# This is the previous code block example.
129+
# Our app.py that includes the get_json() function
130+
# This is the previous code block example
132131
import app
133132
134-
# A Custom class to be the mock return value.
135-
# It needs to override the requests.Response returned from requests.get.
133+
# A Custom class to be the mock return value
134+
# It needs to override the requests.Response returned from requests.get
136135
class MockResponse:
137136
138-
# The class has a json() method that we want to mock.
139-
# The mock method always returns a specific testing dictionary.
137+
# The class has a json() method that we want to mock
138+
# The mock method always returns a specific testing dictionary
140139
@staticmethod
141140
def json():
142141
return {"mock_key": "mock_response"}
143142
144143
145144
def test_get_json(monkeypatch):
146145
147-
# This function is used in the monkeypatch of requests.get().
146+
# This function is used in the monkeypatch of requests.get()
148147
# Any arguments may be passed and it will always return our
149148
# mocked object, which only has the .json() method.
150149
def mock_get(*args, **kwargs):
151150
return MockResponse()
152151
153-
# Apply the monkeypatch for requests.get to mock_get.
152+
# Apply the monkeypatch for requests.get to mock_get
154153
monkeypatch.setattr(requests, "get", mock_get)
155154
156-
# Our simple but illustrative test.
157-
# app.get_json, which contains requests.get, uses the monkeypatch.
158-
# Therefore, our result is our mock.
155+
# Our simple but illustrative test
156+
# app.get_json, which contains requests.get, uses the monkeypatch
157+
# Therefore, our result is our mock
159158
result = app.get_json("https://fakeurl")
160159
assert result["mock_key"] == "mock_response"
161160
162161
163-
``Monkeypatch`` applies the mock for ``requests.get`` with our ``mock_get`` function.
162+
``monkeypatch`` applies the mock for ``requests.get`` with our ``mock_get`` function.
164163
The ``mock_get`` function returns an instance of the ``MockResponse`` class, which
165164
has a ``json()`` method defined to return a known testing dictionary and does not
166165
require any outside API connection.
@@ -170,25 +169,25 @@ the scenario you are testing. For instance, it could include an ``ok`` property
170169
always returns ``True``, or return different values from the ``json()`` mocked method
171170
based on input strings.
172171

173-
This mock can be shared across tests using the ``fixture`` syntax:
172+
This mock can be shared across tests using a ``fixture``:
174173

175174
.. code-block:: python
176175
177-
# Contents of test_app.py, a simple test for our API retrieval.
176+
# Contents of test_app.py, a simple test for our API retrieval
178177
import pytest
179178
import requests
180179
181-
# Our app.py that includes the get_json() function.
180+
# Our app.py that includes the get_json() function
182181
import app
183182
184-
# A Custom class to be the mock.
183+
# A Custom class to be the mock
185184
class MockResponse:
186185
@staticmethod
187186
def json():
188187
return {"mock_key": "mock_response"}
189188
190189
191-
# Monkeypatched requests.get moved to a fixture.
190+
# monkeypatched requests.get moved to a fixture
192191
@pytest.fixture
193192
def mock_response(monkeypatch):
194193
"""Requests.get() mocked to return {'mock_key':'mock_response'}."""
@@ -199,14 +198,14 @@ This mock can be shared across tests using the ``fixture`` syntax:
199198
monkeypatch.setattr(requests, "get", mock_get)
200199
201200
202-
# Notice our test uses the custom fixture instead of monkeypatch directly.
201+
# Notice our test uses the custom fixture instead of monkeypatch directly
203202
def test_get_json(mock_response):
204203
result = app.get_json("https://fakeurl")
205204
assert result["mock_key"] == "mock_response"
206205
207206
208207
Furthermore, if the mock was designed to be applied to all tests, the ``fixture`` could
209-
be moved to ``conftest.py`` with ``autouse=True``.
208+
be moved to a ``conftest.py`` file and use the with ``autouse=True`` option.
210209

211210

212211
Global patch example: preventing "requests" from remote operations
@@ -261,12 +260,12 @@ Monkeypatching environment variables
261260
------------------------------------
262261

263262
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
263+
or delete them from the system for testing purposes. ``monkeypatch`` provides a mechanism
265264
to do this using the ``setenv`` and ``delenv`` method. Our example code to test:
266265

267266
.. code-block:: python
268267
269-
# Contents of our original code file e.g. code.py.
268+
# Contents of our original code file e.g. code.py
270269
import os
271270
272271
@@ -286,7 +285,7 @@ both paths can be safely tested without impacting the running environment:
286285

287286
.. code-block:: python
288287
289-
# Contents of our test file e.g. test_code.py.
288+
# Contents of our test file e.g. test_code.py
290289
import pytest
291290
292291
@@ -307,6 +306,7 @@ This behavior can be moved into ``fixture`` structures and shared across tests:
307306

308307
.. code-block:: python
309308
309+
# Contents of our test file e.g. test_code.py
310310
import pytest
311311
312312
@@ -320,7 +320,7 @@ This behavior can be moved into ``fixture`` structures and shared across tests:
320320
monkeypatch.delenv("USER", raising=False)
321321
322322
323-
# Notice the tests reference the fixtures for mocks.
323+
# Notice the tests reference the fixtures for mocks
324324
def test_upper_to_lower(mock_env_user):
325325
assert get_os_user_lower() == "testinguser"
326326
@@ -338,7 +338,7 @@ to specific values during tests. Take this simplified connection string example:
338338

339339
.. code-block:: python
340340
341-
# Contents of app.py to generate a simple connection string.
341+
# Contents of app.py to generate a simple connection string
342342
DEFAULT_CONFIG = {"user": "user1", "database": "db1"}
343343
344344
@@ -351,8 +351,8 @@ For testing purposes we can patch the ``DEFAULT_CONFIG`` dictionary to specific
351351

352352
.. code-block:: python
353353
354-
# Contents of test_app.py.
355-
# Our app.py with the connection string function (prior code block).
354+
# Contents of test_app.py
355+
# Our app.py with the connection string function (prior code block)
356356
import app
357357
358358
@@ -363,27 +363,27 @@ For testing purposes we can patch the ``DEFAULT_CONFIG`` dictionary to specific
363363
monkeypatch.setitem(app.DEFAULT_CONFIG, "user", "test_user")
364364
monkeypatch.setitem(app.DEFAULT_CONFIG, "database", "test_db")
365365
366-
# The expected result based on the mocks.
366+
# The expected result based on the mocks
367367
expected = "User Id=test_user; Location=test_db;"
368368
369-
# The test uses the monkeypatched dictionary settings.
369+
# The test uses the monkeypatched dictionary settings
370370
result = app.create_connection_string()
371371
assert result == expected
372372
373373
You can use the :py:meth:`monkeypatch.delitem` to remove values.
374374

375375
.. code-block:: python
376376
377-
# Contents of test_app.py.
377+
# Contents of test_app.py
378378
import pytest
379379
380-
# Our app.py with the connection string function.
380+
# Our app.py with the connection string function
381381
import app
382382
383383
384384
def test_missing_user(monkeypatch):
385385
386-
# Patch the DEFAULT_CONFIG t be missing the 'user' key.
386+
# Patch the DEFAULT_CONFIG t be missing the 'user' key
387387
monkeypatch.delitem(app.DEFAULT_CONFIG, "user", raising=False)
388388
389389
# Key error expected because a config is not passed, and the
@@ -392,18 +392,18 @@ You can use the :py:meth:`monkeypatch.delitem` to remove values.
392392
_ = app.create_connection_string()
393393
394394
395-
The modularity of the ``fixture`` syntax gives you the flexibility to define
396-
separate ``fixtures`` for each potential mock and reference them in the needed tests.
395+
The modularity of fixtures gives you the flexibility to define
396+
separate fixtures for each potential mock and reference them in the needed tests.
397397

398398
.. code-block:: python
399399
400-
# Contents of test_app.py.
400+
# Contents of test_app.py
401401
import pytest
402402
403-
# Our app.py with the connection string function.
403+
# Our app.py with the connection string function
404404
import app
405405
406-
# All of the mocks are moved into separated fixtures.
406+
# All of the mocks are moved into separated fixtures
407407
@pytest.fixture
408408
def mock_test_user(monkeypatch):
409409
"""Set the DEFAULT_CONFIG user to test_user."""
@@ -422,7 +422,7 @@ separate ``fixtures`` for each potential mock and reference them in the needed t
422422
monkeypatch.delitem(app.DEFAULT_CONFIG, "user", raising=False)
423423
424424
425-
# Tests reference only the fixture mocks that are needed.
425+
# Tests reference only the fixture mocks that are needed
426426
def test_connection(mock_test_user, mock_test_database):
427427
428428
expected = "User Id=test_user; Location=test_db;"
@@ -431,7 +431,7 @@ separate ``fixtures`` for each potential mock and reference them in the needed t
431431
assert result == expected
432432
433433
434-
def test_missing_user(mock_missing_default_user, mock_test_database):
434+
def test_missing_user(mock_missing_default_user):
435435
436436
with pytest.raises(KeyError):
437437
_ = app.create_connection_string()

0 commit comments

Comments
 (0)