Skip to main content

HTTP traffic mocking and expectations made easy

Project description

pook Build Status PyPI Coverage Status Documentation Status Stability Code Climate Python Versions

Versatile, expressive and hackable utility library for HTTP traffic mocking and expectations made easy in Python.

Heavily inspired by gock.

To get started, see the documentation, how it works, FAQ or examples.

Note: still beta quality library. More docs, examples and better test coverage are still a work in progress.

Features

  • 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 any testing framework/engine (unittest, pytest, nosetests…).

  • 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.

  • Fits good for painless test doubles.

  • Does not support WebSocket traffic mocking.

  • Works with Python +2.7 and +3.0 (including PyPy).

  • Dependency-less: just 2 small dependencies for JSONSchema and XML tree comparison.

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:

More HTTP clients can be supported progressively.

Note: only recent HTTP client package versions were tested.

Installation

Using pip package manager (requires pip 1.8+):

pip install --upgrade pook

Or install the latest sources from Github:

pip install -e git+git://github.com/h2non/pook.git#egg=pook

Getting started

See ReadTheDocs documentation:

Documentation Status

API

See annotated API reference documention.

Examples

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

Basic mocking:

import pook
import requests

@pook.activate
def test_my_api():
    mock = pook.get('http://twitter.com/api/1/foobar', reply=404, response_json={'error': 'foo'})

    resp = requests.get('http://twitter.com/api/1/foobar')
    assert resp.status_code == 404
    assert resp.json() == {"error": "not found"}
    assert mock.calls == 1

Using the chainable API DSL:

import pook
import requests

@pook.on
def test_my_api():
    mock = (pook.get('http://twitter.com/api/1/foobar')
              .reply(404)
              .json({'error': 'not found'}))

    resp = requests.get('http://twitter.com/api/1/foobar')
    assert resp.json() == {"error": "not found"}
    assert mock.calls == 1

Using the decorator:

import pook
import requests

@pook.get('http://httpbin.org/status/500', reply=204)
@pook.get('http://httpbin.org/status/400', reply=200)
def fetch(url):
    return requests.get(url)

res = fetch('http://httpbin.org/status/400')
print('#1 status:', res.status_code)

res = fetch('http://httpbin.org/status/500')
print('#2 status:', res.status_code)

Simple unittest integration:

import pook
import unittest
import requests


class TestUnitTestEngine(unittest.TestCase):

    @pook.activate
    def test_request(self):
        pook.get('server.com/foo').reply(204)
        res = requests.get('http://server.com/foo')
        self.assertEqual(res.status_code, 204)

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

Using the context manager for isolated HTTP traffic interception blocks:

import pook
import requests

# Enable HTTP traffic interceptor
with pook.use():
    pook.get('http://httpbin.org/status/500', reply=204)

    res = requests.get('http://httpbin.org/status/500')
    print('#1 status:', res.status_code)

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

Example using Hy language (Lisp dialect for Python):

(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 "http://server.com/foo" :status 204))))

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

Development

Clone the repository:

git clone git@github.com:h2non/pook.git

Install dependencies:

pip install -r requirements.txt requirements-dev.txt

Install Python dependencies:

make install

Lint code:

make lint

Run tests:

make test

Generate documentation:

make htmldocs

License

MIT - Tomas Aparicio

History

v0.1.9 / 2017-01-06

  • fix(Makefile): remove proper egg file

  • feat(package): add wheel package distribution support

  • feat(docs): add documentation links

v0.1.8 / 2016-12-24

  • fix(assertion): extract regex pattern only when required

  • feat(examples): add regular expression example

v0.1.7 / 2016-12-18

  • feat(#33): add support for user defined custom mock engine

v0.1.6 / 2016-12-14

  • fix(setup.py): force utf-8 encoding

  • feat(setup.py): add encoding header

  • feat(api): add debug mode

  • refactor(docs): minor enhancements

  • refactor(tests): update URL matcher test cases

  • refactor(docs): add note about HTTP clients and update features list

  • fix(setup.py): remove encoding param

  • fix(tests): use strict equality assertion

0.1.5 / 2016-12-12

  • fix(matchers): fix matching issue in URL.

  • refactor(assertion): regex expression based matching must be explicitly enabled.

  • feat(tests): add initial matchers tests.

0.1.4 / 2016-12-08

  • refactor(README): minor changes

  • fix(setup.py): lint error

  • fix(#32): use explicit encoding while reading files in setup.py

0.1.3 / 2016-12-08

  • fix(core): several bug fixes.

  • feat(core): add pending features and major refactors.

  • feat(matchers): use unittest.TestCase matching engine by default.

0.1.2 / 2016-12-01

  • fix(matchers): runtime missing variable.

0.1.1 / 2016-12-01

  • fix: Python 2 dictionary iteration syntax.

  • feat(docs): add more examples.

  • fix(matchers): better regular expression comparison support.

0.1.0 / 2016-11-30

  • First version (still beta)

0.1.0-rc.1 / 2016-11-27

  • First release candidate version (still beta)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pook-0.1.9.tar.gz (45.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pook-0.1.9-py2.py3-none-any.whl (81.8 kB view details)

Uploaded Python 2Python 3

File details

Details for the file pook-0.1.9.tar.gz.

File metadata

  • Download URL: pook-0.1.9.tar.gz
  • Upload date:
  • Size: 45.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for pook-0.1.9.tar.gz
Algorithm Hash digest
SHA256 b7a3460d72d9b278e4f935faac7b0b1cf5037cab47dd8699d9a4f64b6f462cba
MD5 42f2a67ba23c99520dc4e63c2208ccb8
BLAKE2b-256 8ae1b8151447d39fc1069dd593c7a9084799b7cc5bdc27efe0efddf7e0897e9d

See more details on using hashes here.

File details

Details for the file pook-0.1.9-py2.py3-none-any.whl.

File metadata

File hashes

Hashes for pook-0.1.9-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 129a7eb3fc8ecb29a927ac0c3627c8d34577f0c509be4c04d13dafdd74ad2e78
MD5 5add022300919eb35657bbb99aea0274
BLAKE2b-256 d05fc806a6730e87e3c1905c29ab71dbc3719473febe3c5204999fcd63205236

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page