Course contentsShow
← Python
Lesson 515 of 1,0608. Professional Tooling and PackagingFree lesson

Decoupling Tests from Application Code

You will move test suites into a top-level tests directory to ensure your distribution packages remain lightweight and free of development artifacts.

In this lesson, you will learn how to clean up your distribution packages by relocating your test suite into a top-level tests/ directory.

Why Decouple Tests?

When you are developing an application, it is common to place tests right next to your logic (e.g., my_module.py and test_my_module.py). However, as your project grows and you prepare to share your code or install it as a package, including tests inside your application source directory becomes problematic. It increases the package size, includes development dependencies in production environments, and complicates your directory structure.

By decoupling your tests, you treat your application as a pure, lightweight engine and your tests as a separate, auxiliary verification layer.

The Src-Layout Approach

To achieve this, move your application code into a dedicated src/ folder and place your tests/ folder at the root of your project. Here is how your directory structure should look:

my_project/
├── src/
│   └── my_package/
│       ├── __init__.py
│       └── logic.py
├── tests/
│   ├── __init__.py
│   └── test_logic.py
├── pyproject.toml
└── README.md

How It Works

By isolating tests/ at the root, you ensure that when you build your project for distribution—using tools like poetry or pip—the packaging process only pulls from the src/ directory. This keeps your production package clean, small, and free of testing artifacts like sample data, mock configurations, or extra test runners.

When you run your test suite, modern tools like pytest automatically handle this structure. Since your src/ directory is at the root, the test runner can easily import your modules as if they were installed in the environment. This separation forces you to ensure your project is properly importable, which is a great "litmus test" for checking if your package metadata is configured correctly.

Key Takeaway: Moving your test suite to a top-level tests/ directory keeps your production distribution lightweight and strictly separates developer-facing validation from your end-user application logic.