pook - HTTP traffic mocking

2.1.6 · active · verified Thu Apr 16

pook is an HTTP traffic mocking library for Python, enabling easy setup of expectations and interception of requests from popular HTTP clients like `requests`, `httpx`, and `aiohttp`. It supports various matching criteria for requests and provides flexible response definitions. The current version is 2.1.6, and it typically sees several patch releases per major version, though releases can sometimes be delayed.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to mock an HTTP GET request using `pook` with the `requests` library. It sets up an expectation for a specific URL, activates the mock, makes the request, and then asserts the mocked response. Remember to deactivate and flush mocks to prevent state leakage between tests.

import pook
import requests
import os

# Configure a mock for a GET request
pook.get('https://api.example.com/data', reply=200, response_json={'status': 'ok', 'data': [1, 2, 3]})

# Activate pook (can also use @pook.on decorator or with pook.use():)
pook.activate()

try:
    # Make a request using requests, which pook will intercept
    response = requests.get('https://api.example.com/data')

    print(f"Status Code: {response.status_code}")
    print(f"Response JSON: {response.json()}")

    assert response.status_code == 200
    assert response.json() == {'status': 'ok', 'data': [1, 2, 3]}

finally:
    # Always deactivate pook and clear mocks to avoid leakage
    pook.off()
    pook.flush()

view raw JSON →