xdoctest.doctest_example module

This module defines the main class that holds a DocTest example

class xdoctest.doctest_example.DoctestConfig(*args, **kwargs)[source]

Bases: dict

Doctest configuration

Static configuration for collection, execution, and reporting doctests. Note dynamic directives are not managed by DoctestConfig, they use RuntimeState.

_populate_from_cli(ns)[source]
_update_argparse_cli(add_argument, prefix=None, defaults={})[source]

Updates a pytest or argparse CLI

Parameters:

add_argument (callable) – the parser.add_argument function

getvalue(key, given=None)[source]
Parameters:
  • key (str) – The configuration key

  • given (Any) – A user override

Returns:

if given is None returns the configured value

Return type:

Any

class xdoctest.doctest_example.DocTest(docsrc, modpath=None, callname=None, num=0, lineno=1, fpath=None, block_type=None, mode='pytest')[source]

Bases: object

Holds information necessary to execute and verify a doctest

Variables:
  • docsrc (str) – doctest source code

  • modpath (str | PathLike) – module the source was read from

  • callname (str) – name of the function/method/class/module being tested

  • num (int) – the index of the doctest in the docstring. (i.e. this object refers to the num-th doctest within a docstring)

  • lineno (int) – The line (starting from 1) in the file that the doctest begins on. (i.e. if you were to go to this line in the file, the first line of the doctest should be on this line).

  • fpath (PathLike) – Typically the same as modpath, only specified for non-python files (e.g. rst files).

  • block_type (str | None) – Hint indicating the type of docstring block. Can be (‘Example’, ‘Doctest’, ‘Script’, ‘Benchmark’, ‘zero-arg’, etc..).

  • mode (str) – Hint at what created / is running this doctest. This impacts how results are presented and what doctests are skipped. Can be “native” or “pytest”. Defaults to “pytest”.

  • config (DoctestConfig) – configuration for running / checking the doctest

  • module (ModuleType | None) – a reference to the module that contains the doctest

  • modname (str) – name of the module that contains the doctest.

  • failed_tb_lineno (int | None) – Line number a failure occurred on.

  • exc_info (None | TracebackType) – traceback of a failure if one occurred.

  • failed_part (None | DoctestPart) – the part containing the failure if one occurred.

  • warn_list (list) – from warnings.catch_warnings()

  • logged_evals (OrderedDict) – Mapping from part index to what they evaluated to (if anything)

  • logged_stdout (OrderedDict) – Mapping from part index to captured stdout.

  • global_namespace (dict) – globals visible to the doctest

CommandLine

xdoctest -m xdoctest.doctest_example DocTest

Example

>>> from xdoctest import core
>>> from xdoctest import doctest_example
>>> import os
>>> modpath = doctest_example.__file__.replace('.pyc', '.py')
>>> modpath = os.path.realpath(modpath)
>>> testables = core.parse_doctestables(modpath)
>>> for test in testables:
>>>     if test.callname == 'DocTest':
>>>         self = test
>>>         break
>>> assert self.num == 0
>>> assert self.modpath == modpath
>>> print(self)
<DocTest(xdoctest.doctest_example DocTest:0 ln ...)>
Parameters:
  • docsrc (str) – the text of the doctest

  • modpath (str | PathLike | None)

  • callname (str | None)

  • num (int)

  • lineno (int)

  • fpath (str | None)

  • block_type (str | None)

  • mode (str)

UNKNOWN_MODNAME = '<modname?>'
UNKNOWN_MODPATH = '<modpath?>'
UNKNOWN_CALLNAME = '<callname?>'
UNKNOWN_FPATH = '<fpath?>'
is_disabled(pytest=False)[source]

Checks for comment directives on the first line of the doctest

A doctest is force-disabled if it starts with any of the following patterns

  • >>> # DISABLE_DOCTEST

  • >>> # SCRIPT

  • >>> # UNSTABLE

  • >>> # FAILING

And if running in pytest, you can also use

  • >>> import pytest; pytest.skip()

Note

modern versions of xdoctest contain directives like # xdoctest: +SKIP, which are a better way to do this.

Todo

Robustly deprecate these non-standard ways of disabling a doctest. Generate a warning for several versions if they are used, and indicate what the replacement strategy is. Then raise an error for several more versions before finally removing this code.

Return type:

bool

property unique_callname

A key that references this doctest given its module

Returns:

str

property node

A key that references this doctest within pytest

Returns:

str

property valid_testnames

A set of callname and unique_callname

Returns:

Set[str]

wants()[source]

Returns a list of the populated wants

Yields:

str

format_parts(linenos=True, colored=None, want=True, offset_linenos=None, prefix=True)[source]

Used by format_src()

Parameters:
  • linenos (bool) – show line numbers

  • colored (bool | None) – pygmentize the code

  • want (bool) – include the want value if it exists

  • offset_linenos (bool) – if True include the line offset relative to the source file

  • prefix (bool) – if False, exclude the doctest ``>>> `` prefix

format_src(linenos=True, colored=None, want=True, offset_linenos=None, prefix=True)[source]

Adds prefix and line numbers to a doctest

