Sign inDemoInstall


Package Overview
File Explorer

Install Socket

Protect your apps from supply chain attacks



HTTP traffic mocking and expectations made easy




pook |PyPI| |Coverage Status| |Documentation Status| |Stability| |Quality| |Versions|

Versatile, expressive and hackable utility library for HTTP traffic mocking
and expectations made easy in `Python`_. Heavily inspired by `gock`_.

To get started, read the `documentation`_, `how it works`_, `FAQ`_ or `examples`_.


-  Simple, expressive and fluent API.
-  Provides both Pythonic and chainable DSL API styles.
-  Full-featured HTTP response definitions and expectations.
-  Matches any HTTP protocol primitive (URL, method, query params, headers, body...).
-  Full regular expressions capable mock expectations matching.
-  Supports most popular HTTP clients via interceptor adapters.
-  Configurable volatile, persistent or TTL limited mocks.
-  Works with unittest and pytest.
-  First-class JSON & XML support matching and responses.
-  Supports JSON Schema body matching.
-  Works in both runtime and testing environments.
-  Can be used as decorator and/or via context managers.
-  Supports real networking mode with optional traffic filtering.
-  Map/filter mocks easily for generic or custom mock expectations.
-  Custom user-defined mock matcher functions.
-  Simulated raised error exceptions.
-  Network delay simulation (only available for ``aiohttp``).
-  Pluggable and hackable API.
-  Customizable HTTP traffic mock interceptor engine.
-  Supports third-party mocking engines, such as `mocket`_.
-  Fits good for painless test doubles.
-  Does not support WebSocket traffic mocking.
-  Works with +3.8 (including PyPy).
-  Dependency-less: just 3 small dependencies for JSONSchema, XML tree comparison, and URL parsing.

Supported HTTP clients

``pook`` can work with multiple mock engines, however it provides a
built-in one by default, which currently supports traffic mocking in
the following HTTP clients:

-  ✔  `urllib3`_ v1+
-  ✔  `requests`_ v2+
-  ✔  `aiohttp`_ v3+
-  ✔  `urllib`_ / `http.client`_
-  ✔  `httpx`_

More HTTP clients can be supported progressively.

**Note**: only recent HTTP client package versions were tested.


Using ``pip`` package manager (requires pip 1.8+):

.. code:: bash

    pip install --upgrade pook

Or install the latest sources from Github:

.. code:: bash

    pip install -e git+git://

Getting started

See ReadTheDocs documentation:

|Documentation Status|


See `annotated API reference`_ documention.


See `examples`_ documentation for full featured code and use case examples.

Basic mocking:

.. code:: python

    import pook
    import requests

    def test_my_api():
        mock = pook.get('', reply=404, response_json={'error': 'not found'})

        resp = requests.get('')
        assert resp.status_code == 404
        assert resp.json() == {"error": "not found"}
        assert mock.calls == 1

Using the chainable API DSL:

.. code:: python

    import pook
    import requests

    def test_my_api():
        mock = (pook.get('')
                  .json({'error': 'not found'}))

        resp = requests.get('')
        assert resp.json() == {"error": "not found"}
        assert mock.calls == 1

Using the decorator:

.. code:: python

    import pook
    import requests

    @pook.get('', reply=204)
    @pook.get('', reply=200)
    def fetch(url):
        return requests.get(url)

    res = fetch('')
    print('#1 status:', res.status_code)

    res = fetch('')
    print('#2 status:', res.status_code)

Simple ``unittest`` integration:

.. code:: python

    import pook
    import unittest
    import requests

    class TestUnitTestEngine(unittest.TestCase):

        def test_request(self):
            res = requests.get('')
            self.assertEqual(res.status_code, 204)

        def test_request_with_context_manager(self):
            with pook.use():
                pook.get('', reply=204)
                res = requests.get('')
                self.assertEqual(res.status_code, 204)

Using the context manager for isolated HTTP traffic interception blocks:

.. code:: python

    import pook
    import requests

    # Enable HTTP traffic interceptor
    with pook.use():
        pook.get('', reply=204)

        res = requests.get('')
        print('#1 status:', res.status_code)

    # Interception-free HTTP traffic
    res = requests.get('')
    print('#2 status:', res.status_code)

Example using `mocket`_ Python library as underlying mock engine:

.. code:: python

    import pook
    import requests
    from mocket.plugins.pook_mock_engine import MocketEngine

    # Use mocket library as underlying mock engine

    # Explicitly enable pook HTTP mocking (optional)

    # Target server URL to mock out
    url = ''

    # Define your mock
    mock = pook.get(url,
                    reply=404, times=2,
                    headers={'content-type': 'application/json'},
                    response_json={'error': 'foo'})

    # Run first HTTP request
    assert mock.calls == 1

    # Run second HTTP request
    res = requests.get(url)
    assert mock.calls == 2

    # Assert response data
    assert res.status_code == 404
    assert res.json() == {'error': 'foo'}

    # Explicitly disable pook (optional)

Example using Hy language (Lisp dialect for Python):

.. code:: hy

    (import [pook])
    (import [requests])

    (defn request [url &optional [status 404]]
      (doto (.mock pook url) (.reply status))
      (let [res (.get requests url)]
        (. res status_code)))

    (defn run []
      (with [(.use pook)]
        (print "Status:" (request "" :status 204))))

    ;; Run test program
    (defmain [&args] (run))


Clone the repository:

.. code:: bash

    git clone

Use [`hatch`]( to configure the environment by running the test suite:

.. code:: bash

    hatch run test

Install the pre-commit hook:

.. code:: bash

    hatch run lint:install

Lint the code:

.. code:: bash

    hatch run lint:run

Run tests on all supported Python versions and implementations (this requires your host operating system to have each implementation available):

.. code:: bash

    hatch run test:test

To run tests only for a specific version, affix the version designation to the environment name (the left side of the `:`):

.. code:: bash

    hatch run test.pypy3.10:test

Generate documentation:

.. code:: bash

    hatch run docs:build


MIT - Tomas Aparicio

.. _Go:
.. _Python:
.. _gock:
.. _annotated API reference:
.. _examples:
.. _aiohttp:
.. _httpx:
.. _requests:
.. _urllib3:
.. _urllib:
.. _http.client:
.. _documentation:
.. _FAQ:
.. _how it works:
.. _mocket:

.. |PyPI| image::
.. |Coverage Status| image::
.. |Documentation Status| image::
   :alt: Documentation Status
.. |Quality| image::
   :alt: Code Climate
.. |Stability| image::
   :alt: Stability
.. |Versions| image::
   :alt: Python Versions


Did you know?

Socket installs a GitHub app to automatically flag issues on every pull request and report the health of your dependencies. Find out what is inside your node modules and prevent malicious activity before you update the dependencies.


Related posts

SocketSocket SOC 2 Logo


  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc