pook package¶
Subpackages¶
- pook.interceptors package
- pook.matchers package
- Submodules
- pook.matchers.api module
- pook.matchers.base module
- pook.matchers.body module
- pook.matchers.headers module
- pook.matchers.json module
- pook.matchers.json_schema module
- pook.matchers.method module
- pook.matchers.path module
- pook.matchers.query module
- pook.matchers.url module
- pook.matchers.xml module
- Module contents
Submodules¶
pook.activate_async module¶
pook.api module¶
- class pook.api.Engine(network=False)[source]¶
Bases:
object
Engine represents the mock interceptor and matcher engine responsible of triggering interceptors and match outgoing HTTP traffic.
- Parameters:
network (bool, optional) – enables/disables real networking mode.
- unmatched_reqs¶
stores engine-level unmatched outgoing HTTP requests.
- Type:
- activate()[source]¶
Activates the registered interceptors in the mocking engine.
This means any HTTP traffic captures by those interceptors will trigger the HTTP mock matching engine in order to determine if a given HTTP transaction should be mocked out or not.
- add_interceptor(*interceptors)[source]¶
Adds one or multiple HTTP traffic interceptors to the current mocking engine.
Interceptors are typically HTTP client specific wrapper classes that implements the pook interceptor interface.
Note: this method is may not be implemented if using a custom mock engine.
- Parameters:
interceptors (pook.interceptors.BaseInterceptor) –
- add_mock(mock)[source]¶
Adds a new mock instance to the current engine.
- Parameters:
mock (pook.Mock) – mock instance to add.
- enable_network(*hostnames)[source]¶
Enables real networking mode, optionally passing one or multiple hostnames that would be used as filter.
If at least one hostname matches with the outgoing traffic, the request will be executed via the real network.
- Parameters:
*hostnames – optional list of host names to enable real network against them. hostname value can be a regular expression.
- filter(*filters)[source]¶
Append engine-level HTTP request filter functions.
- Parameters:
filters* – variadic filter functions to be added.
- flush_interceptors()[source]¶
Flushes registered interceptors in the current mocking engine.
This method is low-level. Only call it if you know what you are doing.
Note: this method is may not be implemented if using a custom mock engine.
- flush_network_filters()[source]¶
Flushes registered real networking filters in the current mock engine.
- isactive()[source]¶
Returns the current engine enabled/disabled status.
- Returns:
True
if the engine is active. OtherwiseFalse
.- Return type:
- isdone()[source]¶
Returns True if all the registered mocks has been triggered.
- Returns:
True is all the registered mocks are gone, otherwise False.
- Return type:
- ispending()[source]¶
Returns the
True
if the engine has pending mocks to be matched. OtherwiseFalse
.- Returns:
bool
- isunmatched()[source]¶
Returns
True
if there are unmatched requests. OtherwiseFalse
.Unmatched requests will be registered only if
networking
mode has been enabled.- Returns:
bool
- map(*mappers)[source]¶
Append engine-level HTTP request mapper functions.
- Parameters:
filters* – variadic mapper functions to be added.
- match(request)[source]¶
Matches a given Request instance contract against the registered mocks.
If a mock passes all the matchers, its response will be returned.
- Parameters:
request (pook.Request) – Request contract to match.
- Raises:
pook.PookNoMatches – if networking is disabled and no mock matches with the given request contract.
- Returns:
the mock response to be used by the interceptor.
- Return type:
- pending()[source]¶
Returns the number of pending mocks to be matched.
- Returns:
number of pending mocks.
- Return type:
- pending_mocks()[source]¶
Returns a
tuple
of pending mocks to be matched.- Returns:
pending mock instances.
- Return type:
- remove_interceptor(name)[source]¶
Removes a specific interceptor by name.
Note: this method is may not be implemented if using a custom mock engine.
- remove_mock(mock)[source]¶
Removes a specific mock instance by object reference.
- Parameters:
mock (pook.Mock) – mock instance to remove.
- set_mock_engine(engine)[source]¶
Sets a custom mock engine, replacing the built-in one.
This is particularly useful if you want to replace the built-in HTTP traffic mock interceptor engine with your custom one.
For mock engine implementation details, see pook.MockEngine.
- Parameters:
engine (pook.MockEngine) – custom mock engine to use.
- should_use_network(request)[source]¶
Verifies if real networking mode should be used for the given request, passing it to the registered network filters.
- Parameters:
request (pook.Request) – outgoing HTTP request to test.
- Returns:
bool
- unmatched()[source]¶
Returns the total number of unmatched requests intercepted by pook.
Unmatched requests will be registered only if
networking
mode has been enabled.- Returns:
total number of unmatched requests.
- Return type:
- class pook.api.MatcherEngine(iterable=(), /)[source]¶
Bases:
list
HTTP request matcher engine used by pook.Mock to test if an intercepted outgoing HTTP request must be mocked out or not.
- add(matcher)[source]¶
Adds a new matcher function to the current engine.
- Parameters:
matcher (function) – matcher function to be added.
- match(request)[source]¶
Match the given HTTP request instance against the registered matcher functions in the current engine.
- Parameters:
request (pook.Request) – outgoing request to match.
- Returns:
True
if all matcher testspasses, otherwise
False
. Also returns an optional list of error exceptions.
- Return type:
- class pook.api.Mock(request=None, response=None, **kw)[source]¶
Bases:
object
Mock is used to declare and compose the HTTP request/response mock definition and matching expectations, which provides fluent API DSL.
- Parameters:
url (str) – URL to match. E.g:
server.com/api?foo=bar
.method (str) – HTTP method name to match. E.g:
GET
.path (str) – URL path to match. E.g:
/api/users
.headers (dict) – Header values to match. E.g:
{'server': 'nginx'}
.header_present (str) – Matches is a header is present.
headers_present (list|tuple) – Matches if multiple headers are present.
type (str) – Matches MIME
Content-Type
header. E.g:json
,xml
,html
,text/plain
content (str) – Same as
type
argument.params (dict) – Matches the given URL params.
param_exists (str) – Matches if a given URL param exists.
params_exists (list|tuple) – Matches if a given URL params exists.
body (str|regex) – Matches the payload body by regex or strict comparison.
json (dict|list|str|regex) – Matches the payload body against the given JSON or regular expression.
jsonschema (dict|str) – Matches the payload body against the given JSONSchema.
xml (str|regex) – matches the payload body against the given XML string or regular expression.
file (str) – Disk file path to load body from. Analog to
body
param.times (int) – Mock TTL or maximum number of times that the mock can be matched.
persist (bool) – Enable persistent mode. Mock won’t be flushed even if it matched one or multiple times.
delay (int) – Optional network delay simulation (only applicable when using
aiohttp
HTTP client).callback (function) – optional callback function called every time the mock is matched.
reply (int) – Mock response status. Defaults to
200
.response_status (int) – Mock response status. Alias to
reply
param.response_headers (dict) – Response headers to use.
response_type (str) – Response MIME type expression or alias. Analog to
type
param. E.g:json
,xml
,text/plain
.response_body (str) – Response body to use.
response_json (dict|list|str) – Response JSON to use. If Python is passed, it will be serialized as JSON transparently.
response_xml (str) – XML body string to use.
request (pook.Request) – Optional. Request mock definition object.
response (pook.Response) – Optional. Response mock definition object.
- Returns:
pook.Mock
- add_matcher(matcher)[source]¶
Adds one or multiple custom matchers instances.
Matchers must implement the following interface:
.__init__(expectation)
.match(request)
.name = str
Matchers can optionally inherit from
pook.matchers.BaseMatcher
.- Parameters:
*matchers (pook.matchers.BaseMatcher) – matchers to add.
- Returns:
current Mock instance.
- Return type:
self
- body(body, binary=False)[source]¶
Defines the body data to match.
body
argument can be astr
,binary
or a regular expression.
- callback(*callbacks)[source]¶
Registers one or multiple callback that will be called every time the current mock matches an outgoing HTTP request.
- Parameters:
*callbacks (function) – callback functions to call.
- Returns:
current Mock instance.
- Return type:
self
- property calls¶
Accessor to retrieve the amount of mock matched calls.
- Returns:
int
- content(value)[source]¶
Defines the
Content-Type
outgoing header value to match.You can pass one of the following type aliases instead of the full MIME type representation:
json
=application/json
xml
=application/xml
html
=text/html
text
=text/plain
urlencoded
=application/x-www-form-urlencoded
form
=application/x-www-form-urlencoded
form-data
=application/x-www-form-urlencoded
- Parameters:
value (str) – type alias or header value to match.
- Returns:
current Mock instance.
- Return type:
self
- delay(delay=1000)[source]¶
Delay network response with certain milliseconds. Only supported by asynchronous HTTP clients, such as
aiohttp
.- Parameters:
delay (int) – milliseconds to delay response.
- Returns:
current Mock instance.
- Return type:
self
- property done¶
Attribute accessor that would be
True
if the current mock is done, and therefore have been matched multiple times.- Returns:
bool
- file(path)[source]¶
Reads the body to match from a disk file.
- Parameters:
path (str) – relative or absolute path to file to read from.
- Returns:
current Mock instance.
- Return type:
self
- filter(*filters)[source]¶
Registers one o multiple request filters used during the matching phase.
- Parameters:
*mappers (function) – variadic mapper functions.
- Returns:
current Mock instance.
- Return type:
self
- header(name, value)[source]¶
Defines a URL path to match.
Only call this method if the URL has no path already defined.
- Parameters:
path (str) – URL path value to match. E.g:
/api/users
.- Returns:
current Mock instance.
- Return type:
self
- header_present(*names)[source]¶
Defines a new header matcher expectation that must be present in the outgoing request in order to be satisfied, no matter what value it hosts.
Header keys are case insensitive.
- Parameters:
*names (str) – header or headers names to match.
- Returns:
current Mock instance.
- Return type:
self
Example:
(pook.get('server.com/api') .header_present('content-type'))
- headers(headers=None, **kw)[source]¶
Defines a dictionary of arguments.
Header keys are case insensitive.
- headers_present(headers)[source]¶
Defines a list of headers that must be present in the outgoing request in order to satisfy the matcher, no matter what value the headers hosts.
Header keys are case insensitive.
- Parameters:
- Returns:
current Mock instance.
- Return type:
self
Example:
(pook.get('server.com/api') .headers_present(['content-type', 'Authorization']))
- isdone()[source]¶
Returns
True
if the mock has been matched by outgoing HTTP traffic.- Returns:
True
if the mock was matched succesfully.- Return type:
- json(json)[source]¶
Defines the JSON body to match.
json
argument can be an JSON string, a JSON serializable Python structure, such as adict
orlist
or it can be a regular expression used to match the body.
- map(*mappers)[source]¶
Registers one o multiple request mappers used during the mapping phase.
- Parameters:
*mappers (function) – variadic mapper functions.
- Returns:
current Mock instance.
- Return type:
self
- match(request)[source]¶
Matches an outgoing HTTP request against the current mock matchers.
This method acts like a delegator to pook.MatcherEngine.
- property matched¶
Accessor property that would be
True
if the current mock have been matched at least once.See
Mock.total_matches
for more information.- Returns:
bool
- property matches¶
Accessor to retrieve the mock match calls registry.
- Returns:
list[MockCall]
- method(method)[source]¶
Defines the HTTP method to match. Use
*
to match any method.- Parameters:
method (str) – method value to match. E.g:
GET
.- Returns:
current Mock instance.
- Return type:
self
- param_exists(name, allow_empty=False)[source]¶
Checks if a given URL param name is present in the URL.
- params(params)[source]¶
Defines a set of URL query params to match.
- Parameters:
params (dict) – set of params to match.
- Returns:
current Mock instance.
- Return type:
self
- path(path)[source]¶
Defines a URL path to match.
Only call this method if the URL has no path already defined.
- Parameters:
path (str) – URL path value to match. E.g:
/api/users
.- Returns:
current Mock instance.
- Return type:
self
- persist(status=None)[source]¶
Enables persistent mode for the current mock.
- Returns:
current Mock instance.
- Return type:
self
- reply(status=200, new_response=False, **kw)[source]¶
Defines the mock response.
- Parameters:
- Returns:
mock response definition instance.
- Return type:
- response(status=200, **kw)[source]¶
Defines the mock response. Alias to
.reply()
- Parameters:
- Returns:
mock response definition instance.
- Return type:
- status(code=200)[source]¶
Defines the response status code. Equivalent to
self.reply(code)
.- Parameters:
code (int) – response status code. Defaults to
200
.- Returns:
mock response definition instance.
- Return type:
- times(times=1)[source]¶
Defines the TTL limit for the current mock.
The TTL number will determine the maximum number of times that the current mock can be matched and therefore consumed.
- Parameters:
times (int) – TTL number. Defaults to
1
.- Returns:
current Mock instance.
- Return type:
self
- property total_matches¶
Accessor property to retrieve the total number of times that the current mock has been matched.
- Returns:
int
- type(value)[source]¶
Defines the request
Content-Type
header to match.You can pass one of the following aliases instead of the full MIME type representation:
json
=application/json
xml
=application/xml
html
=text/html
text
=text/plain
urlencoded
=application/x-www-form-urlencoded
form
=application/x-www-form-urlencoded
form-data
=application/x-www-form-urlencoded
- Parameters:
value (str) – type alias or header value to match.
- Returns:
current Mock instance.
- Return type:
self
- url(url)[source]¶
Defines the mock URL to match. It can be a full URL with path and query params.
Protocol schema is optional, defaults to
http://
.- Parameters:
url (str) – mock URL to match. E.g:
server.com/api
.- Returns:
current Mock instance.
- Return type:
self
- use(*matchers)[source]¶
Adds one or multiple custom matchers instances.
Matchers must implement the following interface:
.__init__(expectation)
.match(request)
.name = str
Matchers can optionally inherit from
pook.matchers.BaseMatcher
.- Parameters:
*matchers (pook.matchers.BaseMatcher) – matchers to add.
- Returns:
current Mock instance.
- Return type:
self
- class pook.api.MockEngine(engine)[source]¶
Bases:
object
MockEngine
represents the low-level mocking engine abstraction layer betweenpook
and the underlying mocking mechanism responsible of intercepting and trigger outgoing HTTP traffic within the Python runtime.MockEngine
implements the built-in pook mock engine based on HTTP interceptors strategy.Developers can implement and plug in their own
MockEngine
in order to fit custom mocking logic needs.You can see a custom
MockEngine
implementation here: http://bit.ly/2EymMroCustom mock engines must implementent at least the following methods:
engine.__init__(self, engine)
engine.activate(self)
engine.disable(self)
Custom mock engines can optionally implement the following methods:
engine.add_interceptors(self, *interceptors)
engine.flush_interceptors(self)
engine.disable_interceptor(self, name) -> bool
- Parameters:
engine (pook.Engine) – injected pook engine to be used.
- engine¶
stores pook engine to be used.
- Type:
- activate()[source]¶
Activates the registered interceptors in the mocking engine.
This means any HTTP traffic captures by those interceptors will trigger the HTTP mock matching engine in order to determine if a given HTTP transaction should be mocked out or not.
- add_interceptor(*interceptors)[source]¶
Adds one or multiple HTTP traffic interceptors to the current mocking engine.
Interceptors are typically HTTP client specific wrapper classes that implements the pook interceptor interface.
- Parameters:
interceptors (pook.interceptors.BaseInterceptor) –
- class pook.api.Request(method='GET', **kw)[source]¶
Bases:
object
Request object representing the request mock expectation DSL.
- Parameters:
method (str) – HTTP method to match. Defaults to
GET
.url (str) – URL request to intercept and match.
headers (dict) – HTTP headers to match.
query (dict) – URL query params to match. Complementely to URL defined query params.
body (str|regex) – request body payload to match.
json (str|dict|list) – JSON payload body structure to match.
xml (str) – XML payload data structure to match.
- property body¶
- copy()[source]¶
Copies the current Request object instance for side-effects purposes.
- Returns:
copy of the current Request instance.
- Return type:
- property extra¶
- property headers¶
- property json¶
- keys = ('method', 'headers', 'body', 'url', 'query')¶
- property method¶
- property query¶
- property rawurl¶
- property url¶
- property xml¶
- class pook.api.Response(**kw)[source]¶
Bases:
object
Response is used to declare and compose an HTTP mock responses fields.
It provides a chainable DSL interface for easier and declarative usage.
- Parameters:
- content(name)[source]¶
Defines the response
Content-Type
header.You can pass one of the following type aliases instead of the full MIME type representation:
json
=application/json
xml
=application/xml
html
=text/html
text
=text/plain
urlencoded
=application/x-www-form-urlencoded
form
=application/x-www-form-urlencoded
form-data
=application/x-www-form-urlencoded
- Parameters:
value (str) – type alias or header value to match.
- Returns:
pook.Response
current instance.- Return type:
self
- file(path)[source]¶
Defines the response body from file contents.
- Parameters:
path (str) – disk file path to load.
- Returns:
pook.Response
current instance.- Return type:
self
- property mock¶
Getter accessor for mock attribute.
- status(code=200)[source]¶
Defines the response status code.
- Parameters:
code (int) – response status code.
- Returns:
pook.Response
current instance.- Return type:
self
- type(name)[source]¶
Defines the response
Content-Type
header. Alias toResponse.content(mime)
.You can pass one of the following type aliases instead of the full MIME type representation:
json
=application/json
xml
=application/xml
html
=text/html
text
=text/plain
urlencoded
=application/x-www-form-urlencoded
form
=application/x-www-form-urlencoded
form-data
=application/x-www-form-urlencoded
- Parameters:
value (str) – type alias or header value to match.
- Returns:
pook.Response
current instance.- Return type:
self
- pook.api.activate(fn=None)[source]¶
Enables the HTTP traffic interceptors.
This function can be used as decorator.
- Parameters:
fn (function|coroutinefunction) – Optional function argument if used as decorator.
- Returns:
- decorator wrapper function, only if called as decorator,
otherwise
None
.
- Return type:
function
Example:
# Standard use case pook.activate() pook.mock('server.com/foo').reply(404) res = requests.get('server.com/foo') assert res.status_code == 404 pook.disable() # Decorator use case @pook.activate def test_request(): pook.mock('server.com/foo').reply(404) res = requests.get('server.com/foo') assert res.status_code == 404
- pook.api.disable_network()[source]¶
Disables real traffic networking mode in the current mock engine.
- pook.api.enable_network(*hostnames)[source]¶
Enables real networking mode for unmatched mocks in the current mock engine.
- pook.api.engine()[source]¶
Returns the current running mock engine.
- Returns:
current used engine.
- Return type:
- pook.api.isactive()[source]¶
Returns
True
if pook is active and intercepting traffic. OtherwiseFalse
.- Returns:
True if pook is active, otherwise False.
- Return type:
- pook.api.isdone()[source]¶
Returns True if all the registered mocks has been triggered.
- Returns:
True if all the registered mocks are gone, otherwise False.
- Return type:
- pook.api.ispending()[source]¶
Returns the numbers of pending mocks to be matched.
- Returns:
number of pending mocks to match.
- Return type:
- pook.api.isunmatched()[source]¶
Returns
True
if there are unmatched requests. OtherwiseFalse
.Unmatched requests will be registered only if
networking
mode has been enabled.- Returns:
bool
- pook.api.off()[source]¶
Disables mock engine, HTTP traffic interceptors and flushed all the registered mocks.
Internally, it calls
pook.disable()
andpook.off()
.
- pook.api.on(fn=None)[source]¶
Enables the HTTP traffic interceptors. Alias to
pook.activate()
.- Parameters:
fn (function|coroutinefunction) – Optional function argument if used as decorator.
- Returns:
decorator wrapper function, only if called as decorator.
- Return type:
function
Example:
# Standard usage pook.on() pook.mock('server.com/foo').reply(404) res = requests.get('server.com/foo') assert res.status_code == 404 # Usage as decorator @pook.on def test_request(): pook.mock('server.com/foo').reply(404) res = requests.get('server.com/foo') assert res.status_code == 404
- pook.api.pending()[source]¶
Returns the numbers of pending mocks to be matched.
- Returns:
number of pending mocks to match.
- Return type:
- pook.api.pending_mocks()[source]¶
Returns pending mocks to be matched.
- Returns:
pending mock instances.
- Return type:
- pook.api.regex(expression, flags=RegexFlag.IGNORECASE)[source]¶
Convenient shortcut to
re.compile()
for fast, easy to use regular expression compilation without an extra import statement.- Parameters:
- Returns:
string based regular expression.
- Return type:
expression (str)
- Raises:
Exception – in case of regular expression compilation error
Example:
(pook .get('api.com/foo') .header('Content-Type', pook.regex('[a-z]{1,4}')))
- pook.api.reset()[source]¶
Resets current mock engine state, flushing all the registered mocks.
This action will not disable the mock engine.
- pook.api.set_mock_engine(engine)[source]¶
Sets a custom mock engine, replacing the built-in one.
This is particularly useful if you want to replace the built-in HTTP traffic mock interceptor engine with your custom one.
For mock engine implementation details, see pook.MockEngine.
- Parameters:
engine (pook.MockEngine) – custom mock engine to use.
- pook.api.unmatched()[source]¶
Returns the total number of unmatched requests intercepted by pook.
Unmatched requests will be registered only if
networking
mode has been enabled.- Returns:
total number of unmatched requests.
- Return type:
- pook.api.unmatched_requests()[source]¶
Returns a
tuple
of unmatched requests.Unmatched requests will be registered only if
networking
mode has been enabled.- Returns:
unmatched intercepted requests.
- Return type:
- pook.api.use(network=False)[source]¶
Creates a new isolated mock engine to be used via context manager.
Example:
with pook.use() as engine: pook.mock('server.com/foo').reply(404) res = requests.get('server.com/foo') assert res.status_code == 404
pook.assertion module¶
- pook.assertion.equal(x, y)[source]¶
Shortcut function for
unittest.TestCase.assertEqual()
.- Parameters:
x (mixed) –
y (mixed) –
- Raises:
AssertionError – in case of assertion error.
- Returns:
bool
- pook.assertion.matches(x, y, regex_expr=False)[source]¶
Tries to match a regular expression value
x
againsty
. Aliast``unittest.TestCase.assertEqual()``- Parameters:
- Raises:
AssertionError – in case of mismatching.
- Returns:
bool
- pook.assertion.test(x, y, regex_expr=False)[source]¶
Compares to values based on regular expression matching or strict equality comparison.
- Parameters:
- Raises:
AssertionError – in case of matching error.
- Returns:
bool
pook.compare module¶
- pook.compare.compare(expr, value, regex_expr=False)[source]¶
Compares an string or regular expression againast a given value.
- Parameters:
- Raises:
AssertionError – in case of assertion error.
- Returns:
bool
pook.constants module¶
pook.engine module¶
- class pook.engine.Engine(network=False)[source]¶
Bases:
object
Engine represents the mock interceptor and matcher engine responsible of triggering interceptors and match outgoing HTTP traffic.
- Parameters:
network (bool, optional) – enables/disables real networking mode.
- unmatched_reqs¶
stores engine-level unmatched outgoing HTTP requests.
- Type:
- activate()[source]¶
Activates the registered interceptors in the mocking engine.
This means any HTTP traffic captures by those interceptors will trigger the HTTP mock matching engine in order to determine if a given HTTP transaction should be mocked out or not.
- add_interceptor(*interceptors)[source]¶
Adds one or multiple HTTP traffic interceptors to the current mocking engine.
Interceptors are typically HTTP client specific wrapper classes that implements the pook interceptor interface.
Note: this method is may not be implemented if using a custom mock engine.
- Parameters:
interceptors (pook.interceptors.BaseInterceptor) –
- add_mock(mock)[source]¶
Adds a new mock instance to the current engine.
- Parameters:
mock (pook.Mock) – mock instance to add.
- enable_network(*hostnames)[source]¶
Enables real networking mode, optionally passing one or multiple hostnames that would be used as filter.
If at least one hostname matches with the outgoing traffic, the request will be executed via the real network.
- Parameters:
*hostnames – optional list of host names to enable real network against them. hostname value can be a regular expression.
- filter(*filters)[source]¶
Append engine-level HTTP request filter functions.
- Parameters:
filters* – variadic filter functions to be added.
- flush_interceptors()[source]¶
Flushes registered interceptors in the current mocking engine.
This method is low-level. Only call it if you know what you are doing.
Note: this method is may not be implemented if using a custom mock engine.
- flush_network_filters()[source]¶
Flushes registered real networking filters in the current mock engine.
- isactive()[source]¶
Returns the current engine enabled/disabled status.
- Returns:
True
if the engine is active. OtherwiseFalse
.- Return type:
- isdone()[source]¶
Returns True if all the registered mocks has been triggered.
- Returns:
True is all the registered mocks are gone, otherwise False.
- Return type:
- ispending()[source]¶
Returns the
True
if the engine has pending mocks to be matched. OtherwiseFalse
.- Returns:
bool
- isunmatched()[source]¶
Returns
True
if there are unmatched requests. OtherwiseFalse
.Unmatched requests will be registered only if
networking
mode has been enabled.- Returns:
bool
- map(*mappers)[source]¶
Append engine-level HTTP request mapper functions.
- Parameters:
filters* – variadic mapper functions to be added.
- match(request)[source]¶
Matches a given Request instance contract against the registered mocks.
If a mock passes all the matchers, its response will be returned.
- Parameters:
request (pook.Request) – Request contract to match.
- Raises:
pook.PookNoMatches – if networking is disabled and no mock matches with the given request contract.
- Returns:
the mock response to be used by the interceptor.
- Return type:
- pending()[source]¶
Returns the number of pending mocks to be matched.
- Returns:
number of pending mocks.
- Return type:
- pending_mocks()[source]¶
Returns a
tuple
of pending mocks to be matched.- Returns:
pending mock instances.
- Return type:
- remove_interceptor(name)[source]¶
Removes a specific interceptor by name.
Note: this method is may not be implemented if using a custom mock engine.
- remove_mock(mock)[source]¶
Removes a specific mock instance by object reference.
- Parameters:
mock (pook.Mock) – mock instance to remove.
- set_mock_engine(engine)[source]¶
Sets a custom mock engine, replacing the built-in one.
This is particularly useful if you want to replace the built-in HTTP traffic mock interceptor engine with your custom one.
For mock engine implementation details, see pook.MockEngine.
- Parameters:
engine (pook.MockEngine) – custom mock engine to use.
- should_use_network(request)[source]¶
Verifies if real networking mode should be used for the given request, passing it to the registered network filters.
- Parameters:
request (pook.Request) – outgoing HTTP request to test.
- Returns:
bool
- unmatched()[source]¶
Returns the total number of unmatched requests intercepted by pook.
Unmatched requests will be registered only if
networking
mode has been enabled.- Returns:
total number of unmatched requests.
- Return type:
pook.exceptions module¶
pook.headers module¶
- class pook.headers.HTTPHeaderDict(headers=None, **kwargs)[source]¶
Bases:
MutableMapping
- Parameters:
headers – An iterable of field-value pairs. Must not contain multiple field names when compared case-insensitively.
kwargs – Additional field-value pairs to pass in to
dict.update
.
A
dict
like container for storing HTTP Headers. Field names are stored and compared case-insensitively in compliance with RFC 7230. Iteration provides the first case-sensitive key seen for each case-insensitive pair. Using__setitem__
syntax overwrites fields that compare equal case-insensitively in order to maintaindict
’s api. For fields that compare equal, instead create a newHTTPHeaderDict
and use.add
in a loop. If multiple fields that are equal case-insensitively are passed to the constructor or.update
, the behavior is undefined and some will be lost.Usage:
headers = HTTPHeaderDict() headers.add('Set-Cookie', 'foo=bar') headers.add('set-cookie', 'baz=quxx') headers['content-length'] = '7' headers['SET-cookie'] > 'foo=bar, baz=quxx' headers['Content-Length'] > '7'
- add(key, val)[source]¶
Adds a (name, value) pair, doesn’t overwrite the value if it already exists.
Usage:
headers = HTTPHeaderDict(foo='bar') headers.add('Foo', 'baz') headers['foo'] > 'bar, baz'
- extend(mapping, **kwargs)[source]¶
Generic import function for any type of header-like object. Adapted version of MutableMapping.update in order to insert items with self.add instead of self.__setitem__
- getallmatchingheaders(key)¶
Returns a list of all the values for the named field. Returns an empty list if the key doesn’t exist.
- getheaders(key)¶
Returns a list of all the values for the named field. Returns an empty list if the key doesn’t exist.
- getlist(key)[source]¶
Returns a list of all the values for the named field. Returns an empty list if the key doesn’t exist.
- iget(key)¶
Returns a list of all the values for the named field. Returns an empty list if the key doesn’t exist.
- pop(k[, d]) v, remove specified key and return the [source]¶
corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.
- pook.headers.to_string_value(value)[source]¶
Retrieve a string value for an arbitrary value.
HTTP header values are specified as ASCII strings. However, the specificiation also states that non-ASCII bytes should be treated as arbitrary data. In that case, we just rely on unicode escaping to return a value that at least somewhat resembles the inputs (at least moreso than other encodings that would significantly obscure the input, like base 64).
- Arguments::
- value (mixed):
The value to cast to
str
.
- Returns::
- str:
Unicode escaped
value
if it wasbytes
; otherwise,value
is returned, cast throughstr
.
pook.helpers module¶
- pook.helpers.trigger_methods(instance, args, key_order=None)[source]¶
Triggers specific class methods using a simple reflection mechanism based on the given input dictionary params.
- Parameters:
instance (object) – target instance to dynamically trigger methods.
args (iterable) – input arguments to trigger objects to
key_order (None|iterable) – optional order in which to process keys; falls back to sorted’s default behaviour if not present
- Returns:
None
pook.matcher module¶
- class pook.matcher.MatcherEngine(iterable=(), /)[source]¶
Bases:
list
HTTP request matcher engine used by pook.Mock to test if an intercepted outgoing HTTP request must be mocked out or not.
- add(matcher)[source]¶
Adds a new matcher function to the current engine.
- Parameters:
matcher (function) – matcher function to be added.
- match(request)[source]¶
Match the given HTTP request instance against the registered matcher functions in the current engine.
- Parameters:
request (pook.Request) – outgoing request to match.
- Returns:
True
if all matcher testspasses, otherwise
False
. Also returns an optional list of error exceptions.
- Return type:
pook.mock module¶
- class pook.mock.Mock(request=None, response=None, **kw)[source]¶
Bases:
object
Mock is used to declare and compose the HTTP request/response mock definition and matching expectations, which provides fluent API DSL.
- Parameters:
url (str) – URL to match. E.g:
server.com/api?foo=bar
.method (str) – HTTP method name to match. E.g:
GET
.path (str) – URL path to match. E.g:
/api/users
.headers (dict) – Header values to match. E.g:
{'server': 'nginx'}
.header_present (str) – Matches is a header is present.
headers_present (list|tuple) – Matches if multiple headers are present.
type (str) – Matches MIME
Content-Type
header. E.g:json
,xml
,html
,text/plain
content (str) – Same as
type
argument.params (dict) – Matches the given URL params.
param_exists (str) – Matches if a given URL param exists.
params_exists (list|tuple) – Matches if a given URL params exists.
body (str|regex) – Matches the payload body by regex or strict comparison.
json (dict|list|str|regex) – Matches the payload body against the given JSON or regular expression.
jsonschema (dict|str) – Matches the payload body against the given JSONSchema.
xml (str|regex) – matches the payload body against the given XML string or regular expression.
file (str) – Disk file path to load body from. Analog to
body
param.times (int) – Mock TTL or maximum number of times that the mock can be matched.
persist (bool) – Enable persistent mode. Mock won’t be flushed even if it matched one or multiple times.
delay (int) – Optional network delay simulation (only applicable when using
aiohttp
HTTP client).callback (function) – optional callback function called every time the mock is matched.
reply (int) – Mock response status. Defaults to
200
.response_status (int) – Mock response status. Alias to
reply
param.response_headers (dict) – Response headers to use.
response_type (str) – Response MIME type expression or alias. Analog to
type
param. E.g:json
,xml
,text/plain
.response_body (str) – Response body to use.
response_json (dict|list|str) – Response JSON to use. If Python is passed, it will be serialized as JSON transparently.
response_xml (str) – XML body string to use.
request (pook.Request) – Optional. Request mock definition object.
response (pook.Response) – Optional. Response mock definition object.
- Returns:
pook.Mock
- add_matcher(matcher)[source]¶
Adds one or multiple custom matchers instances.
Matchers must implement the following interface:
.__init__(expectation)
.match(request)
.name = str
Matchers can optionally inherit from
pook.matchers.BaseMatcher
.- Parameters:
*matchers (pook.matchers.BaseMatcher) – matchers to add.
- Returns:
current Mock instance.
- Return type:
self
- body(body, binary=False)[source]¶
Defines the body data to match.
body
argument can be astr
,binary
or a regular expression.
- callback(*callbacks)[source]¶
Registers one or multiple callback that will be called every time the current mock matches an outgoing HTTP request.
- Parameters:
*callbacks (function) – callback functions to call.
- Returns:
current Mock instance.
- Return type:
self
- property calls¶
Accessor to retrieve the amount of mock matched calls.
- Returns:
int
- content(value)[source]¶
Defines the
Content-Type
outgoing header value to match.You can pass one of the following type aliases instead of the full MIME type representation:
json
=application/json
xml
=application/xml
html
=text/html
text
=text/plain
urlencoded
=application/x-www-form-urlencoded
form
=application/x-www-form-urlencoded
form-data
=application/x-www-form-urlencoded
- Parameters:
value (str) – type alias or header value to match.
- Returns:
current Mock instance.
- Return type:
self
- delay(delay=1000)[source]¶
Delay network response with certain milliseconds. Only supported by asynchronous HTTP clients, such as
aiohttp
.- Parameters:
delay (int) – milliseconds to delay response.
- Returns:
current Mock instance.
- Return type:
self
- property done¶
Attribute accessor that would be
True
if the current mock is done, and therefore have been matched multiple times.- Returns:
bool
- file(path)[source]¶
Reads the body to match from a disk file.
- Parameters:
path (str) – relative or absolute path to file to read from.
- Returns:
current Mock instance.
- Return type:
self
- filter(*filters)[source]¶
Registers one o multiple request filters used during the matching phase.
- Parameters:
*mappers (function) – variadic mapper functions.
- Returns:
current Mock instance.
- Return type:
self
- header(name, value)[source]¶
Defines a URL path to match.
Only call this method if the URL has no path already defined.
- Parameters:
path (str) – URL path value to match. E.g:
/api/users
.- Returns:
current Mock instance.
- Return type:
self
- header_present(*names)[source]¶
Defines a new header matcher expectation that must be present in the outgoing request in order to be satisfied, no matter what value it hosts.
Header keys are case insensitive.
- Parameters:
*names (str) – header or headers names to match.
- Returns:
current Mock instance.
- Return type:
self
Example:
(pook.get('server.com/api') .header_present('content-type'))
- headers(headers=None, **kw)[source]¶
Defines a dictionary of arguments.
Header keys are case insensitive.
- headers_present(headers)[source]¶
Defines a list of headers that must be present in the outgoing request in order to satisfy the matcher, no matter what value the headers hosts.
Header keys are case insensitive.
- Parameters:
- Returns:
current Mock instance.
- Return type:
self
Example:
(pook.get('server.com/api') .headers_present(['content-type', 'Authorization']))
- isdone()[source]¶
Returns
True
if the mock has been matched by outgoing HTTP traffic.- Returns:
True
if the mock was matched succesfully.- Return type:
- json(json)[source]¶
Defines the JSON body to match.
json
argument can be an JSON string, a JSON serializable Python structure, such as adict
orlist
or it can be a regular expression used to match the body.
- map(*mappers)[source]¶
Registers one o multiple request mappers used during the mapping phase.
- Parameters:
*mappers (function) – variadic mapper functions.
- Returns:
current Mock instance.
- Return type:
self
- match(request)[source]¶
Matches an outgoing HTTP request against the current mock matchers.
This method acts like a delegator to pook.MatcherEngine.
- property matched¶
Accessor property that would be
True
if the current mock have been matched at least once.See
Mock.total_matches
for more information.- Returns:
bool
- property matches¶
Accessor to retrieve the mock match calls registry.
- Returns:
list[MockCall]
- method(method)[source]¶
Defines the HTTP method to match. Use
*
to match any method.- Parameters:
method (str) – method value to match. E.g:
GET
.- Returns:
current Mock instance.
- Return type:
self
- param_exists(name, allow_empty=False)[source]¶
Checks if a given URL param name is present in the URL.
- params(params)[source]¶
Defines a set of URL query params to match.
- Parameters:
params (dict) – set of params to match.
- Returns:
current Mock instance.
- Return type:
self
- path(path)[source]¶
Defines a URL path to match.
Only call this method if the URL has no path already defined.
- Parameters:
path (str) – URL path value to match. E.g:
/api/users
.- Returns:
current Mock instance.
- Return type:
self
- persist(status=None)[source]¶
Enables persistent mode for the current mock.
- Returns:
current Mock instance.
- Return type:
self
- reply(status=200, new_response=False, **kw)[source]¶
Defines the mock response.
- Parameters:
- Returns:
mock response definition instance.
- Return type:
- response(status=200, **kw)[source]¶
Defines the mock response. Alias to
.reply()
- Parameters:
- Returns:
mock response definition instance.
- Return type:
- status(code=200)[source]¶
Defines the response status code. Equivalent to
self.reply(code)
.- Parameters:
code (int) – response status code. Defaults to
200
.- Returns:
mock response definition instance.
- Return type:
- times(times=1)[source]¶
Defines the TTL limit for the current mock.
The TTL number will determine the maximum number of times that the current mock can be matched and therefore consumed.
- Parameters:
times (int) – TTL number. Defaults to
1
.- Returns:
current Mock instance.
- Return type:
self
- property total_matches¶
Accessor property to retrieve the total number of times that the current mock has been matched.
- Returns:
int
- type(value)[source]¶
Defines the request
Content-Type
header to match.You can pass one of the following aliases instead of the full MIME type representation:
json
=application/json
xml
=application/xml
html
=text/html
text
=text/plain
urlencoded
=application/x-www-form-urlencoded
form
=application/x-www-form-urlencoded
form-data
=application/x-www-form-urlencoded
- Parameters:
value (str) – type alias or header value to match.
- Returns:
current Mock instance.
- Return type:
self
- url(url)[source]¶
Defines the mock URL to match. It can be a full URL with path and query params.
Protocol schema is optional, defaults to
http://
.- Parameters:
url (str) – mock URL to match. E.g:
server.com/api
.- Returns:
current Mock instance.
- Return type:
self
- use(*matchers)[source]¶
Adds one or multiple custom matchers instances.
Matchers must implement the following interface:
.__init__(expectation)
.match(request)
.name = str
Matchers can optionally inherit from
pook.matchers.BaseMatcher
.- Parameters:
*matchers (pook.matchers.BaseMatcher) – matchers to add.
- Returns:
current Mock instance.
- Return type:
self
pook.mock_engine module¶
- class pook.mock_engine.MockEngine(engine)[source]¶
Bases:
object
MockEngine
represents the low-level mocking engine abstraction layer betweenpook
and the underlying mocking mechanism responsible of intercepting and trigger outgoing HTTP traffic within the Python runtime.MockEngine
implements the built-in pook mock engine based on HTTP interceptors strategy.Developers can implement and plug in their own
MockEngine
in order to fit custom mocking logic needs.You can see a custom
MockEngine
implementation here: http://bit.ly/2EymMroCustom mock engines must implementent at least the following methods:
engine.__init__(self, engine)
engine.activate(self)
engine.disable(self)
Custom mock engines can optionally implement the following methods:
engine.add_interceptors(self, *interceptors)
engine.flush_interceptors(self)
engine.disable_interceptor(self, name) -> bool
- Parameters:
engine (pook.Engine) – injected pook engine to be used.
- engine¶
stores pook engine to be used.
- Type:
- activate()[source]¶
Activates the registered interceptors in the mocking engine.
This means any HTTP traffic captures by those interceptors will trigger the HTTP mock matching engine in order to determine if a given HTTP transaction should be mocked out or not.
- add_interceptor(*interceptors)[source]¶
Adds one or multiple HTTP traffic interceptors to the current mocking engine.
Interceptors are typically HTTP client specific wrapper classes that implements the pook interceptor interface.
- Parameters:
interceptors (pook.interceptors.BaseInterceptor) –
pook.regex module¶
- pook.regex.isregex(value)[source]¶
Returns
True
if the input argument object is a native regular expression object, otherwiseFalse
.- Parameters:
value (mixed) – input value to test.
- Returns:
bool
pook.request module¶
- class pook.request.Request(method='GET', **kw)[source]¶
Bases:
object
Request object representing the request mock expectation DSL.
- Parameters:
method (str) – HTTP method to match. Defaults to
GET
.url (str) – URL request to intercept and match.
headers (dict) – HTTP headers to match.
query (dict) – URL query params to match. Complementely to URL defined query params.
body (str|regex) – request body payload to match.
json (str|dict|list) – JSON payload body structure to match.
xml (str) – XML payload data structure to match.
- property body¶
- copy()[source]¶
Copies the current Request object instance for side-effects purposes.
- Returns:
copy of the current Request instance.
- Return type:
- property extra¶
- property headers¶
- property json¶
- keys = ('method', 'headers', 'body', 'url', 'query')¶
- property method¶
- property query¶
- property rawurl¶
- property url¶
- property xml¶
pook.response module¶
- class pook.response.Response(**kw)[source]¶
Bases:
object
Response is used to declare and compose an HTTP mock responses fields.
It provides a chainable DSL interface for easier and declarative usage.
- Parameters:
- content(name)[source]¶
Defines the response
Content-Type
header.You can pass one of the following type aliases instead of the full MIME type representation:
json
=application/json
xml
=application/xml
html
=text/html
text
=text/plain
urlencoded
=application/x-www-form-urlencoded
form
=application/x-www-form-urlencoded
form-data
=application/x-www-form-urlencoded
- Parameters:
value (str) – type alias or header value to match.
- Returns:
pook.Response
current instance.- Return type:
self
- file(path)[source]¶
Defines the response body from file contents.
- Parameters:
path (str) – disk file path to load.
- Returns:
pook.Response
current instance.- Return type:
self
- property mock¶
Getter accessor for mock attribute.
- status(code=200)[source]¶
Defines the response status code.
- Parameters:
code (int) – response status code.
- Returns:
pook.Response
current instance.- Return type:
self
- type(name)[source]¶
Defines the response
Content-Type
header. Alias toResponse.content(mime)
.You can pass one of the following type aliases instead of the full MIME type representation:
json
=application/json
xml
=application/xml
html
=text/html
text
=text/plain
urlencoded
=application/x-www-form-urlencoded
form
=application/x-www-form-urlencoded
form-data
=application/x-www-form-urlencoded
- Parameters:
value (str) – type alias or header value to match.
- Returns:
pook.Response
current instance.- Return type:
self
Module contents¶
- class pook.Engine(network=False)[source]¶
Bases:
object
Engine represents the mock interceptor and matcher engine responsible of triggering interceptors and match outgoing HTTP traffic.
- Parameters:
network (bool, optional) – enables/disables real networking mode.
- unmatched_reqs¶
stores engine-level unmatched outgoing HTTP requests.
- Type:
- activate()[source]¶
Activates the registered interceptors in the mocking engine.
This means any HTTP traffic captures by those interceptors will trigger the HTTP mock matching engine in order to determine if a given HTTP transaction should be mocked out or not.
- add_interceptor(*interceptors)[source]¶
Adds one or multiple HTTP traffic interceptors to the current mocking engine.
Interceptors are typically HTTP client specific wrapper classes that implements the pook interceptor interface.
Note: this method is may not be implemented if using a custom mock engine.
- Parameters:
interceptors (pook.interceptors.BaseInterceptor) –
- add_mock(mock)[source]¶
Adds a new mock instance to the current engine.
- Parameters:
mock (pook.Mock) – mock instance to add.
- enable_network(*hostnames)[source]¶
Enables real networking mode, optionally passing one or multiple hostnames that would be used as filter.
If at least one hostname matches with the outgoing traffic, the request will be executed via the real network.
- Parameters:
*hostnames – optional list of host names to enable real network against them. hostname value can be a regular expression.
- filter(*filters)[source]¶
Append engine-level HTTP request filter functions.
- Parameters:
filters* – variadic filter functions to be added.
- flush_interceptors()[source]¶
Flushes registered interceptors in the current mocking engine.
This method is low-level. Only call it if you know what you are doing.
Note: this method is may not be implemented if using a custom mock engine.
- flush_network_filters()[source]¶
Flushes registered real networking filters in the current mock engine.
- isactive()[source]¶
Returns the current engine enabled/disabled status.
- Returns:
True
if the engine is active. OtherwiseFalse
.- Return type:
- isdone()[source]¶
Returns True if all the registered mocks has been triggered.
- Returns:
True is all the registered mocks are gone, otherwise False.
- Return type:
- ispending()[source]¶
Returns the
True
if the engine has pending mocks to be matched. OtherwiseFalse
.- Returns:
bool
- isunmatched()[source]¶
Returns
True
if there are unmatched requests. OtherwiseFalse
.Unmatched requests will be registered only if
networking
mode has been enabled.- Returns:
bool
- map(*mappers)[source]¶
Append engine-level HTTP request mapper functions.
- Parameters:
filters* – variadic mapper functions to be added.
- match(request)[source]¶
Matches a given Request instance contract against the registered mocks.
If a mock passes all the matchers, its response will be returned.
- Parameters:
request (pook.Request) – Request contract to match.
- Raises:
pook.PookNoMatches – if networking is disabled and no mock matches with the given request contract.
- Returns:
the mock response to be used by the interceptor.
- Return type:
- pending()[source]¶
Returns the number of pending mocks to be matched.
- Returns:
number of pending mocks.
- Return type:
- pending_mocks()[source]¶
Returns a
tuple
of pending mocks to be matched.- Returns:
pending mock instances.
- Return type:
- remove_interceptor(name)[source]¶
Removes a specific interceptor by name.
Note: this method is may not be implemented if using a custom mock engine.
- remove_mock(mock)[source]¶
Removes a specific mock instance by object reference.
- Parameters:
mock (pook.Mock) – mock instance to remove.
- set_mock_engine(engine)[source]¶
Sets a custom mock engine, replacing the built-in one.
This is particularly useful if you want to replace the built-in HTTP traffic mock interceptor engine with your custom one.
For mock engine implementation details, see pook.MockEngine.
- Parameters:
engine (pook.MockEngine) – custom mock engine to use.
- should_use_network(request)[source]¶
Verifies if real networking mode should be used for the given request, passing it to the registered network filters.
- Parameters:
request (pook.Request) – outgoing HTTP request to test.
- Returns:
bool
- unmatched()[source]¶
Returns the total number of unmatched requests intercepted by pook.
Unmatched requests will be registered only if
networking
mode has been enabled.- Returns:
total number of unmatched requests.
- Return type:
- class pook.MatcherEngine(iterable=(), /)[source]¶
Bases:
list
HTTP request matcher engine used by pook.Mock to test if an intercepted outgoing HTTP request must be mocked out or not.
- add(matcher)[source]¶
Adds a new matcher function to the current engine.
- Parameters:
matcher (function) – matcher function to be added.
- match(request)[source]¶
Match the given HTTP request instance against the registered matcher functions in the current engine.
- Parameters:
request (pook.Request) – outgoing request to match.
- Returns:
True
if all matcher testspasses, otherwise
False
. Also returns an optional list of error exceptions.
- Return type:
- class pook.Mock(request=None, response=None, **kw)[source]¶
Bases:
object
Mock is used to declare and compose the HTTP request/response mock definition and matching expectations, which provides fluent API DSL.
- Parameters:
url (str) – URL to match. E.g:
server.com/api?foo=bar
.method (str) – HTTP method name to match. E.g:
GET
.path (str) – URL path to match. E.g:
/api/users
.headers (dict) – Header values to match. E.g:
{'server': 'nginx'}
.header_present (str) – Matches is a header is present.
headers_present (list|tuple) – Matches if multiple headers are present.
type (str) – Matches MIME
Content-Type
header. E.g:json
,xml
,html
,text/plain
content (str) – Same as
type
argument.params (dict) – Matches the given URL params.
param_exists (str) – Matches if a given URL param exists.
params_exists (list|tuple) – Matches if a given URL params exists.
body (str|regex) – Matches the payload body by regex or strict comparison.
json (dict|list|str|regex) – Matches the payload body against the given JSON or regular expression.
jsonschema (dict|str) – Matches the payload body against the given JSONSchema.
xml (str|regex) – matches the payload body against the given XML string or regular expression.
file (str) – Disk file path to load body from. Analog to
body
param.times (int) – Mock TTL or maximum number of times that the mock can be matched.
persist (bool) – Enable persistent mode. Mock won’t be flushed even if it matched one or multiple times.
delay (int) – Optional network delay simulation (only applicable when using
aiohttp
HTTP client).callback (function) – optional callback function called every time the mock is matched.
reply (int) – Mock response status. Defaults to
200
.response_status (int) – Mock response status. Alias to
reply
param.response_headers (dict) – Response headers to use.
response_type (str) – Response MIME type expression or alias. Analog to
type
param. E.g:json
,xml
,text/plain
.response_body (str) – Response body to use.
response_json (dict|list|str) – Response JSON to use. If Python is passed, it will be serialized as JSON transparently.
response_xml (str) – XML body string to use.
request (pook.Request) – Optional. Request mock definition object.
response (pook.Response) – Optional. Response mock definition object.
- Returns:
pook.Mock
- add_matcher(matcher)[source]¶
Adds one or multiple custom matchers instances.
Matchers must implement the following interface:
.__init__(expectation)
.match(request)
.name = str
Matchers can optionally inherit from
pook.matchers.BaseMatcher
.- Parameters:
*matchers (pook.matchers.BaseMatcher) – matchers to add.
- Returns:
current Mock instance.
- Return type:
self
- body(body, binary=False)[source]¶
Defines the body data to match.
body
argument can be astr
,binary
or a regular expression.
- callback(*callbacks)[source]¶
Registers one or multiple callback that will be called every time the current mock matches an outgoing HTTP request.
- Parameters:
*callbacks (function) – callback functions to call.
- Returns:
current Mock instance.
- Return type:
self
- property calls¶
Accessor to retrieve the amount of mock matched calls.
- Returns:
int
- content(value)[source]¶
Defines the
Content-Type
outgoing header value to match.You can pass one of the following type aliases instead of the full MIME type representation:
json
=application/json
xml
=application/xml
html
=text/html
text
=text/plain
urlencoded
=application/x-www-form-urlencoded
form
=application/x-www-form-urlencoded
form-data
=application/x-www-form-urlencoded
- Parameters:
value (str) – type alias or header value to match.
- Returns:
current Mock instance.
- Return type:
self
- delay(delay=1000)[source]¶
Delay network response with certain milliseconds. Only supported by asynchronous HTTP clients, such as
aiohttp
.- Parameters:
delay (int) – milliseconds to delay response.
- Returns:
current Mock instance.
- Return type:
self
- property done¶
Attribute accessor that would be
True
if the current mock is done, and therefore have been matched multiple times.- Returns:
bool
- file(path)[source]¶
Reads the body to match from a disk file.
- Parameters:
path (str) – relative or absolute path to file to read from.
- Returns:
current Mock instance.
- Return type:
self
- filter(*filters)[source]¶
Registers one o multiple request filters used during the matching phase.
- Parameters:
*mappers (function) – variadic mapper functions.
- Returns:
current Mock instance.
- Return type:
self
- header(name, value)[source]¶
Defines a URL path to match.
Only call this method if the URL has no path already defined.
- Parameters:
path (str) – URL path value to match. E.g:
/api/users
.- Returns:
current Mock instance.
- Return type:
self
- header_present(*names)[source]¶
Defines a new header matcher expectation that must be present in the outgoing request in order to be satisfied, no matter what value it hosts.
Header keys are case insensitive.
- Parameters:
*names (str) – header or headers names to match.
- Returns:
current Mock instance.
- Return type:
self
Example:
(pook.get('server.com/api') .header_present('content-type'))
- headers(headers=None, **kw)[source]¶
Defines a dictionary of arguments.
Header keys are case insensitive.
- headers_present(headers)[source]¶
Defines a list of headers that must be present in the outgoing request in order to satisfy the matcher, no matter what value the headers hosts.
Header keys are case insensitive.
- Parameters:
- Returns:
current Mock instance.
- Return type:
self
Example:
(pook.get('server.com/api') .headers_present(['content-type', 'Authorization']))
- isdone()[source]¶
Returns
True
if the mock has been matched by outgoing HTTP traffic.- Returns:
True
if the mock was matched succesfully.- Return type:
- json(json)[source]¶
Defines the JSON body to match.
json
argument can be an JSON string, a JSON serializable Python structure, such as adict
orlist
or it can be a regular expression used to match the body.
- map(*mappers)[source]¶
Registers one o multiple request mappers used during the mapping phase.
- Parameters:
*mappers (function) – variadic mapper functions.
- Returns:
current Mock instance.
- Return type:
self
- match(request)[source]¶
Matches an outgoing HTTP request against the current mock matchers.
This method acts like a delegator to pook.MatcherEngine.
- property matched¶
Accessor property that would be
True
if the current mock have been matched at least once.See
Mock.total_matches
for more information.- Returns:
bool
- property matches¶
Accessor to retrieve the mock match calls registry.
- Returns:
list[MockCall]
- method(method)[source]¶
Defines the HTTP method to match. Use
*
to match any method.- Parameters:
method (str) – method value to match. E.g:
GET
.- Returns:
current Mock instance.
- Return type:
self
- param_exists(name, allow_empty=False)[source]¶
Checks if a given URL param name is present in the URL.
- params(params)[source]¶
Defines a set of URL query params to match.
- Parameters:
params (dict) – set of params to match.
- Returns:
current Mock instance.
- Return type:
self
- path(path)[source]¶
Defines a URL path to match.
Only call this method if the URL has no path already defined.
- Parameters:
path (str) – URL path value to match. E.g:
/api/users
.- Returns:
current Mock instance.
- Return type:
self
- persist(status=None)[source]¶
Enables persistent mode for the current mock.
- Returns:
current Mock instance.
- Return type:
self
- reply(status=200, new_response=False, **kw)[source]¶
Defines the mock response.
- Parameters:
- Returns:
mock response definition instance.
- Return type:
- response(status=200, **kw)[source]¶
Defines the mock response. Alias to
.reply()
- Parameters:
- Returns:
mock response definition instance.
- Return type:
- status(code=200)[source]¶
Defines the response status code. Equivalent to
self.reply(code)
.- Parameters:
code (int) – response status code. Defaults to
200
.- Returns:
mock response definition instance.
- Return type:
- times(times=1)[source]¶
Defines the TTL limit for the current mock.
The TTL number will determine the maximum number of times that the current mock can be matched and therefore consumed.
- Parameters:
times (int) – TTL number. Defaults to
1
.- Returns:
current Mock instance.
- Return type:
self
- property total_matches¶
Accessor property to retrieve the total number of times that the current mock has been matched.
- Returns:
int
- type(value)[source]¶
Defines the request
Content-Type
header to match.You can pass one of the following aliases instead of the full MIME type representation:
json
=application/json
xml
=application/xml
html
=text/html
text
=text/plain
urlencoded
=application/x-www-form-urlencoded
form
=application/x-www-form-urlencoded
form-data
=application/x-www-form-urlencoded
- Parameters:
value (str) – type alias or header value to match.
- Returns:
current Mock instance.
- Return type:
self
- url(url)[source]¶
Defines the mock URL to match. It can be a full URL with path and query params.
Protocol schema is optional, defaults to
http://
.- Parameters:
url (str) – mock URL to match. E.g:
server.com/api
.- Returns:
current Mock instance.
- Return type:
self
- use(*matchers)[source]¶
Adds one or multiple custom matchers instances.
Matchers must implement the following interface:
.__init__(expectation)
.match(request)
.name = str
Matchers can optionally inherit from
pook.matchers.BaseMatcher
.- Parameters:
*matchers (pook.matchers.BaseMatcher) – matchers to add.
- Returns:
current Mock instance.
- Return type:
self
- class pook.MockEngine(engine)[source]¶
Bases:
object
MockEngine
represents the low-level mocking engine abstraction layer betweenpook
and the underlying mocking mechanism responsible of intercepting and trigger outgoing HTTP traffic within the Python runtime.MockEngine
implements the built-in pook mock engine based on HTTP interceptors strategy.Developers can implement and plug in their own
MockEngine
in order to fit custom mocking logic needs.You can see a custom
MockEngine
implementation here: http://bit.ly/2EymMroCustom mock engines must implementent at least the following methods:
engine.__init__(self, engine)
engine.activate(self)
engine.disable(self)
Custom mock engines can optionally implement the following methods:
engine.add_interceptors(self, *interceptors)
engine.flush_interceptors(self)
engine.disable_interceptor(self, name) -> bool
- Parameters:
engine (pook.Engine) – injected pook engine to be used.
- engine¶
stores pook engine to be used.
- Type:
- activate()[source]¶
Activates the registered interceptors in the mocking engine.
This means any HTTP traffic captures by those interceptors will trigger the HTTP mock matching engine in order to determine if a given HTTP transaction should be mocked out or not.
- add_interceptor(*interceptors)[source]¶
Adds one or multiple HTTP traffic interceptors to the current mocking engine.
Interceptors are typically HTTP client specific wrapper classes that implements the pook interceptor interface.
- Parameters:
interceptors (pook.interceptors.BaseInterceptor) –
- class pook.Request(method='GET', **kw)[source]¶
Bases:
object
Request object representing the request mock expectation DSL.
- Parameters:
method (str) – HTTP method to match. Defaults to
GET
.url (str) – URL request to intercept and match.
headers (dict) – HTTP headers to match.
query (dict) – URL query params to match. Complementely to URL defined query params.
body (str|regex) – request body payload to match.
json (str|dict|list) – JSON payload body structure to match.
xml (str) – XML payload data structure to match.
- property body¶
- copy()[source]¶
Copies the current Request object instance for side-effects purposes.
- Returns:
copy of the current Request instance.
- Return type:
- property extra¶
- property headers¶
- property json¶
- keys = ('method', 'headers', 'body', 'url', 'query')¶
- property method¶
- property query¶
- property rawurl¶
- property url¶
- property xml¶
- class pook.Response(**kw)[source]¶
Bases:
object
Response is used to declare and compose an HTTP mock responses fields.
It provides a chainable DSL interface for easier and declarative usage.
- Parameters:
- content(name)[source]¶
Defines the response
Content-Type
header.You can pass one of the following type aliases instead of the full MIME type representation:
json
=application/json
xml
=application/xml
html
=text/html
text
=text/plain
urlencoded
=application/x-www-form-urlencoded
form
=application/x-www-form-urlencoded
form-data
=application/x-www-form-urlencoded
- Parameters:
value (str) – type alias or header value to match.
- Returns:
pook.Response
current instance.- Return type:
self
- file(path)[source]¶
Defines the response body from file contents.
- Parameters:
path (str) – disk file path to load.
- Returns:
pook.Response
current instance.- Return type:
self
- property mock¶
Getter accessor for mock attribute.
- status(code=200)[source]¶
Defines the response status code.
- Parameters:
code (int) – response status code.
- Returns:
pook.Response
current instance.- Return type:
self
- type(name)[source]¶
Defines the response
Content-Type
header. Alias toResponse.content(mime)
.You can pass one of the following type aliases instead of the full MIME type representation:
json
=application/json
xml
=application/xml
html
=text/html
text
=text/plain
urlencoded
=application/x-www-form-urlencoded
form
=application/x-www-form-urlencoded
form-data
=application/x-www-form-urlencoded
- Parameters:
value (str) – type alias or header value to match.
- Returns:
pook.Response
current instance.- Return type:
self
- pook.activate(fn=None)[source]¶
Enables the HTTP traffic interceptors.
This function can be used as decorator.
- Parameters:
fn (function|coroutinefunction) – Optional function argument if used as decorator.
- Returns:
- decorator wrapper function, only if called as decorator,
otherwise
None
.
- Return type:
function
Example:
# Standard use case pook.activate() pook.mock('server.com/foo').reply(404) res = requests.get('server.com/foo') assert res.status_code == 404 pook.disable() # Decorator use case @pook.activate def test_request(): pook.mock('server.com/foo').reply(404) res = requests.get('server.com/foo') assert res.status_code == 404
- pook.enable_network(*hostnames)[source]¶
Enables real networking mode for unmatched mocks in the current mock engine.
- pook.engine()[source]¶
Returns the current running mock engine.
- Returns:
current used engine.
- Return type:
- pook.isactive()[source]¶
Returns
True
if pook is active and intercepting traffic. OtherwiseFalse
.- Returns:
True if pook is active, otherwise False.
- Return type:
- pook.isdone()[source]¶
Returns True if all the registered mocks has been triggered.
- Returns:
True if all the registered mocks are gone, otherwise False.
- Return type:
- pook.ispending()[source]¶
Returns the numbers of pending mocks to be matched.
- Returns:
number of pending mocks to match.
- Return type:
- pook.isunmatched()[source]¶
Returns
True
if there are unmatched requests. OtherwiseFalse
.Unmatched requests will be registered only if
networking
mode has been enabled.- Returns:
bool
- pook.off()[source]¶
Disables mock engine, HTTP traffic interceptors and flushed all the registered mocks.
Internally, it calls
pook.disable()
andpook.off()
.
- pook.on(fn=None)[source]¶
Enables the HTTP traffic interceptors. Alias to
pook.activate()
.- Parameters:
fn (function|coroutinefunction) – Optional function argument if used as decorator.
- Returns:
decorator wrapper function, only if called as decorator.
- Return type:
function
Example:
# Standard usage pook.on() pook.mock('server.com/foo').reply(404) res = requests.get('server.com/foo') assert res.status_code == 404 # Usage as decorator @pook.on def test_request(): pook.mock('server.com/foo').reply(404) res = requests.get('server.com/foo') assert res.status_code == 404
- pook.pending()[source]¶
Returns the numbers of pending mocks to be matched.
- Returns:
number of pending mocks to match.
- Return type:
- pook.pending_mocks()[source]¶
Returns pending mocks to be matched.
- Returns:
pending mock instances.
- Return type:
- pook.regex(expression, flags=RegexFlag.IGNORECASE)[source]¶
Convenient shortcut to
re.compile()
for fast, easy to use regular expression compilation without an extra import statement.- Parameters:
- Returns:
string based regular expression.
- Return type:
expression (str)
- Raises:
Exception – in case of regular expression compilation error
Example:
(pook .get('api.com/foo') .header('Content-Type', pook.regex('[a-z]{1,4}')))
- pook.reset()[source]¶
Resets current mock engine state, flushing all the registered mocks.
This action will not disable the mock engine.
- pook.set_mock_engine(engine)[source]¶
Sets a custom mock engine, replacing the built-in one.
This is particularly useful if you want to replace the built-in HTTP traffic mock interceptor engine with your custom one.
For mock engine implementation details, see pook.MockEngine.
- Parameters:
engine (pook.MockEngine) – custom mock engine to use.
- pook.unmatched()[source]¶
Returns the total number of unmatched requests intercepted by pook.
Unmatched requests will be registered only if
networking
mode has been enabled.- Returns:
total number of unmatched requests.
- Return type:
- pook.unmatched_requests()[source]¶
Returns a
tuple
of unmatched requests.Unmatched requests will be registered only if
networking
mode has been enabled.- Returns:
unmatched intercepted requests.
- Return type:
- pook.use(network=False)[source]¶
Creates a new isolated mock engine to be used via context manager.
Example:
with pook.use() as engine: pook.mock('server.com/foo').reply(404) res = requests.get('server.com/foo') assert res.status_code == 404