Testland
Browse all skills & agents

tavern-testing

Authors Tavern API tests as YAML files (`test_*.tavern.yaml`) with `test_name` + `stages` + `request` + `response` blocks, runs them through the Tavern pytest plugin (auto-discovered), and gates CI on the resulting JUnit XML. Covers RESTful, MQTT, and gRPC variants. Use when the project runs on pytest and prefers YAML over a Python- or Java-DSL; on the JVM use karate-testing or restassured-testing instead, and for schema-driven property-based fuzzing on the same pytest stack use schemathesis-fuzzing.

Install with skills.sh (any agent)

npx skills add testland/qa --skill tavern-testing
View source

tavern-testing

Overview

Tavern is "a pytest plugin, command-line tool, and Python library for automated testing of APIs, with a simple, concise, and flexible YAML-based syntax" (tavern-docs (opens in new window)). Tests live in test_*.tavern.yaml files and are picked up automatically by pytest's discovery mechanism.

The integration shape: write YAML, run pytest, read JUnit XML. Tavern adds zero Python code to the test surface - the YAML IS the test. This is the closest thing to "code-less" API testing in the Python ecosystem.

When to use

  • The project's primary test runner is pytest (Python) and the team wants API tests in the same harness as unit tests.
  • The team prefers YAML over a fluent DSL - tests are reviewed by non-engineers (PMs, support engineers).
  • The API surface includes non-HTTP protocols (MQTT, gRPC) - Tavern has first-party support for both.
  • A pytest project already has fixtures (database setup, auth tokens) that the API tests should reuse.

If the team is already deep in REST Assured or Karate, switching to Tavern is rarely worthwhile. If the team is on Node, use postman-collections instead.

Install

pip install tavern[pytest]

(Per tavern-docs (opens in new window).)

For richer matchers, the optional extras include tavern[mqtt], tavern[grpc], and tavern[mocking]. Install only what the project needs.

File shape

tests/api/test_orders.tavern.yaml:

---
test_name: Get an order returns the expected fields

stages:
  - name: Authenticate
    request:
      url: https://staging.example.com/auth/login
      method: POST
      json:
        username: !env STAGING_USER
        password: !env STAGING_PASS
    response:
      status_code: 200
      save:
        json:
          access_token: access_token

  - name: Fetch order 42
    request:
      url: https://staging.example.com/orders/42
      method: GET
      headers:
        Authorization: 'Bearer {access_token}'
    response:
      status_code: 200
      json:
        order_id: 42
        status: !anything
        items:
          - sku: !anystr
            qty: !anyint

(Adapted from tavern-docs (opens in new window).)

Per tavern-docs (opens in new window):

  • File name pattern: test_*.tavern.yaml. Pytest auto-discovers.
  • Each YAML doc (--- separated) is one test.
  • test_name is the visible test title in pytest output.
  • stages: is an ordered list; each stage is one HTTP request + response check.

Request block

Each stage's request: accepts:

FieldPurpose
urlFull URL or path (combine with a tavern-global-config.yaml for base URL).
methodGET, POST, PUT, DELETE, PATCH.
headersMap of request headers; values can interpolate from saved variables.
paramsQuery parameters (auto-encoded).
jsonJSON body (preferred over data when the API expects JSON).
dataForm-encoded body or raw string body.
filesMultipart upload.
authTuple form for HTTP Basic; OAuth via custom strategies.

Variable interpolation uses Python's str.format style: '{access_token}'.

Response block

Each stage's response: accepts:

FieldPurpose
status_codeInteger or list of acceptable codes ([200, 201]).
headersMap of expected header values; supports regex with !re_match.
jsonMap of expected body shape; supports built-in matchers.
saveMap declaring values to capture for use in later stages.
verify_response_withList of custom validator function dotted paths.
redirect_query_paramsFor redirect-flow tests.

Built-in matchers

Per tavern-docs (opens in new window):

