# API Documentation

## Core API

- pook.activate
- pook.on
- pook.disable
- pook.off
- pook.reset
- pook.engine
- pook.use
- pook.context
- pook.enable_network
- pook.disable_network
- pook.use_network
- pook.use_network_filter
- pook.flush_network_filters
- pook.mock
- pook.get
- pook.put
- pook.delete
- pook.head
- pook.patch
- pook.options
- pook.pending
- pook.ispending
- pook.pending_mocks
- pook.unmatched_requests
- pook.unmatched
- pook.isunmatched
- pook.isactive
- pook.isdone
- pook.regex
- pook.Mock
- pook.Engine
- pook.Request
- pook.Response
- pook.MockEngine
- pook.MatcherEngine

class pook.Engine(network=False)

  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.

  debug

    enables/disables debug mode.

    Type:

      bool

  active

    stores the current engine activation status.

    Type:

      bool

  networking

    stores the current engine networking mode status.

    Type:

      bool

  mocks

    stores engine mocks.

    Type:

      list[pook.Mock]

  filters

    stores engine-level mock filter functions.

    Type:

      list[function]

  mappers

    stores engine-level mock mapper functions.

    Type:

      list[function]

  interceptors

    stores engine-level HTTP traffic interceptors.

    Type:

      list[pook.BaseInterceptor]

  unmatched_reqs

    stores engine-level unmatched outgoing HTTP requests.

    Type:

      list[pook.Request]

  network_filters

    stores engine-level real networking mode filters.

    Type:

      list[function]

  activate()

    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)

    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)

    Adds a new mock instance to the current engine.

    Parameters:

      mock (pook.Mock) – mock instance to add.

  disable()

    Disables interceptors and stops intercepting any outgoing HTTP traffic.

  disable_network()

    Disables real networking mode.

  enable_network(*hostnames)

    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)

    Append engine-level HTTP request filter functions.

    Parameters:

      filters* – variadic filter functions to be added.

  flush_interceptors()

    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_mocks()

    Flushes the current mocks.

  flush_network_filters()

    Flushes registered real networking filters in the current mock engine.

  isactive()

    Returns the current engine enabled/disabled status.

    Returns:

      `True` if the engine is active. Otherwise `False`.

    Return type:

      bool

  isdone()

    Returns True if all the registered mocks has been triggered.

    Returns:

      True is all the registered mocks are gone, otherwise False.

    Return type:

      bool

  ispending()

    Returns the `True` if the engine has pending mocks to be matched. Otherwise `False`.

    Returns:

      bool

  isunmatched()

    Returns `True` if there are unmatched requests. Otherwise `False`.

    Unmatched requests will be registered only if `networking` mode has been enabled.

    Returns:

      bool

  map(*mappers)

    Append engine-level HTTP request mapper functions.

    Parameters:

      filters* – variadic mapper functions to be added.

  match(request)

    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:

      pook.Response

  mock(url=None, **kw)

    Creates and registers a new HTTP mock in the current engine.

    Parameters:

      - url (str) – request URL to mock.

      - activate (bool) – force mock engine activation. Defaults to `False`.

      - **kw (mixed) – variadic keyword arguments for `Mock` constructor.

    Returns:

      new mock instance.

    Return type:

      pook.Mock

  pending()

    Returns the number of pending mocks to be matched.

    Returns:

      number of pending mocks.

    Return type:

      int

  pending_mocks()

    Returns a `tuple` of pending mocks to be matched.

    Returns:

      pending mock instances.

    Return type:

      tuple

  remove_interceptor(name)

    Removes a specific interceptor by name.

    Note: this method is may not be implemented if using a custom mock engine.

    Parameters:

      name (str) – interceptor name to disable.

    Returns:

      True if the interceptor was disabled, otherwise False.

    Return type:

      bool

  remove_mock(mock)

    Removes a specific mock instance by object reference.

    Parameters:

      mock (pook.Mock) – mock instance to remove.

  reset()

    Resets and flushes engine state and mocks to defaults.

  set_mock_engine(engine)

    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)

    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()

    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:

      int

  unmatched_requests()

    Returns a `tuple` of unmatched requests.

    Unmatched requests will be registered only if `networking` mode has been enabled.

    Returns:

      unmatched intercepted requests.

    Return type:

      list

  use_network_filter(*fn)

    Adds network filters to determine if certain outgoing unmatched HTTP traffic can stablish real network connections.

    Parameters:

      *fn (function) – variadic function filter arguments to be used.

