0
0
PyTesttesting~8 mins

Test naming conventions in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Test naming conventions
Folder Structure
tests/
├── test_login.py
├── test_shopping_cart.py
├── test_checkout.py
└── conftest.py

This is a simple pytest project structure. Each test file starts with test_ and contains test functions also starting with test_.

Test Framework Layers
  • Tests: Files named test_*.py with functions named test_* to be auto-discovered by pytest.
  • Fixtures: In conftest.py or test files, provide setup and teardown for tests.
  • Utilities: Helper functions or classes imported by tests, named clearly but not starting with test_.
  • Configuration: pytest.ini or pyproject.toml to configure pytest behavior.
Configuration Patterns
  • pytest.ini to set markers and test discovery rules.
  • Use environment variables or pytest --env options to select environments.
  • Use fixtures in conftest.py to manage browser or API client setup.
  • Keep credentials in environment variables or secure vaults, never hard-coded.
# pytest.ini example
[pytest]
markers =
    smoke: quick smoke tests
    regression: full regression suite
python_files = test_*.py
python_functions = test_*
Test Reporting and CI/CD Integration
  • Use pytest built-in reports with -v for verbose output.
  • Integrate with plugins like pytest-html for HTML reports.
  • Configure CI pipelines (GitHub Actions, Jenkins) to run tests on push or pull requests.
  • Fail the build if any test fails to ensure quality.
Best Practices for Test Naming Conventions
  1. Start test files and functions with test_: This allows pytest to find and run them automatically.
  2. Use descriptive names: Names should clearly describe what the test checks, e.g., test_login_with_valid_credentials.
  3. Use lowercase and underscores: This improves readability and follows Python style.
  4. Avoid spaces or special characters: Keep names simple and consistent.
  5. Group related tests in files: For example, all login tests in test_login.py.
Self Check

Where would you add a new test function named test_user_can_reset_password in this framework structure?

Key Result
Use clear, consistent test file and function names starting with 'test_' for pytest to auto-discover and run tests.