vcrpy

8.1.1 · active · verified Thu Apr 09

vcrpy (version 8.1.1) is a Python library that automatically mocks your HTTP interactions, making tests faster and more reliable by 'recording' network requests and 'replaying' them from a local file (a 'cassette'). It supports various HTTP libraries like `requests`, `aiohttp`, and `httpx`. The library maintains an active development pace with frequent updates and bug fixes, typically releasing new versions every few months.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `vcrpy` as a context manager with `requests` to record and replay HTTP interactions. The `vcr.VCR()` object is configured to store cassettes in a specified directory. The first run will make a real network request and save it; subsequent runs with the same cassette name will replay the recorded response, speeding up tests and isolating them from network fluctuations.

import vcr
import requests

def fetch_data():
    # Simulate an external API call
    response = requests.get('http://worldtimeapi.org/api/timezone/America/New_York')
    response.raise_for_status()
    return response.json()

# Configure VCR to store cassettes in a specific directory
my_vcr = vcr.VCR(cassette_library_dir='fixtures/vcr_cassettes')

# Use VCR as a context manager to record/replay HTTP interactions
with my_vcr.use_cassette('timezone_ny.yaml'):
    print("Fetching data with VCR...")
    data = fetch_data()
    print(f"Current time: {data['datetime']}")

# The next time this runs, it will use the recorded cassette if present.
print("Fetching data again (should be from cassette if run previously)...")
with my_vcr.use_cassette('timezone_ny.yaml'):
    data = fetch_data()
    print(f"Replayed time: {data['datetime']}")

# Example of clearing a created directory for clean runs (optional)
import os
import shutil
if os.path.exists('fixtures'):
    print("Cleaning up 'fixtures' directory.")
    shutil.rmtree('fixtures')

view raw JSON →