Python Testing
Python 测试速查。当需要:(1) 运行 pytest 测试 (2) 使用 mock/patch (3) 参数化测试 (4) fixtures (5) 异步测试 (6) 覆盖率测试时使用。 Skill: Python Testing Owner: afine907 Summary: Python 测试速查。当需要:(1) 运行 pytest 测试 (2) 使用 mock/patch (3) 参数化测试 (4) fixtures (5) 异步测试 (6) 覆盖率测试时使用。 Tags: latest:1.0.0 Version history: v1.0.0 | 2026-05-15T04:11:51.231Z | user Initial release Archive index: Archive v1.0.0: 8 files, 6584 bytes Files: references/async.md (1091b), references/coverage.md (830b), references/fixtures.md (1651b), references/mocking.md (2434b), re
Rank
62
Safety
84
Downloads
1.1k
Updated
Oct 11, 2026
Version
1.0.0
Source
CLAWHUB
About
What it does, and when to use it.
Capability contract not published. No trust telemetry is available yet. 1.1K downloads reported by the source. Last updated 10/11/2026.
Avoid when
- Contract metadata is missing or unavailable for deterministic execution.
Risk flags: missing_or_unavailable_contract, trust_data_unavailable, schema_references_missing
Public facts
Every fact links back to the source it came from.
- Vendor
- Clawhubvendor · observed Oct 11, 2026
- Protocol compatibility
- OpenClawcompatibility · observed Oct 11, 2026
- Adoption signal
- 1.1K downloadsadoption · observed Oct 11, 2026
- Latest release
- 1.0.0release · observed May 15, 2026
- Handshake status
- UNKNOWNsecurity
Install and run
Setup complexity: low.
clawhub skill install s17fm1dbahvthhc4atzm70t6v585c74c:python-testing- Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.
- Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data.
Contract: missing
curl -s "https://www.xpersona.co/api/v1/agents/clawhub-afine907-python-testing/snapshot"
Documentation
CLAWHUB
12,373 characters of source documentation, loaded on request.
Extracted files
5 files captured from the source.
SKILL.md
---
name: python-testing
description: Python 测试速查。当需要:(1) 运行 pytest 测试 (2) 使用 mock/patch (3) 参数化测试 (4) fixtures (5) 异步测试 (6) 覆盖率测试时使用。
---
# Python Testing
Python 测试框架核心用法速查。
## 快速参考
### pytest 基础
```bash
pytest # 运行所有测试
pytest -v # 详细输出
pytest test_module.py # 指定文件
pytest -k "login" # 匹配测试名
pytest -x # 失败时停止
pytest -n 4 # 并行执行
```
### 测试示例
```python
def test_addition():
assert 1 + 1 == 2
@pytest.mark.parametrize("a,b,expected", [(1,2,3), (2,3,5)])
def test_add(a, b, expected):
assert add(a, b) == expected
```
### Mock
```python
from unittest.mock import Mock, patch
mock_db = Mock()
mock_db.query.return_value = []
@patch('module.function')
def test_with_mock(mock_func):
mock_func.return_value = 42
```
### Fixture
```python
@pytest.fixture
def database():
db = Database(":memory:")
yield db
db.close()
def test_query(database):
assert database.query("SELECT 1")
```
### 覆盖率
```bash
pytest --cov=myapp
pytest --cov=myapp --cov-report=html
```
## 详细参考
- **pytest 详解**: [references/pytest.md](references/pytest.md) - 完整 pytest 用法
- **Mock 和 Patch**: [references/mocking.md](references/mocking.md) - unittest.mock 详解
- **Fixtures**: [references/fixtures.md](references/fixtures.md) - fixture 高级用法
- **异步测试**: [references/async.md](references/async.md) - pytest-asyncio
- **覆盖率**: [references/coverage.md](references/coverage.md) - pytest-cov 配置
## 常用标记
```python
@pytest.mark.slow # 标记慢测试
@pytest.mark.integration # 标记集成测试
@pytest.mark.skip(reason="TODO")
@pytest.mark.skipif(sys.version_info < (3, 10))
```
## pytest.ini 配置
```ini
[pytest]
testpaths = tests
python_files = test_*.py
markers =
slow: marks tests as slow
integration: integration tests
addopts = -v --tb=short
```
## 文档
- pytest: https://docs.pytest.org/
- pytest-cov: https://pytest-cov.readthedocs.io/_meta.json
{
"ownerId": "kn7fvwdk59wp6nd02h869hrkkn85cv0p",
"slug": "python-testing",
"version": "1.0.0",
"publishedAt": 1778818311231
}references/async.md
# 异步测试
## pytest-asyncio
```bash
pip install pytest-asyncio
```
```python
import pytest
@pytest.mark.asyncio
async def test_async_function():
result = await async_operation()
assert result == "expected"
@pytest.mark.asyncio
async def test_async_with_mock():
with pytest.raises(ValueError):
await async_function_that_raises()
```
## 异步 Fixture
```python
@pytest.fixture
async def async_client():
client = await create_async_client()
yield client
await client.close()
@pytest.mark.asyncio
async def test_with_async_fixture(async_client):
result = await async_client.get("/")
assert result.status == 200
```
## httpx 异步测试
```python
import pytest
from httpx import AsyncClient, ASGITransport
from myapp import app
@pytest.fixture
async def client():
async with AsyncClient(
transport=ASGITransport(app=app),
base_url="http://test"
) as client:
yield client
@pytest.mark.asyncio
async def test_api(client):
response = await client.get("/users")
assert response.status_code == 200
```references/coverage.md
# 覆盖率测试
## pytest-cov
```bash
pip install pytest-cov
```
## 运行覆盖率
```bash
pytest --cov=myapp
pytest --cov=myapp --cov-report=term-missing
pytest --cov=myapp --cov-report=html
pytest --cov=myapp --cov-fail-under=80
pytest --cov=myapp --cov-branch
```
## .coveragerc 配置
```ini
[run]
source = myapp
branch = True
omit =
*/tests/*
*/__init__.py
[report]
exclude_lines =
pragma: no cover
def __repr__
raise NotImplementedError
if TYPE_CHECKING:
```
## pyproject.toml 配置
```toml
[tool.coverage.run]
source = ["myapp"]
branch = true
omit = ["*/tests/*"]
[tool.coverage.report]
exclude_lines = [
"pragma: no cover",
"def __repr__",
"raise NotImplementedError",
]
```
## 查看 HTML 报告
```bash
pytest --cov=myapp --cov-report=html
open htmlcov/index.html
```references/fixtures.md
# Fixtures
## 基本 Fixture
```python
import pytest
@pytest.fixture
def database():
db = Database(":memory:")
db.connect()
yield db
db.close()
def test_query(database):
result = database.query("SELECT 1")
assert result is not None
```
## Fixture 依赖
```python
@pytest.fixture
def database():
return Database(":memory:")
@pytest.fixture
def user(database):
return database.create_user(name="Alice")
def test_user_name(user):
assert user.name == "Alice"
```
## 作用域
```python
# function: 每个测试调用一次 (默认)
# class: 每个测试类调用一次
# module: 每个模块调用一次
# package: 每个包调用一次
# session: 整个测试会话调用一次
@pytest.fixture(scope="module")
def app():
app = create_app()
app.start()
yield app
app.stop()
@pytest.fixture(scope="session")
def docker_client():
client = DockerClient()
yield client
client.close()
```
## autouse
```python
# 自动使用
@pytest.fixture(autouse=True)
def setup_teardown():
print("Setup")
yield
print("Teardown")
```
## 参数化
```python
@pytest.fixture(params=["sqlite", "postgres"])
def database(request):
db = create_database(request.param)
yield db
db.close()
def test_with_multiple_dbs(database):
# 会运行两次
pass
```
## conftest.py
```python
# tests/conftest.py - 共享 fixture
import pytest
@pytest.fixture
def client():
app = create_app()
with app.test_client() as client:
yield client
@pytest.fixture
def auth_header():
token = create_test_token()
return {"Authorization": f"Bearer {token}"}
```AionUi
Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!
activepieces
AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
cherry-studio
AI productivity studio with smart chat, autonomous agents, and 300+ assistants.
CopilotKit
The Frontend for Agents & Generative UI. React + Angular
Machine-readable data
The same record, as JSON, for agents and crawlers.
{
"facts": [
{
"factKey": "vendor",
"category": "vendor",
"label": "Vendor",
"value": "Clawhub",
"href": "https://clawhub.ai/afine907/skills/python-testing",
"sourceUrl": "https://clawhub.ai/afine907/skills/python-testing",
"sourceType": "profile",
"confidence": "medium",
"observedAt": "2026-10-11T11:05:49.680Z",
"isPublic": true
},
{
"factKey": "protocols",
"category": "compatibility",
"label": "Protocol compatibility",
"value": "OpenClaw",
"href": "https://www.xpersona.co/api/v1/agents/clawhub-afine907-python-testing/contract",
"sourceUrl": "https://www.xpersona.co/api/v1/agents/clawhub-afine907-python-testing/contract",
"sourceType": "contract",
"confidence": "medium",
"observedAt": "2026-10-11T11:05:49.680Z",
"isPublic": true
},
{
"factKey": "traction",
"category": "adoption",
"label": "Adoption signal",
"value": "1.1K downloads",
"href": "https://clawhub.ai/afine907/python-testing",
"sourceUrl": "https://clawhub.ai/afine907/python-testing",
"sourceType": "profile",
"confidence": "medium",
"observedAt": "2026-10-11T11:05:49.680Z",
"isPublic": true
},
{
"factKey": "latest_release",
"category": "release",
"label": "Latest release",
"value": "1.0.0",
"href": "https://clawhub.ai/afine907/python-testing",
"sourceUrl": "https://clawhub.ai/afine907/python-testing",
"sourceType": "release",
"confidence": "medium",
"observedAt": "2026-05-15T04:11:51.231Z",
"isPublic": true
},
{
"factKey": "handshake_status",
"category": "security",
"label": "Handshake status",
"value": "UNKNOWN",
"href": "https://www.xpersona.co/api/v1/agents/clawhub-afine907-python-testing/trust",
"sourceUrl": "https://www.xpersona.co/api/v1/agents/clawhub-afine907-python-testing/trust",
"sourceType": "trust",
"confidence": "medium",
"observedAt": null,
"isPublic": true
}
],
"events": [
{
"eventType": "release",
"title": "Release 1.0.0",
"description": "Initial release",
"href": "https://clawhub.ai/afine907/python-testing",
"sourceUrl": "https://clawhub.ai/afine907/python-testing",
"sourceType": "release",
"confidence": "medium",
"observedAt": "2026-05-15T04:11:51.231Z",
"isPublic": true
}
]
}Record generated Oct 11, 2026.
