0
0
PyTesttesting~8 mins

@pytest.fixture decorator - Framework Patterns

Choose your learning style9 modes available
Framework Mode - @pytest.fixture decorator
Folder Structure
tests/
├── test_example.py       # Test files using fixtures
├── conftest.py           # Fixtures shared across tests
utilities/
├── helpers.py            # Helper functions
configs/
├── config.yaml           # Environment and test configs
reports/
├── latest_report.html    # Test reports
Test Framework Layers
  • Fixtures Layer: Defined in conftest.py or test files using @pytest.fixture. Provides setup and teardown for tests.
  • Test Layer: Test functions in tests/ that use fixtures by declaring them as parameters.
  • Utilities Layer: Helper functions and reusable code to support tests and fixtures.
  • Configuration Layer: Holds environment settings, credentials, and parameters in config files like config.yaml.
Configuration Patterns
  • Use conftest.py to define fixtures that read from config files or environment variables.
  • Store environment-specific data (URLs, credentials) in configs/config.yaml or use pytest.ini for pytest options.
  • Use command line options (pytest --env=staging) to select environment configurations dynamically.
  • Fixtures can accept parameters to customize setup based on config values.
Test Reporting and CI/CD Integration
  • Use pytest plugins like pytest-html to generate readable HTML reports saved in reports/.
  • Integrate pytest runs into CI/CD pipelines (GitHub Actions, Jenkins) to run tests automatically on code changes.
  • Configure pytest to output JUnit XML reports for CI tools to parse test results.
  • Use fixture scopes (function, module, session) to optimize test run times in CI.
Best Practices for @pytest.fixture
  • Define fixtures in conftest.py to share them across multiple test files without imports.
  • Use fixture scopes wisely: function (default) for isolated tests, module or session for expensive setup.
  • Keep fixtures simple and focused on setup/teardown only; avoid putting assertions inside fixtures.
  • Use parametrized fixtures to run tests with multiple data sets cleanly.
  • Use yield in fixtures to separate setup and teardown steps clearly.
Self Check

Where in this framework structure would you add a new fixture that sets up a database connection for multiple tests?

Key Result
Use @pytest.fixture in conftest.py to provide reusable setup and teardown for tests.