Pytest is a popular Python testing framework known for its simplicity and powerful features. It provides functionalities to:
- Write and execute unit tests, integration tests, or functional tests.
- Support for test fixtures to manage setup and teardown.
- Parametrize tests to run the same test with multiple inputs.
- Filter, skip, or mark tests for better control.
- Generate test reports with plugins (like
pytest-html). - Compatible with other Python libraries and tools.
How Does Pytest Know Which Functions to Test?
Pytest automatically discovers test functions based on naming conventions. When you run pytest, it looks for files, classes, and functions that match specific patterns.
Rules for Test Discovery in Pytest
File Names:
Pytest looks for files with names starting withtest_or ending with_test.
Example:test_example.py✅example_test.py✅example.py❌ (Not discovered unless explicitly specified)
Function Names:
Pytest looks for functions inside those files with names starting withtest_.
Example:Class Names:
If you want to organize tests into classes, pytest looks for classes whose names start withTest. These classes should not have an__init__method.
Example:Directories:
Pytest scans directories recursively for test files. By default, it looks in:- The current working directory.
- Any subdirectories that don’t start with
.or_.
Example directory structure:
Running
pytestfrom theproject/directory will automatically findtests/test_math.pyandtests/test_string.py.
Examples
Discovered Test
File: test_sample.py
Command:
Output:
Undiscovered Function
File: test_sample.py
Command:
Output:
How to Override the Default Discovery Rules?
Run Specific Files/Functions Manually:
You can explicitly specify the file or function to test:Change Naming Patterns:
Use the--pyargsor--collect-onlyoptions, or configurepytest.inito adjust discovery:Run All Functions:
Use thepytest --collect-onlycommand to list all functions that match the discovery rules:
No comments:
Post a Comment