0
0
PyTesttesting~8 mins

Single responsibility per test in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Single responsibility per test
Folder Structure
project-root/
├── tests/
│   ├── test_login.py
│   ├── test_registration.py
│   └── test_profile_update.py
├── src/
│   ├── app/
│   │   ├── __init__.py
│   │   └── user.py
│   └── utils/
│       └── helpers.py
├── conftest.py
├── pytest.ini
└── requirements.txt
    
Test Framework Layers
  • Test Cases Layer: Individual test functions in tests/ folder, each testing one specific behavior or feature.
  • Fixtures Layer: conftest.py provides setup and teardown code reusable across tests.
  • Application Code Layer: src/app/ contains the main application logic being tested.
  • Utilities Layer: src/utils/ holds helper functions to support tests and app code.
  • Configuration Layer: pytest.ini configures pytest options and markers.
Configuration Patterns
  • pytest.ini: Configure markers, test paths, and addopts for verbosity or parallel runs.
  • conftest.py: Define fixtures for environment setup, like database connections or test data.
  • Environment Variables: Use os.environ or pytest command line options to switch between test environments (dev, staging, prod).
  • Secrets Management: Store credentials securely outside code, inject via environment variables or CI secrets.
Test Reporting and CI/CD Integration
  • Use pytest built-in reports with --junitxml=report.xml to generate XML reports readable by CI tools.
  • Integrate with CI pipelines (GitHub Actions, Jenkins, GitLab CI) to run tests on each commit or pull request.
  • Fail fast on test failures to quickly catch issues.
  • Use pytest plugins like pytest-html for human-friendly HTML reports.
Best Practices for Single Responsibility per Test
  1. One Assert per Test: Each test should verify one behavior or outcome to keep failures clear.
  2. Clear Test Names: Name tests to describe exactly what they check, e.g., test_login_with_valid_credentials.
  3. Isolate Tests: Avoid dependencies between tests; each test should run independently.
  4. Use Fixtures for Setup: Keep test code focused on assertions by moving setup to fixtures.
  5. Keep Tests Small: Short tests are easier to read, maintain, and debug.
Self Check

Where in this framework structure would you add a new test that checks the password reset feature with a single responsibility?

Key Result
Each test function should focus on one specific behavior to keep tests clear and maintainable.