0
0
PyTesttesting~8 mins

Fixture as function argument in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Fixture as function argument
Folder Structure
project_root/
├── tests/
│   ├── test_example.py
│   └── test_login.py
├── conftest.py
└── utils/
    └── helpers.py
Test Framework Layers
  • Fixtures Layer: Defined in conftest.py or test modules. Provide setup and teardown for tests.
  • Test Layer: Test functions in tests/ folder that receive fixtures as function arguments.
  • Utilities Layer: Helper functions and reusable code in utils/.
  • Configuration Layer: Settings and environment variables managed in conftest.py or separate config files.
Configuration Patterns

Use conftest.py to define fixtures that can be shared across tests. Manage environments and credentials using environment variables or config files loaded in fixtures.

Example: Define a fixture for a database connection that reads credentials from environment variables.

Test Reporting and CI/CD Integration

Use pytest built-in reporting with options like --junitxml=report.xml for CI systems. Integrate with CI/CD pipelines (GitHub Actions, Jenkins) to run tests automatically and collect reports.

Use plugins like pytest-html for readable HTML reports.

Best Practices
  • Define fixtures in conftest.py for reuse and cleaner tests.
  • Use descriptive fixture names to clarify their purpose.
  • Keep fixtures focused on setup and teardown only.
  • Pass fixtures as function arguments to tests to enable automatic injection.
  • Use scopes (function, module, session) to optimize fixture usage.
Self Check

Where in this folder structure would you add a new fixture that provides a web browser instance for tests?

Key Result
Use fixtures defined in conftest.py and pass them as function arguments to tests for clean, reusable setup.