0
0
PyTesttesting~8 mins

Custom markers in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Custom markers
Folder Structure
tests/
├── test_login.py
├── test_checkout.py
├── test_profile.py
pytest.ini
conftest.py
utils/
    └── helpers.py

This is a typical pytest project structure. tests/ holds test files. pytest.ini configures pytest including custom markers. conftest.py contains fixtures and hooks. utils/ has helper functions.

Test Framework Layers
  • Tests: Test functions in tests/ folder, using custom markers to group or select tests.
  • Fixtures & Hooks: In conftest.py, provide setup/teardown and marker validation.
  • Configuration: pytest.ini declares custom markers for pytest to recognize.
  • Utilities: Helper functions in utils/ support test logic.
Configuration Patterns

Define custom markers in pytest.ini to avoid warnings and enable selection:

[pytest]
markers =
    smoke: mark test as smoke test
    regression: mark test as regression test
    slow: mark test as slow running

Use command line options to run tests by marker, e.g., pytest -m smoke.

Store environment variables or credentials securely outside tests, accessed via fixtures.

Test Reporting and CI/CD Integration
  • Use pytest's built-in reporting with verbosity and markers to filter results.
  • Integrate with CI/CD pipelines (GitHub Actions, Jenkins) to run tests with specific markers.
  • Generate reports with plugins like pytest-html to show marker-based test groups.
  • Fail builds if critical marker tests (e.g., smoke) fail.
Best Practices for Custom Markers
  1. Declare all custom markers in pytest.ini to avoid warnings.
  2. Use markers to categorize tests by purpose or speed (e.g., smoke, regression, slow).
  3. Keep marker names clear and consistent.
  4. Use markers in combination with fixtures for flexible test setup.
  5. Leverage markers in CI to run targeted test suites efficiently.
Self Check

Where in this framework structure would you add a new custom marker called api to group API tests?

Key Result
Use pytest.ini to declare custom markers and apply them in tests for flexible grouping and selection.