API Reference

Comparisons

testfixtures.compare(*args: ~typing.Any, x: ~typing.Any = <unspecified>, y: ~typing.Any = <unspecified>, expected: ~typing.Any = <unspecified>, actual: ~typing.Any = <unspecified>, prefix: str | ~typing.Callable[[], str] | None = None, suffix: str | ~typing.Callable[[], str] | None = None, x_label: str | None = None, y_label: str | None = None, raises: bool = True, recursive: bool = True, strict: bool = False, ignore_eq: bool | type | ~collections.abc.Iterable[type] = False, comparers: dict[type, ~typing.Callable[[~typing.Any, ~typing.Any, ~testfixtures.comparison.CompareContext], str | None]] | None = None, **options: ~typing.Any) str | None

Compare two objects, raising an AssertionError if they are not the same. The AssertionError raised will attempt to provide descriptions of the differences found.

The two objects to compare can be passed either positionally or using explicit keyword arguments named x and y, or expected and actual, or a mixture of these.

Parameters:
  • prefix (str | Callable[[], str] | None) – If provided, in the event of an AssertionError being raised, the prefix supplied will be prepended to the message in the AssertionError. This may be a callable, in which case it will only be resolved if needed.

  • suffix (str | Callable[[], str] | None) – If provided, in the event of an AssertionError being raised, the suffix supplied will be appended to the message in the AssertionError. This may be a callable, in which case it will only be resolved if needed.

  • x_label (str | None) – If provided, in the event of an AssertionError being raised, the object passed as the first positional argument, or x keyword argument, will be labelled with this string in the message in the AssertionError.

  • y_label (str | None) – If provided, in the event of an AssertionError being raised, the object passed as the second positional argument, or y keyword argument, will be labelled with this string in the message in the AssertionError.

  • raises (bool) – If False, the message that would be raised in the AssertionError will be returned instead of the exception being raised.

  • recursive (bool) – If True, when a difference is found in a nested data structure, attempt to highlight the location of the difference.

  • strict (bool) – If True, objects will only compare equal if they are of the same type as well as being equal.

  • ignore_eq (bool | type | Iterable[type]) –

    Controls when __eq__ is skipped in favour of a registered comparer (or the hash-equality fallback):

    • True — skip __eq__ for every object.

    • False (default) — honour __eq__ except for types registered with ignore_eq=True.

    • a type — also skip __eq__ whenever an instance of that type is on either side of a comparison.

    • an iterable of types — as above, for each type.

  • comparers (dict[type, Callable[[Any, Any, CompareContext], str | None]] | None) – If supplied, should be a dictionary mapping types to comparer functions for those types. These will be added to the comparer registry for the duration of this call.

Any other keyword parameters supplied will be passed to the functions that end up doing the comparison. See the API documentation below for details of these.

class testfixtures.Comparison(object_or_type: Any, attribute_dict: dict[str, Any] | None = None, partial: bool = False, **attributes: Any)

These are used when you need to compare an object’s type, a subset of its attributes or make equality checks with objects that do not natively support comparison.

Parameters:
  • object_or_type (Any) – The object or class from which to create the Comparison.

  • attribute_dict (dict[str, Any] | None) – An optional dictionary containing attributes to place on the Comparison.

  • partial (bool) – If true, only the specified attributes will be checked and any extra attributes of the object being compared with will be ignored.

  • attributes (Any) – Any other keyword parameters passed will placed as attributes on the Comparison.

testfixtures.like(t: type[T], **attributes: Any) T

Create a type-safe partial comparison for use in strictly typed code.

This is a convenience function that creates a Comparison with partial=True but is typed to return the type being compared, making it compatible with strict type checkers like mypy.

Parameters:
  • t (type[T]) – The type to compare against.

  • attributes (Any) – Keyword arguments specifying the attributes to check.

Returns:

A Comparison object typed as the input type.

Return type:

T

class testfixtures.MappingComparison(*expected_mapping: tuple[Any, Any] | Mapping[Any, Any], ordered: bool = False, partial: bool = False, recursive: bool = False, **expected_items: Any)

An object that can be used in comparisons of expected and actual mappings.

Parameters:
  • expected_mapping (tuple[Any, Any] | Mapping[Any, Any]) – The mapping that should be matched expressed as either a sequence of (key, value) tuples or a mapping.

  • expected_items (Any) – The items that should be matched.

  • ordered (bool) – If True, then the keys in the mapping are expected to be in the order specified. Defaults to False.

  • partial (bool) – If True, then any keys not expected will be ignored. Defaults to False.

  • recursive (bool) – If a difference is found, recursively compare the value where the difference was found to highlight exactly what was different. Defaults to False.

class testfixtures.Permutation(*expected: Any)

A shortcut for SequenceComparison that checks if the set of items in the sequence is as expected, but without checking ordering.

class testfixtures.RoundComparison(value: float, precision: int)

An object that can be used in comparisons of expected and actual numerics to a specified precision.

Parameters:
  • value (float) – numeric to be compared.

  • precision (int) – Number of decimal places to round to in order to perform the comparison.

class testfixtures.RangeComparison(lower_bound: Any, upper_bound: Any)

An object that can be used in comparisons of orderable types to check that a value specified within the given range.

Parameters:
  • lower_bound (Any) – the inclusive lower bound for the acceptable range.

  • upper_bound (Any) – the inclusive upper bound for the acceptable range.

class testfixtures.SequenceComparison(*expected: Any, ordered: bool = True, partial: bool = False, recursive: bool = False)

An object that can be used in comparisons of expected and actual sequences.

Parameters:
  • expected (Any) – The items expected to be in the sequence.

  • ordered (bool) – If True, then the items are expected to be in the order specified. If False, they may be in any order. Defaults to True.

  • partial (bool) – If True, then any keys not expected will be ignored. Defaults to False.

  • recursive (bool) – If a difference is found, recursively compare the item where the difference was found to highlight exactly what was different. Defaults to False.

testfixtures.sequence(partial: bool = False, ordered: bool = True, recursive: bool = True) Callable[[S], S]
testfixtures.sequence(partial: bool = False, ordered: bool = True, recursive: bool = True, *, returns: type[S_]) Callable[[S], S_]

Create a type-safe sequence comparison with configurable partial matching and ordering requirements.

This function returns a callable that wraps a sequence in a comparison object, making it compatible with strict type checkers.

Parameters:
  • partial (bool) – If True, only items in the expected sequence need to be present in the actual sequence. Defaults to False.

  • ordered (bool) – If True, items must appear in the same order. Defaults to True.

  • recursive (bool) – If True, provide detailed recursive comparison when differences are found. Defaults to True.

  • returns – Optional type hint for the return type, used to satisfy type checkers when the comparison needs to appear as a different sequence type.

Returns:

A callable that takes a sequence and returns a comparison object typed as a sequence.

Return type:

Callable[[S], S | S_]

testfixtures.contains(items: S) S
testfixtures.contains(items: S, *, returns: type[S_]) S_

Create a type-safe partial sequence comparison that ignores order.

Checks that the specified items are present in the actual sequence, regardless of their order or what other items are present. This is useful when you only care that certain elements exist in a collection.

Parameters:
  • items (S) – The sequence of items that must be present.

  • returns – Optional type hint for the return type, used to satisfy type checkers when the comparison needs to appear as a different sequence type.

Returns:

A comparison object typed as a sequence.

Return type:

S | S_

testfixtures.unordered(items: S) S
testfixtures.unordered(items: S, *, returns: type[S_]) S_

Create a type-safe sequence comparison that ignores order but requires all items to match.

Checks that the actual sequence contains exactly the same items as specified, but in any order. This is useful when order doesn’t matter but you want to ensure no extra or missing items.

Parameters:
  • items (S) – The sequence of items that must match exactly.

  • returns – Optional type hint for the return type, used to satisfy type checkers when the comparison needs to appear as a different sequence type.

Returns:

A comparison object typed as a sequence.

Return type:

S | S_

class testfixtures.Subset(*expected: Any)

A shortcut for SequenceComparison that checks if the specified items are present in the sequence.

class testfixtures.StringComparison(regex_source: str, flags: int | None = None, **flag_names: str)

An object that can be used in comparisons of expected and actual strings where the string expected matches a pattern rather than a specific concrete string.

Parameters:
  • regex_source (str) – A string containing the source for a regular expression that will be used whenever this StringComparison is compared with any str instance.

  • flags (int | None) – Flags passed to re.compile().

  • flag_names (str) – See the examples.

testfixtures.comparison

testfixtures.comparison.register(type_: type, comparer: Callable[[Any, Any, CompareContext], str | None]) None
testfixtures.comparison.register(type_: type, comparer: Callable[[Any, Any, CompareContext], str | None], *, ignore_eq: bool) None
testfixtures.comparison.register(type_: type, *, ignore_eq: Literal[True]) None

Register the supplied comparer for the specified type, and/or mark the type as one whose __eq__ should be ignored during comparison.

