A context manager that creates a temporary directory and changes the current working directory to it. This isolates tests that affect the contents of the CWD to prevent them from interfering with each other. :param temp_dir: Create the temporary directory under this
(
self, temp_dir: str | os.PathLike[str] | None = None
)
| 740 | |
| 741 | @contextlib.contextmanager |
| 742 | def isolated_filesystem( |
| 743 | self, temp_dir: str | os.PathLike[str] | None = None |
| 744 | ) -> cabc.Generator[str]: |
| 745 | """A context manager that creates a temporary directory and |
| 746 | changes the current working directory to it. This isolates tests |
| 747 | that affect the contents of the CWD to prevent them from |
| 748 | interfering with each other. |
| 749 | |
| 750 | :param temp_dir: Create the temporary directory under this |
| 751 | directory. If given, the created directory is not removed |
| 752 | when exiting. |
| 753 | |
| 754 | .. versionchanged:: 8.0 |
| 755 | Added the ``temp_dir`` parameter. |
| 756 | """ |
| 757 | cwd = os.getcwd() |
| 758 | dt = tempfile.mkdtemp(dir=temp_dir) |
| 759 | os.chdir(dt) |
| 760 | |
| 761 | try: |
| 762 | yield dt |
| 763 | finally: |
| 764 | os.chdir(cwd) |
| 765 | |
| 766 | if temp_dir is None: |
| 767 | import shutil |
| 768 | |
| 769 | try: |
| 770 | shutil.rmtree(dt) |
| 771 | except OSError: |
| 772 | pass |
no outgoing calls
no test coverage detected