0
0
PyTesttesting~8 mins

Factory fixtures in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Factory fixtures
Folder Structure
tests/
├── factories/
│   ├── __init__.py
│   ├── user_factory.py
│   └── product_factory.py
├── test_users.py
├── test_products.py
├── conftest.py
└── utils/
    ├── __init__.py
    └── helpers.py
Test Framework Layers
  • Factories Layer: Contains factory fixtures that create test data objects (e.g., users, products). Located in tests/factories/.
  • Fixtures Layer: conftest.py defines reusable pytest fixtures that use factories to provide test data to tests.
  • Tests Layer: Test files like test_users.py and test_products.py use fixtures to run tests with prepared data.
  • Utilities Layer: Helper functions and utilities supporting factories and tests, located in tests/utils/.
Configuration Patterns
  • Environment Variables: Use environment variables or .env files to store sensitive data like database URLs or API keys.
  • Fixture Parameters: Factory fixtures can accept parameters to customize created objects (e.g., user roles, product categories).
  • Centralized Setup: Use conftest.py to register fixtures globally for all tests.
  • Data Isolation: Each test gets fresh data from factory fixtures to avoid shared state and flaky tests.
Test Reporting and CI/CD Integration
  • Use pytest's built-in reporting with --junitxml=report.xml to generate XML reports for CI tools.
  • Integrate with CI/CD pipelines (GitHub Actions, GitLab CI, Jenkins) to run tests automatically on code changes.
  • Use plugins like pytest-html for readable HTML reports.
  • Ensure factory fixtures run quickly to keep CI feedback fast.
Best Practices
  • Single Responsibility: Each factory fixture creates one type of object with clear parameters.
  • Reusability: Define factories in separate files to reuse across multiple tests.
  • Parameterization: Allow customization of factory data to cover different test scenarios.
  • Isolation: Always return new instances to avoid test data pollution.
  • Readability: Name fixtures clearly to express their purpose in tests.
Self Check

Where in this folder structure would you add a new factory fixture for creating Order objects?

Key Result
Use factory fixtures in pytest to create reusable, customizable test data objects for clean and isolated tests.