0
0
PyTesttesting~8 mins

Handling shared resources in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Handling shared resources
Folder Structure
tests/
├── test_login.py
├── test_shopping_cart.py
├── test_checkout.py
conftest.py
utils/
├── db_helper.py
├── api_client.py
pytest.ini
requirements.txt
Test Framework Layers
  • Fixtures Layer: Defined in conftest.py to setup and teardown shared resources like database connections, test data, or web drivers.
  • Tests Layer: Test files inside tests/ folder use fixtures to access shared resources safely.
  • Utilities Layer: Helper modules in utils/ provide reusable functions for resource management, e.g., database queries or API calls.
  • Configuration Layer: pytest.ini and environment variables control test settings and resource parameters.
Configuration Patterns
  • Use pytest.ini to define default test options and markers.
  • Use environment variables or .env files to store sensitive data like credentials or URLs.
  • Define fixtures in conftest.py that read configuration and initialize shared resources once per session or module.
  • Example: a database connection fixture with scope="session" to share the connection across all tests safely.
Test Reporting and CI/CD Integration
  • Use pytest built-in reporting with options like --junitxml=report.xml for CI systems.
  • Integrate with CI tools (GitHub Actions, Jenkins) to run tests on every push or pull request.
  • Ensure shared resources are properly cleaned up after tests to avoid side effects in CI runs.
  • Use plugins like pytest-html for readable HTML reports.
Best Practices
  1. Use fixtures with appropriate scope: session, module, or function to control resource lifetime.
  2. Isolate tests: Avoid tests changing shared resources in ways that affect others.
  3. Cleanup resources: Use finalizers or yield fixtures to release resources after use.
  4. Parameterize fixtures: To handle different configurations or environments easily.
  5. Keep fixtures simple and reusable: Avoid complex logic inside fixtures to maintain clarity.
Self Check

Where in this framework structure would you add a new fixture to manage a shared API client used by multiple tests?

Key Result
Use pytest fixtures in conftest.py to manage shared resources with proper scope and cleanup.