File: mocker.rst

package info (click to toggle)
python-requests-mock 1.12.1-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 688 kB
  • sloc: python: 2,339; makefile: 162
file content (265 lines) | stat: -rw-r--r-- 9,435 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
.. _Mocker:

================
Using the Mocker
================

The mocker is a loading mechanism to ensure the adapter is correctly in place to intercept calls from requests.
Its goal is to provide an interface that is as close to the real requests library interface as possible.

:py:class:`requests_mock.Mocker` takes optional parameters:

:real_http (bool): If :py:const:`True` then any requests that are not handled by the mocking adapter will be forwarded to the real server (see :ref:`RealHTTP`), or the containing Mocker if applicable (see :ref:`NestingMockers`). Defaults to :py:const:`False`.
:json_encoder (json.JSONEncoder): If set uses the provided json encoder for all JSON responses compiled as part of the mocker.
:session (requests.Session): If set, only the given session instance is mocked (see :ref:`SessionMocking`).

Activation
==========

Loading of the Adapter is handled by the :py:class:`requests_mock.Mocker` class, which provides two ways to load an adapter:

Context Manager
---------------

The Mocker object can work as a context manager.

.. doctest::

    >>> import requests
    >>> import requests_mock

    >>> with requests_mock.Mocker() as m:
    ...     m.get('http://test.com', text='resp')
    ...     requests.get('http://test.com').text
    ...
    'resp'

Decorator
---------

Mocker can also be used as a decorator. The created object will then be passed as the last positional argument.

.. doctest::

    >>> @requests_mock.Mocker()
    ... def test_function(m):
    ...     m.get('http://test.com', text='resp')
    ...     return requests.get('http://test.com').text
    ...
    >>> test_function()
    'resp'

If the position of the mock is likely to conflict with other arguments you can pass the `kw` argument to the Mocker to have the mocker object passed as that keyword argument instead.

.. doctest::

    >>> @requests_mock.Mocker(kw='mock')
    ... def test_kw_function(**kwargs):
    ...     kwargs['mock'].get('http://test.com', text='resp')
    ...     return requests.get('http://test.com').text
    ...
    >>> test_kw_function()
    'resp'

Contrib
-------

The contrib module also provides ways of loading the mocker based on other frameworks.
These will require additional dependencies but may provide a better experience depending on your tests setup.

See :doc:`contrib` for these additions.


Class Decorator
===============

Mocker can also be used to decorate a whole class. It works exactly like in case of decorating a normal function.
When used in this way they wrap every test method on the class. The mocker recognise methods that start with *test* as being test methods.
This is the same way that the `unittest.TestLoader` finds test methods by default.
It is possible that you want to use a different prefix for your tests. You can inform the mocker of the different prefix by setting `requests_mock.Mocker.TEST_PREFIX`:

.. doctest::

    >>> requests_mock.Mocker.TEST_PREFIX = 'foo'
    >>>
    >>> @requests_mock.Mocker()
    ... class Thing(object):
    ...     def foo_one(self, m):
    ...        m.register_uri('GET', 'http://test.com', text='resp')
    ...        return requests.get('http://test.com').text
    ...     def foo_two(self, m):
    ...         m.register_uri('GET', 'http://test.com', text='resp')
    ...         return requests.get('http://test.com').text
    ...
    >>>
    >>> Thing().foo_one()
    'resp'
    >>> Thing().foo_two()
    'resp'


This behavior mimics how patchers from `mock` library works.


Methods
=======

The mocker object can be used with a similar interface to requests itself.

.. doctest::

    >>> with requests_mock.Mocker() as mock:
    ...     mock.get('http://test.com', text='resp')
    ...     requests.get('http://test.com').text
    ...
    'resp'


The following functions exist for the common HTTP methods:

  - :py:meth:`~requests_mock.MockerCore.delete`
  - :py:meth:`~requests_mock.MockerCore.get`
  - :py:meth:`~requests_mock.MockerCore.head`
  - :py:meth:`~requests_mock.MockerCore.options`
  - :py:meth:`~requests_mock.MockerCore.patch`
  - :py:meth:`~requests_mock.MockerCore.post`
  - :py:meth:`~requests_mock.MockerCore.put`

As well as the basic:

  - :py:meth:`~requests_mock.MockerCore.request`
  - :py:meth:`~requests_mock.MockerCore.register_uri`

These methods correspond to the HTTP method of your request, so to mock POST requests you would use the :py:meth:`~requests_mock.MockerCore.post` function.
Further information about what can be matched from a request can be found at :doc:`matching`

.. _RealHTTP:

Real HTTP Requests
==================

