Python API
CoverageMap
CoverageMap
Tracks API test coverage against an OpenAPI specification.
from_dict
from_dict(schema, *, base_path=None, location=None)
Create a coverage map from a parsed OpenAPI specification.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schema |
dict |
Parsed OpenAPI specification | required |
base_path |
str | None |
Base path prefix for all operations | None |
location |
str | None |
File path or URL shown in error messages | None |
Example
import tracecov
# From a dictionary (e.g., loaded from a file or API response)
schema = {"openapi": "3.0.0", "info": {"title": "API", "version": "1.0"}, "paths": {}}
coverage = tracecov.CoverageMap.from_dict(schema)
# With base path for APIs hosted under a prefix
coverage = tracecov.CoverageMap.from_dict(schema, base_path="/api/v1")
Tip
To load a schema from a URL, use from_url() instead.
from_path
from_path(path, *, base_path=None)
Create a coverage map from an OpenAPI specification file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path |
str | Path |
Path to OpenAPI specification (JSON or YAML) | required |
base_path |
str | None |
Base path prefix for all operations | None |
Example
import tracecov
coverage = tracecov.CoverageMap.from_path("openapi.json")
coverage = tracecov.CoverageMap.from_path("openapi.yaml", base_path="/api/v1")
from_url
from_url(url, *, base_path=None)
Create a coverage map from an OpenAPI specification URL.
Fetches the schema from the given URL and parses it as JSON or YAML.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url |
str |
URL to fetch the OpenAPI specification from | required |
base_path |
str | None |
Base path prefix for all operations | None |
Example
import tracecov
coverage = tracecov.CoverageMap.from_url("https://api.example.com/openapi.json")
coverage = tracecov.CoverageMap.from_url(
"https://api.example.com/openapi.yaml",
base_path="/api/v1"
)
record
record(request, response=None, timestamp=None)
Record an HTTP interaction for coverage tracking.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request |
HttpRequest |
Request to record | required |
response |
HttpResponse | None |
Response to record | None |
timestamp |
float | None |
Unix timestamp of the interaction | None |
Example
from tracecov import HttpRequest, HttpResponse
coverage.record(
request=HttpRequest(
method="GET",
url="https://api.example.com/users/1",
body=None,
headers={"Authorization": "Bearer token"}
),
response=HttpResponse(status_code=200, elapsed=0.5)
)
generate_report
generate_report(*, format="html", title=None)
Generate a coverage report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
format |
str |
Output format: "html" or "json" |
"html" |
title |
str | None |
Custom title for HTML reports | None |
Returns: Report content as a string. See JSON Report Format for JSON schema and usage.
Example
# HTML report
html = coverage.generate_report(title="My API Coverage")
# JSON report for CI integration
import json
data = json.loads(coverage.generate_report(format="json"))
if data["summary"]["operations"]["percent"] < 80:
raise SystemExit("Coverage below threshold")
save_report
save_report(*, output_file=None, format="html", title=None)
Save a coverage report to a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_file |
str | None |
Output path (coverage.html or coverage.json by default) |
None |
format |
str |
Output format: "html" or "json" |
"html" |
title |
str | None |
Custom title for HTML reports | None |
Example
coverage.save_report() # saves to coverage.html
coverage.save_report(output_file="report.html", title="API Coverage")
coverage.save_report(format="json") # saves to coverage.json
generate_text_report
generate_text_report(*, width, colored=True, skip_covered=False, skip_empty=False, show_missing=None)
Generate a text coverage report for terminal output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
width |
int |
Terminal width for formatting | required |
colored |
bool |
Use ANSI colors in output | True |
skip_covered |
bool |
Hide fully covered items | False |
skip_empty |
bool |
Hide items with no traffic | False |
show_missing |
list[str] | None |
Items to show in missing column | None |
Returns: Formatted text report as a string.
Example
report = coverage.generate_text_report(width=120)
print(report)
# Compact view without fully covered items
report = coverage.generate_text_report(width=80, skip_covered=True)
statistic
statistic()
Get aggregate coverage statistics.
Returns: Dictionary with keys:
operations-{"seen": int, "total": int}parameters-{"seen": int, "total": int}keywords-{"partial": int, "full": int, "total": int}
Example
stats = coverage.statistic()
print(f"Operations: {stats['operations']['seen']}/{stats['operations']['total']}")
print(f"Keywords: {stats['keywords']['partial']}/{stats['keywords']['total']}")
uncovered_keywords
uncovered_keywords()
Get a list of keywords without full coverage.
Returns: List of dictionaries with keys:
method- HTTP methodpath- API pathlocation- Parameter location (query, header, path, cookie, body)parameter- Parameter nameschema_path- JSON pointer to the keyword in the schemastate- What coverage is missing ("valid"or"invalid")satisfiability- Satisfiability constraint ("Normal","Positive", or"Negative")
Example
uncovered = coverage.uncovered_keywords()
for entry in uncovered:
print(f"{entry['method']} {entry['path']} - {entry['parameter']}: needs {entry['state']}")
requests
requests
Integration for the requests library.
Returns: RequestsPlugin instance.
httpx
httpx
Integration for the httpx library.
Returns: HttpxPlugin instance.
postman
postman
Import traffic from Postman Collections (Professional).
Returns: PostmanPlugin instance.
har
har
Import traffic from HAR files (Professional).
Returns: HarPlugin instance.
vcr
vcr
Import traffic from VCR cassettes.
Returns: VcrPlugin instance.
django
django
Integration for Django test clients.
Returns: DjangoPlugin instance.
flask
flask
Integration for Flask test clients.
Returns: FlaskPlugin instance.
RequestsPlugin
RequestsPlugin
Integration for the requests library.
track_session
track_session(session)
Attach coverage tracking to a requests Session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session |
requests.Session |
required |
Returns: The same session with coverage tracking enabled.
Example
import requests
session = coverage.requests.track_session(requests.Session())
response = session.get("https://api.example.com/users")
record
record(request, response=None, timestamp=None)
Record a request/response pair.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request |
requests.Request |
required | |
response |
requests.Response | None |
None |
|
timestamp |
float | None |
Unix timestamp of the interaction | None |
Example
response = requests.get("https://api.example.com/users")
coverage.requests.record(request=response.request, response=response)
response_hook
response_hook()
Create a response hook for manual session configuration.
Returns: A ResponseHook callable.
Example
hook = coverage.requests.response_hook()
response = requests.get(
"https://api.example.com/users",
hooks={"response": [hook]}
)
HttpxPlugin
HttpxPlugin
Integration for the httpx library.
track_client
track_client(client)
Attach coverage tracking to an httpx Client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client |
httpx.Client | httpx.AsyncClient |
required |
Returns: The same client with coverage tracking enabled.
Example
import httpx
# Synchronous
client = coverage.httpx.track_client(httpx.Client())
response = client.get("https://api.example.com/users")
# Asynchronous
async_client = coverage.httpx.track_client(httpx.AsyncClient())
response = await async_client.get("https://api.example.com/users")
record
record(request, response=None, timestamp=None)
Record a request/response pair.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request |
httpx.Request |
required | |
response |
httpx.Response | None |
None |
|
timestamp |
float | None |
Unix timestamp of the interaction | None |
response_hook
response_hook()
Create a synchronous response hook.
Returns: A SyncResponseHook callable.
async_response_hook
async_response_hook()
Create an asynchronous response hook.
Returns: An AsyncResponseHook callable.
PostmanPlugin
PostmanPlugin
Import traffic from Postman Collections (Professional).
record_from_path
record_from_path(path)
Import traffic from a Postman Collection file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path |
str | Path |
Path to Postman Collection JSON | required |
Example
coverage.postman.record_from_path("collection.json")
record_from_dict
record_from_dict(data)
Import traffic from a parsed Postman Collection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data |
dict |
Postman Collection as dictionary | required |
Supported formats: Postman Collection v1.0, v2.0, v2.1
HarPlugin
HarPlugin
Import traffic from HAR files (Professional).
record_from_path
record_from_path(path)
Import traffic from a HAR file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path |
str | Path |
Path to HAR file | required |
Example
coverage.har.record_from_path("traffic.har")
record_from_dict
record_from_dict(archive)
Import traffic from a parsed HAR archive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
archive |
dict |
HAR archive as dictionary | required |
Supported formats: HAR v1.2, v1.3 from Chrome, Firefox, Edge, Postman.
VcrPlugin
VcrPlugin
Import traffic from VCR cassettes.
record_from_path
record_from_path(path)
Import traffic from a VCR cassette file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path |
str | Path |
Path to VCR cassette (YAML/JSON) | required |
record_from_dict
record_from_dict(cassette)
Import traffic from a parsed VCR cassette.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cassette |
dict |
VCR cassette as dictionary | required |
Supported formats: Ruby VCR, Schemathesis cassettes.
DjangoPlugin
DjangoPlugin
Integration for Django test clients.
track_client
track_client(client)
Attach coverage tracking to a Django test client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client |
django.test.Client | rest_framework.test.APIClient |
Django or DRF test client | required |
Returns: The same client with coverage tracking enabled.
Example
from django.test import Client
client = coverage.django.track_client(Client())
response = client.get("/api/users/")
record
record(request, response=None, timestamp=None, elapsed=None)
Record a Django request/response pair.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request |
HttpRequest |
Django request object | required |
response |
HttpResponse | None |
Django response object | None |
timestamp |
float | None |
Unix timestamp of the interaction | None |
elapsed |
float | None |
Response time in seconds | None |
FlaskPlugin
FlaskPlugin
Integration for Flask test clients.
track_client
track_client(client)
Attach coverage tracking to a Flask test client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client |
flask.testing.FlaskClient |
Flask test client | required |
Returns: The same client with coverage tracking enabled.
Example
from flask import Flask
app = Flask("myapp")
client = coverage.flask.track_client(app.test_client())
response = client.get("/api/users/")
record
record(request, response=None, timestamp=None, elapsed=None)
Record a Flask request/response pair.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request |
Request |
Flask/Werkzeug request object | required |
response |
Response | None |
Flask/Werkzeug response object | None |
timestamp |
float | None |
Unix timestamp of the interaction | None |
elapsed |
float | None |
Response time in seconds | None |
Low-Level Types
HttpRequest
HttpRequest(method, url, body=None, headers=None)
HTTP request for coverage tracking.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method |
str |
HTTP method (GET, POST, etc.) | required |
url |
str |
Full URL including query parameters | required |
body |
bytes | None |
Request body | None |
headers |
dict | None |
Request headers | None |
HttpResponse
HttpResponse(status_code, elapsed)
HTTP response for coverage tracking.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
status_code |
int |
HTTP status code | required |
elapsed |
float |
Response time in seconds | required |