python-fastapi-pytest
Skill1 starsChanged 35 days agoMITView on GitHub
Python testing and FastAPI patterns — pytest, async tests, Azure OpenAI mocking, worker test harness. Use when: 'write pytest', 'test this endpoint', 'mock azure openai', 'add python tests', 'test this worker', 'pytest fixture', 'async test', 'mock httpx', 'test fastapi route', 'write a test for this python function'.
In this repository14 other files it gives its agents.
- appinsights-instrumentationSkill
- csharp-toolkitSkill
- delegateSkill
- deploy-verifySkill
- diagnoseSkill
- documentation-writerSkill
- flywheelSkill
- grill-meSkill
- javascript-typescript-jestSkill
- microsoft-docsSkill
- nuget-managerSkill
- performance-optimizationSkill
- sql-toolkitSkill
- tddSkill
The file
We split this skill into the rules it gives an agent
3 rules. About 0 are common, 0 are distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 181
Always assert on the return shape of run(): keys alert, title, priority, url all present when not None.
- Very specific: line 184
Don't use sleep in tests — mock time or use freezegun for time-dependent logic.
- Very specific: line 185
Keep tests independent: each test gets tmp_path fresh dirs, never shares state with siblings.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Python FastAPI + pytest Skill
Covers pytest patterns for FastAPI services and APScheduler workers.
Stack
- Python 3.12+
pytest+pytest-anyiofor async testshttpx.AsyncClient/TestClientfor FastAPI endpoint testsunittest.mock.patch/MagicMockfor Azure OpenAI and external service mocking- Worker
run()harness for APScheduler workers
pytest Conventions
# pytest.ini or pyproject.toml
[tool.pytest.ini_options]
asyncio_mode = "auto" # pytest-anyio global mode
testpaths = ["tests", "workers"]Name files test_{module}.py, classes Test{Feature}, functions test_{scenario}_{expected}.
FastAPI Endpoint Tests
import pytest
from httpx import AsyncClient, ASGITransport
from web.app import app # your FastAPI app
@pytest.fixture
async def client():
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
yield c
async def test_chat_returns_200(client):
resp = await client.post("/chat", json={"message": "hello"})
assert resp.status_code == 200
data = resp.json()
assert "reply" in dataFor sync FastAPI apps use TestClient (no async needed):
from fastapi.testclient import TestClient
client = TestClient(app)
def test_health():
resp = client.get("/health")
assert resp.status_code == 200Mocking Azure OpenAI
from unittest.mock import AsyncMock, patch, MagicMock
@pytest.fixture
def mock_openai():
with patch("core.llm.openai_client") as mock_client:
mock_response = MagicMock()
mock_response.choices[0].message.content = "Mocked LLM response"
mock_client.chat.completions.create = AsyncMock(return_value=mock_response)
yield mock_client
async def test_chat_uses_llm(client, mock_openai):
resp = await client.post("/chat", json={"message": "hello"})
assert resp.status_code == 200
mock_openai.chat.completions.create.assert_called_once()For TTS mocking:
@pytest.fixture
def mock_tts():
with patch("core.tts.openai_client") as mock_client:
mock_client.audio.speech.create = AsyncMock(
return_value=MagicMock(content=b"fake-mp3-bytes")
)
yield mock_clientAPScheduler Worker Tests
Worker run() signature: run(params: dict, data_dir: Path, reports_dir: Path) -> dict | None
import pytest
from pathlib import Path
from workers.my_worker import run
@pytest.fixture
def tmp_dirs(tmp_path):
data_dir = tmp_path / "data"
reports_dir = tmp_path / "reports"
data_dir.mkdir()
reports_dir.mkdir()
return data_dir, reports_dir
def test_run_no_change_returns_none(tmp_dirs):
data_dir, reports_dir = tmp_dirs
# Seed state to simulate no new data
(data_dir / "my-worker-state.json").write_text('{"last_seen": "v1.0"}')
result = run({}, data_dir, reports_dir)
assert result is None
def test_run_returns_alert_on_change(tmp_dirs, mock_httpx):
data_dir, reports_dir = tmp_dirs
result = run({}, data_dir, reports_dir)
assert result is not None
assert "alert" in result
assert result["priority"] in ("low", "normal", "high")
def test_run_handles_corrupt_state_file(tmp_dirs):
data_dir, reports_dir = tmp_dirs
(data_dir / "my-worker-state.json").write_bytes(b"NOT JSON{{{{")
# Must not raise — should reset and continue
result = run({}, data_dir, reports_dir)
assert result is None or "alert" in resultMocking httpx in Workers
import pytest
from unittest.mock import patch, MagicMock
@pytest.fixture
def mock_httpx():
with patch("workers.my_worker.httpx") as mock:
resp = MagicMock()
resp.status_code = 200
resp.json.return_value = {"items": [{"id": "a1", "price": 999}]}
resp.raise_for_status = MagicMock()
mock.get.return_value = resp
yield mockAsync Tests with anyio
import anyio
import pytest
@pytest.mark.anyio
async def test_async_worker_function():
result = await some_async_fn()
assert result == expected
# Or with pytest-anyio global asyncio_mode = "auto" — no mark needed:
async def test_auto_async():
result = await some_async_fn()
assert result == expectedCommon Patterns
- Always assert on the return shape of
run(): keysalert,title,priority,urlall present when not None. - Priority must be
"low","normal", or"high"— never"default". - State files must be written via
atomic_write_json— tests that check post-run state should read fromdata_dir. - Don't use
sleepin tests — mock time or usefreezegunfor time-dependent logic. - Keep tests independent: each test gets
tmp_pathfresh dirs, never shares state with siblings.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

