API Reference

Comparisons

testfixtures.compare(x, y, prefix=None, suffix=None, raises=True, recursive=True, strict=False, comparers=None, **kw)

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.

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.

Parameters
  • prefix – If provided, in the event of an AssertionError being raised, the prefix supplied will be prepended to the message in the AssertionError.

  • suffix – If provided, in the event of an AssertionError being raised, the suffix supplied will be appended to the message in the AssertionError.

  • x_label – 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 – 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 – If False, the message that would be raised in the AssertionError will 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.

class testfixtures.Comparison(object_or_type, attribute_dict=None, partial=False, **attributes)

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.

  • strict

    Deprecated since version 6.16.0: Use partial instead.

class testfixtures.MappingComparison(*expected_mapping, **expected_items)

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 the keys in the mapping are expected to be in the order specified. Defaults to False.

  • partial – If any keys not expected should be ignored. Defaults to False.

  • 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)

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, precision)

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, upper_bound)

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, **kw)

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 the items are expected to be in the order specified. Defaults to True.

  • partial – If any items not expected should be ignored. Defaults to False.

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

class testfixtures.Subset(*expected)

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

class testfixtures.StringComparison(regex_source, flags=None, **flag_names)

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 StringComparison is compared with any basestring instance.

  • flags – Flags passed to re.compile().

  • flag_names – See the examples.

testfixtures.comparison

testfixtures.comparison.register(type, comparer)

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, y, context)

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

testfixtures.comparison.compare_object(x, y, context, ignore_attributes=())

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 fucntion, it may only be a list of strings.

testfixtures.comparison.compare_exception(x, y, context)

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

testfixtures.comparison.compare_with_type(x, y, context)

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

testfixtures.comparison.compare_sequence(x, y, context, prefix=True)

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

testfixtures.comparison.compare_generator(x, y, context)

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, y, context)

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.comparison.compare_dict(x, y, context)

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

testfixtures.comparison.compare_set(x, y, context)

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

testfixtures.comparison.compare_text(x, y, context)

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.

Capturing

class testfixtures.LogCapture(names=None, install=True, level=1, propagate=None, attributes=('name', 'levelname', 'getMessage'), recursive_check=False, ensure_checks_above=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 LogCapture will 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, None will be used in its place.

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

  • recursive_check – If True, log messages will be compared recursively by LogCapture.check().

  • ensure_checks_above – The log level above which checks must be made for logged events.

actual()

The sequence of actual records logged, having had their attributes extracted as specified by the attributes parameter to the LogCapture constructor.

This can be useful for making more complex assertions about logged records. The actual records logged can also be inspected by using the records attribute.

Return type

List

check(*expected)

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

Parameters

expected – A sequence of entries of the structure specified by the attributes passed to the constructor.

check_present(*expected, **kw)

This will check if the captured 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 – A sequence of entries of the structure specified by the attributes passed 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.

clear()

Clear any entries that have been captured.

emit(record)

Do whatever it takes to actually log the specified logging record.

This version is intended to be implemented by subclasses and so raises a NotImplementedError.

ensure_checked(level=None)

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

Parameters

level (Optional[int]) – the logging level, defaults to ensure_checks_above.

install()

Install this LogHandler into 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 LogCapture in order to capture all logging.

mark_all_checked()

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

uninstall()

Un-install this LogHandler from 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()

This will uninstall all existing LogHandler objects.

testfixtures.log_capture(*names, **kw)

A decorator for making a LogCapture installed an 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 install may also be supplied and will be passed on to the LogCapture constructor.

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

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

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

  • fd – 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 – 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.

property captured

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

compare(expected='', stdout='', stderr='')

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

Parameters
  • expected – A string containing the expected combined output of stdout and stderr.

  • stdout – A string containing the expected output to stdout.

  • stderr – A string containing the expected output to stderr.

disable()

Disable the output capture if it is enabled.

enable()

Enable the output capture if it is disabled.

Mocking

class testfixtures.Replace(target, replacement, strict=True)

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

Parameters
  • target – A string containing the dotted-path to 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.

  • 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.

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.

replace(target, replacement, strict=True)

Replace the specified target with the supplied replacement.

Parameters
  • target – A string containing the dotted-path to 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.

  • 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.

restore()

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

testfixtures.replace(target, replacement, strict=True)

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

Parameters
  • target – A string containing the dotted-path to 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.

  • 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.

testfixtures.test_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.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 – 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 – The type of the delta to use between values returned from today(). This can be any keyword parameter accepted by the timedelta constructor.

  • strict – 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 with the exception of the following members:

tdate.add(*args, **kw)

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.

tdate.set(*args, **kw)

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.

tdate.tick(*args, **kw)

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 tdate.today()

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

testfixtures.test_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.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 – An optional datetime.tzinfo, see Timezones.

  • delta – The size of the delta to use between values returned from now(). 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 now(). This can be any keyword parameter accepted by the timedelta constructor.

  • date_type – The type to use for the return value of the date() method. This can help with gotchas that occur when type checking if performed on values returned by the mock’s date() method.

  • strict – 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 with the exception of the following members:

tdatetime.add(*args, **kw)

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.

tdatetime.set(*args, *kw)

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.

tdatetime.tick(*args, **kw)

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 tdatetime.now([tz])
Parameters

tz – 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 tdatetime.utcnow()

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.

classmethod tdatetime.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.test_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 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 – 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 timedelta constructor.

The mock additionally has the following methods available on it:

ttime.add(*args, **kw)

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.

ttime.set(*args, **kw)

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.

ttime.tick(*args, **kw)

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.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

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

set_command(command, stdout=b'', stderr=b'', returncode=0, pid=1234, poll_count=3, behaviour=None)

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

Parameters
  • command – A string representing the command to be simulated.

  • stdout – A string representing the simulated content written by the process to the stdout pipe.

  • stderr – A string representing 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 MockPopen.poll() can be called before MockPopen.returncode is set and returned by MockPopen.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 for that command and returns a PopenBehaviour instance.

set_default(stdout=b'', stderr=b'', returncode=0, pid=1234, poll_count=3, behaviour=None)

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

Parameters
  • stdout – A string representing the simulated content written by the process to the stdout pipe.

  • stderr – A string representing 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 MockPopen.poll() can be called before MockPopen.returncode is set and returned by MockPopen.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 for that command and returns a PopenBehaviour instance.

class testfixtures.popen.MockPopenInstance(mock_class, root_call, args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), encoding=None, errors=None, text=None)

A mock process as returned by MockPopen.

calls

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

communicate(input=None, timeout=None)

Simulate calls to subprocess.Popen.communicate()

kill()

Simulate calls to subprocess.Popen.kill()

poll()

Simulate calls to subprocess.Popen.poll()

returncode

The return code of this mock process.

root_call

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

send_signal(signal)

Simulate calls to subprocess.Popen.send_signal()

stderr = None

A file representing error output from this process.

stdin = 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.

stdout = None

A file representing standard output from this process.

terminate()

Simulate calls to subprocess.Popen.terminate()

wait(timeout=None)

Simulate calls to subprocess.Popen.wait()

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

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

Assertions

