⚙API documentation

pytest plugin

pytest_response.plugin.pytest_addoption(parser)[source]

Pytest hook for adding cmd-line options.

Adds relevent cmd-line and ini-config options.

pytest_response.plugin.pytest_configure(config)[source]

Pytest hook for setting up pytest_response.app.Response

pytest_response.plugin.pytest_unconfigure(config)[source]

Pytest hook for cleaning up.


Response

class pytest_response.app.BaseMockResponse(status: int, data: bytes, headers: dict = {})[source]

Bases: object

Basic response for mocking requests.

Parameters
  • status (int) – Status code of the response.

  • data (bytes) – Response data.

  • headers (dict, optional) – Default to {}.

close()None[source]
flush()[source]
getcode()int[source]
info()dict[source]
read(*args, **kwargs)bytes[source]

Wrapper for _io.BytesIO.read

readinto(*args, **kwargs)bytes[source]

Wrapper for _io.BytesIO.readinto

readline(*args, **kwargs)bytes[source]

Wrapper for _io.BytesIO.readline

class pytest_response.app.Response(path: str = 'interceptors', capture: bool = False, remote: bool = False, response: bool = False, log_level: str = 'debug', database: str = 'database.db')[source]

Bases: object

Controlling and configuration application for pytest-remote-response

Parameters
  • path (str, optional) – Path for the interceptors. Defaults to pytest_response.interceptors

  • capture (bool, optional) – if True captures data and headers in the database. Defaults to False

  • remote (bool, optional) – if False blocks connection requests. Defaults to False

  • response (bool, optional) – if True responds with data and headers from the database. Defaults to False

  • log_level (str, optional) – Log level. Defaults to debug

Examples

>>> from pytest_response import response
>>> response.setup_database({{ Path to the database}})
>>> response.post({{ Interceptor }})
>>> ...
>>> response.unpost()
activate(interceptors: Union[str, list])[source]

Wrapper to apply the interceptor decorator.

Parameters

interceptor (str, list) – interceptors to apply

Examples

>>> @response.activate("urllib_quick")
>>> def test_urllib():
>>>     url = "https://www.python.org"
>>>     r = urlopen(url)
>>>     assert r.status == 200
apply(mock: Optional[Union[str, list]] = None)bool[source]

Activates intercepter module provided in mock otherwise activates all.

Parameters

mock (str, optional) – Applies the mock.

property available: List[str]
property capture: bool
configure(remote: bool = False, capture: bool = False, response: bool = False)None[source]

Helper method for configuring interceptors.

Parameters
  • remote (bool, optional) – If False blocks connection requests. Defaults to False.

  • capture (bool, optional) – If True captures data and headers in the database. Defaults to False.

  • response (bool, optional) – If True responds with data and headers from the database. Defaults to False.

get(url: str, *args, **kwargs)[source]

Wrapper function for pytest_response.database.ResponseDB.get()

Parameters

url (str) – URL to be queried.

Returns

  • status (int) – Status code

  • data (bytes) – Response data.

  • headers (dict) – Response header.

insert(url: str, response: bytes, headers: str, status: int, *args, **kwargs)bool[source]

Wrapper function for pytest_response.database.ResponseDB.insert()

Parameters
  • url (str) – URL of the dump.

  • response (bytes) – Data captured.

  • headers (str) – Headers captured.

  • status (int) – Status code of the response.

  • **kwargs (dict) – Any additional parameter to be dumped.

post(mock: Union[str, list])None[source]

Registers and applies the mock under the same hood.

Internally uses Response.register() followed by Response.apply()

Parameters

mock (str) – Registers and applies the mock.

register(mock: Union[str, list])None[source]

Registers interceptor modules; applies using Response.apply()

Parameters

mock (str, list) – Interceptor; check Response.available() for more info.

registered()Dict[str, module][source]

Returns registered modules.

Returns

Returns the list of registered interceptors.

Return type

list of pathlib.Path

property remote: bool
property response: bool
setup_database(path: str)bool[source]

Method to setup-up database.

Parameters

path (str) – Path for the database.

unapply(*args, **kwargs)bool[source]

Un-applies interceptor modules.

unpost()bool[source]

Unapplied and unregisters mocks under the same hood.

Internally uses Response.unapply() followed by Response.unregister()

unregister()bool[source]

Deactivates interceptor modules.


Database

class pytest_response.database.ResponseDB(path: str)[source]

Bases: object

Wrapper class for sqlite3

Parameters

path (str) – Path for the database

Examples

>>> db = ResponseDB("database.db")
all()dict[source]

Method to return all records in the database.

Returns

Return type

Return list of all elements.

close()None[source]
get(url: str, **kwargs)Tuple[int, bytes, dict][source]

Method for getting response and header for a perticular query url. Currently working by locating url only; multi-query to be implemented later.

Parameters

url (str) – URL to be queried.

