Last active
November 7, 2022 14:24
-
-
Save kentavv/8b9d4adbea4fec6c9f23d04a0645f786 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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