Skip to content

How-To: Fix Hardcoded Paths in Python Tests

A common reason test suites fail on CI/CD pipelines or different developer machines is the use of hardcoded, absolute paths based on file hierarchy.

The Problem: Absolute Path Resolution

Consider this database configuration:

# ❌ Fragile: Assumes the script is always exactly 2 directories deep
top_dir = Path(__file__).resolve().parents[1]
db_path = str(top_dir / "crud-in-the-cloud.db")

If you execute pytest from the root directory, or if the project is packaged into a different structure, __file__ resolves differently, and your tests will look for the database in the wrong folder.

The Solution: Environment Variables & Relative Fallbacks

To make your application portable, use environment variables to inject paths, and provide safe relative fallbacks.

Step 1: Use os.getenv with a Relative Default

Modify your configuration to rely on an environment variable first, and default to a relative file name in the current working directory.

import os

def get_db_path():
    # ✅ Robust: Reads from ENV, defaults to current working directory
    return os.getenv("SQLITE_DATABASE", "crud-in-the-cloud.db")

Step 2: Override the Path in conftest.py

When running tests, you want to ensure the production database is never touched. You can override the environment variable dynamically in your pytest configuration:

# tests/conftest.py
import os

# Override the database to use an in-memory SQLite instance for testing
os.environ["SQLITE_DATABASE"] = ":memory:"

# Now import your database logic
from config.database import get_db

This ensures your test suite runs blazing fast entirely in RAM, while your production app defaults safely to the local directory without fragile __file__ dependencies!