pytest-recording

0.13.4 · active · verified Fri Apr 10

pytest-recording is a pytest plugin that integrates VCR.py to record and replay HTTP traffic during tests. It aims to make testing code that interacts with external services faster and more reliable by preventing unnecessary network requests. The library uses VCR.py's 'none' recording mode by default to avoid unintentional live network calls. The current version is 0.13.4, and it maintains an active release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up `pytest-recording` to record and replay HTTP requests using the `@pytest.mark.vcr` decorator. It includes a `vcr_config` fixture, typically placed in a `conftest.py` file or at the top of a test module, to apply global VCR.py configurations like filtering sensitive headers. To run these tests and record the network interactions, use `pytest --record-mode=once your_test_file.py`. The `--record-mode=once` argument is crucial for the initial recording, as `pytest-recording` defaults to `none` mode to prevent accidental network requests. Subsequent runs without this flag will replay from the cassette.

import pytest
import requests
import os

# Define a vcr_config fixture in conftest.py or test file scope
@pytest.fixture(scope="module")
def vcr_config():
    """
    Global VCR.py configuration for all tests in this module/session.
    Filters out sensitive Authorization headers to prevent them from being written to cassettes.
    """
    return {"filter_headers": ["Authorization"], "ignore_localhost": True}

@pytest.mark.vcr
def test_http_get_request():
    """
    Records a simple HTTP GET request to httpbin.org.
    The cassette will be saved in a default location, e.g., cassettes/{module_name}/test_http_get_request.yaml.
    """
    response = requests.get("http://httpbin.org/get")
    assert response.status_code == 200
    assert response.json()["url"] == "http://httpbin.org/get"

@pytest.mark.vcr
def test_authenticated_api_call():
    """
    Demonstrates recording an API call with an Authorization header.
    The header is filtered by the vcr_config fixture defined above.
    """
    # Simulate retrieving an API key from environment variables
    api_key = os.environ.get('PYTEST_TEST_API_KEY', 'fake_api_key_123')
    headers = {"Authorization": f"Bearer {api_key}"}
    response = requests.get("http://httpbin.org/headers", headers=headers)
    assert response.status_code == 200
    # Verify that the Authorization header is not in the recorded response (due to filtering)
    assert "Authorization" not in response.json().get("headers", {})
    assert "fake_api_key_123" not in str(response.json()) # Ensure actual key content not present

view raw JSON →