class pook.MatcherEngine(iterable=(), /)

  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)

    Adds a new matcher function to the current engine.

    Parameters:

      matcher (function) – matcher function to be added.

  flush()

    Flushes the current matcher engine, removing all the registered matcher functions.

  match(request)

    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 tests

        passes, otherwise `False`. Also returns an optional list of error exceptions.

    Return type:

      tuple(bool, list[Exception])

class pook.Mock(request=None, response=None, **kw)

  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)

    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)

    Defines the body data to match.

    `body` argument can be a `str`, `binary` or a regular expression.

    Parameters:

      body (str|binary|regex) – body data to match.

    Returns:

      current Mock instance.

    Return type:

      self

  callback(*callbacks)

    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)

    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)

    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

  error(error)

    Defines a simulated exception error that will be raised.

    Parameters:

      error (str|Exception) – error to raise.

    Returns:

      current Mock instance.

    Return type:

      self

  file(path)

    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)

    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)

    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)

    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)

    Defines a dictionary of arguments.

    Header keys are case insensitive.

    Parameters:

      - headers (dict) – headers to match.

      - **headers (dict) – headers to match as variadic keyword arguments.

    Returns:

      current Mock instance.

    Return type:

      self

  headers_present(headers)

    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:

      headers (list|tuple) – header keys to match.

    Returns:

      current Mock instance.

    Return type:

      self

    Example:

        (pook.get('server.com/api')
            .headers_present(['content-type', 'Authorization']))

  isdone()

    Returns `True` if the mock has been matched by outgoing HTTP traffic.

    Returns:

      `True` if the mock was matched succesfully.

    Return type:

      bool

  ismatched()

    Returns `True` if the mock has been matched at least once time.

    Returns:

      bool

  json(json)

    Defines the JSON body to match.

    `json` argument can be an JSON string, a JSON serializable Python structure, such as a `dict` or `list` or it can be a regular expression used to match the body.

    Parameters:

      json (str|dict|list|regex) – body JSON to match.

    Returns:

      current Mock instance.

    Return type:

      self

  jsonschema(schema)

    Defines a JSONSchema representation to be used for body matching.

    Parameters:

      schema (str|dict) – dict or JSONSchema string to use.

    Returns:

      current Mock instance.

    Return type:

      self

  map(*mappers)

    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)

    Matches an outgoing HTTP request against the current mock matchers.

    This method acts like a delegator to pook.MatcherEngine.

    Parameters:

      request (pook.Request) – request instance to match.

    Raises:

      Exception – if the mock has an exception defined.

    Returns:

      `True` if the mock matches

        the outgoing HTTP request, otherwise `False`. Also returns an optional list of error exceptions.

    Return type:

      tuple(bool, list[Exception])

  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)

    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(name, value)

    Defines an URL param key and value to match.

    Parameters:

      - name (str) – param name value to match.

      - value (str) – param name value to match.

    Returns:

      current Mock instance.

    Return type:

      self

  param_exists(name)

    Checks if a given URL param name is present in the URL.

    Parameters:

      name (str) – param name to check existence.

    Returns:

      current Mock instance.

    Return type:

      self

  params(params)

    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)

    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)

    Enables persistent mode for the current mock.

    Returns:

      current Mock instance.

    Return type:

      self

  reply(status=200, new_response=False, **kw)

    Defines the mock response.

    Parameters:

      - status (int, optional) – response status code. Defaults to `200`.

      - **kw (dict) – optional keyword arguments passed to `pook.Response` constructor.

    Returns:

      mock response definition instance.

    Return type:

      pook.Response

  response(status=200, **kw)

    Defines the mock response. Alias to `.reply()`

    Parameters:

      - status (int) – response status code. Defaults to `200`.

      - **kw (dict) – optional keyword arguments passed to `pook.Response` constructor.

    Returns:

      mock response definition instance.

    Return type:

      pook.Response

  status(code=200)

    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:

      pook.Response

  times(times=1)

    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)

    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)

    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)

    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

  xml(xml)

    Defines a XML body value to match.

    Parameters:

      xml (str|regex) – body XML to match.

    Returns:

      current Mock instance.

    Return type:

      self

