Skip to content

Instantly share code, notes, and snippets.

@matthewdeanmartin
Created April 13, 2024 16:18
Show Gist options
  • Save matthewdeanmartin/370829084fcaf4731f5c1b8d0b5ca58e to your computer and use it in GitHub Desktop.
Save matthewdeanmartin/370829084fcaf4731f5c1b8d0b5ca58e to your computer and use it in GitHub Desktop.
"""
Depends on this in conftest.py
```python
import os
import pytest
@pytest.fixture(autouse=True)
def set_tmp_path_env(tmp_path):
os.environ['PYTEST_TMP_PATH'] = str(tmp_path)
```
"""
import os
import sys
from pathlib import Path
def unit_tests_must_write_to_tmp_path(target_folder: Path)->None:
"""
Checks if pytest is in the system modules and if the target folder is not within pytest's tmp_path.
If the conditions are met, raise an exception to alert the developer.
Args:
target_folder (Path): The target folder to check as a Path object.
"""
# Check if 'pytest' is among the loaded modules
if "pytest" in sys.modules:
if not target_folder:
raise ValueError(f"Target file/folder {target_folder} must be set explicitly and inside tmp_path during unit testing.")
# Attempt to get the tmp_path from an environment variable
pytest_tmp_path_str = os.environ.get('PYTEST_TMP_PATH')
if pytest_tmp_path_str is None:
raise EnvironmentError("PYTEST_TMP_PATH environment variable is not set.")
pytest_tmp_path = Path(pytest_tmp_path_str)
# Check if the target folder is not within pytest's tmp_path
if not pytest_tmp_path in target_folder.parents:
raise ValueError(f"Target folder {target_folder} is outside pytest's tmp_path {pytest_tmp_path}.")
# If not under pytest or if the check passes, do nothing
return
if __name__ == '__main__':
def example():
# Example usage in your code
# Assuming '/path/to/target/folder' is the path you want to check
target_folder_path = '/path/to/target/folder'
unit_tests_must_write_to_tmp_path(Path(target_folder_path))
example()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment