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 | None = None, suffix: 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 = 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
AssertionErrorif they are not the same. TheAssertionErrorraised 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
xandy, orexpectedandactual, or a mixture of these.- Parameters:
prefix – If provided, in the event of an
AssertionErrorbeing raised, the prefix supplied will be prepended to the message in theAssertionError. This may be a callable, in which case it will only be resolved if needed.suffix – If provided, in the event of an
AssertionErrorbeing raised, the suffix supplied will be appended to the message in theAssertionError. This may be a callable, in which case it will only be resolved if needed.x_label – If provided, in the event of an
AssertionErrorbeing raised, the object passed as the first positional argument, orxkeyword argument, will be labelled with this string in the message in theAssertionError.y_label – If provided, in the event of an
AssertionErrorbeing raised, the object passed as the second positional argument, orykeyword argument, will be labelled with this string in the message in theAssertionError.raises – If
False, the message that would be raised in theAssertionErrorwill be returned instead of the exception being raised.recursive – If
True, when a difference is found in a nested data structure, attempt to highlight the location of the difference.strict – If
True, objects will only compare equal if they are of the same type as well as being equal.ignore_eq – If
True, object equality, which relies on__eq__being correctly implemented, will not be used. Instead, comparers will be looked up and used and, if no suitable comparer is found, objects will be considered equal if their hash is equal.comparers – 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 belowfor 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 – The object or class from which to create the
Comparison.attribute_dict – An optional dictionary containing attributes to place on the
Comparison.partial – If true, only the specified attributes will be checked and any extra attributes of the object being compared with will be ignored.
attributes – 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
Comparisonwithpartial=Truebut is typed to return the type being compared, making it compatible with strict type checkers like mypy.- Parameters:
t – The type to compare against.
attributes – Keyword arguments specifying the attributes to check.
- Returns:
A
Comparisonobject typed as the input type.
- 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 – The mapping that should be matched expressed as either a sequence of
(key, value)tuples or a mapping.expected_items – The items that should be matched.
ordered – If
True, then the keys in the mapping are expected to be in the order specified. Defaults toFalse.partial – If
True, then any keys not expected will be ignored. Defaults toFalse.recursive – 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
SequenceComparisonthat 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 – numeric to be compared.
precision – 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 – the inclusive lower bound for the acceptable range.
upper_bound – 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 – The items expected to be in the sequence.
ordered – If
True, then the items are expected to be in the order specified. IfFalse, they may be in any order. Defaults toTrue.partial – If
True, then any keys not expected will be ignored. Defaults toFalse.recursive – 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 – If
True, only items in the expected sequence need to be present in the actual sequence. Defaults toFalse.ordered – If
True, items must appear in the same order. Defaults toTrue.recursive – If
True, provide detailed recursive comparison when differences are found. Defaults toTrue.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.
- 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 – 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.
- 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 – 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.
- class testfixtures.Subset(*expected: Any)¶
A shortcut for
SequenceComparisonthat 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 – A string containing the source for a regular expression that will be used whenever this
StringComparisonis compared with anystrinstance.flags – Flags passed to
re.compile().flag_names – See the examples.
testfixtures.comparison¶
- testfixtures.comparison.register(type_: type, comparer: Callable[[Any, Any, CompareContext], str | None]) None¶
Register the supplied comparer for the specified type. This registration is global and will be in effect from the point this function is called until the end of the current process.
- testfixtures.comparison.compare_simple(x: Any, y: Any, context: CompareContext) str | None¶
Returns a very simple textual difference between the two supplied objects.
- testfixtures.comparison.compare_object(x: object, y: object, context: CompareContext, ignore_attributes: Iterable[str] = ()) str | None¶
Compare the two supplied objects based on their type and attributes.
- Parameters:
ignore_attributes –
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.
This may be specified as either a parameter to this function or in the
context. If specified in both, they will both apply with precedence given to whatever is specified is specified as a parameter. If specified as a parameter to this function, it may only be a list of strings.
- testfixtures.comparison.compare_exception(x: BaseException, y: BaseException, context: CompareContext) str | None¶
Compare the two supplied exceptions based on their message, type and attributes.
- testfixtures.comparison.compare_exception_group(x: BaseExceptionGroup, y: BaseExceptionGroup, context: CompareContext) str | None¶
Compare the two supplied exception groups
- testfixtures.comparison.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.comparison.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.comparison.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.comparison.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
_fieldsattribute on a tuple is used to decide whether or not it is anamedtuple().
- testfixtures.comparison.compare_dict(x: dict, y: dict, context: CompareContext) str | None¶
Returns a textual description of the differences between the two supplied dictionaries.
- testfixtures.comparison.compare_set(x: set, y: set, context: CompareContext) str | None¶
Returns a textual description of the differences between the two supplied sets.
- testfixtures.comparison.compare_text(x: str, y: str, context: CompareContext) 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 – If False, then when comparing multi-line strings, any blank lines in either argument will be ignored.
trailing_whitespace – If False, then when comparing multi-line strings, trailing whilespace on lines will be ignored.
show_whitespace – If True, then whitespace characters in multi-line strings will be replaced with their representations.
- class testfixtures.comparison.CompareContext(x_label: str | None, y_label: str | None, recursive: bool = True, strict: bool = False, ignore_eq: bool = 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().
Capturing¶
- 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] = ('name', 'levelname', 'getMessage'), recursive_check: bool = False, ensure_checks_above: int | None = None)¶
These are used to capture entries logged to the Python logging framework and make assertions about what was logged.
- Parameters:
names – A string (or tuple of strings) containing the dotted name(s) of loggers to capture. By default, the root logger is captured.
install – If True, the
LogCapturewill be installed as part of its instantiation.propagate – 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 –
The sequence of attribute names to return for each record or a callable that extracts a row from a record.
If a sequence of attribute names, those attributes will be taken from the
LogRecord. If an attribute is callable, the value used will be the result of calling it. If an attribute is missing,Nonewill be used in its place.If a callable, it will be called with the
LogRecordand the value returned will be used as the row.recursive_check – If
True, log messages will be compared recursively byLogCapture.check().ensure_checks_above – The log level above which checks must be made for logged events. See
ensure_checked().
- actual() list[Any]¶
The sequence of actual records logged, having had their attributes extracted as specified by the
attributesparameter to theLogCaptureconstructor.This can be useful for making more complex assertions about logged records. The actual records logged can also be inspected by using the
recordsattribute.
- check(*expected: Any) None¶
This will compare the captured entries with the expected entries provided and raise an
AssertionErrorif they do not match.- Parameters:
expected – A sequence of entries of the structure specified by the
attributespassed to the constructor.
- check_present(*expected: Any, order_matters: bool = True) None¶
This will check if the captured entries contain all of the expected entries provided and raise an
AssertionErrorif not. This will ignore entries that have been captured but that do not match those inexpected.- Parameters:
expected – A sequence of entries of the structure specified by the
attributespassed to the constructor.order_matters – 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.
- close() None¶
Tidy up any resources used by the handler.
This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods.
- ensure_checked(level: int | None = None) None¶
Ensure every entry logged above the specified level has been checked. Raises an
AssertionErrorif this is not the case.- Parameters:
level – the logging level, defaults to
ensure_checks_above.
- install() Self | None¶
Install this
LogCaptureinto the Python logging framework for the named loggers.This will remove any existing handlers for those loggers and drop their level to that specified on this
LogCapturein order to capture all logging.
- mark_all_checked() None¶
Mark all captured events as checked. This should be called if you have made assertions about logging other than through
LogCapturemethods.
- records: List[LogRecord]¶
The records captured by this
LogCapture.
- uninstall() None¶
Un-install this
LogCapturefrom the Python logging framework for the named loggers.This will re-instate any existing handlers for those loggers that were removed during installation and restore their level that prior to installation.
- classmethod uninstall_all() None¶
This will uninstall all existing
LogCaptureobjects.
- testfixtures.log_capture(*names: str, **kw: Any) Callable¶
A decorator for making a
LogCaptureinstalled and available for the duration of a test function.- Parameters:
names – An optional sequence of names specifying the loggers to be captured. If not specified, the root logger will be captured.
Keyword parameters other than
installmay also be supplied and will be passed on to theLogCaptureconstructor.
- class testfixtures.OutputCapture(separate: bool = False, fd: bool = False, strip_whitespace: bool = True)¶
A context manager for capturing output to the
sys.stdoutandsys.stderrstreams.- Parameters:
separate – If
True,stdoutandstderrwill be captured separately and their expected values must be passed tocompare().fd – If
True, the underlying file descriptors will be captured, rather than just the attributes onsys. 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 – When
True, which is the default, leading and training whitespace is trimmed from both the expected and actual values when comparing.
Note
If
separateis passed asTrue,OutputCapture.capturedwill be an empty string.- compare(expected: str | StringComparison = '', stdout: str | StringComparison = '', stderr: str | StringComparison = '') None¶
Compare the captured output to that expected. If the output is not the same, an
AssertionErrorwill be raised.- Parameters:
expected – A string containing the expected combined output of
stdoutandstderr.stdout – A string containing the expected output to
stdout.stderr – A string containing the expected output to
stderr.
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
Replacerto replace a single target.- Parameters:
target –
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
namemust be specified.The object to be replaced, in which case
containermust be specified.namemust also be specified if it cannot be obtained from the__name__attribute of the object to be replaced.
replacement – The object to use as a replacement.
strict – 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
accessorto access thenamefrom thecontaineris not identical to thetarget.container – The container of the object from which
targetcan be accessed using eithergetattr()orgetitem().accessor – Either
getattr()orgetitem(). If not supplied, this will be inferred.name – The name used to access the
targetfrom thecontainerusing theaccessor. If required but not specified, the__name__attribute of thetargetwill be used.sep – When
targetis 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 –
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
namemust be specified.The object to be replaced, in which case
containermust be specified.namemust also be specified if it cannot be obtained from the__name__attribute of the object to be replaced.
replacement – The object to use as a replacement.
strict – 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
accessorto access thenamefrom thecontaineris not identical to thetarget.container – The container of the object from which
targetcan be accessed using eithergetattr()orgetitem().accessor – Either
getattr()orgetitem(). If not supplied, this will be inferred.name – The name used to access the
targetfrom thecontainerusing theaccessor. If required but not specified, the__name__attribute of thetargetwill be used.sep – When
targetis 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.environis set to a particular value.If you wish to ensure that an environment variable is not present, then use
not_thereas thereplacement.
- 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
moduleshould be used to specify the module where you would like the replacement to occur.
- 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, thennamemust be used to provide the correct name.
- 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 –
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
namemust be specified.The object to be replaced, in which case
containermust be specified.namemust also be specified if it cannot be obtained from the__name__attribute of the object to be replaced.
replacement – The object to use as a replacement.
strict – 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
accessorto access thenamefrom thecontaineris not identical to thetarget.container – The container of the object from which
targetcan be accessed using eithergetattr()orgetitem().accessor – Either
getattr()orgetitem(). If not supplied, this will be inferred.name – The name used to access the
targetfrom thecontainerusing theaccessor. If required but not specified, the__name__attribute of thetargetwill be used.sep – When
targetis a string, this is the separator between traversal segments.
- 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 –
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
namemust be specified.The object to be replaced, in which case
containermust be specified.namemust also be specified if it cannot be obtained from the__name__attribute of the object to be replaced.
replacement – The object to use as a replacement.
strict – 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
accessorto access thenamefrom thecontaineris not identical to thetarget.container – The container of the object from which
targetcan be accessed using eithergetattr()orgetitem().accessor – Either
getattr()orgetitem(). If not supplied, this will be inferred.name – The name used to access the
targetfrom thecontainerusing theaccessor. If required but not specified, the__name__attribute of thetargetwill be used.sep – When
targetis a string, this is the separator between traversal segments.
- testfixtures.mock_date(year=2001, month=1, day=1, delta=None, delta_type='days', strict=False)¶
A function that returns a mock object that can be used in place of the
datetime.dateclass but where the return value oftoday()can be controlled.If a single positional argument of
Noneis passed, then the queue of dates to be returned will be empty and you will need to callset()oradd()before callingtoday().If an instance of
dateis passed as a single positional argument, that will be used as the first date returned bytoday()- 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 – The size of the delta to use between values returned from
today(). If not specified, it will increase by 1 with each call totoday().delta_type – The type of the delta to use between values returned from
today(). This can be any keyword parameter accepted by thetimedeltaconstructor.strict – If
True, calling the mock class and any of its methods will result in an instance of the mock being returned. IfFalse, the default, an instance ofdatewill be returned instead.
The mock returned will behave exactly as the
datetime.dateclass as well as being a subclass ofMockDate.
- 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.datecreated from the supplied parameters to the queue of dates to be returned bytoday(). An instance ofdatemay also be passed as a single positional argument.
- classmethod set(*args: int | date, **kw: int | tzinfo | None) None¶
This will set the
datetime.datecreated from the supplied parameters as the next date to be returned bytoday(), regardless of any dates in the queue. An instance ofdatemay also be passed as a single positional argument.
- testfixtures.mock_datetime(year=2001, month=1, day=1, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, delta=None, delta_type='seconds', date_type=datetime.date, strict=False)¶
A function that returns a mock object that can be used in place of the
datetime.datetimeclass but where the return value ofnow()can be controlled.If a single positional argument of
Noneis passed, then the queue of datetimes to be returned will be empty and you will need to callset()oradd()before callingnow()orutcnow().If an instance of
datetimeis passed as a single positional argument, that will be used as the first date returned bynow()- 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 – An optional
datetime.tzinfo, see Timezones.delta – 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 – The type of the delta to use between values returned from mocked class methods. This can be any keyword parameter accepted by the
timedeltaconstructor.date_type – 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 – If
True, calling the mock class and any of its methods will result in an instance of the mock being returned. IfFalse, the default, an instance ofdatetimewill be returned instead.
The mock returned will behave exactly as the
datetime.datetimeclass as well as being a subclass ofMockDateTime.
- 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.datetimecreated from the supplied parameters to the queue of datetimes to be returned bynow()orutcnow(). An instance ofdatetimemay also be passed as a single positional argument.
- classmethod set(*args: int | datetime, **kw: int | tzinfo | None) None¶
This will set the
datetime.datetimecreated from the supplied parameters as the next datetime to be returned bynow()orutcnow(), clearing out any datetimes in the queue. An instance ofdatetimemay also be passed as a single positional argument.
- classmethod tick(*args: timedelta, **kw: float) None¶
This method should be called either with a
timedeltaas a positional argument, or with keyword parameters that will be used to construct atimedelta.The
timedeltawill be used to advance the next datetime to be returned bynow()orutcnow().
- classmethod now(tz: tzinfo | None = None) Self¶
- Parameters:
tz – An optional timezone to apply to the returned time. If supplied, it must be an instance of a
tzinfosubclass.
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.
- testfixtures.mock_time(year=2001, month=1, day=1, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, delta=None, delta_type='seconds')¶
A function that returns a
mock objectthat can be used in place of thetime.time()function but where the return value can be controlled.If a single positional argument of
Noneis passed, then the queue of times to be returned will be empty and you will need to callset()oradd()before calling the mock.If an instance of
datetimeis 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 – 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 – The type of the delta to use between values returned. This can be any keyword parameter accepted by the
timedeltaconstructor.
The
add(),set()andtick()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.datetimeconstructor. An instance ofdatetimemay 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.datetimeconstructor. An instance ofdatetimemay also be passed as a single positional argument.
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.CallableBehaviour(*args, **kwargs)¶
- class testfixtures.popen.MockPopen¶
A specialised mock for testing use of
subprocess.Popen. An instance of this class can be used in place of thesubprocess.Popenand is often inserted where it’s needed usingunittest.mock.patch()or aReplacer.- 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 – A
strrepresenting the command to be simulated.stdout –
bytesrepresenting the simulated content written by the process to the stdout pipe.stderr –
bytesrepresenting the simulated content written by the process to the stderr pipe.returncode – An integer representing the return code of the simulated process.
pid – 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 – Specifies the number of times
poll()can be called beforereturncodeis set and returned bypoll().
If supplied,
behaviourmust be either aPopenBehaviourinstance or a callable that takes thecommandstring representing the command to be simulated and thestdinsupplied when instantiating thesubprocess.Popenwith that command and should return aPopenBehaviourinstance.
- 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 –
bytesrepresenting the simulated content written by the process to the stdout pipe.stderr –
bytesrepresenting the simulated content written by the process to the stderr pipe.returncode – An integer representing the return code of the simulated process.
pid – 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 – Specifies the number of times
poll()can be called beforereturncodeis set and returned bypoll().
If supplied,
behaviourmust be either aPopenBehaviourinstance or a callable that takes thecommandstring representing the command to be simulated and thestdinsupplied when instantiating thesubprocess.Popenwith that command and should return aPopenBehaviourinstance.
- 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.- communicate(input: str | bytes | None = None, timeout: float | None = None) Tuple[str | bytes | None, str | bytes | None]¶
Simulate calls to
subprocess.Popen.communicate()
- kill() None¶
Simulate calls to
subprocess.Popen.kill()
- poll() int | None¶
Simulate calls to
subprocess.Popen.poll()
- root_call: _Call¶
A
unittest.mock.call()representing the call made to instantiate this mock process.
- send_signal(signal: int) None¶
Simulate calls to
subprocess.Popen.send_signal()
- stdin: Mock | None = None¶
A
Mockrepresenting the pipe into this process. This is only set ifstdin=PIPEis passed the constructor. The mock records writes and closes inMockPopen.all_calls.
- terminate() None¶
Simulate calls to
subprocess.Popen.terminate()
- wait(timeout: float | None = None) int¶
Simulate calls to
subprocess.Popen.wait()
Assertions¶
- class testfixtures.shouldraise.NoException¶
A marker class indicating no exception has been raised.
ShouldRaise.raisedis set to an instance of this class unless an exception has otherwise been seen.
- class testfixtures.ShouldRaise(exception: E | type[E] | 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 –
This can be one of the following:
None, indicating that an exception must be raised, but the type is unimportant.
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 – Can be passed a boolean that, when
Trueindicates 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: E | type[E] | 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 –
This can be one of the following:
None, indicating that an exception must be raised, but the type is unimportant.
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 – Can be passed a boolean that, when
Trueindicates 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
AssertionErroris raised and its text is as expected.- Parameters:
show_whitespace – 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 –
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 – 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 – If passed, these are used to create a filter such that only warnings you are interested in will be considered by this
ShouldWarninstance. The names and meanings are the same as the parameters forwarnings.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.TempDirectory(path: str | Path | None = None, *, ignore: Sequence[str] = (), create: bool | None = None, encoding: str | None = None, cwd: bool = False)¶
A class representing a temporary directory on disk.
- Parameters:
ignore – A sequence of strings containing regular expression patterns that match filenames that should be ignored by the
TempDirectorylisting and checking methods.create – If True, the temporary directory will be created as part of class instantiation.
path – If passed, this should be a string containing an absolute path to use as the temporary directory. When passed,
TempDirectorywill not create a new directory to use.encoding – A default encoding to use for
read()andwrite()operations when theencodingparameter is not passed to those methods.cwd – If
True, set the current working directory to be that of the temporary directory when used as a decorator or context manager.
- as_path(path: str | Sequence[str] | None = None) Path¶
Return the
Paththat corresponds to the path relative to the temporary directory that is passed in.- Parameters:
path –
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 –
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.
- cleanup() None¶
Delete the temporary directory and anything in it. This
TempDirectorycannot be used again unlesscreate()is called.
- classmethod cleanup_all() None¶
Delete all temporary directories associated with all
TempDirectoryobjects.
- compare(expected: Sequence[str], path: str | Sequence[str] | 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
AssertionErrorwill be raised if they are not the same.- Parameters:
expected – 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 –
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 – If specified, directories will be excluded from the list of actual paths used in the comparison.
recursive – If
False, only the direct contents of the directory specified bypathwill be included in the actual contents used for comparison.followlinks – If
True, symlinks and hard links will be followed when recursively building up the actual list of directory contents.
- create() TempDirectory¶
Create a temporary directory for this instance to use if one has not already been created.
- getpath(path: str | Sequence[str] | None = None) str¶
Deprecated since version 7.
Use
as_string()instead.
- listdir(path: str | Sequence[str] | None = None, recursive: bool = False) None¶
Print the contents of the specified directory.
- Parameters:
path –
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 – If True, the directory specified will have its subdirectories recursively listed too.
- makedir(dirpath: str | Sequence[str]) 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 –
The directory to create, which can be:
A tuple of strings.
A forward-slash separated string.
- Returns:
The absolute path of the created directory.
- path = None¶
The absolute path of the
TempDirectoryon disk
- read(filepath: str | Sequence[str], encoding: str | None = None) str | bytes¶
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.
- write(filepath: str | Sequence[str], data: str | bytes, encoding: str | None = None) 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.
- Parameters:
filepath –
The path to the file to create, which can be:
A tuple of strings.
A forward-slash separated string.
data –
bytescontaining the data to be written, or astrifencodinghas been supplied.encoding – The encoding to be used if data is not bytes. Should not be passed if data is already bytes.
- Returns:
The absolute path of the file written.
- testfixtures.tempdir(path: str | Path | None = None, *, ignore: Sequence[str] = (), encoding: str | None = None, cwd: bool = False) Callable[[Callable], Callable]¶
A decorator for making a
TempDirectoryavailable for the duration of a test function.All arguments and parameters are passed through to the
TempDirectoryconstructor.
Helpers and Constants¶
- testfixtures.diff(x: str, y: str, x_label: str | None = '', y_label: str | None = '') str¶
A shorthand function that uses
difflibto return a string representing the differences between the two string arguments.Most useful when comparing multi-line strings.
- 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.
- 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(*args: ~typing.Any, x: ~typing.Any = <unspecified>, y: ~typing.Any = <unspecified>, expected: ~typing.Any = <unspecified>, actual: ~typing.Any = <unspecified>, prefix: str | None = None, suffix: 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 = True, comparers: dict[type, ~typing.Callable[[~typing.Any, ~typing.Any, ~testfixtures.comparison.CompareContext], str | None]] | None = None, **options: ~typing.Any) str | None¶
This is identical to
compare(), but withignore=Trueautomatically set to make comparing djangoModelinstances easier.
- testfixtures.django.compare_model(x: Model, y: Model, context: CompareContext) 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 – A sequence of fields to ignore during comparison, most commonly set to
['id']. By default, no fields are ignored.non_editable_fields – If True, then fields with
editable=Falsewill 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 – This is the name of the
TempDirectoryto use in the Sybil test namespace.
testfixtures.twisted¶
Tools for helping to test Twisted applications.
- class testfixtures.twisted.LogCapture(fields: ~typing.Sequence[str | ~typing.Callable] = ('log_level', <function formatEvent>))¶
A helper for capturing stuff logged using Twisted’s loggers.
- Parameters:
fields – A sequence of field names that
check()will use to build “actual” events to compare against the expected events passed in. If items are strings, they will be treated as keys info the Twisted logging event. If they are callable, they will be called with the event as their only parameter. If only one field is specified, “actual” events will just be that one field; otherwise they will be a tuple of the specified fields.
- check(*expected: Dict[str, Any], order_matters: bool = True) None¶
Check captured events against those supplied. Please see the
fieldsparameter to the constructor to see how “actual” events are built.- Parameters:
order_matters – This defaults to
True. IfFalse, the order of expected logging versus actual logging will be ignored.
- check_failure_text(expected: str, index: int = -1, attribute: str = 'value') None¶
Check the string representation of an attribute of a logged
Failureis as expected.- Parameters:
expected – The expected string representation.
index – The index into
eventswhere the failure should have been logged.attribute – 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 – The index into
eventsfrom where to start looking for failures.
- classmethod make(testcase: TestCase, **kw: Sequence[str | Callable]) Self¶
Instantiate, install and add a cleanup for a
LogCapture.- Parameters:
testcase – This must be an instance of
twisted.trial.unittest.TestCase.kw – Any other parameters are passed directly to the
LogCaptureconstructor.
- Returns:
The
LogCaptureinstantiated by this method.
- 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