In this lesson, you will learn how to structure your project directories and use naming conventions so that pytest automatically locates and runs your tests without manual intervention.
The Power of Conventions
One of pytest’s greatest strengths is that it doesn't require you to write a complex configuration file to start testing. Instead, it relies on "Convention over Configuration." By following a predictable directory structure and naming pattern, pytest knows exactly where to look for your code and your tests.
Naming Conventions
For pytest to discover your tests automatically, it follows a specific set of rules:
- File Names: Test files must start with
test_or end with_test.py. For example,test_calculations.pyis a valid discovery target. - Class Names: If you organize your tests within classes, those classes must be prefixed with
Test(e.g.,TestDataProcessor). Note that these classes should not have an__init__method. - Function Names: Test functions must also start with
test_(e.g.,def test_addition():).
Directory Structure
While you can place tests next to your source code, the community standard for larger projects is to separate them. A common structure looks like this:
my_project/
├── src/
│ └── calculator.py
└── tests/
└── test_calculator.py
When you run the command pytest from the root of your my_project folder, the tool recursively searches through all subdirectories. It looks for files matching the naming convention, imports them, and executes any function or method that also begins with test_.
This "zero-config" approach means you can simply add a new test file to your tests/ directory, and the next time you trigger your test suite, pytest will find and execute it immediately. This keeps your workflow fast and prevents you from accidentally ignoring new test cases as your project grows.
Key Takeaway: By prefixing your test files, classes, and functions with test_ and organizing them within your project structure, pytest will automatically discover and execute your entire test suite without any additional configuration.