vcrpy
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
- breaking vcrpy v8.0.0 dropped support for Python versions older than 3.10. Users on Python 3.9 or earlier will need to upgrade their Python environment.
- breaking vcrpy v8.0.0 dropped support for `urllib3` versions older than 2.0.0. This can cause compatibility issues if your project relies on an older `urllib3` version.
- breaking The `httpx` integration was significantly rewritten in v8.0.0 to patch `httpcore` directly. This change may require recreation of existing `httpx` cassettes and resolves issues like `httpx.ResponseNotRead` exceptions.
- breaking vcrpy v6.0.0 dropped support for the deprecated `boto` library. `boto3` remains fully supported.
- gotcha Cassettes recorded for `httpx` interactions in versions prior to v6.0.0 might be corrupted or incorrectly saved due to a binary format issue fix.
- gotcha Prior to v8.1.1, there were issues with handling synchronous HTTP requests (especially with `httpx`) when executed within an asynchronous context.
Install
-
pip install vcrpy -
pip install vcrpy[requests,aiohttp,httpx]
Imports
- VCR
from vcr import VCR
- use_cassette
import vcr @vcr.use_cassette('cassettes/my_cassette.yaml')
Quickstart
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')