Parameters:
  • linenos (bool) – if True, adds line numbers to output

  • colored (bool) – if True highlight text with ansi colors. Default is specified in the config.

  • want (bool) – if True includes “want” lines (default False).

  • offset_linenos (bool) – if True offset line numbers to agree with their position in the source text file (default False).

  • prefix (bool) – if False, exclude the doctest ``>>> `` prefix

Returns:

str

Example

>>> from xdoctest.core import *
>>> from xdoctest import core
>>> testables = parse_doctestables(core.__file__)
>>> self = next(testables)
>>> self._parse()
>>> print(self.format_src())
>>> print(self.format_src(linenos=False, colored=False))
>>> assert not self.is_disabled()
_parse()[source]

Divide the given string into examples and intervening text.

Returns:

None

Example

>>> s = 'I am a dummy example with three parts'
>>> x = 10
>>> print(s)
I am a dummy example with three parts
>>> s = 'My purpose it so demonstrate how wants work here'
>>> print('The new want applies ONLY to stdout')
>>> print('given before the last want')
>>> '''
    this wont hurt the test at all
    even though its multiline '''
>>> y = 20
The new want applies ONLY to stdout
given before the last want
>>> # Parts from previous examples are executed in the same context
>>> print(x + y)
30

this is simply text, and doesnt apply to the previous doctest the <BLANKLINE> directive is still in effect.

Example

>>> from xdoctest import parser
>>> from xdoctest.docstr import docscrape_google
>>> from xdoctest import doctest_example
>>> DocTest = doctest_example.DocTest
>>> docstr = DocTest._parse.__doc__
>>> blocks = docscrape_google.split_google_docblocks(docstr)
>>> doclineno = DocTest._parse.__code__.co_firstlineno
>>> key, (docsrc, offset) = blocks[-2]
>>> lineno = doclineno + offset
>>> self = DocTest(docsrc, doctest_example.__file__, '_parse', 0,
>>>                lineno)
>>> self._parse()
>>> assert len(self._parts) >= 3
>>> #p1, p2, p3 = self._parts
>>> self.run()
_import_module()[source]

After this point we are in dynamic analysis mode, in most cases xdoctest should have been in static-analysis-only mode.

Returns:

None

static _extract_future_flags(namespace)[source]

Return the compiler-flags associated with the future features that have been imported into the given namespace (i.e. globals).

Returns:

int

_test_globals()[source]
anything_ran()[source]
Returns:

bool

run(verbose=None, on_error=None)[source]

Executes the doctest, checks the results, reports the outcome.

Parameters:
  • verbose (int) – verbosity level

  • on_error (str) – can be ‘raise’ or ‘return’

Returns:

summary

Return type:

Dict

property globs

Alias for global_namespace for pytest 8.0 compatability

property cmdline

A cli-instruction that can be used to execute this doctest.

Return type:

str

property _block_prefix
_pre_run(verbose)[source]
failed_line_offset()[source]

Determine which line in the doctest failed.

Returns:

int | None

failed_lineno()[source]
Returns:

int | None

repr_failure(with_tb=True)[source]

Constructs lines detailing information about a failed doctest

Parameters:

with_tb (bool) – if True include the traceback

Returns:

List[str]

CommandLine

python -m xdoctest.core DocTest.repr_failure:0
python -m xdoctest.core DocTest.repr_failure:1
python -m xdoctest.core DocTest.repr_failure:2

Example

>>> from xdoctest.core import *
>>> docstr = utils.codeblock(
    '''
    >>> x = 1
    >>> print(x + 1)
    2
    >>> print(x + 3)
    3
    >>> print(x + 100)
    101
    ''')
>>> parsekw = dict(fpath='foo.txt', callname='bar', lineno=42)
>>> self = list(parse_docstr_examples(docstr, **parsekw))[0]
>>> summary = self.run(on_error='return', verbose=0)
>>> print('[res]' + '\n[res]'.join(self.repr_failure()))

Example

>>> from xdoctest.core import *
>>> docstr = utils.codeblock(
    r'''
    >>> 1
    1
    >>> print('.▴  .\n.▴ ▴.') # xdoc: -NORMALIZE_WHITESPACE
    . ▴ .
    .▴ ▴.
    ''')
>>> parsekw = dict(fpath='foo.txt', callname='bar', lineno=42)
>>> self = list(parse_docstr_examples(docstr, **parsekw))[0]
>>> summary = self.run(on_error='return', verbose=1)
>>> print('[res]' + '\n[res]'.join(self.repr_failure()))

Example

>>> from xdoctest.core import *
>>> docstr = utils.codeblock(
    '''
    >>> assert True
    >>> assert False
    >>> x = 100
    ''')
>>> self = list(parse_docstr_examples(docstr))[0]
>>> summary = self.run(on_error='return', verbose=0)
>>> print('[res]' + '\n[res]'.join(self.repr_failure()))
_print_captured()[source]
_color(text, color, enabled=None)[source]

conditionally color text based on config and flags

_post_run(verbose)[source]
Returns:

summary

Return type:

Dict

xdoctest.doctest_example._traverse_traceback(tb)[source]