
Allow users to specify methods via the same HTTP method based format that requests does. It makes them look more synchronous.
2.6 KiB
Mocker Loading
Loading of the Adapter is handled by the :pyrequests_mock.Mocker
class,
which provides two ways to load an adapter.
Context Manager
The Mocker object can work as a context manager.
>>> import requests >>> import requests_mock
>>> with requests_mock.Mocker() as m: ... m.register_uri('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.
>>> @requests_mock.Mocker() ... def test_function(m): ... m.register_uri('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.
>>> @requests_mock.Mocker(kw='mock') ... def test_kw_function(**kwargs): ... kwargs['mock'].register_uri('GET', 'http://test.com', text='resp') ... return requests.get('http://test.com').text ... >>> test_kw_function() 'resp'
Methods
The mocker object can be used with a similar interface to requests itself. Mocker objects can be called with simply the
>>> with requests_mock.Mocker() as mock: ... mock.get('http://test.com', text='resp') ... requests.get('http://test.com').text ... 'resp'
The functions exist for the common HTTP method:
- :py
~requests_mock.MockerCore.delete
- :py
~requests_mock.MockerCore.get
- :py
~requests_mock.MockerCore.head
- :py
~requests_mock.MockerCore.options
- :py
~requests_mock.MockerCore.patch
- :py
~requests_mock.MockerCore.post
- :py
~requests_mock.MockerCore.put
As well as the base:
- :py
~requests_mock.MockerCore.request
Real HTTP Requests
The Mocker object takes the following parameters:
- real_http (bool)
-
If True then any requests that are not handled by the mocking adapter will be forwarded to the real server. Defaults to False.
>>> 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