class pook.MockEngine(engine)

  Bases: `object`

  `MockEngine` represents the low-level mocking engine abstraction layer between `pook` 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/2EymMro

  Custom 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:

      pook.Engine

  interceptors

    stores engine-level HTTP traffic interceptors.

    Type:

      list[pook.BaseInterceptor]

  activate()

    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)

    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) –

  disable()

    Disables interceptors and stops intercepting any outgoing HTTP traffic.

  flush_interceptors()

    Flushes registered interceptors in the current mocking engine.

    This method is low-level. Only call it if you know what you are doing.

  remove_interceptor(name)

    Removes a specific interceptor by name.

    Parameters:

      name (str) – interceptor name to disable.

    Returns:

      True if the interceptor was disabled, otherwise False.

    Return type:

      bool

class pook.Request(method='GET', **kw)

  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.

  method

    HTTP method to match. Defaults to `GET`.

    Type:

      str

  url

    URL request to intercept and match.

    Type:

      str

  headers

    HTTP headers to match.

    Type:

      dict

  query

    URL query params to match. Complementely to URL defined query params.

    Type:

      dict

  body

    request body payload to match.

    Type:

      str|regex

  json

    JSON payload body structure to match.

    Type:

      str|dict|list

  xml

    XML payload data structure to match.

    Type:

      str

  property body
  copy()

    Copies the current Request object instance for side-effects purposes.

    Returns:

      copy of the current Request instance.

    Return type:

      pook.Request

  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)

  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:

    - status (int) – HTTP response status code. Defaults to `200`.

    - headers (dict) – HTTP response headers.

    - body (str|bytes) – HTTP response body.

    - json (str|dict|list) – HTTP response JSON body.

    - xml (str) – HTTP response XML body.

    - type (str) – HTTP response content MIME type.

    - file (str) – file path to HTTP body response.

  mock

    reference to mock instance.

    Type:

      pook.Mock

  body(body, chunked=False)

    Defines response body data.

    Parameters:

      - body (str|bytes|list) – response body to use.

      - chunked (bool) – return a chunked response.

    Returns:

      `pook.Response` current instance.

    Return type:

      self

  content(name)

    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)

    Defines the response body from file contents.

    Parameters:

      path (str) – disk file path to load.

    Returns:

      `pook.Response` current instance.

    Return type:

      self

  header(key, value)

    Defines a new response header. Alias to `Response.header()`.

    Parameters:

      - header (str) – header name.

      - value (str) – header value.

    Returns:

      `pook.Response` current instance.

    Return type:

      self

  headers(headers)

    Defines a new response header. Alias to `Response.header()`.

    Parameters:

      - header (str) – header name.

      - value (str) – header value.

    Returns:

      `pook.Response` current instance.

    Return type:

      self

  json(data)

    Defines the mock response JSON body.

    Parameters:

      data (dict|list|str) – JSON body data.

    Returns:

      `pook.Response` current instance.

    Return type:

      self

  property mock

    Getter accessor for mock attribute.

  set(header, value)

    Defines a new response header. Alias to `Response.header()`.

    Parameters:

      - header (str) – header name.

      - value (str) – header value.

    Returns:

      `pook.Response` current instance.

    Return type:

      self

  status(code=200)

    Defines the response status code.

    Parameters:

      code (int) – response status code.

    Returns:

      `pook.Response` current instance.

    Return type:

      self

  type(name)

    Defines the response `Content-Type` header. Alias to `Response.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

  xml(xml)

    Defines the mock response XML body.

    For not it only supports `str` as input type.

    Parameters:

      xml (str) – XML body data to use.

    Returns:

      `pook.Response` current instance.

    Return type:

      self

pook.activate(fn=None)

  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.delete(url, **kw)

  Registers a new mock HTTP request with DELETE method.

  Parameters:

    - url (str) – request URL to mock.

    - activate (bool) – force mock engine activation. Defaults to `False`.

    - **kw (mixed) – variadic arguments to `pook.Mock` constructor.

  Returns:

    mock instance

  Return type:

    pook.Mock

pook.disable()

  Disables HTTP traffic interceptors.

pook.disable_network()

  Disables real traffic networking mode in the current mock engine.

pook.enable_network(*hostnames)

  Enables real networking mode for unmatched mocks in the current mock engine.

pook.engine()

  Returns the current running mock engine.

  Returns:

    current used engine.

  Return type:

    pook.Engine

pook.get(url, **kw)

  Registers a new mock HTTP request with GET method.

  Parameters:

    - url (str) – request URL to mock.

    - activate (bool) – force mock engine activation. Defaults to `False`.

    - **kw (mixed) – variadic arguments to `pook.Mock` constructor.

  Returns:

    mock instance

  Return type:

    pook.Mock

pook.head(url, **kw)

  Registers a new mock HTTP request with HEAD method.

  Parameters:

    - url (str) – request URL to mock.

    - activate (bool) – force mock engine activation. Defaults to `False`.

    - **kw (mixed) – variadic arguments to `pook.Mock` constructor.

  Returns:

    mock instance

  Return type:

    pook.Mock

pook.isactive()

  Returns `True` if pook is active and intercepting traffic. Otherwise `False`.

  Returns:

    True is all the registered mocks are gone, otherwise False.

  Return type:

    bool

pook.isdone()

  Returns True if all the registered mocks has been triggered.

  Returns:

    True is all the registered mocks are gone, otherwise False.

  Return type:

    bool

pook.ispending()

  Returns the numbers of pending mocks to be matched.

  Returns:

    number of pending mocks to match.

  Return type:

    int

pook.isunmatched()

  Returns `True` if there are unmatched requests. Otherwise `False`.

  Unmatched requests will be registered only if `networking` mode has been enabled.

  Returns:

    bool

pook.mock(url=None, **kw)

  Creates and register a new HTTP mock.

  Parameters:

    - url (str) – request URL to mock.

    - activate (bool) – force mock engine activation. Defaults to `False`.

    - **kw (mixed) – variadic keyword arguments.

  Returns:

    mock instance

  Return type:

    pook.Mock

pook.off()

  Disables mock engine, HTTP traffic interceptors and flushed all the registered mocks.

  Internally, it calls `pook.disable()` and `pook.off()`.

pook.on(fn=None)

  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.options(url=None, **kw)

  Registers a new mock HTTP request with OPTIONS method.

  Parameters:

    - url (str) – request URL to mock.

    - activate (bool) – force mock engine activation. Defaults to `False`.

    - **kw (mixed) – variadic arguments to `pook.Mock` constructor.

  Returns:

    new mock instance.

  Return type:

    pook.Mock

pook.patch(url=None, **kw)

  Registers a new mock HTTP request with PATCH method.

  Parameters:

    - url (str) – request URL to mock.

    - activate (bool) – force mock engine activation. Defaults to `False`.

    - **kw (mixed) – variadic arguments to `pook.Mock` constructor.

  Returns:

    new mock instance.

  Return type:

    pook.Mock

pook.pending()

  Returns the numbers of pending mocks to be matched.

  Returns:

    number of pending mocks to match.

  Return type:

    int

pook.pending_mocks()

  Returns pending mocks to be matched.

  Returns:

    pending mock instances.

  Return type:

    list

pook.post(url, **kw)

  Registers a new mock HTTP request with POST method.

  Parameters:

    - url (str) – request URL to mock.

    - activate (bool) – force mock engine activation. Defaults to `False`.

    - **kw (mixed) – variadic arguments to `pook.Mock` constructor.

  Returns:

    mock instance

  Return type:

    pook.Mock

pook.put(url, **kw)

  Registers a new mock HTTP request with PUT method.

  Parameters:

    - url (str) – request URL to mock.

    - activate (bool) – force mock engine activation. Defaults to `False`.

    - **kw (mixed) – variadic arguments to `pook.Mock` constructor.

  Returns:

    mock instance

  Return type:

    pook.Mock

pook.regex(expression, flags=RegexFlag.IGNORECASE)

  Convenient shortcut to `re.compile()` for fast, easy to use regular expression compilation without an extra import statement.

  Parameters:

    - expression (str) – regular expression value.

    - flags (int) – optional regular expression flags. Defaults to `re.IGNORECASE`

  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()

  Resets current mock engine state, flushing all the registered mocks.

  This action will not disable the mock engine.

pook.set_mock_engine(engine)

  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()

  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:

    int

pook.unmatched_requests()

  Returns a `tuple` of unmatched requests.

  Unmatched requests will be registered only if `networking` mode has been enabled.

  Returns:

    unmatched intercepted requests.

  Return type:

    list

pook.use(network=False)

  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.use_network()

  Creates a new mock engine to be used as context manager

  Example:

      with pook.use_network() as engine:
          pook.mock('server.com/foo').reply(404)

          res = requests.get('server.com/foo')
          assert res.status_code == 404

pook.use_network_filter(*fn)

  Adds network filters to determine if certain outgoing unmatched HTTP traffic can stablish real network connections.

  Parameters:

    *fn (function) – variadic function filter arguments to be used.

## Matchers API

- pook.matchers.init
- pook.matchers.add
- pook.matchers.get
- pook.matchers.BaseMatcher
- pook.matchers.MethodMatcher
- pook.matchers.URLMatcher
- pook.matchers.HeadersMatcher
- pook.matchers.PathMatcher
- pook.matchers.BodyMatcher
- pook.matchers.XMLMatcher
- pook.matchers.JSONMatcher
- pook.matchers.JSONSchemaMatcher
- pook.matchers.QueryMatcher

## Interceptors API

- pook.interceptors.add
- pook.interceptors.get
- pook.interceptors.BaseInterceptor
- pook.interceptors.Urllib3Interceptor
- pook.interceptors.AIOHTTPInterceptor
- pook.interceptors.HTTPClientInterceptor

class pook.interceptors.AIOHTTPInterceptor(engine)

  Bases: `BaseInterceptor`

  aiohttp HTTP client traffic interceptor.

  activate()

    Activates the traffic interceptor. This method must be implemented by any interceptor.

  disable()

    Disables the traffic interceptor. This method must be implemented by any interceptor.

class pook.interceptors.BaseInterceptor(engine)

  Bases: `object`

  BaseInterceptor provides a base class for HTTP traffic interceptors implementations.

  abstract activate()

    Activates the traffic interceptor. This method must be implemented by any interceptor.

  abstract disable()

    Disables the traffic interceptor. This method must be implemented by any interceptor.

  property name

    Exposes the interceptor class name.

class pook.interceptors.HTTPClientInterceptor(engine)

  Bases: `BaseInterceptor`

  urllib / http.client HTTP traffic interceptor.

  activate()

    Activates the traffic interceptor. This method must be implemented by any interceptor.

  disable()

    Disables the traffic interceptor. This method must be implemented by any interceptor.

class pook.interceptors.Urllib3Interceptor(engine)

  Bases: `BaseInterceptor`

  Urllib3 HTTP traffic interceptor.

  activate()

    Activates the traffic interceptor. This method must be implemented by any interceptor.

  disable()

    Disables the traffic interceptor. This method must be implemented by any interceptor.

pook.interceptors.add(*custom_interceptors)

  Registers a new HTTP client interceptor.

  Parameters:

    *custom_interceptors (interceptor) – interceptor(s) to be added.

pook.interceptors.get(name)

  Returns an interceptor by class name.

  Parameters:

    name (str) – interceptor class name or alias.

  Returns:

    found interceptor instance, otherwise `None`.

  Return type:

    interceptor