0
0
PyTesttesting~8 mins

Temporary directory management in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Temporary directory management
Folder Structure
tests/
├── test_example.py
├── conftest.py
└── resources/
    └── sample_data.txt

# Temporary directories are managed by pytest fixtures, no special folder needed
Test Framework Layers
  • Tests: Test functions using pytest in tests/ folder.
  • Fixtures: Defined in conftest.py to provide temporary directories using tmp_path or tmp_path_factory.
  • Utilities: Helper functions for file creation or cleanup if needed.
  • Resources: Static test data files under tests/resources/.
  • Configuration: pytest.ini or pyproject.toml for pytest settings.
Configuration Patterns
  • Use pytest built-in tmp_path fixture for temporary directory management in tests.
  • For multiple temporary directories, use tmp_path_factory fixture to create isolated folders.
  • Configure pytest options in pytest.ini or pyproject.toml for test discovery and markers.
  • Environment variables can be accessed via os.environ if needed for dynamic paths.
  • Credentials or sensitive data should not be stored in temp dirs; use environment variables or secure vaults.
Test Reporting and CI/CD Integration
  • pytest outputs test results to console by default with pass/fail status.
  • Use plugins like pytest-html to generate detailed HTML reports.
  • Temporary directories are cleaned automatically after each test run to avoid clutter.
  • Integrate pytest runs in CI/CD pipelines (GitHub Actions, Jenkins) with commands like pytest --html=report.html.
  • Ensure logs and reports are archived in CI artifacts for review.
Best Practices
  1. Use pytest built-in fixtures: Always prefer tmp_path or tmp_path_factory for temporary directories to ensure isolation and automatic cleanup.
  2. Keep tests independent: Each test should get a fresh temporary directory to avoid side effects.
  3. Do not hardcode paths: Use the fixtures to get paths dynamically instead of fixed folder names.
  4. Clean up is automatic: Avoid manual deletion; pytest handles temp directory cleanup after tests.
  5. Use descriptive names: When creating temp directories with tmp_path_factory, use meaningful names for easier debugging.
Self Check

Where in this framework structure would you add a new fixture that creates a temporary directory with some default files for testing?

Key Result
Use pytest's built-in tmp_path and tmp_path_factory fixtures to manage temporary directories with automatic cleanup and isolation.