At least one of comparer or ignore_eq=True must be supplied.

This registration is global and will be in effect from the point this function is called until the end of the current process.

class testfixtures.comparison.CompareContext(x_label: str | None, y_label: str | None, recursive: bool = True, strict: bool = False, ignore_eq: bool | type | Iterable[type] = False, comparers: dict[type, Callable[[Any, Any, CompareContext], str | None]] | None = None, options: dict[str, Any] | None = None)

Stores the context of the current comparison in process during a call to testfixtures.compare().

label(side: Literal['x', 'y'], value: Any) str

Generate a labelled representation of the value for one side of a comparison.

qualified_equals(x: Any, y: Any) bool

Determines if two objects are equal, taking strict, ignore_eq and instances of AlreadySeen into account.

different(x: Any, y: Any, breadcrumb: str) bool | str | None

Comparers can call this method to hand off comparison of elements within the objects they are currently comparing.

testfixtures.comparers

testfixtures.comparers.compare_simple(x: Any, y: Any, context: CompareContext, newline_threshold: int = 15) str | None

Returns a very simple textual difference between the two supplied objects.

testfixtures.comparers.compare_object(x: object, y: object, context: CompareContext, ignore_attributes: Iterable[str] | Mapping[type, Iterable[str]] = ()) str | None

Compare the two supplied objects based on their type and attributes.

Parameters:

ignore_attributes (Iterable[str] | Mapping[type, Iterable[str]]) –

Either a sequence of strings containing attribute names to be ignored when comparing, or a Mapping of type to sequence of strings containing attribute names to be ignored when comparing that type.

When specified as a mapping, you can use Any as a key to specify attributes that should be ignored for all types.

testfixtures.comparers.merge_ignored_attributes(*ignored: Iterable[str] | Mapping[type, Iterable[str]] | str | None) Mapping[type, set[str]]

Merge multiple specifications of attributes to ignore into a single mapping.

This is particularly useful when implementing custom comparers that need to combine their own attribute ignores with those passed via the context.

Each argument can be:

  • None: ignored

  • A Mapping of type to iterable of attribute names: attributes for specific types

  • An iterable of attribute names: applies to all types

  • A single attribute name string: applies to all types

Returns a mapping of types to sets of attribute names to ignore, where Any is used as the key for attributes that apply to all types.

testfixtures.comparers.compare_exception(x: BaseException, y: BaseException, context: CompareContext) str | None

Compare the two supplied exceptions based on their message, type and attributes.

testfixtures.comparers.compare_exception_group(x: BaseExceptionGroup, y: BaseExceptionGroup, context: CompareContext) str | None

Compare the two supplied exception groups

testfixtures.comparers.compare_with_type(x: Any, y: Any, context: CompareContext) str

Return a textual description of the difference between two objects including information about their types.

testfixtures.comparers.compare_sequence(x: Sequence, y: Sequence, context: CompareContext, prefix: bool = True) str | None

Returns a textual description of the differences between the two supplied sequences.

testfixtures.comparers.compare_generator(x: Iterable, y: Iterable, context: CompareContext) str | None

Returns a textual description of the differences between the two supplied generators.

This is done by first unwinding each of the generators supplied into tuples and then passing those tuples to compare_sequence().

testfixtures.comparers.compare_tuple(x: tuple, y: tuple, context: CompareContext) str | None

Returns a textual difference between two tuples or collections.namedtuple() instances.

The presence of a _fields attribute on a tuple is used to decide whether or not it is a namedtuple().

testfixtures.comparers.compare_dict(x: dict, y: dict, context: CompareContext) str | None

Returns a textual description of the differences between the two supplied dictionaries.

testfixtures.comparers.compare_set(x: set, y: set, context: CompareContext) str | None

Returns a textual description of the differences between the two supplied sets.

testfixtures.comparers.compare_text(x: str, y: str, context: CompareContext, blanklines: bool = True, trailing_whitespace: bool = True, show_whitespace: bool = False) str | None

Returns an informative string describing the differences between the two supplied strings. The way in which this comparison is performed can be controlled using the following parameters:

Parameters:
  • blanklines (bool) – If False, then when comparing multi-line strings, any blank lines in either argument will be ignored.

  • trailing_whitespace (bool) – If False, then when comparing multi-line strings, trailing whilespace on lines will be ignored.

  • show_whitespace (bool) – If True, then whitespace characters in multi-line strings will be replaced with their representations.

testfixtures.comparers.safe_repr(obj: Any) str

A fault-tolerant version of repr().

KeyboardInterrupt and SystemExit are not caught.

testfixtures.comparers.safe_pformat(obj: Any) str

A fault-tolerant version of pprint.pformat() but tolerant. Falls back to safe_repr() when pformat() fails.

class testfixtures.comparers.AlreadySeen(id_: int, obj: Any, breadcrumb: str)

A marker for an object that has already been seen during a compare() call. These are used to prevent infinite recursion during comparison.

Capturing

class testfixtures.LogCapture(*sources: CaptureSource, install: bool = True, recursive_check: bool = False, ensure_checks_above: int | None = None)
class testfixtures.LogCapture(names: str | Tuple[str | None, ...] | None = None, *, install: bool = True, level: int = 1, propagate: bool | None = None, attributes: Sequence[str | Callable[[LogRecord], Any]] | Callable[[LogRecord], Any] = ..., recursive_check: bool = False, ensure_checks_above: int | None = None)

Captures log entries from one or more sources and provides methods to check what was logged.

Parameters:
  • sources – One or more capture sources

  • install (bool) – If True (the default), capturing starts immediately on construction. If False, installation is deferred until install() is called.

  • recursive_check (bool) – If True, entries are compared recursively by check().

  • ensure_checks_above (int | None) – The log level above which entries must have been checked. See ensure_checked().

For compatibility with earlier versions, capturing only standard library logging is supported by instantiating using these parameters:

Parameters:
  • names – A string (or tuple of strings) containing the dotted name(s) of loggers to capture. By default, the root logger is captured.

  • level (int) – The minimum log level to capture. Defaults to 1, capturing everything.

  • propagate (bool | None) – If specified, any captured loggers will have their propagate attribute set to the supplied value. This can be used to prevent propagation from a child logger to a parent logger that has configured handlers.

  • attributes (Sequence[str | Callable[[LogRecord], Any]] | Callable[[LogRecord], Any]) –

    The sequence of attributes to return for each record or a callable that extracts actual from a record.

    If a sequence of attribute names is passed, for each item, an attribute of that name will be obtained from the logging.LogRecord. If the attribute is callable, the result of calling it will be used as the attribute value. If an attribute is missing, None will be used in its place.

    If a callable is passed, it will be called with the LogRecord and the value returned will be used as actual.

entries: list[Entry]

The list of entries captured so far.

property records: List[LogRecord]

The records captured by this LogCapture.

Deprecated since version 12: Use the entries attribute instead.

default_ensure_checks_above: int | None = None

Class-level default for ensure_checked(). Set this to apply a level threshold to all LogCapture instances that do not override it explicitly.

clear() None

Clear any entries that have been captured.

mark_all_checked() None

Mark all captured events as checked. This should be called if you have made assertions about logging other than through LogCapture methods.

ensure_checked(level: int | None = None) None

Ensure every entry logged above the specified level has been checked. Raises an AssertionError if this is not the case.

Parameters:

level (int | None) – This defaults to the level passed during LogCapture instantiation.

install() Self | None

Install this LogCapture, enabling all configured sources to begin capturing.

uninstall() None

Uninstall this LogCapture, restoring all sources to their previous state.

classmethod uninstall_all() None

This will uninstall all existing LogCapture objects.

actual() list[Any]

The sequence of actual items captured.

This can be useful for making more complex assertions about captured logging. The full Entry objects captured for each logging call can be accessed through entries.

check(*expected: Any, order_matters: bool = True, raises: bool = True) str | None

This will compare the captured entries with the expected entries provided and raise an AssertionError if they do not match.

Parameters:
  • expected (Any) – A sequence of expected actual items.

  • order_matters (bool) – A keyword-only parameter that controls whether the order of the captured entries is required to match those of the expected entries. Defaults to True.

  • raises (bool) – If False, the message that would be raised in the AssertionError will be returned instead of the exception being raised.

raise_first_exception(start_index: int = 0) None

Raise the first captured exception from start_index onwards.

Parameters:

start_index (int) – The index into entries from where to start looking.

check_exception_str(expected: str, index: int = -1) None

Check the string representation of a captured exception.

Parameters:
  • expected (str) – The expected string.

  • index (int) – The index into entries where the exception should have been captured.

check_present(*expected: Any, order_matters: bool = True, raises: bool = True) str | None

This will check if the captured attr:entries contain all of the expected entries provided and raise an AssertionError if not. This will ignore entries that have been captured but that do not match those in expected.

Parameters:
  • expected (Any) – A sequence of expected actual items.

  • order_matters (bool) – A keyword-only parameter that controls whether the order of the captured entries is required to match those of the expected entries. Defaults to True.

  • raises (bool) – If False, the message that would be raised in the AssertionError will be returned instead of the exception being raised.

class testfixtures.LoggingSource(attributes: Sequence[str | Callable[[LogRecord], Any]] | Callable[[LogRecord], Any] = ('levelname', 'getMessage'), level: int = 1, *, names: Tuple[str | None, ...] = (None,), propagate: bool | None = None)

A CaptureSource for the standard-library logging framework, for use with LogCapture.

Parameters:
  • attributes (Sequence[str | Callable[[LogRecord], Any]] | Callable[[LogRecord], Any]) –

    The sequence of attributes to return for each record or a callable that extracts actual from a record.

    If a sequence of attribute names is passed, for each item, an attribute of that name will be obtained from the logging.LogRecord. If the attribute is callable, the result of calling it will be used as the attribute value. If an attribute is missing, None will be used in its place.

    If a callable is passed, it will be called with the LogRecord and the value returned will be used as actual.

  • level (int) – The minimum log level to capture. Defaults to 1, capturing everything.

  • names (Tuple[str | None, ...]) – A string (or tuple of strings) containing the dotted name(s) of loggers to capture. By default, the root logger is captured.

  • propagate (bool | None) – If specified, any captured loggers will have their propagate attribute set to the supplied value. This can be used to prevent propagation from a child logger to a parent logger that has configured handlers.

testfixtures.log_capture(*names: str, **kw: Any) Callable

A decorator for making a LogCapture installed and available for the duration of a test function.

Parameters:

names (str) – An optional sequence of names specifying the loggers to be captured. If not specified, the root logger will be captured.

Keyword parameters other than install may also be supplied and will be passed on to the LogCapture constructor.

class testfixtures.logcapture.CaptureSource(*args, **kwargs)

Protocol that LogCapture sources must implement.

install(collector: Callable[[Entry], None]) None

Start capturing.

Parameters:

collector (Callable[[Entry], None]) – The destination for captured entries.

uninstall() None

Stop capturing and restore any previous state.

class testfixtures.logcapture.Entry(raw: Any, actual: Any, level: int | None, exception: BaseException | None = None, checked: bool = False)

A captured log entry captured by a CaptureSource.

raw: Any

The raw object delivered by the logging framework. This is a LogRecord for standard library logging.

actual: Any

The extracted value used by check() and related methods. Its structure is determined by the attributes parameter of the source.

level: int | None

Numeric log level used by ensure_checked(), or None if the source does not provide a comparable numeric level.

exception: BaseException | None = None

The exception associated with this entry if one was captured, otherwise None.

checked: bool = False

Whether this entry has been marked as checked by a check() call.

class testfixtures.OutputCapture(separate: bool = False, fd: bool = False, strip_whitespace: bool = True)

A context manager for capturing output to the sys.stdout and sys.stderr streams.

Parameters:
  • separate (bool) – If True, stdout and stderr will be captured separately and their expected values must be passed to compare().

  • fd (bool) – If True, the underlying file descriptors will be captured, rather than just the attributes on sys. This allows you to capture things like subprocesses that write directly to the file descriptors, but is more invasive, so only use it when you need it.

  • strip_whitespace (bool) – When True, which is the default, leading and training whitespace is trimmed from both the expected and actual values when comparing.

Note

If separate is passed as True, OutputCapture.captured will be an empty string.

disable() None

Disable the output capture if it is enabled.

enable() None

Enable the output capture if it is disabled.

property captured: str

A property containing any output that has been captured so far.

compare(expected: str | StringComparison = '', stdout: str | StringComparison = '', stderr: str | StringComparison = '', raises: bool = True) str | None

Compare the captured output to that expected. If the output is not the same, an AssertionError will be raised.

Parameters:
  • expected (str | StringComparison) – A string containing the expected combined output of stdout and stderr.

  • stdout (str | StringComparison) – A string containing the expected output to stdout.

  • stderr (str | StringComparison) – A string containing the expected output to stderr.

  • raises (bool) – If False, the message that would be raised in the AssertionError will be returned instead of the exception being raised.

Mocking

class testfixtures.Replace(target: Any, replacement: R, strict: bool = True, container: Any | None = None, accessor: Callable[[Any, str], Any] | None = None, name: str | None = None, sep: str = '.')

A context manager that uses a Replacer to replace a single target.

Parameters:
  • target (Any) –

    This must be one of the following:

    • A string containing the dotted-path to the object to be replaced, in which case it will be resolved the the object to be replaced.

      This path may specify a module in a package, an attribute of a module, or any attribute of something contained within a module.

    • The container of the object to be replaced, in which case name must be specified.

    • The object to be replaced, in which case container must be specified. name must also be specified if it cannot be obtained from the __name__ attribute of the object to be replaced.

  • replacement (R) – The object to use as a replacement.

  • strict (bool) – When True, an exception will be raised if an attempt is made to replace an object that does not exist or if the object that is obtained using the accessor to access the name from the container is not identical to the target.

  • container (Any | None) – The container of the object from which target can be accessed using either getattr() or getitem().

  • accessor (Callable[[Any, str], Any] | None) – Either getattr() or getitem(). If not supplied, this will be inferred.

  • name (str | None) – The name used to access the target from the container using the accessor. If required but not specified, the __name__ attribute of the target will be used.

  • sep (str) – When target is a string, this is the separator between traversal segments.

testfixtures.replace_in_environ(name: str, replacement: Any) Iterator[None]

This context manager provides a quick way to use Replacer.in_environ().

testfixtures.replace_on_class(attribute: Callable, replacement: Any, name: str | None = None) Iterator[None]

This context manager provides a quick way to use Replacer.on_class().

testfixtures.replace_in_module(target: Any, replacement: Any, module: ModuleType | None = None) Iterator[None]

This context manager provides a quick way to use Replacer.in_module().

class testfixtures.Replacer

These are used to manage the mocking out of objects so that units of code can be tested without having to rely on their normal dependencies.

__call__(target: Any, replacement: R, strict: bool = True, container: Any | None = None, accessor: Callable[[Any, str], Any] | None = None, name: str | None = None, sep: str = '.') R

Replace the specified target with the supplied replacement.

Parameters:
  • target (Any) –

    This must be one of the following:

    • A string containing the dotted-path to the object to be replaced, in which case it will be resolved the the object to be replaced.

      This path may specify a module in a package, an attribute of a module, or any attribute of something contained within a module.

    • The container of the object to be replaced, in which case name must be specified.

    • The object to be replaced, in which case container must be specified. name must also be specified if it cannot be obtained from the __name__ attribute of the object to be replaced.

  • replacement (R) – The object to use as a replacement.

  • strict (bool) – When True, an exception will be raised if an attempt is made to replace an object that does not exist or if the object that is obtained using the accessor to access the name from the container is not identical to the target.

  • container (Any | None) – The container of the object from which target can be accessed using either getattr() or getitem().

  • accessor (Callable[[Any, str], Any] | None) – Either getattr() or getitem(). If not supplied, this will be inferred.

  • name (str | None) – The name used to access the target from the container using the accessor. If required but not specified, the __name__ attribute of the target will be used.

  • sep (str) – When target is a string, this is the separator between traversal segments.

replace(target: Any, replacement: Any, strict: bool = True, container: Any | None = None, accessor: Callable[[Any, str], Any] | None = None, name: str | None = None) None

Replace the specified target with the supplied replacement.

Parameters:
  • target (Any) –

    This must be one of the following:

    • A string containing the dotted-path to the object to be replaced, in which case it will be resolved the the object to be replaced.

      This path may specify a module in a package, an attribute of a module, or any attribute of something contained within a module.

    • The container of the object to be replaced, in which case name must be specified.

    • The object to be replaced, in which case container must be specified. name must also be specified if it cannot be obtained from the __name__ attribute of the object to be replaced.

  • replacement (Any) – The object to use as a replacement.

  • strict (bool) – When True, an exception will be raised if an attempt is made to replace an object that does not exist or if the object that is obtained using the accessor to access the name from the container is not identical to the target.

  • container (Any | None) – The container of the object from which target can be accessed using either getattr() or getitem().

  • accessor (Callable[[Any, str], Any] | None) – Either getattr() or getitem(). If not supplied, this will be inferred.

  • name (str | None) – The name used to access the target from the container using the accessor. If required but not specified, the __name__ attribute of the target will be used.

  • sep – When target is a string, this is the separator between traversal segments.

in_environ(name: str, replacement: Any) None

This method provides a convenient way of ensuring an environment variable in os.environ is set to a particular value.

If you wish to ensure that an environment variable is not present, then use not_there as the replacement.

on_class(attribute: Callable, replacement: Any, name: str | None = None) None

This method provides a convenient way to replace methods, static methods and class methods on their classes.

If the attribute being replaced has a __name__ that differs from the attribute name on the class, such as that returned by poorly implemented decorators, then name must be used to provide the correct name.

in_module(target: Any, replacement: Any, module: ModuleType | None = None) None

This method provides a convenient way to replace targets that are module globals, particularly functions or other objects with a __name__ attribute.

If an object has been imported into a module other than the one where it has been defined, then module should be used to specify the module where you would like the replacement to occur.

restore() None

Restore all the original objects that have been replaced by calls to the replace() method of this Replacer.

testfixtures.replace(target: Any, replacement: Any, strict: bool = True, container: Any | None = None, accessor: Callable[[Any, str], Any] | None = None, name: str | None = None, sep: str = '.') Callable[[Callable], Callable]

A decorator to replace a target object for the duration of a test function.

Parameters:
  • target (Any) –

    This must be one of the following:

    • A string containing the dotted-path to the object to be replaced, in which case it will be resolved the the object to be replaced.

      This path may specify a module in a package, an attribute of a module, or any attribute of something contained within a module.

    • The container of the object to be replaced, in which case name must be specified.

    • The object to be replaced, in which case container must be specified. name must also be specified if it cannot be obtained from the __name__ attribute of the object to be replaced.

  • replacement (Any) – The object to use as a replacement.

  • strict (bool) – When True, an exception will be raised if an attempt is made to replace an object that does not exist or if the object that is obtained using the accessor to access the name from the container is not identical to the target.

  • container (Any | None) – The container of the object from which target can be accessed using either getattr() or getitem().

  • accessor (Callable[[Any, str], Any] | None) – Either getattr() or getitem(). If not supplied, this will be inferred.

  • name (str | None) – The name used to access the target from the container using the accessor. If required but not specified, the __name__ attribute of the target will be used.

  • sep (str) – When target is a string, this is the separator between traversal segments.

testfixtures.mock_date(*args: int | date | None, delta: float | None = None, delta_type: str = 'days', strict: bool = False, **kw: int) type[MockDate]

A function that returns a mock object that can be used in place of the datetime.date class but where the return value of today() can be controlled.

If a single positional argument of None is passed, then the queue of dates to be returned will be empty and you will need to call set() or add() before calling today().

If an instance of date is passed as a single positional argument, that will be used as the first date returned by today()

Parameters:
  • year – An optional year used to create the first date returned by today().

  • month – An optional month used to create the first date returned by today().

  • day – An optional day used to create the first date returned by today().

  • delta (float | None) – The size of the delta to use between values returned from today(). If not specified, it will increase by 1 with each call to today().

  • delta_type (str) – The type of the delta to use between values returned from today(). This can be any keyword parameter accepted by the timedelta constructor.

  • strict (bool) – If True, calling the mock class and any of its methods will result in an instance of the mock being returned. If False, the default, an instance of date will be returned instead.

The mock returned will behave exactly as the datetime.date class as well as being a subclass of MockDate.

class testfixtures.datetime.MockDate(*args: int, **kw: int | tzinfo | None)
classmethod add(*args: int | date, **kw: int | tzinfo | None) None

This will add the datetime.date created from the supplied parameters to the queue of dates to be returned by today(). An instance of date may also be passed as a single positional argument.

classmethod set(*args: int | date, **kw: int | tzinfo | None) None

This will set the datetime.date created from the supplied parameters as the next date to be returned by today(), regardless of any dates in the queue. An instance of date may also be passed as a single positional argument.

classmethod tick(*args: timedelta, **kw: float) None

This method should be called either with a timedelta as a positional argument, or with keyword parameters that will be used to construct a timedelta.

The timedelta will be used to advance the next date to be returned by today().

classmethod today() Self

This will return the next supplied or calculated date from the internal queue, rather than the actual current date.

testfixtures.mock_datetime(*args: int | datetime | None | tzinfo, tzinfo: tzinfo | None = None, delta: float | None = None, delta_type: str = 'seconds', date_type: type[date] = <class 'datetime.date'>, strict: bool = False, **kw: int | tzinfo | None) type[MockDateTime]

A function that returns a mock object that can be used in place of the datetime.datetime class but where the return value of now() can be controlled.

If a single positional argument of None is passed, then the queue of datetimes to be returned will be empty and you will need to call set() or add() before calling now() or utcnow().

If an instance of datetime is passed as a single positional argument, that will be used as the first date returned by now()

Parameters:
  • year – An optional year used to create the first datetime returned by now().

  • month – An optional month used to create the first datetime returned by now().

  • day – An optional day used to create the first datetime returned by now().

  • hour – An optional hour used to create the first datetime returned by now().

  • minute – An optional minute used to create the first datetime returned by now().

  • second – An optional second used to create the first datetime returned by now().

  • microsecond – An optional microsecond used to create the first datetime returned by now().

  • tzinfo (tzinfo | None) – An optional datetime.tzinfo, see Timezones.

  • delta (float | None) – The size of the delta to use between values returned from mocked class methods. If not specified, it will increase by 1 with each call to now().

  • delta_type (str) – The type of the delta to use between values returned from mocked class methods. This can be any keyword parameter accepted by the timedelta constructor.

  • date_type (type[date]) – The type to use for the return value of the mocked class methods. This can help with gotchas that occur when type checking is performed on values returned by the date() method.

  • strict (bool) – If True, calling the mock class and any of its methods will result in an instance of the mock being returned. If False, the default, an instance of datetime will be returned instead.

The mock returned will behave exactly as the datetime.datetime class as well as being a subclass of MockDateTime.

class testfixtures.datetime.MockDateTime(*args: int, **kw: int | tzinfo | None)
classmethod add(*args: int | datetime, **kw: int | tzinfo | None) None

This will add the datetime.datetime created from the supplied parameters to the queue of datetimes to be returned by now() or utcnow(). An instance of datetime may also be passed as a single positional argument.

classmethod set(*args: int | datetime, **kw: int | tzinfo | None) None

This will set the datetime.datetime created from the supplied parameters as the next datetime to be returned by now() or utcnow(), clearing out any datetimes in the queue. An instance of datetime may also be passed as a single positional argument.

classmethod tick(*args: timedelta, **kw: float) None

This method should be called either with a timedelta as a positional argument, or with keyword parameters that will be used to construct a timedelta.

The timedelta will be used to advance the next datetime to be returned by now() or utcnow().

classmethod now(tz: tzinfo | None = None) Self
Parameters:

tz (tzinfo | None) – An optional timezone to apply to the returned time. If supplied, it must be an instance of a tzinfo subclass.

This will return the next supplied or calculated datetime from the internal queue, rather than the actual current datetime.

If tz is supplied, see Timezones.

classmethod utcnow() Self

This will return the next supplied or calculated datetime from the internal queue, rather than the actual current UTC datetime.

If you care about timezones, see Timezones.

date() date

This will return the date component of the current mock instance, but using the date type supplied when the mock class was created.

testfixtures.mock_time(*args: int | datetime | None, delta: float | None = None, delta_type: str = 'seconds', **kw: int) MockTime

A function that returns a mock object that can be used in place of the time.time() function but where the return value can be controlled.

If a single positional argument of None is passed, then the queue of times to be returned will be empty and you will need to call set() or add() before calling the mock.

If an instance of datetime is passed as a single positional argument, that will be used to create the first time returned.

Parameters:
  • year – An optional year used to create the first time returned.

  • month – An optional month used to create the first time.

  • day – An optional day used to create the first time.

  • hour – An optional hour used to create the first time.

  • minute – An optional minute used to create the first time.

  • second – An optional second used to create the first time.

  • microsecond – An optional microsecond used to create the first time.

  • delta (float | None) – The size of the delta to use between values returned. If not specified, it will increase by 1 with each call to the mock.

  • delta_type (str) – The type of the delta to use between values returned. This can be any keyword parameter accepted by the timedelta constructor.

The add(), set() and tick() methods on the mock can be used to control the return values.

class testfixtures.datetime.MockTime(factory: type[MockedCurrent[datetime]])
add(*args: int | datetime, **kw: int | tzinfo | None) None

This will add the time specified by the supplied parameters to the queue of times to be returned by calls to the mock. The parameters are the same as the datetime.datetime constructor. An instance of datetime may also be passed as a single positional argument.

set(*args: int | datetime, **kw: int | tzinfo | None) None

This will set the time specified by the supplied parameters as the next time to be returned by a call to the mock, regardless of any times in the queue. The parameters are the same as the datetime.datetime constructor. An instance of datetime may also be passed as a single positional argument.

tick(*args: timedelta, **kw: float) None

This method should be called either with a timedelta as a positional argument, or with keyword parameters that will be used to construct a timedelta.

The timedelta will be used to advance the next time to be returned by a call to the mock.

testfixtures.mock

A facade for either unittest.mock or its rolling backport, if it is installed, with a preference for the latter as it may well have newer functionality and bugfixes.

The facade also contains any bugfixes that are critical to the operation of functionality provided by testfixtures.

testfixtures.popen

