All Projects → h2non → Pook

h2non / Pook

Licence: mit
HTTP traffic mocking and testing made simple in Python

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to Pook

automock
A library for testing classes with auto mocking capabilities using jest-mock-extended
Stars: ✭ 26 (-89.88%)
Mutual labels:  mock, mocking
Hippolyte
HTTP Stubbing in Swift
Stars: ✭ 109 (-57.59%)
Mutual labels:  mock, mocking
open-api-mocker
A mock server based in OpenAPI Specification
Stars: ✭ 58 (-77.43%)
Mutual labels:  mock, mocking
chrome-extension-mocker
The most convenient tool to mock requests for axios, with built-in Chrome extension support.
Stars: ✭ 37 (-85.6%)
Mutual labels:  mock, mocking
mountebank-api-php
Working with mountebank api it's easy!
Stars: ✭ 17 (-93.39%)
Mutual labels:  mock, mocking
MockAlamofire
A simple example showing how to override the URLProtocol to return mock data on Alamofire responses. Helpful if you are looking for a simple way to mock an Alamofire response, with out any additional dependencies.
Stars: ✭ 22 (-91.44%)
Mutual labels:  mock, mocking
CNeptune
CNeptune improve productivity & efficiency by urbanize .net module with meta-code to lay foundation for frameworks
Stars: ✭ 30 (-88.33%)
Mutual labels:  mock, mocking
aem-stubs
Tool for providing sample data for AEM applications in a simple and flexible way. Stubbing server on AEM, no separate needed.
Stars: ✭ 40 (-84.44%)
Mutual labels:  mock, mocking
ineeda
Mocking library for TypeScript and JavaScript using Proxies!
Stars: ✭ 53 (-79.38%)
Mutual labels:  mock, mocking
better-mock
Forked from Mockjs, Generate random data & Intercept ajax request. Support miniprogram.
Stars: ✭ 140 (-45.53%)
Mutual labels:  mock, mocking
dexopener
An Android library that provides the ability to mock your final classes on Android devices.
Stars: ✭ 112 (-56.42%)
Mutual labels:  mock, mocking
elixir mock
Creates clean, concurrent, inspectable mocks from elixir modules
Stars: ✭ 21 (-91.83%)
Mutual labels:  mock, mocking
mockingbird
🐦 Decorator Powered TypeScript Library for Creating Mocks
Stars: ✭ 70 (-72.76%)
Mutual labels:  mock, mocking
laika
Log, test, intercept and modify Apollo Client's operations
Stars: ✭ 99 (-61.48%)
Mutual labels:  mock, mocking
springmock
alternative spring mocking infrastructure
Stars: ✭ 22 (-91.44%)
Mutual labels:  mock, mocking
Mockaco
🐵 HTTP mock server, useful to stub services and simulate dynamic API responses, leveraging ASP.NET Core features, built-in fake data generation and pure C# scripting
Stars: ✭ 213 (-17.12%)
Mutual labels:  mock, mocking
Http Fake Backend
Build a fake backend by providing the content of JSON files or JavaScript objects through configurable routes.
Stars: ✭ 253 (-1.56%)
Mutual labels:  mock, mocking
go-github-mock
A library to aid unittesting code that uses Golang's Github SDK
Stars: ✭ 63 (-75.49%)
Mutual labels:  mock, mocking
umock-c
A pure C mocking library
Stars: ✭ 29 (-88.72%)
Mutual labels:  mock, mocking
mswjs.io
Official website and documentation for the Mock Service Worker library.
Stars: ✭ 77 (-70.04%)
Mutual labels:  mock, mocking

pook |Build Status| |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, see the documentation, how it works, FAQ_ or examples_.

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.
  • Supports third-party mocking engines, such as mocket_.
  • 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:

  • urllib3_ v1+
  • requests_ v2+
  • aiohttp_ v1+ - v2+
  • urllib_ / http.client_ v2/3
  • pycurl_ (see #16_)

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+):

.. code:: bash

pip install --upgrade pook

Or install the latest sources from Github:

.. code:: bash

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:

.. code:: python

import pook
import requests

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

    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:

.. code:: python

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:

.. code:: python

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:

.. code:: python

import pook
import unittest
import requests


class TestUnitTestEngine(unittest.TestCase):

    @pook.on
    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:

.. code:: python

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 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
pook.set_mock_engine(MocketEngine)

# Explicitly enable pook HTTP mocking (optional)
pook.on()

# Target server URL to mock out
url = 'http://twitter.com/api/1/foobar'

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

# Run first HTTP request
requests.get(url)
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)
pook.off()

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

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

Development

Clone the repository:

.. code:: bash

git clone [email protected]:h2non/pook.git

Install dependencies:

.. code:: bash

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

Install Python dependencies:

.. code:: bash

make install

Lint code:

.. code:: bash

make lint

Run tests:

.. code:: bash

make test

Generate documentation:

.. code:: bash

make htmldocs

License

MIT - Tomas Aparicio

.. _Go: https://golang.org .. _Python: http://python.org .. _gock: https://github.com/h2non/gock .. _annotated API reference: http://pook.readthedocs.io/en/latest/api.html .. _#16: https://github.com/h2non/pook/issues/16 .. _examples: http://pook.readthedocs.io/en/latest/examples.html .. _aiohttp: https://github.com/KeepSafe/aiohttp .. _requests: http://docs.python-requests.org/en/master/ .. _urllib3: https://github.com/shazow/urllib3 .. _urllib: https://docs.python.org/3/library/urllib.html .. _http.client: https://docs.python.org/3/library/http.client.html .. _pycurl: http://pycurl.io .. _documentation: http://pook.readthedocs.io/en/latest/ .. _FAQ: http://pook.readthedocs.io/en/latest/faq.html .. _how it works: http://pook.readthedocs.io/en/latest/how_it_works.html .. _mocket: https://github.com/mindflayer/python-mocket

.. |Build Status| image:: https://travis-ci.org/h2non/pook.svg?branch=master :target: https://travis-ci.org/h2non/pook .. |PyPI| image:: https://img.shields.io/pypi/v/pook.svg?maxAge=2592000?style=flat-square :target: https://pypi.python.org/pypi/pook .. |Coverage Status| image:: https://coveralls.io/repos/github/h2non/pook/badge.svg?branch=master :target: https://coveralls.io/github/h2non/pook?branch=master .. |Documentation Status| image:: https://img.shields.io/badge/docs-latest-green.svg?style=flat :target: http://pook.readthedocs.io/en/latest/?badge=latest .. |Quality| image:: https://codeclimate.com/github/h2non/pook/badges/gpa.svg :target: https://codeclimate.com/github/h2non/pook :alt: Code Climate .. |Stability| image:: https://img.shields.io/pypi/status/pook.svg :target: https://pypi.python.org/pypi/pook :alt: Stability .. |Versions| image:: https://img.shields.io/pypi/pyversions/pook.svg :target: https://pypi.python.org/pypi/pook :alt: Python Versions

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].