hbutils.testing.isolated.directory

Isolated directory execution utilities for tests.

This module provides a single public context manager, isolated_directory(), which creates a temporary working directory and optionally populates it with a mapping of files or directories copied from the original working directory. The context manager changes the current working directory to the temporary location for the duration of the context and restores it afterwards.

The main public component is:

Note

This utility is typically used in tests to avoid polluting the real working directory and to work with a controlled file system layout.

Example:

>>> import os
>>> from hbutils.testing.isolated.directory import isolated_directory
>>>
>>> with isolated_directory():
...     with open('example.txt', 'w') as f:
...         _ = f.write('hello')
...     os.listdir('.')
['example.txt']
>>> os.path.exists('example.txt')
False

__all__

hbutils.testing.isolated.directory.__all__ = ['isolated_directory']

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

isolated_directory

hbutils.testing.isolated.directory.isolated_directory(mapping: Dict[str, str] | None = None) ContextManager[None][source]

Execute code in an isolated temporary directory with optional mappings.

This context manager creates a temporary directory, optionally copies the mapped sources into that directory, changes the working directory to the temporary location, and restores the original working directory when the context exits.

Parameters:

mapping (Optional[Dict[str, str]]) – Mapping of destination paths (relative to the temporary directory) to source paths (relative to the original working directory). If None, the isolated directory starts empty.

Returns:

A context manager that yields control inside the isolated directory.

Return type:

ContextManager[None]

Raises:
  • OSError – If directory creation or working directory changes fail.

  • FileNotFoundError – If a source path in the mapping does not exist.

  • NotADirectoryError – If a copy operation expects a directory but the target is not a directory.

Example:

>>> import os
>>> import pathlib
>>> from hbutils.testing.isolated.directory import isolated_directory
>>>
>>> with isolated_directory():
...     with open('file.txt', 'w') as f:
...         print("Line 1", file=f)
...         print("Line 2rd", file=f)
...     print(os.listdir('.'))
...     print(pathlib.Path('file.txt').read_text())
['file.txt']
Line 1
Line 2rd

>>> with isolated_directory({
...     'ts': 'hbutils/testing',
...     'README.md': 'README.md',
... }):
...     print(os.listdir('.'))
...     print(os.listdir('ts'))
['README.md', 'ts']
['capture', 'generator', 'isolated', '__init__.py']