API测试
- 作者仓库星标 0
- 作者更新于 实时读取
- 作者仓库 skills-registry
- 领域
- 设计与多媒体
- 兼容 Agent
-
- Claude Code
- Cursor
- Cline
- Codex
- Windsurf
- Gemini CLI
- +20
- 信任分
- 88 / 100 · 社区维护
- 作者 / 版本 / 许可
- @tomevault-io · 未声明 license
- Token 消耗评级
- 低消耗
- 接入复杂程度
- 需手动接入
- 是否需要外部 API Key
- 需要 · Vendor-specific
- 兼容的系统
- macOS · Linux · Windows
- 底层运行要求
- Node.js · Python
- 文件与系统权限
-
- 只读
- 允许写入 / 修改
- Shell 执行
- 网络行为
- 允许外网请求
- 安装命令数
- 26 条
档案由构建时根据 SKILL.md 与安装命令自动衍生,可能与作者实际意图存在差异。
需要注意: 未限定 allowed-tools,默认拥有全部工具权限。
---
name: pytest-api
description: When the user wants to design, implement, debug, or scale Python API tests using pytest + reques…
category: 设计与多媒体
runtime: Node.js / Python
---
# pytest-api 输出预览
## PART A: 任务判断
- 适用问题:视觉内容、演示材料、信息图或设计交付。
- 输入要求:目标材料、限制条件、期望输出和验收方式。
- 证据边界:围绕“Initial Assessment / Why pytest + requests/httpx / Test layout”读取原文规则,不把推断写成作者承诺。
## PART B: 执行结果
- **01** 任务判断:确认你的需求是否属于视觉内容、演示材料、信息图或设计交付,并标出输入、限制和预期结果。
- **02** 执行计划:优先按“Initial Assessment / Why pytest + requests/httpx / Test layout”拆成步骤,说明每一步会读取什么、修改什么、产出什么。
- **03** 交付结果:给出可复制的命令、文件改动、检查清单或内容草稿,并说明如何继续迭代。
- **04** 风险边界:结合 读取文件、写入/修改文件、执行终端命令、会按任务需要访问外部网络、需要准备 Vendor-specific API Key 给出执行前确认项。
## Running Rules
- 读取文件、写入/修改文件、执行终端命令;会按任务需要访问外部网络;需要准备 Vendor-specific API Key。
- 先小样例验证,再放大到真实任务。
- 交付时同时给结果、检查口径和下一步迭代建议。 原文没有稳定的斜杠命令要求。安装验证后通常全局生效,直接在对话里点名这个 Skill 并描述任务即可。
告诉 Agent 目标文件或材料、期望结果、不可改范围、是否允许联网或执行命令。本 Skill 的权限画像是:读取文件、写入/修改文件、执行终端命令。
先用一个小任务确认它会围绕“Initial Assessment / Why pytest + requests/httpx / Test layout”工作;涉及文件或命令时,先看 diff、日志、预览或测试结果。
检查最终产物是否包含明确结果、必要证据和下一步动作;如果输出泛泛而谈,就补充输入、边界和验收标准后重跑。
---
name: pytest-api
description: When the user wants to design, implement, debug, or scale Python API tests using pytest + reques…
category: 设计与多媒体
source: tomevault-io/skills-registry
---
# pytest-api
## 什么时候使用
- 用于组织测试、定位失败并形成修复闭环 适合处理界面、视觉、封面、信息图或演示材料交付,核心价值是把输入、判断、执行、验证和交付边界固定下来,避免 Agent 泛泛回答。 把任务拆成可执行、可检查、可继续迭代的步骤;使用前要准备 Vend…
- 面向视觉内容、演示材料、信息图或设计交付,优先处理能明确输入、步骤和验收标准的工作。
## 需要提供什么
- 目标材料、目录范围、期望结果和不可改动内容。
- 是否允许联网、执行命令、读写文件或调用外部服务。
## 执行规则
- 围绕「Initial Assessment / Why pytest + requests/httpx / Test layout」组织步骤,不把推断写成作者事实。
- 读取文件、写入/修改文件、执行终端命令;会按任务需要访问外部网络;需要准备 Vendor-specific API Key。
- 先跑小样例,确认结果可检查后再扩大任务范围。
## 输出要求
- 给出最终产物、关键证据、验证方式和下一步动作。
- 信息不足时标记 unknown,不编造命令、平台或依赖。 作者原文负责流程事实;仓库文件负责来源和命令;流狐只补充适用场景、限制和质量判断。
skill "pytest-api" {
输入层 -> 用户目标 + 目标文件 + 禁止范围 + 验收标准
上下文层 -> Initial Assessment / Why pytest + requests/httpx / Test layout
规则层 -> SKILL.md 触发条件 / 执行顺序 / 输出格式
运行层 -> Node.js / Python | 读取文件、写入/修改文件、执行终端命令 | 会按任务需要访问外部网络
安全层 -> 需要准备 Vendor-specific API Key + 小任务验证 + diff / 日志复核
输出层 -> 可复制结果 + 检查清单 + 下一步迭代
} pytest API Testing
You are an expert in API testing with Python + pytest + requests / httpx. Your goal is to help engineers write maintainable, fast pytest suites for REST (and JSON-RPC, gRPC-over-REST gateways, etc.) — without fabricating fixture signatures, library APIs, or pytest plugin names. When uncertain, point the reader to docs.pytest.org, docs.python-requests.org, or python-httpx.org.
Initial Assessment
Check .agents/qa-context.md (fallback: .claude/qa-context.md) before answering. Pay attention to:
- HTTP client —
requests(sync, by far the most common),httpx(sync + async), or the framework's test client (e.g., FastAPI'sTestClient, Django'sClient). - Sync vs async — if the system under test is async (FastAPI / Starlette / aiohttp),
httpx.AsyncClientis the natural fit. - Pytest plugins in use —
pytest-xdist(parallel),pytest-asyncio(async),pytest-httpx/responses(mocking),pytest-vcr(cassettes),schemathesis(property-based / OpenAPI-driven). - Auth model — Bearer / Basic / OAuth / cookies / mTLS. Affects fixture design.
- Target environment — local in-process (TestClient), local server (compose), or remote (staging URL).
If the file does not exist, ask: HTTP client choice, sync or async, in-process or against a server, target framework, and any pytest plugins already standardized.
Why pytest + requests/httpx
- First-class fixtures — declarative, scoped, composable. Setup once, reuse everywhere.
- Parametrization — boundary cases and data-driven tests are trivial (
@pytest.mark.parametrize). - Parallel execution —
pytest-xdistfor free CPU scaling. - Rich ecosystem — assertion plugins, reporters, OpenAPI integration, property-based testing via
hypothesis/schemathesis. - Pythonic — refactors, types (with mypy), IDE support all work.
When not to use pytest:
- Non-Python stack with no Python expertise → use the language-native option.
- Pure Postman/QA-led workflows → postman-newman.
Test layout
tests/
├── conftest.py # shared fixtures (auth, base url, http client)
├── conftest_helpers.py # non-fixture utilities (data builders, schema loaders)
├── api/
│ ├── conftest.py # api-scoped fixtures
│ ├── test_users.py
│ ├── test_orders.py
│ └── test_search.py
├── fixtures/
│ └── users.json
└── schemas/
└── user.schema.json
conftest.py is auto-discovered — fixtures defined there are available to tests in the same directory and below. Use the nearest conftest.py for the narrowest scope.
Core fixture patterns
Base URL and HTTP client
# conftest.py
import os
import pytest
import requests
@pytest.fixture(scope="session")
def base_url():
return os.environ.get("API_BASE_URL", "https://staging.example.com")
@pytest.fixture
def http(base_url):
session = requests.Session()
session.headers.update({"Accept": "application/json"})
session.hooks["response"] = [lambda r, *a, **kw: r.raise_for_status() if False else None]
yield session
session.close()
Auth
@pytest.fixture(scope="session")
def access_token(base_url):
resp = requests.post(
f"{base_url}/auth/login",
json={"email": os.environ["QA_USER"], "password": os.environ["QA_PASS"]},
)
resp.raise_for_status()
return resp.json()["token"]
@pytest.fixture
def authed(http, access_token):
http.headers["Authorization"] = f"Bearer {access_token}"
return http
Tests use def test_thing(authed, base_url): — the auth setup runs once per session.
Test data builders
def make_user(**overrides):
return {"email": "qa.user@example.com", "name": "QA User", "role": "viewer", **overrides}
Keep builders in a tests/_data.py (or similar) and import them. Avoid pytest.fixture for plain data — functions are simpler.
httpx for async
# conftest.py
import pytest
import httpx
@pytest.fixture
async def client(base_url):
async with httpx.AsyncClient(base_url=base_url, timeout=10.0) as c:
yield c
@pytest.mark.asyncio
async def test_get_user(client):
resp = await client.get("/users/user-42")
assert resp.status_code == 200
Requires pytest-asyncio (set asyncio_mode = "auto" in pytest.ini to drop the explicit marker on every async test).
In-process testing
For FastAPI / Starlette:
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
def test_health():
assert client.get("/health").status_code == 200
For Django REST: django.test.Client or rest_framework.test.APIClient. These skip the network entirely — faster, but miss network/TLS/container realism.
Mocking external HTTP
Two main libraries:
| Library | Use |
|---|---|
responses |
Mock requests calls. Decorator or context manager. |
respx |
Mock httpx calls. Same idea. |
pytest-httpx |
pytest plugin wrapper around httpx mocking. |
vcr.py (pytest-vcr) |
Record real responses to "cassettes," replay on subsequent runs. Useful for third-party APIs you can't mock easily. |
import responses
@responses.activate
def test_calls_billing():
responses.add(
responses.POST,
"https://billing.example.com/charge",
json={"id": "ch_123"},
status=201,
)
# ... code under test that calls billing.example.com
assert len(responses.calls) == 1
Use mocks for external dependencies. Don't mock your own API — test against it.
Schema validation
import json
import jsonschema
with open("tests/schemas/user.schema.json") as f:
USER_SCHEMA = json.load(f)
def test_user_shape(authed, base_url):
resp = authed.get(f"{base_url}/users/user-42")
assert resp.status_code == 200
jsonschema.validate(resp.json(), USER_SCHEMA)
For OpenAPI-driven projects, schemathesis generates property-based tests from your spec:
schemathesis run https://staging.example.com/openapi.json
This catches contract drift between the spec and the implementation. Pair with the OpenAPI spec living in the same repo.
Parametrization
import pytest
@pytest.mark.parametrize("email,expected", [
("qa.user@example.com", 200),
("invalid-email", 400),
("", 400),
("a" * 256 + "@example.com", 400),
])
def test_signup_email_validation(authed, base_url, email, expected):
resp = authed.post(f"{base_url}/users", json={"email": email})
assert resp.status_code == expected
For larger data sets, load from a JSON/CSV fixture and use pytest.mark.parametrize with pytest.param(..., id=...) for readable test IDs.
Running tests
| Command | Purpose |
|---|---|
pytest |
Run all tests. |
pytest tests/api/test_users.py |
One file. |
pytest -k "user and not slow" |
Filter by name expression. |
pytest -m smoke |
Run tests marked @pytest.mark.smoke. |
pytest -n auto |
Parallel via pytest-xdist (auto = CPU count). |
pytest --maxfail=5 |
Stop after N failures. |
pytest -x |
Stop on first failure. |
pytest --lf |
Last failed. |
pytest --ff |
Failed first, then the rest. |
pytest --junitxml=report.xml |
JUnit XML for CI. |
Verify flags with pytest --help against your installed version.
CI integration
- run: pip install -r requirements-dev.txt
- run: pytest -n auto --junitxml=report.xml --cov=src --cov-report=xml
- if: always()
uses: actions/upload-artifact@v4
with:
name: pytest-report
path: report.xml
For Allure: pytest --alluredir=allure-results, then publish with the Allure CLI.
Common Pitfalls
- Stuffing too much in fixtures — fixtures are great for setup, bad for orchestration. Don't build complex multi-call flows in a fixture if the test reads cleaner inline.
- Session-scoped state that should be function-scoped — a "logged-in user" fixture at session scope is fine; a "user with 5 orders" fixture at session scope leaks state between tests.
- Hardcoded URLs / tokens in tests — every URL comes from
base_url; every credential from env. time.sleepwaiting for async backend work — poll with backoff or expose a status endpoint.- Asserting
assert resp.status_code == 200 and 'foo' in resp.json()on one line — split for clearer failure messages. - Not using
requests.Session()— everyrequests.get(...)creates a new connection. Sessions share connection pools and headers. - Mixing
requestsandhttpxin the same suite without reason — pick one, stick with it. - Letting
raise_for_status()mask test intent — tests for error cases need to assert the error explicitly, not catch it. - No timeouts — every HTTP call should have a timeout. A hanging API will hang the test.
- Mocking your own API — kills coverage. Use mocks for external dependencies only.
Task-Specific Questions
When helping with pytest API testing, ask:
- HTTP client —
requests,httpx, or framework TestClient? - Sync or async — and is the SUT async?
- In-process (TestClient / mocked DB) or against a deployed server?
- Auth — Bearer, OAuth, cookie, mTLS?
- Pytest plugins standardized — xdist, asyncio, httpx/responses, vcr, allure, schemathesis?
- Is there an OpenAPI spec — can it drive schemathesis tests?
- CI parallelism —
-n autoper machine, or matrix split across machines?
Related Skills
- pytest — for general pytest fundamentals (fixtures, marks, parametrization).
- rest-assured — JVM equivalent.
- supertest — Node equivalent.
- postman-newman — when QA-led collections complement code tests.
- pact-contract-testing — Pact's Python implementation works alongside pytest.
- wiremock — for service virtualization that pytest tests can target.
- test-data-management — for factories, fixtures, and synthetic-data strategy.
- ci-test-orchestration — for pytest-xdist tuning and sharding strategy.
Source: aks-builds/quality-skills — distributed by TomeVault.
先判断是否适合
作者设计意图
作者的方法与取舍
边界和复核