Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

vcrpy

БесплатноБез исполняемых скриптовНе проверен

VCR.py records the HTTP calls a Python test makes into a cassette file and replays them on later runs, so tests that depend on third-party APIs become fast…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Об этом скилле

VCR.py — record and replay HTTP in Python tests

Overview

VCR.py wraps the HTTP client libraries a Python program uses. The first time a test runs inside a cassette, VCR lets the real request through and writes the request and response to a YAML file (the cassette). On later runs it answers matching requests from that file and makes no network call. Tests keep passing offline or when the vendor is down, run in milliseconds, and the cassette in git documents exactly what the API returned.

The pytest plugin pytest-recording adds a @pytest.mark.vcr marker, command-line record modes and network blocking, and is the integration the VCR.py docs recommend. The older pytest-vcr is no longer maintained.

Instructions

Install

python -m venv .venv && . .venv/bin/activate
pip install vcrpy pytest pytest-recording requests

Use a cassette directly

import requests
import vcr

with vcr.use_cassette("tests/cassettes/rates.yaml"):
    resp = requests.get("https://api.ratesdb.io/latest", params={"base": "EUR"})

@vcr.use_cassette("tests/cassettes/rates.yaml")   # decorator form
def test_rates():
    ...

With the decorator you may omit the path; the cassette is then named after the test function and stored next to the test file. Inside the context manager as cass gives access to cass.requests, cass.responses, len(cass) and cass.play_count, useful for asserting that the code made exactly the calls you expect.

Record modes

Mode Behaviour
once (VCR.py default) Replay a cassette that exists; record if the file does not exist; raise on any request not in an existing cassette
new_episodes Replay what matches, record anything new and append it
none Replay only; any unmatched request raises CannotOverwriteExistingCassetteException
all Ignore the stored responses, hit the network and record again (use to refresh)

Set it per cassette (vcr.use_cassette(path, record_mode="none")) or for a configured vcr.VCR(...) object. Use none in CI so a test can never reach the network by accident.

pytest with pytest-recording

import pytest

@pytest.mark.vcr
def test_fetch_rate():
    ...

The cassette is written to cassettes/test_invoices/test_total_converted_to_usd.yaml for that test in test_invoices.py next to the test file. Run with the mode on the command line:

pytest --record-mode=once tests/        # first run: record missing cassettes
pytest tests/                           # default mode is "none": replay only, fail on a new request
pytest --record-mode=rewrite tests/     # rebuild cassettes from scratch (re-record stale ones)
pytest --block-network tests/           # also block sockets for tests without a cassette
pytest --disable-recording tests/       # turn the plugin off, talk to the real service

--record-mode accepts once, new_episodes, none, all and rewrite. rewrite replaces the default cassette instead of extending it (as all does). Allow specific hosts under --block-network with --allowed-hosts=localhost,api.ratesdb.io (regexes, comma-separated) or @pytest.mark.block_network(allowed_hosts=[...]). Use @pytest.mark.default_cassette("rates.yaml") to share one cassette name, and @pytest.mark.vcr("a.yaml", "b.yaml") to load several.

Shared configuration goes in a vcr_config fixture; any vcr.VCR keyword works:

# tests/conftest.py
import pytest

@pytest.fixture(scope="module")
def vcr_config():
    return {
        "filter_headers": [("authorization", "DUMMY")],
        "filter_query_parameters": ["api_key"],
        "filter_post_data_parameters": ["client_secret"],
        "ignore_hosts": ["localhost"],
    }

Marker arguments override the fixture for one test: @pytest.mark.vcr(filter_query_parameters=["token"]).

Keep secrets out of cassettes

Cassettes are committed, so scrub them at record time. Filters are applied before the file is written and also before matching.

  • filter_headers=["authorization", "x-api-key"] removes the header; [("authorization", "DUMMY")] replaces its value; a callable (key, value, request) computes one.
  • filter_query_parameters=["api_key"] and filter_post_data_parameters=["client_secret"] do the same for the query string and form bodies.
  • before_record_request=fn and before_record_response=fn take a request or response, may mutate it, and return None to drop the interaction entirely (for example a login call).
  • Response bodies are not filtered by the option lists above. If a response contains tokens or personal data, scrub it in before_record_response.

After recording, always check the files: grep -rniE "bearer|api[_-]?key|token" tests/cassettes.

Control request matching

By default a request replays when method, scheme, host, port, path and query match. Change it with match_on, from method, uri, scheme, host, port, path, query, body, raw_body, `head

Полный SKILL.md на GitHub

Установить vcrpy в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл vcrpy?

VCR.py records the HTTP calls a Python test makes into a cassette file and replays them on later runs, so tests that depend on third-party APIs become fast, offline and deterministic. Use when the user asks to stop tests hitting a real API, record or replay HTTP in pytest, fix flaky network tests, keep API keys out of recorded fixtures, re-record stale cassettes, or says "vcr", "vcrpy", "cassette", "pytest-recording".

Как установить скилл vcrpy?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл vcrpy запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить vcrpy с