MatcherMeaning
!anythingAny value (presence-only check).
!anystrAny string.
!anyintAny integer.
!anyfloatAny float.
!anyboolAny boolean.
!anylistAny list.
!anydictAny dict.
!re_matchRegex match: !re_match '^[A-Z]{3}-\\d+$'.
!re_searchRegex search anywhere in the string.
!re_fullmatchRegex full match.

Variable saving

The save: block captures values for later stages. Two common forms:

response:
  status_code: 200
  save:
    json:
      # Save response.json()['access_token'] as variable `access_token`
      access_token: access_token
    headers:
      # Save the Location header as variable `created_url`
      created_url: location

Saved variables are interpolated in subsequent stages with '{access_token}'.

Authentication

For OAuth2 / token-based auth, the canonical pattern is a two-stage test where the first stage authenticates and save:s the token, the second stage uses it (see the worked example above).

For HTTP Basic Auth:

request:
  url: ...
  method: GET
  auth:
    - !env API_USER
    - !env API_PASS

For API key in header:

request:
  url: ...
  headers:
    X-API-KEY: !env API_KEY

!env VAR resolves the env var at run time; never put secrets in the YAML directly.

Global config

For shared base URLs, default headers, or strict-checking flags, create tavern-global-config.yaml:

variables:
  base_url: https://staging.example.com
  default_timeout: 5
strict:
  - json:on

Reference variables in any YAML test file: url: '{base_url}/orders/42'.

Running

# Run every Tavern YAML file
pytest tests/api/

# Run a specific YAML file
pytest tests/api/test_orders.tavern.yaml

# Run with verbose output (helpful for debugging stage failures)
pytest -v tests/api/

# Generate JUnit XML for CI ingestion
pytest tests/api/ --junitxml=results.xml

(Per tavern-docs (opens in new window).)

CI integration

# .github/workflows/api-tests.yml
name: api-tests

on:
  pull_request:
  push:
    branches: [main]

jobs:
  tavern:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5

      - uses: actions/setup-python@v5
        with:
          python-version: '3.12'

      - name: Install
        run: pip install -r requirements-test.txt   # contains 'tavern[pytest]'

      - name: Run Tavern suite
        env:
          STAGING_USER: ${{ secrets.STAGING_USER }}
          STAGING_PASS: ${{ secrets.STAGING_PASS }}
          API_KEY:      ${{ secrets.API_KEY }}
        run: |
          pytest tests/api/ \
            --junitxml=results.xml \
            --tavern-global-cfg=tavern-global-config.yaml

      - name: Upload report
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: tavern-reports
          path: results.xml
          retention-days: 14

      - name: Surface JUnit results
        if: always()
        uses: dorny/test-reporter@v1
        with:
          name: Tavern API tests
          path: results.xml
          reporter: java-junit

Anti-patterns

Anti-patternWhy it failsFix
Embedding tokens / secrets in the YAMLLeaks into git; rotation pain.Use !env VAR for everything secret.
Hard-coded base URLs in every testTests bind to one environment.Use tavern-global-config.yaml variables.base_url.
One mega-stage list (15+ stages per test)Failure mid-list halts everything; no per-stage isolation.Split into multiple test_name blocks; each test owns its own auth → action → assert chain.
Using !anything everywhere instead of typed matchers!anything accepts null / wrong type - defeats the assertion.Use !anystr, !anyint, !re_match to constrain.
Skipping --tavern-global-cfg in CIVariable interpolation fails silently; tests hit the wrong env.Always pass --tavern-global-cfg=<file> so the project's defaults apply.
Mixing Tavern YAML with Python pytest cases without separationFailure attribution is confusing; output volume mixes formats.Keep Tavern YAML under tests/api/ and pure Python tests under tests/unit/.

Limitations

  • Pytest-only. No standalone runner; the YAML files don't run outside pytest's discovery.
  • Limited dynamic logic. Tavern is intentionally declarative; for branching, retries, or computed expectations, drop into a pytest fixture or a custom validator referenced via verify_response_with.
  • Schema validation needs an extra dependency. For JSON Schema enforcement, install a separate matcher; built-in matchers cover shape but not full schema constraints.
  • Variable interpolation can mask null bugs. A typo in '{accest_token}' (missing s) won't error - the literal string goes through. Watch for these in code review.

