0
0
PyTesttesting~8 mins

Approximate comparisons (pytest.approx) - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Approximate comparisons (pytest.approx)
Folder Structure
test_project/
├── tests/
│   ├── test_math_operations.py
│   └── test_utils.py
├── src/
│   └── math_functions.py
├── conftest.py
├── pytest.ini
└── requirements.txt
Test Framework Layers
  • Tests Layer: Contains test files like test_math_operations.py where pytest.approx is used for approximate value assertions.
  • Source Code Layer: Application code under src/ folder, e.g., math functions to be tested.
  • Fixtures & Config Layer: conftest.py for shared fixtures and setup.
  • Utilities Layer: Helper functions or custom assertion utilities if needed.
  • Configuration Layer: pytest.ini to configure pytest options.
Configuration Patterns
  • pytest.ini: Configure markers, addopts, and test paths.
    [pytest]
    addopts = -v --tb=short
    markers =
        slow: marks tests as slow
    
  • Environment Handling: Use environment variables or pytest command line options to switch test parameters if needed.
  • Approximate Comparison Settings: Use pytest.approx with relative or absolute tolerance directly in tests, no global config needed.
Test Reporting and CI/CD Integration
  • Use pytest built-in verbose reporting with -v option for clear pass/fail output.
  • Integrate with CI tools (GitHub Actions, Jenkins) to run tests on push or pull requests.
  • Generate JUnit XML reports with --junitxml=report.xml for CI dashboards.
  • Use pytest plugins like pytest-html for human-readable HTML reports.
  • Approximate comparison failures show clear diffs with pytest's built-in assertion introspection.
Best Practices
  • Use pytest.approx for floating-point comparisons: Avoid exact equality to handle rounding errors.
  • Set tolerances explicitly: Use rel or abs parameters in approx to control precision.
  • Keep tests readable: Write assertions like assert result == pytest.approx(expected, rel=1e-6) for clarity.
  • Organize tests by feature: Group approximate comparison tests logically in test files.
  • Use fixtures for setup: Share common test data or parameters via conftest.py fixtures.
Self Check

Where in this folder structure would you add a new test file to verify approximate comparisons for a new math function?

Key Result
Use pytest.approx in test files under tests/ to handle floating-point approximate comparisons with clear, configurable tolerances.