Go to the latest version of this document.
search in docstrings

Search bar offers the following options:

- Term presence. The below example searches for documents that must contain “foo”, might contain “bar” and must not contain “baz”: `+foo bar -baz`
- Wildcards. The below example searches for documents with words beginning with “foo”: `foo*`
- Search in specific fields. The following search matches all objects in "twisted.mail" that matches “search”: `+qname:twisted.mail.* +search`

  Possible fields: 'name', 'qname' (fully qualified name), 'docstring', and 'kind'. Last two fields are only applicable if "search in docstrings" is enabled.

- Fuzzy matches. The following search matches all documents that have a word within 1 edit distance of “foo”: `foo~1`

Results provided by Lunr.js

# ``twisted`.`trial`.`unittest`.`SynchronousTestCase``

class documentation

`class SynchronousTestCase(_Assertions): (source)`

Known subclasses: `twisted.trial.unittest.TestCase`

View In Hierarchy

A unit test. The atom of the unit testing universe.

This class extends `unittest.TestCase` from the standard library. A number of convenient testing helpers are added, including logging and warning integration, monkey-patching support, and more.

To write a unit test, subclass `SynchronousTestCase` and define a method (say, 'test_foo') on the subclass. To run the test, instantiate your subclass with the name of the method, and call `run` on the instance, passing a `TestResult` object.

The `trial` script will automatically find any `SynchronousTestCase` subclasses defined in modules beginning with 'test_' and construct test cases for all methods beginning with 'test'.

If an error is logged during the test run, the test will fail with an error. See `log.err`.

Method | `__eq__` | Override the comparison defined by the base TestCase which considers instances of the same class with the same _testMethodName to be equal. Since trial puts TestCase instances into a set, that definition of comparison makes it impossible to run the same test method twice...
Method | `__hash__` | Undocumented
Method | `__init__` | Undocumented
Method | `addCleanup` | Add the given function to a list of functions to be called after the test has run, but before `tearDown`.
Method | `callDeprecated` | Call a function that should have been deprecated at a specific version and in favor of a specific alternative, and assert that it was thusly deprecated.
Method | `flushLoggedErrors` | Remove stored errors received from the log.
Method | `flushWarnings` | Remove stored warnings from the list of captured warnings and return them.
Method | `getDeprecatedModuleAttribute` | Retrieve a module attribute which should have been deprecated, and assert that we saw the appropriate deprecation warning.
Method | `getSkip` | Return the skip reason set on this test, if any is set. Checks on the instance first, then the class, then the module, then packages. As soon as it finds something with a `skip` attribute, returns that in a tuple (...
Method | `getTodo` | Return a `Todo` object if the test is marked todo. Checks on the instance first, then the class, then the module, then packages. As soon as it finds something with a `todo` attribute, returns that. Returns ...
Method | `mktemp` | Create a new path name which can be used for a new file or directory.
Method | `patch` | Monkey patch an object for the duration of the test.
Method | `run` | Run the test case, storing the results in `result`.
Method | `runTest` | If no `methodName` argument is passed to the constructor, `run` will treat this method as the thing with the actual test inside.
Method | `shortDescription` | Undocumented
Instance Variable | `failureException` | An exception class, defaulting to `FailTest`. If the test method raises this exception, it will be reported as a failure, rather than an exception. All of the assertion methods raise this if the assertion fails.
Instance Variable | `skip` | `None` or a string explaining why this test is to be skipped. If defined, the test will not be run. Instead, it will be reported to the result object as 'skipped' (if the `TestResult` supports skipping).
Instance Variable | `suppress` | `None` or a list of tuples of `(args, kwargs)` to be passed to `warnings.filterwarnings`. Use these to suppress warnings raised in a test. Useful for testing deprecated code. See also `util.suppress`.
Instance Variable | `todo` | `None`, a string or a tuple of `(errors, reason)` where `errors` is either an exception class or an iterable of exception classes, and `reason` is a string. See `Todo` or `makeTodo` for more information.
Method | `_getSkipReason` | Return the reason to use for skipping a test method.
Method | `_getSuppress` | Returns any warning suppressions set for this test. Checks on the instance first, then the class, then the module, then packages. As soon as it finds something with a `suppress` attribute, returns that. ...
Method | `_installObserver` | Undocumented
Method | `_removeObserver` | Undocumented
Method | `_run` | Run a single method, either a test method or fixture.
Method | `_runCleanups` | Synchronously run any cleanups which have been added.
Method | `_runFixturesAndTest` | Run `setUp`, a test method, test cleanups, and `tearDown`.
Instance Variable | `_cleanups` | Undocumented
Instance Variable | `_observer` | Undocumented
Instance Variable | `_parents` | Undocumented
Instance Variable | `_passed` | Undocumented
Instance Variable | `_testMethodName` | Undocumented
Instance Variable | `_warnings` | Undocumented

Inherited from `_Assertions`:

Method | `assertAlmostEqual` | Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero.
Method | `assertApproximates` | Fail if `first` - `second` > `tolerance`
Method | `assertEqual` | Fail the test if `first` and `second` are not equal.
Method | `assertFalse` | Fail the test if `condition` evaluates to True.
Method | `assertIn` | Fail the test if `containee` is not found in `container`.
Method | `assertIs` | Fail the test if `first` is not `second`. This is an obect-identity-equality test, not an object equality (i.e. `__eq__`) test.
Method | `assertIsInstance` | Fail if `instance` is not an instance of the given class or of one of the given classes.
Method | `assertIsNot` | Fail the test if `first` is `second`. This is an obect-identity-equality test, not an object equality (i.e. `__eq__`) test.
Method | `assertNoResult` | Assert that `deferred` does not have a result at this point.
Method | `assertNotAlmostEqual` | Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero.
Method | `assertNotEqual` | Fail the test if `first` == `second`.
Method | `assertNotIn` | Fail the test if `containee` is found in `container`.
Method | `assertNotIsInstance` | Fail if `instance` is an instance of the given class or of one of the given classes.
Method | `assertNotSubstring` | Fail if `astring` contains `substring`.
Method | `assertRaises` | Fail the test unless calling the function `f` with the given `args` and `kwargs` raises `exception`. The failure will report the traceback and call stack of the unexpected exception.
Method | `assertSubstring` | Fail if `substring` does not exist within `astring`.
Method | `assertTrue` | Fail the test if `condition` evaluates to False.
Method | `assertWarns` | Fail if the given function doesn't generate the specified warning when called. It calls the function, checks the warning, and forwards the result of the function if everything is fine.
Method | `fail` | Absolutely fail the test. Do not pass go, do not collect $200.
Method | `failureResultOf` | Return the current failure result of `deferred` or raise `self.failureException`.
Method | `successResultOf` | Return the current success result of `deferred` or raise `self.failureException`.

def __eq__(self, other): (source)

Override the comparison defined by the base TestCase which considers instances of the same class with the same _testMethodName to be equal. Since trial puts TestCase instances into a set, that definition of comparison makes it impossible to run the same test method twice. Most likely, trial should stop using a set to hold tests, but until it does, this is necessary on Python 2.6. -exarkun

Parameters
other:`object` | Undocumented
Returns
`bool` | Undocumented

def __hash__(self): (source)

Undocumented

def __init__(self, methodName='runTest'): (source)
overridden in `twisted.trial.unittest.TestCase`

Undocumented

def addCleanup(self, f, *args, **kwargs): (source)
overridden in `twisted.trial.unittest.TestCase`

Add the given function to a list of functions to be called after the test has run, but before `tearDown`.

Functions will be run in reverse order of being added. This helps ensure that tear down complements set up.

As with all aspects of `SynchronousTestCase`, Deferreds are not supported in cleanup functions.

def callDeprecated(self, version, f, *args, **kwargs): (source)

Call a function that should have been deprecated at a specific version and in favor of a specific alternative, and assert that it was thusly deprecated.

Parameters
version | A 2-sequence of (since, replacement), where `since` is a the first `version` that `f` should have been deprecated since, and `replacement` is a suggested replacement for the deprecated functionality, as described by `twisted.python.deprecate.deprecated`. If there is no suggested replacement, this parameter may also be simply a `version` by itself.
f | The deprecated function to call.
*args | The arguments to pass to `f`.
**kwargs | The keyword arguments to pass to `f`.
Returns
Whatever `f` returns.
Raises
`Exception` | Whatever `f` raises. If any exception is raised by `f`, though, no assertions will be made about emitted deprecations.
`FailTest` | if no warnings were emitted by `f`, or if the `DeprecationWarning` emitted did not produce the canonical please-use-something-else message that is standard for Twisted deprecations according to the given version and replacement.

def flushLoggedErrors(self, *errorTypes): (source)

Remove stored errors received from the log.

`TestCase` stores each error logged during the run of the test and reports them as errors during the cleanup phase (after `tearDown`).

Parameters
*errorTypes | If unspecified, flush all errors. Otherwise, only flush errors that match the given types.
Returns
A list of failures that have been removed.

def flushWarnings(self, offendingFunctions=None): (source)

Remove stored warnings from the list of captured warnings and return them.

Parameters

offendingFunctions:`None` or `list` of functions or methods.

If `None`, all warnings issued during the currently running test will be flushed. Otherwise, only warnings which point to a function included in this list will be flushed. All warnings include a filename and source line number; if these parts of a warning point to a source line which is part of a function, then the warning points to that function.

Returns

A `list`, each element of which is a `dict` giving information about one warning which was flushed by this call. The keys of each `dict` are:

- `'message'`: The string which was passed as the message parameter to `warnings.warn`.
- `'category'`: The warning subclass which was passed as the category parameter to `warnings.warn`.
- `'filename'`: The name of the file containing the definition of the code object which was `stacklevel` frames above the call to `warnings.warn`, where `stacklevel` is the value of the `stacklevel` parameter passed to `warnings.warn`.
- `'lineno'`: The source line associated with the active instruction of the code object object which was `stacklevel` frames above the call to `warnings.warn`, where `stacklevel` is the value of the `stacklevel` parameter passed to `warnings.warn`.

Raises
`ValueError` | If `offendingFunctions` is not `None` and includes an object which is not a `types.FunctionType` or `types.MethodType` instance.

def getDeprecatedModuleAttribute(self, moduleName, name, version, message=None): (source)

Retrieve a module attribute which should have been deprecated, and assert that we saw the appropriate deprecation warning.

Parameters
moduleName:`str` | Fully-qualified Python name of the module containing the deprecated attribute; if called from the same module as the attributes are being deprecated in, using the `__name__` global can be helpful
name:`str` | Attribute name which we expect to be deprecated
version | The first `version` that the module attribute was deprecated.
message:`str` | (optional) The expected deprecation message for the module attribute
Returns
The given attribute from the named module
Raises
`FailTest` | if no warnings were emitted on getattr, or if the `DeprecationWarning` emitted did not produce the canonical please-use-something-else message that is standard for Twisted deprecations according to the given version and replacement.
Present Since
Twisted 21.2.0

def getSkip(self): (source)

Return the skip reason set on this test, if any is set. Checks on the instance first, then the class, then the module, then packages. As soon as it finds something with a `skip` attribute, returns that in a tuple (`True`, `str`). If the `skip` attribute does not exist, look for `__unittest_skip__` and `__unittest_skip_why__` attributes which are set by the standard library `unittest.skip` function. Returns (`False`, `None`) if it cannot find anything. See `TestCase` docstring for more details.

Returns
`Tuple[bool, Optional[str]]` | Undocumented

def getTodo(self): (source)

Return a `Todo` object if the test is marked todo. Checks on the instance first, then the class, then the module, then packages. As soon as it finds something with a `todo` attribute, returns that. Returns `None` if it cannot find anything. See `TestCase` docstring for more details.

def mktemp(self): (source)

Create a new path name which can be used for a new file or directory.

The result is a relative path that is guaranteed to be unique within the current working directory. The parent of the path will exist, but the path will not.

For a temporary directory call os.mkdir on the path. For a temporary file just create the file (e.g. by opening the path for writing and then closing it).

Returns
`str` | The newly created path

def patch(self, obj, attribute, value): (source)

Monkey patch an object for the duration of the test.

The monkey patch will be reverted at the end of the test using the `addCleanup` mechanism.

The `monkey.MonkeyPatcher` is returned so that users can restore and re-apply the monkey patch within their tests.

Parameters
obj | The object to monkey patch.
attribute | The name of the attribute to change.
value | The value to set the attribute to.
Returns
A `monkey.MonkeyPatcher` object.

def run(self, result): (source)

Run the test case, storing the results in `result`.

First runs `setUp` on self, then runs the test method (defined in the constructor), then runs `tearDown`. As with the standard library `unittest.TestCase`, the return value of these methods is disregarded. In particular, returning a `Deferred` has no special additional consequences.

Parameters
result | A `TestResult` object.

def runTest(self): (source)

If no `methodName` argument is passed to the constructor, `run` will treat this method as the thing with the actual test inside.

def shortDescription(self): (source)

Undocumented

failureException = (source)

An exception class, defaulting to `FailTest`. If the test method raises this exception, it will be reported as a failure, rather than an exception. All of the assertion methods raise this if the assertion fails.

skip = (source)

`None` or a string explaining why this test is to be skipped. If defined, the test will not be run. Instead, it will be reported to the result object as 'skipped' (if the `TestResult` supports skipping).

suppress = (source)

`None` or a list of tuples of `(args, kwargs)` to be passed to `warnings.filterwarnings`. Use these to suppress warnings raised in a test. Useful for testing deprecated code. See also `util.suppress`.

todo = (source)

`None`, a string or a tuple of `(errors, reason)` where `errors` is either an exception class or an iterable of exception classes, and `reason` is a string. See `Todo` or `makeTodo` for more information.

def _getSkipReason(self, method, skip): (source)

Return the reason to use for skipping a test method.

Parameters
method | The method which produced the skip.
skip | A `unittest.SkipTest` instance raised by `method`.

def _getSuppress(self): (source)

Returns any warning suppressions set for this test. Checks on the instance first, then the class, then the module, then packages. As soon as it finds something with a `suppress` attribute, returns that. Returns any empty list (i.e. suppress no warnings) if it cannot find anything. See `TestCase` docstring for more details.

def _installObserver(self): (source)

Undocumented

def _removeObserver(self): (source)

Undocumented

def _run(self, suppress, todo, method, result): (source)
overridden in `twisted.trial.unittest.TestCase`

Run a single method, either a test method or fixture.

Parameters
suppress | Any warnings to suppress, as defined by the `suppress` attribute on this method, test case, or the module it is defined in.
todo | Any expected failure or failures, as defined by the `todo` attribute on this method, test case, or the module it is defined in.
method | The method to run.
result | The TestResult instance to which to report results.
Returns
`True` if the method fails and no further method/fixture calls should be made, `False` otherwise.

def _runCleanups(self, result): (source)

Synchronously run any cleanups which have been added.

def _runFixturesAndTest(self, result): (source)
overridden in `twisted.trial.unittest.TestCase`

Run `setUp`, a test method, test cleanups, and `tearDown`.

Parameters
result | The TestResult instance to which to report results.

_cleanups: `list` = (source)

Undocumented

_observer = (source)

Undocumented

_parents = (source)

Undocumented

_passed: `bool` = (source)
overridden in `twisted.trial.unittest.TestCase`

Undocumented

_testMethodName = (source)

Undocumented

_warnings: `list` = (source)

Undocumented