Back to module index
Go to module by name
doctest
Module doctest -- a framework for running examples in docstrings.
In simplest use, end each module M to be tested with:
def _test():
import doctest
doctest.testmod()
if __name__ == "__main__":
_test()
Then running the module as a script will cause the examples in the
docstrings to get executed and verified:
python M.py
This won't display anything unless an example fails, in which case the
failing example(s) and the cause(s) of the failure(s) are printed to stdout
(why not stderr? because stderr is a lame hack <0.2 wink>), and the final
line of output is "Test failed.".
Run it with the -v switch instead:
python M.py -v
and a detailed report of all examples tried is printed to stdout, along
with assorted summaries at the end.
You can force verbose mode by passing "verbose=True" to testmod, or prohibit
it by passing "verbose=False". In either of those cases, sys.argv is not
examined by testmod.
There are a variety of other ways to run doctests, including integration
with the unittest framework, and support for running non-Python text
files containing doctests. There are also many ways to override parts
of doctest's default behaviors. See the Library Reference Manual for
details.
Classes
DebugRunner
Run doc tests but raise an exception as soon as there is a failure.
If an unexpected exception occurs, an UnexpectedException is raised.
It contains the test, the example, and the original exception:
>>> runner = DebugRunner(verbose=False)
>>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
... {}, 'foo', 'foo.py', 0)
>>> try:
... runner.run(test)
... except UnexpectedException as f:
... failure = f
>>> failure.test is test
True
>>> failure.example.want
'42\n'
>>> exc_info = failure.exc_info
>>> raise exc_info[1] # Already has the traceback
Traceback (most recent call last):
...
KeyError
We wrap the original exception to give the calling application
access to the test and example information.
If the output doesn't match, then a DocTestFailure is raised:
>>> test = DocTestParser().get_doctest('''
... >>> x = 1
... >>> x
... 2
... ''', {}, 'foo', 'foo.py', 0)
>>> try:
... runner.run(test)
... except DocTestFailure as f:
... failure = f
DocTestFailure objects provide access to the test:
>>> failure.test is test
True
As well as to the example:
>>> failure.example.want
'2\n'
and the actual output:
>>> failure.got
'1\n'
If a failure or error occurs, the globals are left intact:
>>> del test.globs['__builtins__']
>>> test.globs
{'x': 1}
>>> test = DocTestParser().get_doctest('''
... >>> x = 2
... >>> raise KeyError
... ''', {}, 'foo', 'foo.py', 0)
>>> runner.run(test)
Traceback (most recent call last):
...
doctest.UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
>>> del test.globs['__builtins__']
>>> test.globs
{'x': 2}
But the globals are cleared if there is no error:
>>> test = DocTestParser().get_doctest('''
... >>> x = 2
... ''', {}, 'foo', 'foo.py', 0)
>>> runner.run(test)
TestResults(failed=0, attempted=1)
>>> test.globs
{}
merge(self, other)
report_failure(self, out, test, example, got)
report_start(self, out, test, example)
Report that the test runner is about to process the given
example. (Only displays a message if verbose=True)
report_success(self, out, test, example, got)
Report that the given example ran successfully. (Only
displays a message if verbose=True)
report_unexpected_exception(self, out, test, example, exc_info)
run(self, test, compileflags=None, out=None, clear_globs=True)
summarize(self, verbose=None)
Print a summary of all the test cases that have been run by
this DocTestRunner, and return a tuple `(f, t)`, where `f` is
the total number of failed examples, and `t` is the total
number of tried examples.
The optional `verbose` argument controls how detailed the
summary is. If the verbosity is not specified, then the
DocTestRunner's verbosity is used.
DIVIDER = '**********************************************************************'
DocFileCase
tearDownClass.AssertionError
Assertion failed.
with_traceback(...)
Exception.with_traceback(tb) --
set self.__traceback__ to tb and return self.
args = <attribute 'args' of 'BaseException' objects>
addClassCleanup(function, /, *args, **kwargs)
Same as addCleanup, except the cleanup items are called even if
setUpClass fails (unlike tearDownClass).
addCleanup(self, function, /, *args, **kwargs)
Add a function, with arguments, to be called when the test is
completed. Functions added are called on a LIFO basis and are
called after tearDown on test failure or success.
Cleanup items are called even if setUp fails (unlike tearDown).
addTypeEqualityFunc(self, typeobj, function)
Add a type specific assertEqual style function to compare a type.
This method is for use by TestCase subclasses that need to register
their own type equality functions to provide nicer error messages.
Args:
typeobj: The data type to call this function on when both values
are of the same type in assertEqual().
function: The callable taking two arguments and an optional
msg= argument that raises self.failureException with a
useful error message when the two arguments are not equal.
assertAlmostEqual(self, first, second, places=None, msg=None, delta=None)
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, or by comparing that the
difference between the two objects is more than the given
delta.
Note that decimal places (from zero) are usually not the same
as significant digits (measured from the most significant digit).
If the two objects compare equal then they will automatically
compare almost equal.
deprecated_func(*args, **kwargs)
assertCountEqual(self, first, second, msg=None)
Asserts that two iterables have the same elements, the same number of
times, without regard to order.
self.assertEqual(Counter(list(first)),
Counter(list(second)))
Example:
- [0, 1, 1] and [1, 0, 1] compare equal.
- [0, 0, 1] and [0, 1] compare unequal.
assertDictContainsSubset(self, subset, dictionary, msg=None)
Checks whether dictionary is a superset of subset.
assertDictEqual(self, d1, d2, msg=None)
assertEqual(self, first, second, msg=None)
Fail if the two objects are unequal as determined by the '=='
operator.
deprecated_func(*args, **kwargs)
assertFalse(self, expr, msg=None)
Check that the expression is false.
assertGreater(self, a, b, msg=None)
Just like self.assertTrue(a > b), but with a nicer default message.
assertGreaterEqual(self, a, b, msg=None)
Just like self.assertTrue(a >= b), but with a nicer default message.
assertIn(self, member, container, msg=None)
Just like self.assertTrue(a in b), but with a nicer default message.
assertIs(self, expr1, expr2, msg=None)
Just like self.assertTrue(a is b), but with a nicer default message.
assertIsInstance(self, obj, cls, msg=None)
Same as self.assertTrue(isinstance(obj, cls)), with a nicer
default message.
assertIsNone(self, obj, msg=None)
Same as self.assertTrue(obj is None), with a nicer default message.
assertIsNot(self, expr1, expr2, msg=None)
Just like self.assertTrue(a is not b), but with a nicer default message.
assertIsNotNone(self, obj, msg=None)
Included for symmetry with assertIsNone.
assertLess(self, a, b, msg=None)
Just like self.assertTrue(a < b), but with a nicer default message.
assertLessEqual(self, a, b, msg=None)
Just like self.assertTrue(a <= b), but with a nicer default message.
assertListEqual(self, list1, list2, msg=None)
A list-specific equality assertion.
Args:
list1: The first list to compare.
list2: The second list to compare.
msg: Optional message to use on failure instead of a list of
differences.
assertLogs(self, logger=None, level=None)
Fail unless a log message of level *level* or higher is emitted
on *logger_name* or its children. If omitted, *level* defaults to
INFO and *logger* defaults to the root logger.
This method must be used as a context manager, and will yield
a recording object with two attributes: `output` and `records`.
At the end of the context manager, the `output` attribute will
be a list of the matching formatted log messages and the
`records` attribute will be a list of the corresponding LogRecord
objects.
Example::
with self.assertLogs('foo', level='INFO') as cm:
logging.getLogger('foo').info('first message')
logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
'ERROR:foo.bar:second message'])
assertMultiLineEqual(self, first, second, msg=None)
Assert that two multi-line strings are equal.
assertNoLogs(self, logger=None, level=None)
Fail unless no log messages of level *level* or higher are emitted
on *logger_name* or its children.
This method must be used as a context manager.
assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None)
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, or by comparing that the
difference between the two objects is less than the given delta.
Note that decimal places (from zero) are usually not the same
as significant digits (measured from the most significant digit).
Objects that are equal automatically fail.
deprecated_func(*args, **kwargs)
assertNotEqual(self, first, second, msg=None)
Fail if the two objects are equal as determined by the '!='
operator.
deprecated_func(*args, **kwargs)
assertNotIn(self, member, container, msg=None)
Just like self.assertTrue(a not in b), but with a nicer default message.
assertNotIsInstance(self, obj, cls, msg=None)
Included for symmetry with assertIsInstance.
assertNotRegex(self, text, unexpected_regex, msg=None)
Fail the test if the text matches the regular expression.
deprecated_func(*args, **kwargs)
assertRaises(self, expected_exception, *args, **kwargs)
Fail unless an exception of class expected_exception is raised
by the callable when invoked with specified positional and
keyword arguments. If a different type of exception is
raised, it will not be caught, and the test case will be
deemed to have suffered an error, exactly as for an
unexpected exception.
If called with the callable and arguments omitted, will return a
context object used like this::
with self.assertRaises(SomeException):
do_something()
An optional keyword argument 'msg' can be provided when assertRaises
is used as a context object.
The context manager keeps a reference to the exception as
the 'exception' attribute. This allows you to inspect the
exception after the assertion::
with self.assertRaises(SomeException) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
assertRaisesRegex(self, expected_exception, expected_regex, *args, **kwargs)
Asserts that the message in a raised exception matches a regex.
Args:
expected_exception: Exception class expected to be raised.
expected_regex: Regex (re.Pattern object or string) expected
to be found in error message.
args: Function to be called and extra positional args.
kwargs: Extra kwargs.
msg: Optional message used in case of failure. Can only be used
when assertRaisesRegex is used as a context manager.
deprecated_func(*args, **kwargs)
assertRegex(self, text, expected_regex, msg=None)
Fail the test unless the text matches the regular expression.
deprecated_func(*args, **kwargs)
assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None)
An equality assertion for ordered sequences (like lists and tuples).
For the purposes of this function, a valid ordered sequence type is one
which can be indexed, has a length, and has an equality operator.
Args:
seq1: The first sequence to compare.
seq2: The second sequence to compare.
seq_type: The expected datatype of the sequences, or None if no
datatype should be enforced.
msg: Optional message to use on failure instead of a list of
differences.
assertSetEqual(self, set1, set2, msg=None)
A set-specific equality assertion.
Args:
set1: The first set to compare.
set2: The second set to compare.
msg: Optional message to use on failure instead of a list of
differences.
assertSetEqual uses ducktyping to support different types of sets, and
is optimized for sets specifically (parameters must support a
difference method).
assertTrue(self, expr, msg=None)
Check that the expression is true.
assertTupleEqual(self, tuple1, tuple2, msg=None)
A tuple-specific equality assertion.
Args:
tuple1: The first tuple to compare.
tuple2: The second tuple to compare.
msg: Optional message to use on failure instead of a list of
differences.
assertWarns(self, expected_warning, *args, **kwargs)
Fail unless a warning of class warnClass is triggered
by the callable when invoked with specified positional and
keyword arguments. If a different type of warning is
triggered, it will not be handled: depending on the other
warning filtering rules in effect, it might be silenced, printed
out, or raised as an exception.
If called with the callable and arguments omitted, will return a
context object used like this::
with self.assertWarns(SomeWarning):
do_something()
An optional keyword argument 'msg' can be provided when assertWarns
is used as a context object.
The context manager keeps a reference to the first matching
warning as the 'warning' attribute; similarly, the 'filename'
and 'lineno' attributes give you information about the line
of Python code from which the warning was triggered.
This allows you to inspect the warning after the assertion::
with self.assertWarns(SomeWarning) as cm:
do_something()
the_warning = cm.warning
self.assertEqual(the_warning.some_attribute, 147)
assertWarnsRegex(self, expected_warning, expected_regex, *args, **kwargs)
Asserts that the message in a triggered warning matches a regexp.
Basic functioning is similar to assertWarns() with the addition
that only warnings whose messages also match the regular expression
are considered successful matches.
Args:
expected_warning: Warning class expected to be triggered.
expected_regex: Regex (re.Pattern object or string) expected
to be found in error message.
args: Function to be called and extra positional args.
kwargs: Extra kwargs.
msg: Optional message used in case of failure. Can only be used
when assertWarnsRegex is used as a context manager.
deprecated_func(*args, **kwargs)
countTestCases(self)
debug(self)
Run the test case without results and without catching exceptions
The unit test framework includes a debug method on test cases
and test suites to support post-mortem debugging. The test code
is run in such a way that errors are not caught. This way a
caller can catch the errors and initiate post-mortem debugging.
The DocTestCase provides a debug method that raises
UnexpectedException errors if there is an unexpected
exception:
>>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
... {}, 'foo', 'foo.py', 0)
>>> case = DocTestCase(test)
>>> try:
... case.debug()
... except UnexpectedException as f:
... failure = f
The UnexpectedException contains the test, the example, and
the original exception:
>>> failure.test is test
True
>>> failure.example.want
'42\n'
>>> exc_info = failure.exc_info
>>> raise exc_info[1] # Already has the traceback
Traceback (most recent call last):
...
KeyError
If the output doesn't match, then a DocTestFailure is raised:
>>> test = DocTestParser().get_doctest('''
... >>> x = 1
... >>> x
... 2
... ''', {}, 'foo', 'foo.py', 0)
>>> case = DocTestCase(test)
>>> try:
... case.debug()
... except DocTestFailure as f:
... failure = f
DocTestFailure objects provide access to the test:
>>> failure.test is test
True
As well as to the example:
>>> failure.example.want
'2\n'
and the actual output:
>>> failure.got
'1\n'
defaultTestResult(self)
doClassCleanups()
Execute all class cleanup functions. Normally called for you after
tearDownClass.
doCleanups(self)
Execute all cleanup functions. Normally called for you after
tearDown.
fail(self, msg=None)
Fail immediately, with the given message.
deprecated_func(*args, **kwargs)
deprecated_func(*args, **kwargs)
deprecated_func(*args, **kwargs)
deprecated_func(*args, **kwargs)
deprecated_func(*args, **kwargs)
deprecated_func(*args, **kwargs)
deprecated_func(*args, **kwargs)
format_failure(self, err)
id(self)
run(self, result=None)
runTest(self)
setUp(self)
setUpClass()
Hook method for setting up class fixture before running tests in the class.
shortDescription(self)
skipTest(self, reason)
Skip this test.
subTest(self, msg=<object object at 0x7f75e3c95b90>, **params)
Return a context manager that will return the enclosed block
of code in a subtest identified by the optional message and
keyword parameters. A failure in the subtest marks the test
case as failed but resumes execution at the end of the enclosed
block, allowing further test code to be executed.
tearDown(self)
tearDownClass()
Hook method for deconstructing the class fixture after running all tests in the class.
longMessage = True
maxDiff = 640
DocTest
A collection of doctest examples that should be run in a single
namespace. Each `DocTest` defines the following attributes:
- examples: the list of examples.
- globs: The namespace (aka globals) that the examples should
be run in.
- name: A name identifying the DocTest (typically, the name of
the object whose docstring this DocTest was extracted from).
- filename: The name of the file that this DocTest was extracted
from, or `None` if the filename is unknown.
- lineno: The line number within filename where this DocTest
begins, or `None` if the line number is unavailable. This
line number is zero-based, with respect to the beginning of
the file.
- docstring: The string that the examples were extracted from,
or `None` if the string is unavailable.
DocTestCase
tearDownClass.AssertionError
Assertion failed.
with_traceback(...)
Exception.with_traceback(tb) --
set self.__traceback__ to tb and return self.
args = <attribute 'args' of 'BaseException' objects>
addClassCleanup(function, /, *args, **kwargs)
Same as addCleanup, except the cleanup items are called even if
setUpClass fails (unlike tearDownClass).
addCleanup(self, function, /, *args, **kwargs)
Add a function, with arguments, to be called when the test is
completed. Functions added are called on a LIFO basis and are
called after tearDown on test failure or success.
Cleanup items are called even if setUp fails (unlike tearDown).
addTypeEqualityFunc(self, typeobj, function)
Add a type specific assertEqual style function to compare a type.
This method is for use by TestCase subclasses that need to register
their own type equality functions to provide nicer error messages.
Args:
typeobj: The data type to call this function on when both values
are of the same type in assertEqual().
function: The callable taking two arguments and an optional
msg= argument that raises self.failureException with a
useful error message when the two arguments are not equal.
assertAlmostEqual(self, first, second, places=None, msg=None, delta=None)
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, or by comparing that the
difference between the two objects is more than the given
delta.
Note that decimal places (from zero) are usually not the same
as significant digits (measured from the most significant digit).
If the two objects compare equal then they will automatically
compare almost equal.
deprecated_func(*args, **kwargs)
assertCountEqual(self, first, second, msg=None)
Asserts that two iterables have the same elements, the same number of
times, without regard to order.
self.assertEqual(Counter(list(first)),
Counter(list(second)))
Example:
- [0, 1, 1] and [1, 0, 1] compare equal.
- [0, 0, 1] and [0, 1] compare unequal.
assertDictContainsSubset(self, subset, dictionary, msg=None)
Checks whether dictionary is a superset of subset.
assertDictEqual(self, d1, d2, msg=None)
assertEqual(self, first, second, msg=None)
Fail if the two objects are unequal as determined by the '=='
operator.
deprecated_func(*args, **kwargs)
assertFalse(self, expr, msg=None)
Check that the expression is false.
assertGreater(self, a, b, msg=None)
Just like self.assertTrue(a > b), but with a nicer default message.
assertGreaterEqual(self, a, b, msg=None)
Just like self.assertTrue(a >= b), but with a nicer default message.
assertIn(self, member, container, msg=None)
Just like self.assertTrue(a in b), but with a nicer default message.
assertIs(self, expr1, expr2, msg=None)
Just like self.assertTrue(a is b), but with a nicer default message.
assertIsInstance(self, obj, cls, msg=None)
Same as self.assertTrue(isinstance(obj, cls)), with a nicer
default message.
assertIsNone(self, obj, msg=None)
Same as self.assertTrue(obj is None), with a nicer default message.
assertIsNot(self, expr1, expr2, msg=None)
Just like self.assertTrue(a is not b), but with a nicer default message.
assertIsNotNone(self, obj, msg=None)
Included for symmetry with assertIsNone.
assertLess(self, a, b, msg=None)
Just like self.assertTrue(a < b), but with a nicer default message.
assertLessEqual(self, a, b, msg=None)
Just like self.assertTrue(a <= b), but with a nicer default message.
assertListEqual(self, list1, list2, msg=None)
A list-specific equality assertion.
Args:
list1: The first list to compare.
list2: The second list to compare.
msg: Optional message to use on failure instead of a list of
differences.
assertLogs(self, logger=None, level=None)
Fail unless a log message of level *level* or higher is emitted
on *logger_name* or its children. If omitted, *level* defaults to
INFO and *logger* defaults to the root logger.
This method must be used as a context manager, and will yield
a recording object with two attributes: `output` and `records`.
At the end of the context manager, the `output` attribute will
be a list of the matching formatted log messages and the
`records` attribute will be a list of the corresponding LogRecord
objects.
Example::
with self.assertLogs('foo', level='INFO') as cm:
logging.getLogger('foo').info('first message')
logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
'ERROR:foo.bar:second message'])
assertMultiLineEqual(self, first, second, msg=None)
Assert that two multi-line strings are equal.
assertNoLogs(self, logger=None, level=None)
Fail unless no log messages of level *level* or higher are emitted
on *logger_name* or its children.
This method must be used as a context manager.
assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None)
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, or by comparing that the
difference between the two objects is less than the given delta.
Note that decimal places (from zero) are usually not the same
as significant digits (measured from the most significant digit).
Objects that are equal automatically fail.
deprecated_func(*args, **kwargs)
assertNotEqual(self, first, second, msg=None)
Fail if the two objects are equal as determined by the '!='
operator.
deprecated_func(*args, **kwargs)
assertNotIn(self, member, container, msg=None)
Just like self.assertTrue(a not in b), but with a nicer default message.
assertNotIsInstance(self, obj, cls, msg=None)
Included for symmetry with assertIsInstance.
assertNotRegex(self, text, unexpected_regex, msg=None)
Fail the test if the text matches the regular expression.
deprecated_func(*args, **kwargs)
assertRaises(self, expected_exception, *args, **kwargs)
Fail unless an exception of class expected_exception is raised
by the callable when invoked with specified positional and
keyword arguments. If a different type of exception is
raised, it will not be caught, and the test case will be
deemed to have suffered an error, exactly as for an
unexpected exception.
If called with the callable and arguments omitted, will return a
context object used like this::
with self.assertRaises(SomeException):
do_something()
An optional keyword argument 'msg' can be provided when assertRaises
is used as a context object.
The context manager keeps a reference to the exception as
the 'exception' attribute. This allows you to inspect the
exception after the assertion::
with self.assertRaises(SomeException) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
assertRaisesRegex(self, expected_exception, expected_regex, *args, **kwargs)
Asserts that the message in a raised exception matches a regex.
Args:
expected_exception: Exception class expected to be raised.
expected_regex: Regex (re.Pattern object or string) expected
to be found in error message.
args: Function to be called and extra positional args.
kwargs: Extra kwargs.
msg: Optional message used in case of failure. Can only be used
when assertRaisesRegex is used as a context manager.
deprecated_func(*args, **kwargs)
assertRegex(self, text, expected_regex, msg=None)
Fail the test unless the text matches the regular expression.
deprecated_func(*args, **kwargs)
assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None)
An equality assertion for ordered sequences (like lists and tuples).
For the purposes of this function, a valid ordered sequence type is one
which can be indexed, has a length, and has an equality operator.
Args:
seq1: The first sequence to compare.
seq2: The second sequence to compare.
seq_type: The expected datatype of the sequences, or None if no
datatype should be enforced.
msg: Optional message to use on failure instead of a list of
differences.
assertSetEqual(self, set1, set2, msg=None)
A set-specific equality assertion.
Args:
set1: The first set to compare.
set2: The second set to compare.
msg: Optional message to use on failure instead of a list of
differences.
assertSetEqual uses ducktyping to support different types of sets, and
is optimized for sets specifically (parameters must support a
difference method).
assertTrue(self, expr, msg=None)
Check that the expression is true.
assertTupleEqual(self, tuple1, tuple2, msg=None)
A tuple-specific equality assertion.
Args:
tuple1: The first tuple to compare.
tuple2: The second tuple to compare.
msg: Optional message to use on failure instead of a list of
differences.
assertWarns(self, expected_warning, *args, **kwargs)
Fail unless a warning of class warnClass is triggered
by the callable when invoked with specified positional and
keyword arguments. If a different type of warning is
triggered, it will not be handled: depending on the other
warning filtering rules in effect, it might be silenced, printed
out, or raised as an exception.
If called with the callable and arguments omitted, will return a
context object used like this::
with self.assertWarns(SomeWarning):
do_something()
An optional keyword argument 'msg' can be provided when assertWarns
is used as a context object.
The context manager keeps a reference to the first matching
warning as the 'warning' attribute; similarly, the 'filename'
and 'lineno' attributes give you information about the line
of Python code from which the warning was triggered.
This allows you to inspect the warning after the assertion::
with self.assertWarns(SomeWarning) as cm:
do_something()
the_warning = cm.warning
self.assertEqual(the_warning.some_attribute, 147)
assertWarnsRegex(self, expected_warning, expected_regex, *args, **kwargs)
Asserts that the message in a triggered warning matches a regexp.
Basic functioning is similar to assertWarns() with the addition
that only warnings whose messages also match the regular expression
are considered successful matches.
Args:
expected_warning: Warning class expected to be triggered.
expected_regex: Regex (re.Pattern object or string) expected
to be found in error message.
args: Function to be called and extra positional args.
kwargs: Extra kwargs.
msg: Optional message used in case of failure. Can only be used
when assertWarnsRegex is used as a context manager.
deprecated_func(*args, **kwargs)
countTestCases(self)
debug(self)
Run the test case without results and without catching exceptions
The unit test framework includes a debug method on test cases
and test suites to support post-mortem debugging. The test code
is run in such a way that errors are not caught. This way a
caller can catch the errors and initiate post-mortem debugging.
The DocTestCase provides a debug method that raises
UnexpectedException errors if there is an unexpected
exception:
>>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
... {}, 'foo', 'foo.py', 0)
>>> case = DocTestCase(test)
>>> try:
... case.debug()
... except UnexpectedException as f:
... failure = f
The UnexpectedException contains the test, the example, and
the original exception:
>>> failure.test is test
True
>>> failure.example.want
'42\n'
>>> exc_info = failure.exc_info
>>> raise exc_info[1] # Already has the traceback
Traceback (most recent call last):
...
KeyError
If the output doesn't match, then a DocTestFailure is raised:
>>> test = DocTestParser().get_doctest('''
... >>> x = 1
... >>> x
... 2
... ''', {}, 'foo', 'foo.py', 0)
>>> case = DocTestCase(test)
>>> try:
... case.debug()
... except DocTestFailure as f:
... failure = f
DocTestFailure objects provide access to the test:
>>> failure.test is test
True
As well as to the example:
>>> failure.example.want
'2\n'
and the actual output:
>>> failure.got
'1\n'
defaultTestResult(self)
doClassCleanups()
Execute all class cleanup functions. Normally called for you after
tearDownClass.
doCleanups(self)
Execute all cleanup functions. Normally called for you after
tearDown.
fail(self, msg=None)
Fail immediately, with the given message.
deprecated_func(*args, **kwargs)
deprecated_func(*args, **kwargs)
deprecated_func(*args, **kwargs)
deprecated_func(*args, **kwargs)
deprecated_func(*args, **kwargs)
deprecated_func(*args, **kwargs)
deprecated_func(*args, **kwargs)
format_failure(self, err)
id(self)
run(self, result=None)
runTest(self)
setUp(self)
setUpClass()
Hook method for setting up class fixture before running tests in the class.
shortDescription(self)
skipTest(self, reason)
Skip this test.
subTest(self, msg=<object object at 0x7f75e3c95b90>, **params)
Return a context manager that will return the enclosed block
of code in a subtest identified by the optional message and
keyword parameters. A failure in the subtest marks the test
case as failed but resumes execution at the end of the enclosed
block, allowing further test code to be executed.
tearDown(self)
tearDownClass()
Hook method for deconstructing the class fixture after running all tests in the class.
longMessage = True
maxDiff = 640
DocTestFailure
A DocTest example has failed in debugging mode.
The exception instance has variables:
- test: the DocTest object being run
- example: the Example object that failed
- got: the actual output
with_traceback(...)
Exception.with_traceback(tb) --
set self.__traceback__ to tb and return self.
args = <attribute 'args' of 'BaseException' objects>
DocTestFinder
A class used to extract the DocTests that are relevant to a given
object, from its docstring and the docstrings of its contained
objects. Doctests can currently be extracted from the following
object types: modules, functions, classes, methods, staticmethods,
classmethods, and properties.
find(self, obj, name=None, module=None, globs=None, extraglobs=None)
Return a list of the DocTests that are defined by the given
object's docstring, or by any of its contained objects'
docstrings.
The optional parameter `module` is the module that contains
the given object. If the module is not specified or is None, then
the test finder will attempt to automatically determine the
correct module. The object's module is used:
- As a default namespace, if `globs` is not specified.
- To prevent the DocTestFinder from extracting DocTests
from objects that are imported from other modules.
- To find the name of the file containing the object.
- To help find the line number of the object within its
file.
Contained objects whose module does not match `module` are ignored.
If `module` is False, no attempt to find the module will be made.
This is obscure, of use mostly in tests: if `module` is False, or
is None but cannot be found automatically, then all objects are
considered to belong to the (non-existent) module, so all contained
objects will (recursively) be searched for doctests.
The globals for each DocTest is formed by combining `globs`
and `extraglobs` (bindings in `extraglobs` override bindings
in `globs`). A new copy of the globals dictionary is created
for each DocTest. If `globs` is not specified, then it
defaults to the module's `__dict__`, if specified, or {}
otherwise. If `extraglobs` is not specified, then it defaults
to {}.
DocTestParser
A class used to parse strings containing doctest examples.
get_doctest(self, string, globs, name, filename, lineno)
Extract all doctest examples from the given string, and
collect them into a `DocTest` object.
`globs`, `name`, `filename`, and `lineno` are attributes for
the new `DocTest` object. See the documentation for `DocTest`
for more information.
get_examples(self, string, name='<string>')
Extract all doctest examples from the given string, and return
them as a list of `Example` objects. Line numbers are
0-based, because it's most common in doctests that nothing
interesting appears on the same line as opening triple-quote,
and so the first interesting line is called "line 1" then.
The optional argument `name` is a name identifying this
string, and is only used for error messages.
parse(self, string, name='<string>')
Divide the given string into examples and intervening text,
and return them as a list of alternating Examples and strings.
Line numbers for the Examples are 0-based. The optional
argument `name` is a name identifying this string, and is only
used for error messages.
DocTestRunner
A class used to run DocTest test cases, and accumulate statistics.
The `run` method is used to process a single DocTest case. It
returns a tuple `(f, t)`, where `t` is the number of test cases
tried, and `f` is the number of test cases that failed.
>>> tests = DocTestFinder().find(_TestClass)
>>> runner = DocTestRunner(verbose=False)
>>> tests.sort(key = lambda test: test.name)
>>> for test in tests:
... print(test.name, '->', runner.run(test))
_TestClass -> TestResults(failed=0, attempted=2)
_TestClass.__init__ -> TestResults(failed=0, attempted=2)
_TestClass.get -> TestResults(failed=0, attempted=2)
_TestClass.square -> TestResults(failed=0, attempted=1)
The `summarize` method prints a summary of all the test cases that
have been run by the runner, and returns an aggregated `(f, t)`
tuple:
>>> runner.summarize(verbose=1)
4 items passed all tests:
2 tests in _TestClass
2 tests in _TestClass.__init__
2 tests in _TestClass.get
1 tests in _TestClass.square
7 tests in 4 items.
7 passed and 0 failed.
Test passed.
TestResults(failed=0, attempted=7)
The aggregated number of tried examples and failed examples is
also available via the `tries` and `failures` attributes:
>>> runner.tries
7
>>> runner.failures
0
The comparison between expected outputs and actual outputs is done
by an `OutputChecker`. This comparison may be customized with a
number of option flags; see the documentation for `testmod` for
more information. If the option flags are insufficient, then the
comparison may also be customized by passing a subclass of
`OutputChecker` to the constructor.
The test runner's display output can be controlled in two ways.
First, an output function (`out) can be passed to
`TestRunner.run`; this function will be called with strings that
should be displayed. It defaults to `sys.stdout.write`. If
capturing the output is not sufficient, then the display output
can be also customized by subclassing DocTestRunner, and
overriding the methods `report_start`, `report_success`,
`report_unexpected_exception`, and `report_failure`.
merge(self, other)
report_failure(self, out, test, example, got)
Report that the given example failed.
report_start(self, out, test, example)
Report that the test runner is about to process the given
example. (Only displays a message if verbose=True)
report_success(self, out, test, example, got)
Report that the given example ran successfully. (Only
displays a message if verbose=True)
report_unexpected_exception(self, out, test, example, exc_info)
Report that the given example raised an unexpected exception.
run(self, test, compileflags=None, out=None, clear_globs=True)
Run the examples in `test`, and display the results using the
writer function `out`.
The examples are run in the namespace `test.globs`. If
`clear_globs` is true (the default), then this namespace will
be cleared after the test runs, to help with garbage
collection. If you would like to examine the namespace after
the test completes, then use `clear_globs=False`.
`compileflags` gives the set of flags that should be used by
the Python compiler when running the examples. If not
specified, then it will default to the set of future-import
flags that apply to `globs`.
The output of each example is checked using
`DocTestRunner.check_output`, and the results are formatted by
the `DocTestRunner.report_*` methods.
summarize(self, verbose=None)
Print a summary of all the test cases that have been run by
this DocTestRunner, and return a tuple `(f, t)`, where `f` is
the total number of failed examples, and `t` is the total
number of tried examples.
The optional `verbose` argument controls how detailed the
summary is. If the verbosity is not specified, then the
DocTestRunner's verbosity is used.
DIVIDER = '**********************************************************************'
Example
A single doctest example, consisting of source code and expected
output. `Example` defines the following attributes:
- source: A single Python statement, always ending with a newline.
The constructor adds a newline if needed.
- want: The expected output from running the source code (either
from stdout, or a traceback in case of exception). `want` ends
with a newline unless it's empty, in which case it's an empty
string. The constructor adds a newline if needed.
- exc_msg: The exception message generated by the example, if
the example is expected to generate an exception; or `None` if
it is not expected to generate an exception. This exception
message is compared against the return value of
`traceback.format_exception_only()`. `exc_msg` ends with a
newline unless it's `None`. The constructor adds a newline
if needed.
- lineno: The line number within the DocTest string containing
this Example where the Example begins. This line number is
zero-based, with respect to the beginning of the DocTest.
- indent: The example's indentation in the DocTest string.
I.e., the number of space characters that precede the
example's first prompt.
- options: A dictionary mapping from option flags to True or
False, which is used to override default options for this
example. Any option flags not contained in this dictionary
are left at their default value (as specified by the
DocTestRunner's optionflags). By default, no options are set.
IncrementalNewlineDecoder
Codec used when reading a file in universal newlines mode.
It wraps another incremental decoder, translating \r\n and \r into \n.
It also records the types of newlines encountered. When used with
translate=False, it ensures that the newline sequence is returned in
one piece. When used with decoder=None, it expects unicode strings as
decode input and translates newlines without first invoking an external
decoder.
decode(self, /, input, final=False)
getstate(self, /)
reset(self, /)
setstate(self, state, /)
newlines = <attribute 'newlines' of '_io.IncrementalNewlineDecoder' objects>
OutputChecker
A class used to check the whether the actual output from a doctest
example matches the expected output. `OutputChecker` defines two
methods: `check_output`, which compares a given pair of outputs,
and returns true if they match; and `output_difference`, which
returns a string describing the differences between two outputs.
check_output(self, want, got, optionflags)
Return True iff the actual output from an example (`got`)
matches the expected output (`want`). These strings are
always considered to match if they are identical; but
depending on what option flags the test runner is using,
several non-exact match types are also possible. See the
documentation for `TestRunner` for more information about
option flags.
output_difference(self, example, got, optionflags)
Return a string describing the differences between the
expected output for a given example (`example`) and the actual
output (`got`). `optionflags` is the set of option flags used
to compare `want` and `got`.
SkipDocTestCase
test_skip.AssertionError
Assertion failed.
with_traceback(...)
Exception.with_traceback(tb) --
set self.__traceback__ to tb and return self.
args = <attribute 'args' of 'BaseException' objects>
addClassCleanup(function, /, *args, **kwargs)
Same as addCleanup, except the cleanup items are called even if
setUpClass fails (unlike tearDownClass).
addCleanup(self, function, /, *args, **kwargs)
Add a function, with arguments, to be called when the test is
completed. Functions added are called on a LIFO basis and are
called after tearDown on test failure or success.
Cleanup items are called even if setUp fails (unlike tearDown).
addTypeEqualityFunc(self, typeobj, function)
Add a type specific assertEqual style function to compare a type.
This method is for use by TestCase subclasses that need to register
their own type equality functions to provide nicer error messages.
Args:
typeobj: The data type to call this function on when both values
are of the same type in assertEqual().
function: The callable taking two arguments and an optional
msg= argument that raises self.failureException with a
useful error message when the two arguments are not equal.
assertAlmostEqual(self, first, second, places=None, msg=None, delta=None)
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, or by comparing that the
difference between the two objects is more than the given
delta.
Note that decimal places (from zero) are usually not the same
as significant digits (measured from the most significant digit).
If the two objects compare equal then they will automatically
compare almost equal.
deprecated_func(*args, **kwargs)
assertCountEqual(self, first, second, msg=None)
Asserts that two iterables have the same elements, the same number of
times, without regard to order.
self.assertEqual(Counter(list(first)),
Counter(list(second)))
Example:
- [0, 1, 1] and [1, 0, 1] compare equal.
- [0, 0, 1] and [0, 1] compare unequal.
assertDictContainsSubset(self, subset, dictionary, msg=None)
Checks whether dictionary is a superset of subset.
assertDictEqual(self, d1, d2, msg=None)
assertEqual(self, first, second, msg=None)
Fail if the two objects are unequal as determined by the '=='
operator.
deprecated_func(*args, **kwargs)
assertFalse(self, expr, msg=None)
Check that the expression is false.
assertGreater(self, a, b, msg=None)
Just like self.assertTrue(a > b), but with a nicer default message.
assertGreaterEqual(self, a, b, msg=None)
Just like self.assertTrue(a >= b), but with a nicer default message.
assertIn(self, member, container, msg=None)
Just like self.assertTrue(a in b), but with a nicer default message.
assertIs(self, expr1, expr2, msg=None)
Just like self.assertTrue(a is b), but with a nicer default message.
assertIsInstance(self, obj, cls, msg=None)
Same as self.assertTrue(isinstance(obj, cls)), with a nicer
default message.
assertIsNone(self, obj, msg=None)
Same as self.assertTrue(obj is None), with a nicer default message.
assertIsNot(self, expr1, expr2, msg=None)
Just like self.assertTrue(a is not b), but with a nicer default message.
assertIsNotNone(self, obj, msg=None)
Included for symmetry with assertIsNone.
assertLess(self, a, b, msg=None)
Just like self.assertTrue(a < b), but with a nicer default message.
assertLessEqual(self, a, b, msg=None)
Just like self.assertTrue(a <= b), but with a nicer default message.
assertListEqual(self, list1, list2, msg=None)
A list-specific equality assertion.
Args:
list1: The first list to compare.
list2: The second list to compare.
msg: Optional message to use on failure instead of a list of
differences.
assertLogs(self, logger=None, level=None)
Fail unless a log message of level *level* or higher is emitted
on *logger_name* or its children. If omitted, *level* defaults to
INFO and *logger* defaults to the root logger.
This method must be used as a context manager, and will yield
a recording object with two attributes: `output` and `records`.
At the end of the context manager, the `output` attribute will
be a list of the matching formatted log messages and the
`records` attribute will be a list of the corresponding LogRecord
objects.
Example::
with self.assertLogs('foo', level='INFO') as cm:
logging.getLogger('foo').info('first message')
logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
'ERROR:foo.bar:second message'])
assertMultiLineEqual(self, first, second, msg=None)
Assert that two multi-line strings are equal.
assertNoLogs(self, logger=None, level=None)
Fail unless no log messages of level *level* or higher are emitted
on *logger_name* or its children.
This method must be used as a context manager.
assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None)
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, or by comparing that the
difference between the two objects is less than the given delta.
Note that decimal places (from zero) are usually not the same
as significant digits (measured from the most significant digit).
Objects that are equal automatically fail.
deprecated_func(*args, **kwargs)
assertNotEqual(self, first, second, msg=None)
Fail if the two objects are equal as determined by the '!='
operator.
deprecated_func(*args, **kwargs)
assertNotIn(self, member, container, msg=None)
Just like self.assertTrue(a not in b), but with a nicer default message.
assertNotIsInstance(self, obj, cls, msg=None)
Included for symmetry with assertIsInstance.
assertNotRegex(self, text, unexpected_regex, msg=None)
Fail the test if the text matches the regular expression.
deprecated_func(*args, **kwargs)
assertRaises(self, expected_exception, *args, **kwargs)
Fail unless an exception of class expected_exception is raised
by the callable when invoked with specified positional and
keyword arguments. If a different type of exception is
raised, it will not be caught, and the test case will be
deemed to have suffered an error, exactly as for an
unexpected exception.
If called with the callable and arguments omitted, will return a
context object used like this::
with self.assertRaises(SomeException):
do_something()
An optional keyword argument 'msg' can be provided when assertRaises
is used as a context object.
The context manager keeps a reference to the exception as
the 'exception' attribute. This allows you to inspect the
exception after the assertion::
with self.assertRaises(SomeException) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
assertRaisesRegex(self, expected_exception, expected_regex, *args, **kwargs)
Asserts that the message in a raised exception matches a regex.
Args:
expected_exception: Exception class expected to be raised.
expected_regex: Regex (re.Pattern object or string) expected
to be found in error message.
args: Function to be called and extra positional args.
kwargs: Extra kwargs.
msg: Optional message used in case of failure. Can only be used
when assertRaisesRegex is used as a context manager.
deprecated_func(*args, **kwargs)
assertRegex(self, text, expected_regex, msg=None)
Fail the test unless the text matches the regular expression.
deprecated_func(*args, **kwargs)
assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None)
An equality assertion for ordered sequences (like lists and tuples).
For the purposes of this function, a valid ordered sequence type is one
which can be indexed, has a length, and has an equality operator.
Args:
seq1: The first sequence to compare.
seq2: The second sequence to compare.
seq_type: The expected datatype of the sequences, or None if no
datatype should be enforced.
msg: Optional message to use on failure instead of a list of
differences.
assertSetEqual(self, set1, set2, msg=None)
A set-specific equality assertion.
Args:
set1: The first set to compare.
set2: The second set to compare.
msg: Optional message to use on failure instead of a list of
differences.
assertSetEqual uses ducktyping to support different types of sets, and
is optimized for sets specifically (parameters must support a
difference method).
assertTrue(self, expr, msg=None)
Check that the expression is true.
assertTupleEqual(self, tuple1, tuple2, msg=None)
A tuple-specific equality assertion.
Args:
tuple1: The first tuple to compare.
tuple2: The second tuple to compare.
msg: Optional message to use on failure instead of a list of
differences.
assertWarns(self, expected_warning, *args, **kwargs)
Fail unless a warning of class warnClass is triggered
by the callable when invoked with specified positional and
keyword arguments. If a different type of warning is
triggered, it will not be handled: depending on the other
warning filtering rules in effect, it might be silenced, printed
out, or raised as an exception.
If called with the callable and arguments omitted, will return a
context object used like this::
with self.assertWarns(SomeWarning):
do_something()
An optional keyword argument 'msg' can be provided when assertWarns
is used as a context object.
The context manager keeps a reference to the first matching
warning as the 'warning' attribute; similarly, the 'filename'
and 'lineno' attributes give you information about the line
of Python code from which the warning was triggered.
This allows you to inspect the warning after the assertion::
with self.assertWarns(SomeWarning) as cm:
do_something()
the_warning = cm.warning
self.assertEqual(the_warning.some_attribute, 147)
assertWarnsRegex(self, expected_warning, expected_regex, *args, **kwargs)
Asserts that the message in a triggered warning matches a regexp.
Basic functioning is similar to assertWarns() with the addition
that only warnings whose messages also match the regular expression
are considered successful matches.
Args:
expected_warning: Warning class expected to be triggered.
expected_regex: Regex (re.Pattern object or string) expected
to be found in error message.
args: Function to be called and extra positional args.
kwargs: Extra kwargs.
msg: Optional message used in case of failure. Can only be used
when assertWarnsRegex is used as a context manager.
deprecated_func(*args, **kwargs)
countTestCases(self)
debug(self)
Run the test case without results and without catching exceptions
The unit test framework includes a debug method on test cases
and test suites to support post-mortem debugging. The test code
is run in such a way that errors are not caught. This way a
caller can catch the errors and initiate post-mortem debugging.
The DocTestCase provides a debug method that raises
UnexpectedException errors if there is an unexpected
exception:
>>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
... {}, 'foo', 'foo.py', 0)
>>> case = DocTestCase(test)
>>> try:
... case.debug()
... except UnexpectedException as f:
... failure = f
The UnexpectedException contains the test, the example, and
the original exception:
>>> failure.test is test
True
>>> failure.example.want
'42\n'
>>> exc_info = failure.exc_info
>>> raise exc_info[1] # Already has the traceback
Traceback (most recent call last):
...
KeyError
If the output doesn't match, then a DocTestFailure is raised:
>>> test = DocTestParser().get_doctest('''
... >>> x = 1
... >>> x
... 2
... ''', {}, 'foo', 'foo.py', 0)
>>> case = DocTestCase(test)
>>> try:
... case.debug()
... except DocTestFailure as f:
... failure = f
DocTestFailure objects provide access to the test:
>>> failure.test is test
True
As well as to the example:
>>> failure.example.want
'2\n'
and the actual output:
>>> failure.got
'1\n'
defaultTestResult(self)
doClassCleanups()
Execute all class cleanup functions. Normally called for you after
tearDownClass.
doCleanups(self)
Execute all cleanup functions. Normally called for you after
tearDown.
fail(self, msg=None)
Fail immediately, with the given message.
deprecated_func(*args, **kwargs)
deprecated_func(*args, **kwargs)
deprecated_func(*args, **kwargs)
deprecated_func(*args, **kwargs)
deprecated_func(*args, **kwargs)
deprecated_func(*args, **kwargs)
deprecated_func(*args, **kwargs)
format_failure(self, err)
id(self)
run(self, result=None)
runTest(self)
setUp(self)
setUpClass()
Hook method for setting up class fixture before running tests in the class.
shortDescription(self)
skipTest(self, reason)
Skip this test.
subTest(self, msg=<object object at 0x7f75e3c95b90>, **params)
Return a context manager that will return the enclosed block
of code in a subtest identified by the optional message and
keyword parameters. A failure in the subtest marks the test
case as failed but resumes execution at the end of the enclosed
block, allowing further test code to be executed.
tearDown(self)
tearDownClass()
Hook method for deconstructing the class fixture after running all tests in the class.
test_skip(self)
longMessage = True
maxDiff = 640
StringIO
Text I/O implementation using an in-memory buffer.
The initial_value argument sets the value of object. The newline
argument is like the one of TextIOWrapper's constructor.
close(self, /)
Close the IO object.
Attempting any further operation after the object is closed
will raise a ValueError.
This method has no effect if the file is already closed.
detach(...)
Separate the underlying buffer from the TextIOBase and return it.
After the underlying buffer has been detached, the TextIO is in an
unusable state.
fileno(self, /)
Returns underlying file descriptor if one exists.
OSError is raised if the IO object does not use a file descriptor.
flush(self, /)
Flush write buffers, if applicable.
This is not implemented for read-only and non-blocking streams.
getvalue(self, /)
Retrieve the entire contents of the object.
isatty(self, /)
Return whether this is an 'interactive' stream.
Return False if it can't be determined.
read(self, size=-1, /)
Read at most size characters, returned as a string.
If the argument is negative or omitted, read until EOF
is reached. Return an empty string at EOF.
readable(self, /)
Returns True if the IO object can be read.
readline(self, size=-1, /)
Read until newline or EOF.
Returns an empty string if EOF is hit immediately.
readlines(self, hint=-1, /)
Return a list of lines from the stream.
hint can be specified to control the number of lines read: no more
lines will be read if the total size (in bytes/characters) of all
lines so far exceeds hint.
seek(self, pos, whence=0, /)
Change stream position.
Seek to character offset pos relative to position indicated by whence:
0 Start of stream (the default). pos should be >= 0;
1 Current position - pos must be 0;
2 End of stream - pos must be 0.
Returns the new absolute position.
seekable(self, /)
Returns True if the IO object can be seeked.
tell(self, /)
Tell the current file position.
truncate(self, pos=None, /)
Truncate size to pos.
The pos argument defaults to the current file position, as
returned by tell(). The current file position is unchanged.
Returns the new absolute position.
writable(self, /)
Returns True if the IO object can be written.
write(self, s, /)
Write string to file.
Returns the number of characters written, which is always equal to
the length of the string.
writelines(self, lines, /)
Write a list of lines to stream.
Line separators are not added, so it is usual for each of the
lines provided to have a line separator at the end.
closed = <attribute 'closed' of '_io.StringIO' objects>
encoding = <attribute 'encoding' of '_io._TextIOBase' objects>
Encoding of the text stream.
Subclasses should override.
errors = <attribute 'errors' of '_io._TextIOBase' objects>
The error setting of the decoder or encoder.
Subclasses should override.
line_buffering = <attribute 'line_buffering' of '_io.StringIO' objects>
newlines = <attribute 'newlines' of '_io.StringIO' objects>
TestResults
TestResults(failed, attempted)
count(self, value, /)
Return number of occurrences of value.
index(self, value, start=0, stop=9223372036854775807, /)
Return first index of value.
Raises ValueError if the value is not present.
attempted = _tuplegetter(1, 'Alias for field number 1')
Alias for field number 1
failed = _tuplegetter(0, 'Alias for field number 0')
Alias for field number 0
UnexpectedException
A DocTest example has encountered an unexpected exception
The exception instance has variables:
- test: the DocTest object being run
- example: the Example object that failed
- exc_info: the exception info
with_traceback(...)
Exception.with_traceback(tb) --
set self.__traceback__ to tb and return self.
args = <attribute 'args' of 'BaseException' objects>
Functions
DocFileSuite
DocFileSuite(*paths, **kw)
A unittest suite for one or more doctest files.
The path to each doctest file is given as a string; the
interpretation of that string depends on the keyword argument
"module_relative".
A number of options may be provided as keyword arguments:
module_relative
If "module_relative" is True, then the given file paths are
interpreted as os-independent module-relative paths. By
default, these paths are relative to the calling module's
directory; but if the "package" argument is specified, then
they are relative to that package. To ensure os-independence,
"filename" should use "/" characters to separate path
segments, and may not be an absolute path (i.e., it may not
begin with "/").
If "module_relative" is False, then the given file paths are
interpreted as os-specific paths. These paths may be absolute
or relative (to the current working directory).
package
A Python package or the name of a Python package whose directory
should be used as the base directory for module relative paths.
If "package" is not specified, then the calling module's
directory is used as the base directory for module relative
filenames. It is an error to specify "package" if
"module_relative" is False.
setUp
A set-up function. This is called before running the
tests in each file. The setUp function will be passed a DocTest
object. The setUp function can access the test globals as the
globs attribute of the test passed.
tearDown
A tear-down function. This is called after running the
tests in each file. The tearDown function will be passed a DocTest
object. The tearDown function can access the test globals as the
globs attribute of the test passed.
globs
A dictionary containing initial global variables for the tests.
optionflags
A set of doctest option flags expressed as an integer.
parser
A DocTestParser (or subclass) that should be used to extract
tests from the files.
encoding
An encoding that will be used to convert the files to unicode.
DocFileTest
DocFileTest(path, module_relative=True, package=None, globs=None, parser=<doctest.DocTestParser object at 0x7f75e109bee0>, encoding=None, **options)
DocTestSuite
DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None, **options)
Convert doctest tests for a module to a unittest test suite.
This converts each documentation string in a module that
contains doctest tests to a unittest test case. If any of the
tests in a doc string fail, then the test case fails. An exception
is raised showing the name of the file containing the test and a
(sometimes approximate) line number.
The `module` argument provides the module to be tested. The argument
can be either a module or a module name.
If no argument is given, the calling module is used.
A number of options may be provided as keyword arguments:
setUp
A set-up function. This is called before running the
tests in each file. The setUp function will be passed a DocTest
object. The setUp function can access the test globals as the
globs attribute of the test passed.
tearDown
A tear-down function. This is called after running the
tests in each file. The tearDown function will be passed a DocTest
object. The tearDown function can access the test globals as the
globs attribute of the test passed.
globs
A dictionary containing initial global variables for the tests.
optionflags
A set of doctest option flags expressed as an integer.
debug
debug(module, name, pm=False)
Debug a single doctest docstring.
Provide the module (or dotted name of the module) containing the
test to be debugged and the name (within the module) of the object
with the docstring with tests to be debugged.
debug_script
debug_script(src, pm=False, globs=None)
Debug a test script. `src` is the script, as a string.
debug_src
debug_src(src, pm=False, globs=None)
Debug a single doctest docstring, in argument `src`'
namedtuple
namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
register_optionflag
register_optionflag(name)
run_docstring_examples
run_docstring_examples(f, globs, verbose=False, name='NoName', compileflags=None, optionflags=0)
Test examples in the given object's docstring (`f`), using `globs`
as globals. Optional argument `name` is used in failure messages.
If the optional argument `verbose` is true, then generate output
even if there are no failures.
`compileflags` gives the set of flags that should be used by the
Python compiler when running the examples. If not specified, then
it will default to the set of future-import flags that apply to
`globs`.
Optional keyword arg `optionflags` specifies options for the
testing and output. See the documentation for `testmod` for more
information.
script_from_examples
script_from_examples(s)
Extract script from text with examples.
Converts text with examples to a Python script. Example input is
converted to regular code. Example output and all other words
are converted to comments:
>>> text = '''
... Here are examples of simple math.
...
... Python has super accurate integer addition
...
... >>> 2 + 2
... 5
...
... And very friendly error messages:
...
... >>> 1/0
... To Infinity
... And
... Beyond
...
... You can use logic if you want:
...
... >>> if 0:
... ... blah
... ... blah
... ...
...
... Ho hum
... '''
>>> print(script_from_examples(text))
# Here are examples of simple math.
#
# Python has super accurate integer addition
#
2 + 2
# Expected:
## 5
#
# And very friendly error messages:
#
1/0
# Expected:
## To Infinity
## And
## Beyond
#
# You can use logic if you want:
#
if 0:
blah
blah
#
# Ho hum
<BLANKLINE>
set_unittest_reportflags
set_unittest_reportflags(flags)
Sets the unittest option flags.
The old flag is returned so that a runner could restore the old
value if it wished to:
>>> import doctest
>>> old = doctest._unittest_reportflags
>>> doctest.set_unittest_reportflags(REPORT_NDIFF |
... REPORT_ONLY_FIRST_FAILURE) == old
True
>>> doctest._unittest_reportflags == (REPORT_NDIFF |
... REPORT_ONLY_FIRST_FAILURE)
True
Only reporting flags can be set:
>>> doctest.set_unittest_reportflags(ELLIPSIS)
Traceback (most recent call last):
...
ValueError: ('Only reporting flags allowed', 8)
>>> doctest.set_unittest_reportflags(old) == (REPORT_NDIFF |
... REPORT_ONLY_FIRST_FAILURE)
True
testfile
testfile(filename, module_relative=True, name=None, package=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, parser=<doctest.DocTestParser object at 0x7f75e109beb0>, encoding=None)
Test examples in the given file. Return (#failures, #tests).
Optional keyword arg "module_relative" specifies how filenames
should be interpreted:
- If "module_relative" is True (the default), then "filename"
specifies a module-relative path. By default, this path is
relative to the calling module's directory; but if the
"package" argument is specified, then it is relative to that
package. To ensure os-independence, "filename" should use
"/" characters to separate path segments, and should not
be an absolute path (i.e., it may not begin with "/").
- If "module_relative" is False, then "filename" specifies an
os-specific path. The path may be absolute or relative (to
the current working directory).
Optional keyword arg "name" gives the name of the test; by default
use the file's basename.
Optional keyword argument "package" is a Python package or the
name of a Python package whose directory should be used as the
base directory for a module relative filename. If no package is
specified, then the calling module's directory is used as the base
directory for module relative filenames. It is an error to
specify "package" if "module_relative" is False.
Optional keyword arg "globs" gives a dict to be used as the globals
when executing examples; by default, use {}. A copy of this dict
is actually used for each docstring, so that each docstring's
examples start with a clean slate.
Optional keyword arg "extraglobs" gives a dictionary that should be
merged into the globals that are used to execute examples. By
default, no extra globals are used.
Optional keyword arg "verbose" prints lots of stuff if true, prints
only failures if false; by default, it's true iff "-v" is in sys.argv.
Optional keyword arg "report" prints a summary at the end when true,
else prints nothing at the end. In verbose mode, the summary is
detailed, else very brief (in fact, empty if all tests passed).
Optional keyword arg "optionflags" or's together module constants,
and defaults to 0. Possible values (see the docs for details):
DONT_ACCEPT_TRUE_FOR_1
DONT_ACCEPT_BLANKLINE
NORMALIZE_WHITESPACE
ELLIPSIS
SKIP
IGNORE_EXCEPTION_DETAIL
REPORT_UDIFF
REPORT_CDIFF
REPORT_NDIFF
REPORT_ONLY_FIRST_FAILURE
Optional keyword arg "raise_on_error" raises an exception on the
first unexpected exception or failure. This allows failures to be
post-mortem debugged.
Optional keyword arg "parser" specifies a DocTestParser (or
subclass) that should be used to extract tests from the files.
Optional keyword arg "encoding" specifies an encoding that should
be used to convert the file to unicode.
Advanced tomfoolery: testmod runs methods of a local instance of
class doctest.Tester, then merges the results into (or creates)
global Tester instance doctest.master. Methods of doctest.master
can be called directly too, if you want to do something unusual.
Passing report=0 to testmod is especially useful then, to delay
displaying a summary. Invoke doctest.master.summarize(verbose)
when you're done fiddling.
testmod
testmod(m=None, name=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, exclude_empty=False)
m=None, name=None, globs=None, verbose=None, report=True,
optionflags=0, extraglobs=None, raise_on_error=False,
exclude_empty=False
Test examples in docstrings in functions and classes reachable
from module m (or the current module if m is not supplied), starting
with m.__doc__.
Also test examples reachable from dict m.__test__ if it exists and is
not None. m.__test__ maps names to functions, classes and strings;
function and class docstrings are tested even if the name is private;
strings are tested directly, as if they were docstrings.
Return (#failures, #tests).
See help(doctest) for an overview.
Optional keyword arg "name" gives the name of the module; by default
use m.__name__.
Optional keyword arg "globs" gives a dict to be used as the globals
when executing examples; by default, use m.__dict__. A copy of this
dict is actually used for each docstring, so that each docstring's
examples start with a clean slate.
Optional keyword arg "extraglobs" gives a dictionary that should be
merged into the globals that are used to execute examples. By
default, no extra globals are used. This is new in 2.4.
Optional keyword arg "verbose" prints lots of stuff if true, prints
only failures if false; by default, it's true iff "-v" is in sys.argv.
Optional keyword arg "report" prints a summary at the end when true,
else prints nothing at the end. In verbose mode, the summary is
detailed, else very brief (in fact, empty if all tests passed).
Optional keyword arg "optionflags" or's together module constants,
and defaults to 0. This is new in 2.3. Possible values (see the
docs for details):
DONT_ACCEPT_TRUE_FOR_1
DONT_ACCEPT_BLANKLINE
NORMALIZE_WHITESPACE
ELLIPSIS
SKIP
IGNORE_EXCEPTION_DETAIL
REPORT_UDIFF
REPORT_CDIFF
REPORT_NDIFF
REPORT_ONLY_FIRST_FAILURE
Optional keyword arg "raise_on_error" raises an exception on the
first unexpected exception or failure. This allows failures to be
post-mortem debugged.
Advanced tomfoolery: testmod runs methods of a local instance of
class doctest.Tester, then merges the results into (or creates)
global Tester instance doctest.master. Methods of doctest.master
can be called directly too, if you want to do something unusual.
Passing report=0 to testmod is especially useful then, to delay
displaying a summary. Invoke doctest.master.summarize(verbose)
when you're done fiddling.
testsource
testsource(module, name)
Extract the test sources from a doctest docstring as a script.
Provide the module (or dotted name of the module) containing the
test to be debugged and the name (within the module) of the object
with the doc string with tests to be debugged.
Other members
BLANKLINE_MARKER = '<BLANKLINE>'
COMPARISON_FLAGS = 63
DONT_ACCEPT_BLANKLINE = 2
DONT_ACCEPT_TRUE_FOR_1 = 1
ELLIPSIS = 8
ELLIPSIS_MARKER = '...'
FAIL_FAST = 1024
IGNORE_EXCEPTION_DETAIL = 32
NORMALIZE_WHITESPACE = 4
OPTIONFLAGS_BY_NAME = {'DONT_ACCEPT_TRUE_FOR_1': 1, 'DONT_ACCEPT_BLANKLINE': 2, 'NORMALIZE_WHITESPACE': 4, 'ELLIPSIS': 8, 'SKIP': 16, 'IGNORE_EXCEPTION_DETAIL': 32, 'REPORT_UDIFF': 64, 'REPORT_CDIFF': 128, 'REPORT_NDIFF': 256, 'REPORT_ONLY_FIRST_FAILURE': 512, 'FAIL_FAST': 1024}
REPORTING_FLAGS = 1984
REPORT_CDIFF = 128
REPORT_NDIFF = 256
REPORT_ONLY_FIRST_FAILURE = 512
REPORT_UDIFF = 64
SKIP = 16
master = None
Modules
difflib
inspect
linecache
os
pdb
re
sys
traceback
unittest