Skip to main content
In this lesson we’ll build unit tests for a small FastAPI application that serves as a fake-data generator. The repository has been simplified into a single-file app so we can focus on testing core logic and endpoints without extra scaffolding. This guide covers:
  • A concise overview of the refactored application and how it accesses SQLite.
  • The complete application code (app/main.py) used in tests.
  • A test suite (app/test_main.py) using pytest and FastAPI’s TestClient, with mocks to avoid hitting the real database.
  • How to run the tests and recommended best practices for unit testing APIs.
A presentation slide showing the title "Creating Unit Tests" on the left and a large "Demo" label on a dark curved shape on the right. A small "© Copyright KodeKloud" appears in the bottom-left corner.

Application overview

The simplified app consolidates the logic into app/main.py. Key responsibilities:
  • Provide a context manager get_db_connection() to open an SQLite connection and set row_factory to sqlite3.Row so query results become dictionaries.
  • Implement fetch_fake_data(count) to select random rows from the fake_data table using ORDER BY RANDOM() and LIMIT ?.
  • Expose a POST endpoint /api/v1/getfakedata that:
    • Validates count (must be > 0 and <= 1000).
    • Returns data when found.
    • Returns proper HTTP errors for invalid input, missing data, and database errors.
These constraints make the API predictable and easier to test.

app/main.py

Below is the complete application code used for the tests.
Use clear validation rules and enforce sensible limits (for example, count capped at 1000) to protect your API from accidental or malicious heavy requests. Returning appropriate HTTP status codes (400, 404, 500) improves testability and automation of client error handling.

Testing with pytest

We use pytest and FastAPI’s TestClient to unit-test the endpoint logic. The test file app/test_main.py sits next to main.py so it can import the application module directly for easier mocking. The tests cover:
  • The DB connection context manager behavior (ensuring sqlite3.connect is called and row_factory is set).
  • The endpoint success path where fetch_fake_data is mocked to return sample data.
  • Input validation errors (count <= 0 and count > 1000).
  • The “no data” response when fetch_fake_data returns an empty list.
  • Handling of database errors when fetch_fake_data raises sqlite3.Error.

Test suite code

Test-to-purpose mapping


Running the tests

  1. Create and activate a virtual environment.
  2. Install testing dependencies:
  • pytest
  • pytest-asyncio
  • httpx (for async HTTP client usage; TestClient bundles a sync client but httpx is commonly used)
Example install command:
  1. Run the test suite from the project root:
Example output:

Notes and best practices

  • For small projects it’s convenient to keep tests next to source files (e.g., app/test_main.py). For larger projects, prefer a top-level tests/ directory to separate concerns.
  • Unit tests should avoid touching external resources. Mock I/O, network, and database access so tests are fast and deterministic. Use integration tests with a test database to verify end-to-end behavior.
  • Use descriptive test names and fixtures (like sample_data) to make intent clear.
  • Keep validation and error handling explicit in your API code. That makes tests easier to write and more meaningful.

Watch Video