0
0
PyTesttesting~8 mins

tmp_path and tmp_path_factory in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - tmp_path and tmp_path_factory
Folder Structure
tests/
├── test_example.py
├── conftest.py
└── resources/
    └── sample_data.txt

This simple structure keeps test files in tests/. The conftest.py file holds shared fixtures. The resources/ folder stores static files for tests.

Test Framework Layers
  • Test Layer: Test functions using tmp_path to create temporary files and directories safely.
  • Fixture Layer: tmp_path and tmp_path_factory fixtures provided by pytest to manage temporary paths.
  • Utility Layer: Helper functions to write/read files in temporary directories if needed.
  • Config Layer: pytest.ini or conftest.py to configure pytest behavior.
Configuration Patterns
  • Temporary Path Usage: Use tmp_path fixture for a fresh temporary directory per test function.
  • Shared Temporary Directories: Use tmp_path_factory to create temporary directories shared across multiple tests or modules.
  • Environment Isolation: Temporary paths are automatically cleaned after tests, ensuring no leftover files.
  • pytest.ini: Configure test discovery and add markers if needed, but no special config needed for tmp_path.
Test Reporting and CI/CD Integration
  • pytest outputs clear pass/fail results for tests using tmp_path.
  • Temporary files do not affect reports since they are isolated and cleaned up.
  • Integrate pytest with CI tools (GitHub Actions, Jenkins) to run tests automatically on code changes.
  • Use plugins like pytest-html for detailed HTML reports if desired.
Best Practices
  1. Use tmp_path for test isolation: Each test gets a clean folder to avoid interference.
  2. Use tmp_path_factory for shared temp dirs: When multiple tests need access to the same temp directory.
  3. Never hardcode paths: Always use these fixtures to avoid polluting your real file system.
  4. Clean code with fixtures: Let pytest handle cleanup automatically instead of manual deletes.
  5. Write simple tests: Use tmp_path to create files or folders quickly and test file operations safely.
Self Check

Where in this folder structure would you add a new fixture that creates a temporary directory shared by multiple test files?

Key Result
Use pytest's tmp_path for isolated temp directories per test and tmp_path_factory for shared temp directories across tests.