Skip to content

mockish.requests

Classes

Response

Response(status_code: int | None = None, headers: dict[str, str] | None = None, content: str | None = None, content_type: str | None = None, encoding: str | None = None, elapsed: timedelta | None = None, _data: models.ResponseData | None = None)

A requests.Response object, useful when mocking/patching HTTP calls.

PARAMETER DESCRIPTION
status_code

TYPE: int | None DEFAULT: None

headers

TYPE: dict[str, str] | None DEFAULT: None

content

TYPE: str | None DEFAULT: None

content_type

TYPE: str | None DEFAULT: None

encoding

TYPE: str | None DEFAULT: None

elapsed

TYPE: timedelta | None DEFAULT: None

Examples:

Common imports

>>> from mockish import Mock, patch
>>> from mockish.requests import Response
>>> import requests
  • mockish.requests.Response
>>> resp: requests.Response = Response(content='hello world')
>>> resp.content
b'hello world'
>>> resp.status_code
200
  • mockish.requests.Response.from_dict(...)
>>> resp: requests.Response = Response.from_dict(
...     {'hello': 'world'},
...     status_code=201
... )
>>> resp.json()
{'hello': 'world'}
>>> resp.status_code
201
>>> resp.headers
{'Content-Type': 'application/json', 'Content-Length': '18'}
  • Mocking a requests session:
>>> session = Mock(spec_set=requests.Session, **{
...     'get': Mock(
...         return_once=Response.from_dict({'hello': 'world'})
...     ),
...     'post': Mock(
...         return_once=Response.from_dict(
...             {'hello': 'world'},
...             status_code=201
...         ),
...     ),
... })
>>> session.get('https://www.fresh2.dev')
<Response [200]>
>>> session.post('https://www.fresh2.dev')
<Response [201]>
  • Complete example with patching:
>>> mock_resp = Response.from_dict({'hello': 'world'})
>>> with patch.object(
...     requests,
...     'get',
...     Mock(return_once=mock_resp)
... ):
...     resp: requests.Response = requests.get('https://www.fresh2.dev')
...     requests.get.assert_called_once()
>>> resp
<Response [200]>
>>> resp.json()
{'hello': 'world'}

Functions