class testfixtures.ShouldRaise(exception=None, unless=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 True indicates that no exception is expected. This is useful when checking that exceptions are only raised on certain versions of Python.

raised = None

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

class testfixtures.should_raise(exception=None, unless=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 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)

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

class testfixtures.ShouldWarn(*expected, **filters)

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.

  • filters – 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.TempDirectory(ignore=(), create=True, path=None, encoding=None)

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 TempDirectory listing 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 a physical path to use as the temporary directory. When passed, TempDirectory will not create a new directory to use.

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

check(*expected)

Deprecated since version 4.3.0.

Compare the contents of the temporary directory with the expected contents supplied.

This method only checks the root of the temporary directory.

Parameters

expected – A sequence of strings containing the names expected in the directory.

check_all(dir, *expected)

Deprecated since version 4.3.0.

Recursively compare the contents of the specified directory with the expected contents supplied.

Parameters
  • dir

    The directory to check, which can be:

    • 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 checked.

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

    • An empty string, indicating that the whole temporary directory should be checked.

  • 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.

check_dir(dir, *expected)

Deprecated since version 4.3.0.

Compare the contents of the specified subdirectory of the temporary directory with the expected contents supplied.

This method will only check the contents of the subdirectory specified and will not recursively check subdirectories.

Parameters
  • dir

    The subdirectory to check, which can be:

    • 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 checked.

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

  • expected – A sequence of strings containing the names expected in the directory.

cleanup()

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

classmethod cleanup_all()

Delete all temporary directories associated with all TempDirectory objects.

compare(expected, path=None, files_only=False, recursive=True, followlinks=False)

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 – 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 passed as False, only the direct contents of the directory specified by path will be included in the actual contents used for comparison.

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

create()

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

getpath(path)

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 full path.

listdir(path=None, recursive=False)

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)

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 full path of the created directory.

path = None

The physical path of the TempDirectory on disk

read(filepath, encoding=None)

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.

Parameters
  • filepath

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

    • A tuple of strings.

    • A forward-slash separated string.

  • encoding – The encoding used to decode the data in the file.

Returns

A string containing the data read.

write(filepath, data, encoding=None)

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 – A string containing the data to be written.

  • encoding – The encoding to be used if data is not bytes. Should not be passed if data is already bytes.

Returns

The full path of the file written.

testfixtures.tempdir(*args, **kw)

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.

testfixtures.generator(*args)

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

Helpers and Constants

testfixtures.diff(x, y, x_label='', y_label='')

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.wrap(before, after=None)

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.

Framework Helpers

Framework-specific helpers provided by testfixtures.

testfixtures.components

Helpers for working with Zope and its components.

class testfixtures.components.TestComponents

A helper for providing a sterile registry when testing with zope.component.

Instantiation will install an empty registry that will be returned by zope.component.getSiteManager().

uninstall()

Remove the sterile registry and replace it with the one that was in place before this TestComponents was instantiated.

testfixtures.django

testfixtures.django.compare(x, y, prefix=None, suffix=None, raises=True, recursive=True, strict=False, comparers=None, **kw)

This is identical to compare(), but with ignore=True automatically set to make comparing django Model instances easier.

testfixtures.django.compare_model(x, y, context)

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=False will be included in the comparison. By default, these fields are ignored.

testfixtures.sybil

class testfixtures.sybil.FileParser(name)

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 TempDirectory to use in the Sybil test namespace.

testfixtures.twisted

Tools for helping to test Twisted applications.

class testfixtures.twisted.LogCapture(fields=('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.

events

The list of events captured.

install()

Start capturing.

uninstall()

Stop capturing.

check(*expected, **kw)

Check captured events against those supplied. Please see the fields parameter to the constructor to see how “actual” events are built.

Parameters

order_matters – This defaults to True. If False, the order of expected logging versus actual logging will be ignored.

check_failure_text(expected, index=- 1, attribute='value')

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

Parameters
  • expected – The expected string representation.

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

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

raise_logged_failure(start_index=0)

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

Parameters

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

classmethod make(testcase, **kw)

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 LogCapture constructor.

Returns

The LogCapture instantiated by this method.

testfixtures.twisted.DEBUG = <LogLevel=debug>

Short reference to Twisted’s LogLevel.debug

testfixtures.twisted.INFO = <LogLevel=info>

Short reference to Twisted’s LogLevel.info

testfixtures.twisted.WARN = <LogLevel=warn>

Short reference to Twisted’s LogLevel.warn

testfixtures.twisted.ERROR = <LogLevel=error>

Short reference to Twisted’s LogLevel.error

testfixtures.twisted.CRITICAL = <LogLevel=critical>

Short reference to Twisted’s LogLevel.critical