References

  • tavern-docs (opens in new window) - canonical reference: install, file shape, request / response / save / matchers, pytest integration, global config.
  • postman-collections - Node-stack alternative.
  • restassured-testing - Java fluent-DSL alternative.
  • schemathesis-fuzzing - Python-stack property-based fuzzing complement to Tavern's example-based tests.

Related skills

api-chaos-runner

Runs the project's existing API tests under injected network chaos - latency, timeouts, dropped connections, bandwidth caps, packet loss - via Toxiproxy (notes on Pumba / Gremlin / LitmusChaos). Builds a per-scenario chaos matrix and reports which assertions break under which conditions, verifying resilience patterns (retry, circuit-breaker, timeout, fallback). Unlike schemathesis-fuzzing and restler-fuzzing, which generate new tests from a schema, this drives your EXISTING example-based suite.

api-testing-overview

Teaches API testing from zero: what functional API testing covers, how it differs from contract testing and load testing, and a decision table that picks one tool from observable project facts (language and build file, whether an OpenAPI or GraphQL schema exists, functional vs spec-conformance fuzzing vs stateful security fuzzing, whether non-engineers read the tests). Names the real options (Postman with newman, REST Assured, Karate, Tavern, Schemathesis, RESTler), gives install and first-run commands with what a passing run looks like, and the traps that bite first: asserting only on HTTP status, order-dependent tests sharing server state, and hardcoded environment URLs and secrets. Use when an HTTP API needs automated tests and no tool has been chosen, or when an inherited suite only checks status codes.

karate-testing

Authors Karate `.feature` files using its Gherkin-flavored DSL for HTTP API tests, leverages the `match` keyword with fuzzy validators (#number / #string / #regex / contains / arrays), runs the suite via JUnit 5 plus Maven Surefire, and produces JUnit XML for CI gating. Use when the project is on the JVM and prefers a feature-file authoring flow over Java-DSL fluent chains; for those fluent chains use restassured-testing, for the same YAML-style flow on a Python/pytest stack use tavern-testing.

postman-collections

Authors Postman collections (requests + tests + variables + environments), runs them headless via the Newman CLI, configures reporters (cli / json / junit / html) for CI artifact upload, and uses iteration data files (JSON / CSV) for data-driven runs. Use when the project ships HTTP API tests authored in Postman and the team needs CI execution alongside or instead of the Postman desktop runner.

restassured-testing

Authors REST Assured (Java) API tests using the given().when().then() BDD-style DSL - status code + JSON/XML path assertions + authentication (Basic, OAuth2, API key). Configures Maven / Gradle dependencies, runs via JUnit 5, and emits Surefire / JaCoCo reports for CI gating. Use when the project is on the JVM and wants type-safe API tests in the app's own language; for a Gherkin feature-file flow on the same JVM use karate-testing, for YAML tests on the pytest stack use tavern-testing.

restler-fuzzing

Runs stateful REST API fuzzing using Microsoft's RESTler - infers producer-consumer dependencies from an OpenAPI spec, drives sequences of requests (POST → GET → DELETE chains), and reports 5xx errors, resource leaks, and hierarchy violations. Wraps the canonical 4-stage workflow (compile → test → fuzz-lean → fuzz). Use when the API is stateful (resources are created, queried, modified, deleted) and Schemathesis's stateless fuzzing is missing the multi-step bugs.

schemathesis-fuzzing

Generates property-based API tests automatically from an OpenAPI 2/3.x or GraphQL schema using Schemathesis, runs them via the `schemathesis run` CLI or as a pytest decorator, configures the canonical checks (status_code_conformance, response_schema_conformance, content_type_conformance, response_headers_conformance, not_a_server_error), and gates CI on schema-conformance failures plus 5xx detection. Use when the project ships an OpenAPI or GraphQL schema and the team wants schema-driven coverage that scales as the API evolves.