Skip to content

Write Tests

This guide shows you how to write effective tests for the IDX API.

import pytest
from 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)

Fixtures provide reusable setup code. The conftest.py file contains shared fixtures:

@pytest.fixture
def 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()

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 == 200

Use pytest markers to categorize your tests:

import pytest
@pytest.mark.auth
def test_api_key_validation():
"""Tests marked with @pytest.mark.auth"""
pass
@pytest.mark.integration
def test_database_operations():
"""Tests that require full stack"""
pass
@pytest.mark.slow
def test_embedding_generation():
"""Tests that take longer to run"""
pass

Markers allow selective test execution:

Terminal window
uv run pytest -m auth # Only auth tests
uv run pytest -m "not slow" # Skip slow tests

Some code is intentionally excluded from coverage:

# pragma: no cover - for code that shouldn't be tested
if __name__ == "__main__": # pragma: no cover
run()

Configure exclusions in pyproject.toml:

[tool.coverage.run]
omit = [
"*/tests/*",
"*/__pycache__/*",
]
  1. Isolate tests - Each test should be independent
  2. Use fixtures - Share setup code via conftest.py
  3. Test edge cases - Invalid input, empty data, boundaries
  4. Name descriptively - test_create_agent_with_invalid_email
  5. Assert specifically - Check exact values, not just “no error”
  6. Clean up - Fixtures should handle teardown