class testfixtures.popen.PopenBehaviour(stdout: bytes = b'', stderr: bytes = b'', returncode: int = 0, pid: int = 1234, poll_count: int = 3)

An object representing the behaviour of a MockPopen when simulating a particular command.

class testfixtures.popen.CallableBehaviour(*args, **kwargs)
class testfixtures.popen.MockPopenInstance(mock_class: MockPopen, root_call: _Call, args: str | bytes | PathLike | Sequence[str | bytes | PathLike], bufsize: int = 0, executable: str | bytes | PathLike | None = None, stdin: None | int | IO[Any] = None, stdout: None | int | IO[Any] = None, stderr: None | int | IO[Any] = None, preexec_fn: Callable[[], Any] | None = None, close_fds: bool = False, shell: bool = False, cwd: str | bytes | PathLike | None = None, env: Mapping[str, str] | None = None, universal_newlines: bool = False, startupinfo: Any = None, creationflags: int = 0, restore_signals: bool = True, start_new_session: bool = False, pass_fds: Collection[int] = (), *, encoding: str | None = None, errors: str | None = None, text: bool | None = None)

A mock process as returned by MockPopen.

stdout: TextIO | None = None

A file representing standard output from this process.

stderr: TextIO | None = None

A file representing error output from this process.

root_call: _Call

A unittest.mock.call() representing the call made to instantiate this mock process.

calls: List[_Call]

The calls made on this mock process, represented using call() instances.

stdin: Mock | None = None

A Mock representing the pipe into this process. This is only set if stdin=PIPE is passed the constructor. The mock records writes and closes in MockPopen.all_calls.

returncode: int | None

The return code of this mock process.

wait(timeout: float | None = None) int

Simulate calls to subprocess.Popen.wait()

communicate(input: str | bytes | None = None, timeout: float | None = None) Tuple[str | bytes | None, str | bytes | None]

Simulate calls to subprocess.Popen.communicate()

poll() int | None

Simulate calls to subprocess.Popen.poll()

send_signal(signal: int) None

Simulate calls to subprocess.Popen.send_signal()

terminate() None

Simulate calls to subprocess.Popen.terminate()

kill() None

Simulate calls to subprocess.Popen.kill()

class testfixtures.popen.MockPopen

A specialised mock for testing use of subprocess.Popen. An instance of this class can be used in place of the subprocess.Popen and is often inserted where it’s needed using unittest.mock.patch() or a Replacer.

all_calls: List[_Call]

All calls made using this mock and the objects it returns, represented using call() instances.

set_command(command: str, stdout: bytes = b'', stderr: bytes = b'', returncode: int = 0, pid: int = 1234, poll_count: int = 3, behaviour: PopenBehaviour | CallableBehaviour | None = None) None

Set the behaviour of this mock when it is used to simulate the specified command.

Parameters:
  • command (str) – A str representing the command to be simulated.

  • stdout (bytes) – bytes representing the simulated content written by the process to the stdout pipe.

  • stderr (bytes) – bytes representing the simulated content written by the process to the stderr pipe.

  • returncode (int) – An integer representing the return code of the simulated process.

  • pid (int) – An integer representing the process identifier of the simulated process. This is useful if you have code the prints out the pids of running processes.

  • poll_count (int) – Specifies the number of times poll() can be called before returncode is set and returned by poll().

If supplied, behaviour must be either a PopenBehaviour instance or a callable that takes the command string representing the command to be simulated and the stdin supplied when instantiating the subprocess.Popen with that command and should return a PopenBehaviour instance.

set_default(stdout: bytes = b'', stderr: bytes = b'', returncode: int = 0, pid: int = 1234, poll_count: int = 3, behaviour: PopenBehaviour | CallableBehaviour | None = None) None

Set the behaviour of this mock when it is used to simulate commands that have no explicit behavior specified using set_command().

Parameters:
  • stdout (bytes) – bytes representing the simulated content written by the process to the stdout pipe.

  • stderr (bytes) – bytes representing the simulated content written by the process to the stderr pipe.

  • returncode (int) – An integer representing the return code of the simulated process.

  • pid (int) – An integer representing the process identifier of the simulated process. This is useful if you have code the prints out the pids of running processes.

  • poll_count (int) – Specifies the number of times poll() can be called before returncode is set and returned by poll().

If supplied, behaviour must be either a PopenBehaviour instance or a callable that takes the command string representing the command to be simulated and the stdin supplied when instantiating the subprocess.Popen with that command and should return a PopenBehaviour instance.

Assertions

class testfixtures.shouldraise.NoException

A marker class indicating no exception has been raised.

ShouldRaise.raised is set to an instance of this class unless an exception has otherwise been seen.

class testfixtures.ShouldRaise(exception: type[E], *, match: str | Pattern[str] | None = None, unless: bool | None = False)
class testfixtures.ShouldRaise(exception: singleton = not_there, *, match: str | Pattern[str] | None = None, unless: bool | None = False)
class testfixtures.ShouldRaise(exception: E | None, *, match: None = None, unless: bool | None = False)

This context manager is used to assert that an exception is raised within the context it is managing.

Parameters:
  • exception (E | type[E] | None) –

    This can be one of the following:

    • Not passed, indicating that an exception must be raised, but the type is unimportant.

    • None, indicating that no exception should be raised. This is useful for parameterised tests where the parameter may be either an exception or None.

    • An exception class, indicating that the type of the exception is important but not the parameters it is created with.

    • An exception instance, indicating that an exception exactly matching the one supplied should be raised.

  • unless (bool | None) – Can be passed a boolean that, when True indicates that no exception is expected. This is useful when checking that exceptions are only raised on certain versions of Python.

raised: E = NoException('No exception raised!')

The exception captured by the context manager. Can be used to inspect specific attributes of the exception.

class testfixtures.should_raise(exception: type[E], *, match: str | Pattern[str] | None = None, unless: bool | None = None)
class testfixtures.should_raise(exception: singleton = not_there, *, match: str | Pattern[str] | None = None, unless: bool | None = None)
class testfixtures.should_raise(exception: E | None, *, match: None = None, unless: bool | None = None)

A decorator to assert that the decorated function will raised an exception. An exception class or exception instance may be passed to check more specifically exactly what exception will be raised.

Parameters:
  • exception (E | type[E] | None | singleton) –

    This can be one of the following:

    • Not passed, indicating that an exception must be raised, but the type is unimportant.

    • None, indicating that no exception should be raised. This is useful for parameterised tests where the parameter may be either an exception or None.

    • An exception class, indicating that the type of the exception is important but not the parameters it is created with.

    • An exception instance, indicating that an exception exactly matching the one supplied should be raised.

  • unless (bool | None) – Can be passed a boolean that, when True indicates that no exception is expected. This is useful when checking that exceptions are only raised on certain versions of Python.

testfixtures.ShouldAssert(expected_text: str, show_whitespace: bool = False) Iterator[None]

A context manager to check that an AssertionError is raised and its text is as expected.

Parameters:

show_whitespace (bool) – If True, then whitespace characters in multi-line strings will be replaced with their representations.

class testfixtures.ShouldWarn(*expected: Warning | type[Warning], order_matters: bool = True, **filters: Any)

This context manager is used to assert that warnings are issued within the context it is managing.

Parameters:
  • expected (Warning | type[Warning]) –

    This should be a sequence made up of one or more elements, each of one of the following types:

    • A warning class, indicating that the type of the warnings is important but not the parameters it is created with.

    • A warning instance, indicating that a warning exactly matching the one supplied should have been issued.

    If no expected warnings are passed, you will need to inspect the contents of the list returned by the context manager.

  • order_matters (bool) – A keyword-only parameter that controls whether the order of the captured entries is required to match those of the expected entries. Defaults to True.

  • filters (Any) – If passed, these are used to create a filter such that only warnings you are interested in will be considered by this ShouldWarn instance. The names and meanings are the same as the parameters for warnings.filterwarnings().

class testfixtures.ShouldNotWarn

This context manager is used to assert that no warnings are issued within the context it is managing.

Resources

class testfixtures.TempDir(path: str | Path | None = None, *, ignore: Sequence[str] = (), create: bool | None = None, encoding: str | None = None, cwd: bool = False, formats: Sequence[Format] = (<testfixtures.formats.JSONFormat object>, <testfixtures.formats.YAMLFormat object>, <testfixtures.formats.TOMLFormat object>))
as_path(path: str | Sequence[str] | Path | None = None) Path

Return the Path that corresponds to the path relative to the temporary directory that is passed in.

Parameters:

path (str | Sequence[str] | Path | None) –

The path to the file to create, which can be:

  • A tuple of strings.

  • A forward-slash separated string.

as_string(path: str | Sequence[str] | None = None) str

Return the full path on disk that corresponds to the path relative to the temporary directory that is passed in.

Parameters:

path (str | Sequence[str] | None) –

The path to the file to create, which can be:

  • A tuple of strings.

  • A forward-slash separated string.

Returns:

A string containing the absolute path.

Return type:

str

cleanup() None

Delete the temporary directory and anything in it. This TempDirectory cannot be used again unless create() is called.

classmethod cleanup_all() None

Delete all temporary directories associated with all TempDirectory objects.

compare(expected: Sequence[str], path: str | Sequence[str] | Path | None = None, files_only: bool = False, recursive: bool = True, followlinks: bool = False) None

Compare the expected contents with the actual contents of the temporary directory. An AssertionError will be raised if they are not the same.

Parameters:
  • expected (Sequence[str]) – A sequence of strings containing the paths expected in the directory. These paths should be forward-slash separated and relative to the root of the temporary directory.

  • path (str | Sequence[str] | Path | None) –

    The path to use as the root for the comparison, relative to the root of the temporary directory. This can either be:

    • A tuple of strings, making up the relative path.

    • A forward-slash separated string.

    If it is not provided, the root of the temporary directory will be used.

  • files_only (bool) – If specified, directories will be excluded from the list of actual paths used in the comparison.

  • recursive (bool) – If False, only the direct contents of the directory specified by path will be included in the actual contents used for comparison.

  • followlinks (bool) – If True, symlinks and hard links will be followed when recursively building up the actual list of directory contents.

create() Self

Create a temporary directory for this instance to use if one has not already been created.

getpath(path: str | Sequence[str] | None = None) str

Return the full path on disk that corresponds to the path relative to the temporary directory that is passed in.

Parameters:

path (str | Sequence[str] | None) –

The path to the file to create, which can be:

  • A tuple of strings.

  • A forward-slash separated string.

Returns:

A string containing the absolute path.

Return type:

str

listdir(path: str | Sequence[str] | Path | None = None, recursive: bool = False) None

Print the contents of the specified directory.

Parameters:
  • path (str | Sequence[str] | Path | None) –

    The path to list, which can be:

    • None, indicating the root of the temporary directory should be listed.

    • A tuple of strings, indicating that the elements of the tuple should be used as directory names to traverse from the root of the temporary directory to find the directory to be listed.

    • A forward-slash separated string, indicating the directory or subdirectory that should be traversed to from the temporary directory and listed.

  • recursive (bool) – If True, the directory specified will have its subdirectories recursively listed too.

parse(filepath: str | Sequence[str] | Path, format: Format | None = None) Any

Read and deserialize a file, auto-detecting format from file extension.

Parameters:
  • filepath (str | Sequence[str] | Path) – The path to read, relative to the temporary directory.

  • format (Format | None) – Optional format handler. If provided, uses this format instead of auto-detecting from file extension.

Returns:

The deserialized Python object.

Return type:

Any

read(filepath: str | Sequence[str] | Path, encoding: str | None = None, format: Format | None = None) str | bytes | Any

Reads the file at the specified path within the temporary directory.

The file is always read in binary mode. Bytes will be returned unless an encoding is supplied, in which case a unicode string of the decoded data will be returned, or a format is supplied, in which case the deserialized Python object will be returned.

Parameters:
  • filepath (str | Sequence[str] | Path) –

    The path to the file to read, which can be:

    • A tuple of strings.

    • A forward-slash separated string.

  • encoding (str | None) – The encoding used to decode bytes from the file into a string. When used with format, this controls the decoding of bytes from the file before parsing.

  • format (Format | None) – A Format instance to use for deserializing the data. When used with encoding, the file bytes are first decoded with the specified encoding, then parsed by the format.

Returns:

The contents of the file as a str, bytes, or deserialized Python object depending on the parameters provided.

Return type:

str | bytes | Any

read_bytes(filepath: str | Sequence[str] | Path) bytes

Read file as bytes, mirroring pathlib.Path.read_bytes() behavior.

Parameters:

filepath (str | Sequence[str] | Path) – The path to the file to read.

Returns:

The file contents as bytes.

Return type:

bytes

read_text(filepath: str | Sequence[str] | Path, encoding: str | None = None, errors: str | None = None) str

Read file as text, mirroring pathlib.Path.read_text() behavior.

Parameters:
  • filepath (str | Sequence[str] | Path) – The path to the file to read.

  • encoding (str | None) – Text encoding. Uses instance default encoding if None, then falls back to platform default (locale encoding).

  • errors (str | None) – Error handling strategy (e.g., ‘strict’, ‘ignore’, ‘replace’).

Returns:

The file contents as a string.

Return type:

str

property path: Path

The absolute path where data will be stored

makedir(dirpath: str | Sequence[str] | Path) Path

Make an empty directory at the specified path within the temporary directory. Any intermediate subdirectories that do not exist will also be created.

Parameters:

dirpath (str | Sequence[str] | Path) –

The directory to create, which can be:

  • A tuple of strings.

  • A forward-slash separated string.

Returns:

The absolute path of the created directory.

Return type:

Path

write(filepath: str | Sequence[str] | Path, data: bytes) Path
write(filepath: str | Sequence[str] | Path, data: str, encoding: str | None = None) Path
write(filepath: str | Sequence[str] | Path, data: Any, encoding: str, format: Format) Path
write(filepath: str | Sequence[str] | Path, data: Any, *, format: Format) Path

Write the supplied data to a file at the specified path within the temporary directory. Any subdirectories specified that do not exist will also be created.

The file will always be written in binary mode. The data supplied must either be bytes or an encoding must be supplied to convert the string into bytes, or a format must be supplied to serialize the data.

Parameters:
  • filepath (str | Sequence[str] | Path) –

    The path to the file to create, which can be:

    • A tuple of strings.

    • A forward-slash separated string.

  • data (str | bytes | Any) – bytes containing the data to be written, a str if encoding has been supplied, or any Python object if format has been supplied.

  • encoding (str | None) – The encoding to be used for converting strings to bytes. Should not be passed if data is already bytes. When used with format, this controls the encoding of the formatted string before writing to disk.

  • format (Format | None) – A Format instance to use for serializing the data. When used with encoding, the format first renders the data to a string, then that string is encoded with the specified encoding.

Returns:

The absolute path of the file written.

Return type:

Path

dump(filepath: str | Sequence[str] | Path, data: Any, format: Format | None = None) Path

Serialize and write data to a file, auto-detecting format from file extension.

Parameters:
  • filepath (str | Sequence[str] | Path) – The path to write, relative to the temporary directory.

  • data (Any) – The Python object to serialize.

  • format (Format | None) – Optional format handler. If provided, uses this format instead of auto-detecting from file extension.

Returns:

The full path of the file that was written.

Return type:

Path

clone(source: str | Path, filepath: str | Sequence[str] | Path | None = None) Path

Clone a file or directory from outside the TempDir into it.

Parameters:
  • source (str | Path) – Path to the source file or directory.

  • filepath (str | Sequence[str] | Path | None) – Destination within TempDir. If None, uses source’s name at root. If ends with ‘/’ or is a sequence ending with ‘’, clones into that directory rather than as that path.

Returns:

Absolute path of the cloned content.

Return type:

Path

class testfixtures.TempDirectory(path: str | Path | None = None, *, ignore: Sequence[str] = (), create: bool | None = None, encoding: str | None = None, cwd: bool = False, formats: Sequence[Format] = (<testfixtures.formats.JSONFormat object>, <testfixtures.formats.YAMLFormat object>, <testfixtures.formats.TOMLFormat object>))

Deprecated since version 11: Use TempDir instead.

A class representing a temporary directory on disk.

Parameters:
  • ignore (Sequence[str]) – A sequence of strings containing regular expression patterns that match filenames that should be ignored by the TempDirectory listing and checking methods.

  • create (bool | None) – If True, the temporary directory will be created as part of class instantiation.

  • path (str | Path | None) – If passed, this should be a string containing an absolute path to use as the temporary directory. When passed, TempDirectory will not create a new directory to use.

  • encoding (str | None) – A default encoding to use for read() and write() operations when the encoding parameter is not passed to those methods.

  • cwd (bool) – If True, set the current working directory to be that of the temporary directory when used as a decorator or context manager.

property path: str

The absolute path where data will be stored

makedir(dirpath: str | Sequence[str] | Path) str

Make an empty directory at the specified path within the temporary directory. Any intermediate subdirectories that do not exist will also be created.

Parameters:

dirpath (str | Sequence[str] | Path) –

The directory to create, which can be:

  • A tuple of strings.

  • A forward-slash separated string.

Returns:

The absolute path of the created directory.

Return type:

str

as_path(path: str | Sequence[str] | Path | None = None) Path

Return the Path that corresponds to the path relative to the temporary directory that is passed in.

Parameters:

path (str | Sequence[str] | Path | None) –

The path to the file to create, which can be:

  • A tuple of strings.

  • A forward-slash separated string.

as_string(path: str | Sequence[str] | None = None) str

Return the full path on disk that corresponds to the path relative to the temporary directory that is passed in.

Parameters:

path (str | Sequence[str] | None) –

