Skip to content

Instantly share code, notes, and snippets.

@kentavv
Last active November 7, 2022 14:24
Show Gist options
  • Save kentavv/8b9d4adbea4fec6c9f23d04a0645f786 to your computer and use it in GitHub Desktop.
Save kentavv/8b9d4adbea4fec6c9f23d04a0645f786 to your computer and use it in GitHub Desktop.
import pytest
@pytest.fixture(autouse=True, scope="function")
def temporary_working_directory(tmp_path_factory):
"""
Create (and chdir into) a temporary working directory using
PyTest facilities for the specified scope. After testing scope
is complete, original working directory is restored and temporary
working directory is removed. This fixture could be listed as
a plugin in the pytest configuration or imported into and tuned
for each test file.
Use --basetemp to control the base location of the temporary
working directory
pytest --log-cli-level=DEBUG --capture=tee-sys --basetemp=/tmp/yourtmpdir -k test_module
"""
from pathlib import Path
cwd0 = Path().absolute()
dn = tmp_path_factory.mktemp("_your_base_dirname")
import logging
_log = logging.getLogger(__name__)
_log.debug(f"Temporary working directory: {dn}")
try:
import os
os.chdir(dn)
yield
finally:
os.chdir(cwd0)
try:
_log.debug(f"Removing working directory: {dn}")
import shutil
shutil.rmtree(dn)
except OSError:
pass
@kentavv
Copy link
Author

kentavv commented Nov 7, 2022

The purpose of this fixture is to simply and ensure cleanup of files created as side effects of pytest modules.
This PyTest fixture can be imported into individual test files or automatically loaded by registering as a PyTest plugin.
If imported into individual files, the import line could look like the following, assuming this code has been put into a file of fixtures called tests.fixtures.fixtures.
from tests.fixtures.fixtures import temporary_working_directory

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment