Write Tests
How to Write Tests
Section titled “How to Write Tests”This guide shows you how to write effective tests for the IDX API.
Write a Basic Test
Section titled “Write a Basic Test”import pytestfrom fastapi.testclient import TestClient
def test_list_agents_with_auth(client, admin_headers, sample_agents): """Test listing agents with valid authentication.""" response = client.get("/api/admin/agents", headers=admin_headers)
assert response.status_code == 200 data = response.json() assert "items" in data assert len(data["items"]) == len(sample_agents)Use Test Fixtures
Section titled “Use Test Fixtures”Fixtures provide reusable setup code. The conftest.py file contains shared fixtures:
@pytest.fixturedef db_session(): """Create isolated test database session.""" engine = create_engine("sqlite:///:memory:") Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() yield session session.close()@pytest.fixturedef client(db_session): """FastAPI test client with database override.""" app.dependency_overrides[get_db] = lambda: db_session with TestClient(app) as c: yield c app.dependency_overrides.clear()@pytest.fixturedef admin_headers(db_session): """Headers with admin API key.""" api_key = create_test_api_key(db_session, role="admin") return {"X-API-Key": api_key}Use fixtures by adding them as function parameters:
def test_my_feature(client, db_session, admin_headers): # Fixtures are automatically injected response = client.get("/api/endpoint", headers=admin_headers) assert response.status_code == 200Add Test Markers
Section titled “Add Test Markers”Use pytest markers to categorize your tests:
import pytest
@pytest.mark.authdef test_api_key_validation(): """Tests marked with @pytest.mark.auth""" pass
@pytest.mark.integrationdef test_database_operations(): """Tests that require full stack""" pass
@pytest.mark.slowdef test_embedding_generation(): """Tests that take longer to run""" passMarkers allow selective test execution:
uv run pytest -m auth # Only auth testsuv run pytest -m "not slow" # Skip slow testsExclude Code from Coverage
Section titled “Exclude Code from Coverage”Some code is intentionally excluded from coverage:
# pragma: no cover - for code that shouldn't be testedif __name__ == "__main__": # pragma: no cover run()Configure exclusions in pyproject.toml:
[tool.coverage.run]omit = [ "*/tests/*", "*/__pycache__/*",]Best Practices
Section titled “Best Practices”- Isolate tests - Each test should be independent
- Use fixtures - Share setup code via
conftest.py - Test edge cases - Invalid input, empty data, boundaries
- Name descriptively -
test_create_agent_with_invalid_email - Assert specifically - Check exact values, not just “no error”
- Clean up - Fixtures should handle teardown