The path to the file to create, which can be:

  • A tuple of strings.

  • A forward-slash separated string.

Returns:

A string containing the absolute path.

Return type:

str

cleanup() None

Delete the temporary directory and anything in it. This TempDirectory cannot be used again unless create() is called.

classmethod cleanup_all() None

Delete all temporary directories associated with all TempDirectory objects.

compare(expected: Sequence[str], path: str | Sequence[str] | Path | None = None, files_only: bool = False, recursive: bool = True, followlinks: bool = False) None

Compare the expected contents with the actual contents of the temporary directory. An AssertionError will be raised if they are not the same.

Parameters:
  • expected (Sequence[str]) – A sequence of strings containing the paths expected in the directory. These paths should be forward-slash separated and relative to the root of the temporary directory.

  • path (str | Sequence[str] | Path | None) –

    The path to use as the root for the comparison, relative to the root of the temporary directory. This can either be:

    • A tuple of strings, making up the relative path.

    • A forward-slash separated string.

    If it is not provided, the root of the temporary directory will be used.

  • files_only (bool) – If specified, directories will be excluded from the list of actual paths used in the comparison.

  • recursive (bool) – If False, only the direct contents of the directory specified by path will be included in the actual contents used for comparison.

  • followlinks (bool) – If True, symlinks and hard links will be followed when recursively building up the actual list of directory contents.

create() Self

Create a temporary directory for this instance to use if one has not already been created.

getpath(path: str | Sequence[str] | None = None) str

Return the full path on disk that corresponds to the path relative to the temporary directory that is passed in.

Parameters:

path (str | Sequence[str] | None) –

The path to the file to create, which can be:

  • A tuple of strings.

  • A forward-slash separated string.

Returns:

A string containing the absolute path.

Return type:

str

listdir(path: str | Sequence[str] | Path | None = None, recursive: bool = False) None

Print the contents of the specified directory.

Parameters:
  • path (str | Sequence[str] | Path | None) –

    The path to list, which can be:

    • None, indicating the root of the temporary directory should be listed.

    • A tuple of strings, indicating that the elements of the tuple should be used as directory names to traverse from the root of the temporary directory to find the directory to be listed.

    • A forward-slash separated string, indicating the directory or subdirectory that should be traversed to from the temporary directory and listed.

  • recursive (bool) – If True, the directory specified will have its subdirectories recursively listed too.

parse(filepath: str | Sequence[str] | Path, format: Format | None = None) Any

Read and deserialize a file, auto-detecting format from file extension.

Parameters:
  • filepath (str | Sequence[str] | Path) – The path to read, relative to the temporary directory.

  • format (Format | None) – Optional format handler. If provided, uses this format instead of auto-detecting from file extension.

Returns:

The deserialized Python object.

Return type:

Any

read(filepath: str | Sequence[str] | Path, encoding: str | None = None, format: Format | None = None) str | bytes | Any

Reads the file at the specified path within the temporary directory.

The file is always read in binary mode. Bytes will be returned unless an encoding is supplied, in which case a unicode string of the decoded data will be returned, or a format is supplied, in which case the deserialized Python object will be returned.

Parameters:
  • filepath (str | Sequence[str] | Path) –

    The path to the file to read, which can be:

    • A tuple of strings.

    • A forward-slash separated string.

  • encoding (str | None) – The encoding used to decode bytes from the file into a string. When used with format, this controls the decoding of bytes from the file before parsing.

  • format (Format | None) – A Format instance to use for deserializing the data. When used with encoding, the file bytes are first decoded with the specified encoding, then parsed by the format.

Returns:

The contents of the file as a str, bytes, or deserialized Python object depending on the parameters provided.

Return type:

str | bytes | Any

read_bytes(filepath: str | Sequence[str] | Path) bytes

Read file as bytes, mirroring pathlib.Path.read_bytes() behavior.

Parameters:

filepath (str | Sequence[str] | Path) – The path to the file to read.

Returns:

The file contents as bytes.

Return type:

bytes

read_text(filepath: str | Sequence[str] | Path, encoding: str | None = None, errors: str | None = None) str

Read file as text, mirroring pathlib.Path.read_text() behavior.

Parameters:
  • filepath (str | Sequence[str] | Path) – The path to the file to read.

  • encoding (str | None) – Text encoding. Uses instance default encoding if None, then falls back to platform default (locale encoding).

  • errors (str | None) – Error handling strategy (e.g., ‘strict’, ‘ignore’, ‘replace’).

Returns:

The file contents as a string.

Return type:

str

write(filepath: str | Sequence[str] | Path, data: bytes) str
write(filepath: str | Sequence[str] | Path, data: str, encoding: str | None = None) str
write(filepath: str | Sequence[str] | Path, data: Any, encoding: str, format: Format) str
write(filepath: str | Sequence[str] | Path, data: Any, *, format: Format) str

Write the supplied data to a file at the specified path within the temporary directory. Any subdirectories specified that do not exist will also be created.

The file will always be written in binary mode. The data supplied must either be bytes or an encoding must be supplied to convert the string into bytes, or a format must be supplied to serialize the data.

Parameters:
  • filepath (str | Sequence[str] | Path) –

    The path to the file to create, which can be:

    • A tuple of strings.

    • A forward-slash separated string.

  • data (str | bytes | Any) – bytes containing the data to be written, a str if encoding has been supplied, or any Python object if format has been supplied.

  • encoding (str | None) – The encoding to be used for converting strings to bytes. Should not be passed if data is already bytes. When used with format, this controls the encoding of the formatted string before writing to disk.

  • format (Format | None) – A Format instance to use for serializing the data. When used with encoding, the format first renders the data to a string, then that string is encoded with the specified encoding.

Returns:

The absolute path of the file written.

Return type:

str

dump(filepath: str | Sequence[str] | Path, data: Any, format: Format | None = None) str

Serialize and write data to a file, auto-detecting format from file extension.

Parameters:
  • filepath (str | Sequence[str] | Path) – The path to write, relative to the temporary directory.

  • data (Any) – The Python object to serialize.

  • format (Format | None) – Optional format handler. If provided, uses this format instead of auto-detecting from file extension.

Returns:

The full path of the file that was written.

Return type:

str

clone(source: str | Path, filepath: str | Sequence[str] | Path | None = None) str

Clone a file or directory from outside the TempDir into it.

Parameters:
  • source (str | Path) – Path to the source file or directory.

  • filepath (str | Sequence[str] | Path | None) – Destination within TempDir. If None, uses source’s name at root. If ends with ‘/’ or is a sequence ending with ‘’, clones into that directory rather than as that path.

Returns:

Absolute path of the cloned content.

Return type:

str

testfixtures.tempdir(path: str | Path | None = None, *, ignore: Sequence[str] = (), encoding: str | None = None, cwd: bool = False) Callable[[Callable], Callable]

Deprecated since version 11: Use TempDir as a context manager, or create a pytest fixture.

A decorator for making a TempDirectory available for the duration of a test function.

All arguments and parameters are passed through to the TempDirectory constructor.

Serialization Formats

Format handlers for serialization and deserialization of common data formats.

This module provides a consistent interface for working with JSON, YAML, and TOML formats. Each format handler implements the Format protocol with parse() and render() methods.

class testfixtures.formats.Format(*args, **kwargs)

Protocol for format handlers that can parse and render data.

This protocol defines the interface for serialization formats used with TempDirectory. Implement this protocol to add support for additional formats.

suffixes: Sequence[str]

File extensions supported by this format (with leading dot, e.g. (‘.json’,))

parse(data: str) Any

Parse a string into a Python object.

Parameters:

data (str) – The string to parse.

Returns:

The deserialized Python object.

Return type:

Any

render(obj: Any) str

Render a Python object into a string.

Parameters:

obj (Any) – The Python object to serialize.

Returns:

The serialized string.

Return type:

str

class testfixtures.formats.JSONFormat

JSON format handler using the standard library json module.

parse(data: str) Any

Parse JSON string into a Python object.

render(obj: Any) str

Render a Python object into a JSON string.

class testfixtures.formats.YAMLFormat

YAML format handler. Requires pyyaml to be installed.

parse(data: str) Any

Parse YAML string into a Python object.

render(obj: Any) str

Render a Python object into a YAML string.

class testfixtures.formats.TOMLFormat

TOML format handler. Reading uses the standard library tomllib (3.11+) or tomlkit if available. Writing requires tomlkit.

parse(data: str) Any

Parse TOML string into a Python dict.

render(obj: Any) str

Render a Python dict into a TOML string.

testfixtures.formats.JSON: Format = <testfixtures.formats.JSONFormat object>

JSON format handler using the standard library. Always available.

testfixtures.formats.YAML: Format = <testfixtures.formats.YAMLFormat object>

YAML format handler. Requires the pyyaml package to be installed.

To install the required package, use your package manager to install pyyaml.

testfixtures.formats.TOML: Format = <testfixtures.formats.TOMLFormat object>

TOML format handler. Reading uses the standard library tomllib module (Python 3.11+) or tomlkit if available. Writing requires the tomlkit package.

To install the package for writing support, use your package manager to install tomlkit, or install testfixtures with the toml extra.

Helpers and Constants

testfixtures.diff(x: str, y: str, x_label: str | None = '', y_label: str | None = '') str

A shorthand function that uses difflib to return a string representing the differences between the two string arguments.

Most useful when comparing multi-line strings.

testfixtures.generator(*args: Any) Generator[Any, None, None]

A utility function for creating a generator that will yield the supplied arguments.

testfixtures.wrap(before: Callable[[], T], after: Callable[[], None] | None = None) Callable[[Callable[[P], U]], Callable[[P], U]]

A decorator that causes the supplied callables to be called before or after the wrapped callable, as appropriate.

class testfixtures.singleton(name: str)
testfixtures.not_there

A singleton used to represent the absence of a particular attribute or parameter.

Framework Helpers

Framework-specific helpers provided by testfixtures.

testfixtures.django

testfixtures.django.compare_model(x: Model, y: Model, context: CompareContext, ignore_fields: Sequence[str] = (), non_editable_fields: bool = False) str | None

Returns an informative string describing the differences between the two supplied Django model instances. The way in which this comparison is performed can be controlled using the following parameters:

Parameters:
  • ignore_fields (Sequence[str]) – A sequence of fields to ignore during comparison, most commonly set to ['id']. By default, no fields are ignored.

  • non_editable_fields (bool) – If True, then fields with editable=False will be included in the comparison. By default, these fields are ignored.

testfixtures.sybil

class testfixtures.sybil.FileParser(name: str)

A Sybil parser that parses certain ReST sections to read and write files in the configured TempDirectory.

Parameters:

name (str) – This is the name of the TempDirectory to use in the Sybil test namespace.

testfixtures.loguru

Tools for helping to test applications that use Loguru.

testfixtures.loguru.level_name(record: dict) str

Extract level name from the logged record

Parameters:

record (dict) – A loguru record dict.

class testfixtures.loguru.LoguruSource(attributes: ~typing.Sequence[str | ~typing.Callable[[dict], ~typing.Any]] | ~typing.Callable[[dict], ~typing.Any] = (<function level_name>, 'message'), level: int | str = 0, **kw: ~typing.Any)

A CaptureSource for loguru logging, for use with LogCapture.

On install() all existing loguru handlers are removed and replaced with a single capture handler. On uninstall(), the original handlers are restored.

Parameters:
  • attributes (Sequence[str | Callable[[dict], Any]] | Callable[[dict], Any]) –

    The sequence of attributes to return for each record or a callable that extracts actual from a record.

    If a sequence of attribute names is passed, for each item, a key of that name will be obtained from the record dict. If the key is missing, None will be used in its place.

    If a callable is passed, it will be called with the record and the value returned will be used as actual.

  • level (int | str) – Minimum log level to capture. Defaults to 0, capture everything.

Additional keyword arguments are forwarded to logger.add.

testfixtures.pandas

Tools for helping to test applications that use Pandas.

testfixtures.pandas.compare_dataframe(x: DataFrame, y: DataFrame, context: CompareContext) str | None

Returns a textual description of the differences between two pandas.DataFrame instances, as reported by pandas.testing.assert_frame_equal().

When strict=True is passed to compare(), check_exact=True is used; otherwise pandas’ default tolerances apply.

testfixtures.polars

Tools for helping to test applications that use Polars.

testfixtures.polars.compare_dataframe(x: DataFrame, y: DataFrame, context: CompareContext) str | None

Returns a textual description of the differences between two polars.DataFrame instances, as reported by polars.testing.assert_frame_equal().

When strict=True is passed to compare(), check_exact=True is used; otherwise polars’ default tolerances apply.

testfixtures.structlog

Tools for helping to test applications that use structlog.

testfixtures.structlog.level_name(event_dict: MutableMapping[str, Any]) str

Extract the upper-case level name from a structlog event dict as set by structlog.stdlib.add_log_level().

testfixtures.structlog.raw(event_dict: MutableMapping[str, Any]) MutableMapping[str, Any]

Return the raw structlog event dict for use as the actual value.

class testfixtures.structlog.StructlogSource(attributes: ~typing.Sequence[str | ~typing.Callable[[~typing.MutableMapping[str, ~typing.Any]], ~typing.Any]] | ~typing.Callable[[~typing.MutableMapping[str, ~typing.Any]], ~typing.Any] = (<function level_name>, 'event'), level: int | str = 0, processors: ~typing.Sequence[~typing.Callable[[~typing.Any, str, ~typing.MutableMapping[str, ~typing.Any]], ~typing.Mapping[str, ~typing.Any] | str | bytes | bytearray | ~typing.Tuple[~typing.Any, ...]]] = (<function add_log_level>, <function merge_contextvars>))

A CaptureSource for structlog, for use with LogCapture.

On install(), the current structlog configuration is saved replaced with a chain that captures each event. On uninstall(), the saved configuration is restored.

Parameters:

testfixtures.twisted

Tools for helping to test Twisted applications.

class testfixtures.twisted.TwistedSource(attributes: ~typing.Sequence[str | ~typing.Callable[[dict[str, ~typing.Any]], ~typing.Any]] | ~typing.Callable[[dict[str, ~typing.Any]], ~typing.Any] = (<function level_name>, <function formatEvent>), level: int | str | ~constantly._constants.NamedConstant = 0)

A CaptureSource for Twisted log events, for use with LogCapture.

On install() all existing observers on twisted.logger.globalLogPublisher are replaced with this source; on uninstall() the original observers are restored.

Parameters:
  • attributes (Sequence[str | Callable[[dict[str, Any]], Any]] | Callable[[dict[str, Any]], Any]) –

    The sequence of attributes to return for each LogEvent or a callable that extracts actual from a record.

    If a sequence of attribute names is passed, for each item, a key of that name will be obtained from the LogEvent. If the key is missing, None will be used in its place.

    If a callable is passed, it will be called with the LogEvent and the value returned will be used as actual.

  • level (int | str | NamedConstant) –

    The minimum log level to capture. Accepts an int, a Twisted LogLevel constant, or a level name string such as 'warn'. The module-level constants DEBUG, INFO, WARN, ERROR, CRITICAL can also be used.

    Defaults to 0 (capture everything).

class testfixtures.twisted.LogCapture(fields: ~typing.Sequence[str | ~typing.Callable[[dict[str, ~typing.Any]], ~typing.Any]] | ~typing.Callable[[dict[str, ~typing.Any]], ~typing.Any] = ('log_level', <function formatEvent>), install: bool = False)

A helper for capturing stuff logged using Twisted’s loggers.

Parameters:

fields (Sequence[str | Callable[[dict[str, Any]], Any]] | Callable[[dict[str, Any]], Any]) –

The sequence of fields to return for each LogEvent or a callable that extracts actual from a record.

If a sequence of attribute names is passed, for each item, a key of that name will be obtained from the LogEvent. If the key is missing, None will be used in its place.

If a callable is passed, it will be called with the LogEvent and the value returned will be used as actual.

property events: list[dict[str, Any]]

The list of raw Twisted log events captured.

check_failure_text(expected: str, index: int = -1, attribute: str = 'value') None

Check the string representation of an attribute of a logged Failure is as expected.

Parameters:
  • expected (str) – The expected string representation.

  • index (int) – The index into events where the failure should have been logged.

  • attribute (str) – The attribute of the failure of which to find the string representation.

raise_logged_failure(start_index: int = 0) None

A debugging tool that raises the first failure encountered in captured logging.

Parameters:

start_index (int) – The index into events from where to start looking for failures.

classmethod make(testcase: ~twisted.trial._asynctest.TestCase, fields: ~typing.Sequence[str | ~typing.Callable[[dict[str, ~typing.Any]], ~typing.Any]] | ~typing.Callable[[dict[str, ~typing.Any]], ~typing.Any] = ('log_level', <function formatEvent>)) Self

Instantiate, install and add a cleanup for a LogCapture.

Parameters:

testcase (TestCase) – This must be an instance of twisted.trial.unittest.TestCase.

Any other parameters are passed directly to the LogCapture constructor.

Returns:

The LogCapture instantiated by this method.

Return type:

Self

testfixtures.twisted.DEBUG: NamedConstant = <LogLevel=debug>

Short reference to Twisted’s LogLevel.debug

testfixtures.twisted.INFO: NamedConstant = <LogLevel=info>

Short reference to Twisted’s LogLevel.info

testfixtures.twisted.WARN: NamedConstant = <LogLevel=warn>

Short reference to Twisted’s LogLevel.warn

testfixtures.twisted.ERROR: NamedConstant = <LogLevel=error>

Short reference to Twisted’s LogLevel.error

testfixtures.twisted.CRITICAL: NamedConstant = <LogLevel=critical>

Short reference to Twisted’s LogLevel.critical