If :py:data:`real_http` is set to :py:const:`True`
then any requests that are not handled by the mocking adapter will be forwarded to the real server,
or the containing Mocker if applicable (see :ref:`NestingMockers`).

.. doctest::

    >>> with requests_mock.Mocker(real_http=True) as m:
    ...     m.register_uri('GET', 'http://test.com', text='resp')
    ...     print(requests.get('http://test.com').text)
    ...     print(requests.get('http://www.google.com').status_code)  # doctest: +SKIP
    ...
    'resp'
    200

*New in 1.1*

Similarly when using a mocker you can register an individual URI to bypass the mocking infrastructure and make a real request. Note this only works when using the mocker and not when directly mounting an adapter.

.. doctest::

    >>> with requests_mock.Mocker() as m:
    ...     m.register_uri('GET', 'http://test.com', text='resp')
    ...     m.register_uri('GET', 'http://www.google.com', real_http=True)
    ...     print(requests.get('http://test.com').text)
    ...     print(requests.get('http://www.google.com').status_code)  # doctest: +SKIP
    ...
    'resp'
    200


.. _JsonEncoder:

JSON Encoder
============

In python's json module you can customize the way data is encoded by subclassing the :py:class:`~json.JSONEncoder` object and passing it to encode.
A common example of this might be to use `DjangoJSONEncoder <https://docs.djangoproject.com/en/3.2/topics/serialization/#djangojsonencoder>` for responses.

You can specify this encoder object either when creating the :py:class:`requests_mock.Mocker` or individually at the mock creation time.

.. doctest::

    >>> import django.core.serializers.json.DjangoJSONEncoder as DjangoJSONEncoder
    >>> with requests_mock.Mocker(json_encoder=DjangoJSONEncoder) as m:
    ...     m.register_uri('GET', 'http://test.com', json={'hello': 'world'})
    ...     print(requests.get('http://test.com').text)

or

.. doctest::

    >>> import django.core.serializers.json.DjangoJSONEncoder as DjangoJSONEncoder
    >>> with requests_mock.Mocker() as m:
    ...     m.register_uri('GET', 'http://test.com', json={'hello': 'world'}, json_encoder=DjangoJSONEncoder)
    ...     print(requests.get('http://test.com').text)

.. _NestingMockers:

Nested Mockers
==============

*New in 1.8*

When nesting mockers the innermost Mocker replaces all others.
If :py:data:`real_http` is set to :py:const:`True`, at creation or for a given resource,
the request is passed to the containing Mocker.
The containing Mocker can in turn:

- serve the request;
- raise :py:exc:`NoMockAddress`;
- or pass the request to yet another Mocker (or to the unmocked :py:class:`requests.Session`) if :py:data:`real_http` is set to :py:const:`True`.

.. doctest::

    >>> url = "https://www.example.com/"
    >>> with requests_mock.Mocker() as outer_mock:
    ...     outer_mock.get(url, text='outer')
    ...     with requests_mock.Mocker(real_http=True) as middle_mock:
    ...         with requests_mock.Mocker() as inner_mock:
    ...             inner_mock.get(url, real_http=True)
    ...             print(requests.get(url).text)  # doctest: +SKIP
    ...
    'outer'

Most of the time nesting can be avoided by making the mocker object available to subclasses/subfunctions.

.. warning::
   When starting/stopping mockers manually, make sure to stop innermost mockers first.
   A call from an active inner mocker with a stopped outer mocker leads to undefined behavior.

.. _SessionMocking:

Mocking specific sessions
=========================

*New in 1.8*

:py:class:`requests_mock.Mocker` can be used to mock specific sessions through the :py:data:`session` parameter.

.. doctest::

    >>> url = "https://www.example.com/"
    >>> with requests_mock.Mocker() as global_mock:
    ...     global_mock.get(url, text='global')
    ...     session = requests.Session()
    ...     print("requests.get before session mock:", requests.get(url).text)
    ...     print("session.get before session mock:", session.get(url).text)
    ...     with requests_mock.Mocker(session=session) as session_mock:
    ...         session_mock.get(url, text='session')
    ...         print("Within session mock:", requests.get(url).text)
    ...         print("Within session mock:", session.get(url).text)
    ...     print("After session mock:", requests.get(url).text)
    ...     print("After session mock:", session.get(url).text)
    ...
    'requests.get before session mock: global'
    'session.get before session mock: global'
    'requests.get within session mock: global'
    'session.get within session mock: session'
    'requests.get after session mock: global'
    'session.get after session mock: global'



.. note::
  As an alternative, :py:class:`requests_mock.Adapter` instances can be mounted on specific sessions (see :ref:`Adapter`).