0
0
PyTesttesting~8 mins

Test discovery rules in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Test discovery rules
Folder Structure
project-root/
├── tests/
│   ├── test_example.py
│   ├── test_login.py
│   └── subfolder/
│       └── test_subfeature.py
├── src/
│   └── app_code.py
├── pytest.ini
└── conftest.py
  
Test Framework Layers
  • Tests: Python files starting with test_ or ending with _test.py inside the tests/ folder or its subfolders.
  • Fixtures & Config: conftest.py files provide shared setup and fixtures for tests.
  • Source Code: Application code under src/ or similar folder, separate from tests.
  • Configuration: pytest.ini or tox.ini files configure pytest options and discovery rules.
Configuration Patterns

Use pytest.ini to control test discovery rules and settings:

[pytest]
testpaths = tests
python_files = test_*.py *_test.py
python_classes = Test*
python_functions = test_*
  

This tells pytest to look for tests only in the tests/ folder, and to recognize test files, classes, and functions by these naming patterns.

Environment variables or command line options can override these settings for different environments or browsers.

Test Reporting and CI/CD Integration
  • Use pytest built-in options like --junitxml=report.xml to generate XML reports readable by CI tools.
  • Integrate pytest runs in CI pipelines (GitHub Actions, Jenkins, GitLab CI) to run tests automatically on code changes.
  • Use plugins like pytest-html for human-friendly HTML reports.
  • Configure pytest to fail fast or rerun failed tests for efficient feedback.
Best Practices
  1. Keep test files and functions named with test_ prefix or _test.py suffix for automatic discovery.
  2. Organize tests in a dedicated tests/ folder to separate from application code.
  3. Use pytest.ini to explicitly define discovery rules to avoid surprises.
  4. Use conftest.py for shared fixtures and hooks to keep tests clean.
  5. Run pytest --collect-only to verify which tests pytest finds before running them.
Self Check

Question: Where would you add a new test file for the user registration feature so pytest discovers it automatically?

Answer: Inside the tests/ folder, with a filename starting with test_ (e.g., test_registration.py).

Key Result
pytest discovers tests by naming conventions and folder structure configured in pytest.ini.