Returns

  • status (int) – Status code

  • data (bytes) – Response data.

  • headers (dict) – Response header.

index(index: Optional[str] = 'url')List[str][source]

Returns all occurances of the column index.

Parameters

index (str) – Defaults to url.

Returns

_occurances – All occurances of the selected column index.

Return type

list

insert(url: str, response: bytes, headers: dict, status: Optional[int] = 200, **kwargs)None[source]

Method for dumping url, headers and responses to the database. All additonal kwargs are dumped as well.

Parameters
  • url (str) – URL of the dump.

  • response (bytes) – Data captured.

  • headers (str) – Headers captured.

  • status (int) – Status code of the response.

  • kwargs (dict) – Any additional parameter to be dumped.

setup()bool[source]

Function to setup the database table.

today = '2023-04-27'
truncate()bool[source]

Method to purge all records in the database.


Interceptors

urllib Interceptor module

Functions

urlopen_wrapper(func)

Wrapper for urllib.request

install()

Method to monkey patch the library call with the wrapped one.

uninstall()

Method to undo all monkey patches.

Classes

MockResponse(status, data[, headers])

Class Inheritance Diagram

Inheritance diagram of pytest_response.interceptors.urllib.MockResponse

urllib Interceptor module (unstable)

Functions

install()

uninstall()

Classes

ResponseSocketIO(sock, mode)

Provides a method to write the value of the buffer into another var for dumping.

ResponseSocket(host, port, *args, **kwargs)

Socket implementation of Pytest-Response

Response_SSLSocket(*args, **kwargs)

SSLSocket implementation of Pytest-Response

ResponseHTTPConnection(host[, port, …])

Wrapper for ~http.client.HTTPConnection

ResponseHTTPHandler([debuglevel])

Override the default HTTPHandler class with one that uses the ResponseHTTPConnection class to open HTTP URLs.

ResponseHTTPResponse(sock[, debuglevel, …])

Provides a way to capture or respond with a saved response.

ResponseHTTPSConnection(host[, port, …])

Override the default ~HTTPSConnection to use ~ResponseSocket

ResponseHTTPSHandler([debuglevel, context, …])

Override the default HTTPSHandler class with one that uses the ResponseHTTPSConnection class to open HTTP URLs.

Class Inheritance Diagram

Inheritance diagram of pytest_response.interceptors._urllib.ResponseSocketIO, pytest_response.interceptors._urllib.ResponseSocket, pytest_response.interceptors._urllib.Response_SSLSocket, pytest_response.interceptors._urllib.ResponseHTTPConnection, pytest_response.interceptors._urllib.ResponseHTTPHandler, pytest_response.interceptors._urllib.ResponseHTTPResponse, pytest_response.interceptors._urllib.ResponseHTTPSConnection, pytest_response.interceptors._urllib.ResponseHTTPSHandler

urllib3 Interceptor module

Functions

urlopen_wrapper(func)

Wrapper for urllib3.HTTPConnectionPool.urlopen()

install()

Method to monkey patch the library call with the wrapped one.

uninstall()

Method to undo all monkey patches.

Classes

MockResponse(status, data[, headers])

Class Inheritance Diagram

Inheritance diagram of pytest_response.interceptors.urllib3.MockResponse

urllib3 Interceptor module (unstable)

Functions

install()

uninstall()

Classes

Response_HTTPU3_Intercepter(*args, **kwargs)

Response_HTTPSU3_Intercepter(*args, **kwargs)

Class Inheritance Diagram

Inheritance diagram of pytest_response.interceptors._urllib3.Response_HTTPU3_Intercepter, pytest_response.interceptors._urllib3.Response_HTTPSU3_Intercepter

requests Interceptor Module

Functions

requests_wrapper(func)

Wrapper for requests.get()

install()

Method to monkey patch the library call with the wrapped one.

uninstall()

Method to undo all monkey patches.

Classes

MockResponse(status, data[, headers])

Class Inheritance Diagram

Inheritance diagram of pytest_response.interceptors.requests.MockResponse

aiohttp Interceptor Module

Functions

create_wrapper(func)

Wrapper for aiohttp.ClientResponse.text()

get_wrapper(func)

Wrapper for aiohttp.ClientSession.get()

install()

Method to monkey patch the library call with the wrapped one.

uninstall()

Method to undo all monkey patches.

Classes

MockResponse(status, data[, headers])

Class Inheritance Diagram

Inheritance diagram of pytest_response.interceptors.aiohttp.MockResponse

Exceptions

RemoteBlockedError([reason])

Exception raised when Remote connections are blocked.

ResponseNotFound([reason])

Exception raised when response is not locally available.

MalformedUrl([reason])

Exception raised when a malformed URL is encountered.

InterceptorNotFound([reason])

Exception raised when the requested interceptor is not available.

DatabaseNotFound([reason])

Exception raised when database is not initialized properly.