- 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.

Application overview
The simplified app consolidates the logic intoapp/main.py. Key responsibilities:
- Provide a context manager
get_db_connection()to open an SQLite connection and setrow_factorytosqlite3.Rowso query results become dictionaries. - Implement
fetch_fake_data(count)to select random rows from thefake_datatable usingORDER BY RANDOM()andLIMIT ?. - Expose a POST endpoint
/api/v1/getfakedatathat:- Validates
count(must be > 0 and <= 1000). - Returns data when found.
- Returns proper HTTP errors for invalid input, missing data, and database errors.
- Validates
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 fileapp/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.connectis called androw_factoryis set). - The endpoint success path where
fetch_fake_datais mocked to return sample data. - Input validation errors (count <= 0 and count > 1000).
- The “no data” response when
fetch_fake_datareturns an empty list. - Handling of database errors when
fetch_fake_dataraisessqlite3.Error.
Test suite code
Test-to-purpose mapping
Running the tests
- Create and activate a virtual environment.
- Install testing dependencies:
- pytest
- pytest-asyncio
- httpx (for async HTTP client usage; TestClient bundles a sync client but httpx is commonly used)
- Run the test suite from the project root:
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-leveltests/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.
Links and references
- FastAPI — https://fastapi.tiangolo.com/
- SQLite docs — https://docs.python.org/3/library/sqlite3.html
- pytest — https://docs.pytest.org/
- FastAPI testing guide — https://fastapi.tiangolo.com/tutorial/testing/
- httpx — https://www.python-httpx.org/