xdoctest.stdlib_doctest package

Adapter API for stdlib doctest objects and protocols.

Tools that already produce or consume stdlib doctest objects can use this package to run them through xdoctest without depending on the layout of the private adapter modules.

Quick start

A third-party collector that already produces stdlib doctest objects can register its checker and pass those objects directly to xdoctest:

Example

>>> import doctest
>>> import xdoctest.stdlib_doctest as stdlib_doctest
>>> fix = stdlib_doctest.register_optionflag('_STDLIB_DOCTEST_DOCS_FIX')
>>> class ThirdPartyChecker(stdlib_doctest.OutputChecker):
...     def check_output(self, want, got, optionflags):
...         if optionflags & fix:
...             want = want.replace('L', '')
...             got = got.replace('L', '')
...         return super().check_output(want, got, optionflags)
>>> checker_name = '_stdlib_doctest_docs_checker'
>>> stdlib_doctest.register_checker(checker_name, ThirdPartyChecker)
>>> example = doctest.Example(
...     source='print("10")\n',
...     want='10L\n',
...     lineno=0,
...     options={fix: True},
... )
>>> converted = stdlib_doctest.from_examples(
...     [example],
...     name='third-party-example',
...     config={'output_checker': checker_name},
... )
>>> isinstance(converted, stdlib_doctest.DocTest)
True
>>> converted.run(verbose=0, on_error='raise')['passed']
True

Registration

register_optionflag

Register a stdlib-style option flag by name, optionally binding it to an xdoctest runtime-state key. The returned bit is shared with doctest.register_optionflag().

register_checker

Register a stdlib-shaped output checker under a configuration name. Select it for a test with DocTest.config['output_checker'].

resolve_checker

Resolve the native checker or a previously registered foreign checker.

Conversion

optionflags_to_runtime_state and runtime_state_to_optionflags

Convert between stdlib option-flag integers and xdoctest’s structured runtime state.

from_examples and from_stdlib_doctest

Convert stdlib-shaped examples or a complete doctest.DocTest into a runnable DocTest while preserving source locations, namespaces, option boundaries, and expected output.

Supporting types

StdlibExampleLike

Structural protocol accepted by from_examples().

RuntimeState

Structured runtime state accepted and returned by the conversion helpers.

DocTest

Runnable xdoctest object returned by the intake helpers.

OutputChecker

xdoctest’s native matcher exposed through the stdlib checker interface for composition by foreign checkers.

The overlapping registration, conversion, checker, and optionflag names remain available at the top-level xdoctest namespace for compatibility. This package is the documented home of the stdlib-doctest adapter.

Supporting types

class xdoctest.stdlib_doctest.StdlibExampleLike(*args, **kwargs)[source]

Bases: Protocol

Structural type accepted by from_examples().

The adapter does not require an actual doctest.Example; a small object with the same core attributes is sufficient.

Example

>>> from types import SimpleNamespace
>>> example = SimpleNamespace(source='2 + 3\n', want='5\n', lineno=0)
>>> from_examples([example]).run(verbose=0, on_error='return')['passed']
True
class xdoctest.stdlib_doctest.RuntimeState(default_state: RuntimeStateDict | None = None)[source]

Bases: NiceRepr

Maintains the runtime state for a single run() of an example

Inline directives are pushed and popped after the line is run. Otherwise directives persist until another directive disables it.

CommandLine

xdoctest -m xdoctest.directive RuntimeState

Example

>>> from xdoctest.directive import *
>>> runstate = RuntimeState()
>>> assert not runstate['IGNORE_WHITESPACE']
>>> # Directives modify the runtime state
>>> directives = list(Directive.extract('# xdoc: -ELLIPSIS, +IGNORE_WHITESPACE'))
>>> runstate.update(directives)
>>> assert not runstate['ELLIPSIS']
>>> assert runstate['IGNORE_WHITESPACE']
>>> # Inline directives only persist until the next update
>>> directives = [Directive('IGNORE_WHITESPACE', False, inline=True)]
>>> runstate.update(directives)
>>> assert not runstate['IGNORE_WHITESPACE']
>>> runstate.update({})
>>> assert runstate['IGNORE_WHITESPACE']

Example

>>> # xdoc: +IGNORE_WHITESPACE
>>> print(str(RuntimeState()))
<RuntimeState({
    ASYNC: False,
    DONT_ACCEPT_BLANKLINE: False,
    ELLIPSIS: True,
    FLOAT_CMP: False,
    IGNORE_EXCEPTION_DETAIL: False,
    IGNORE_OUTPUT: False,
    IGNORE_WANT: False,
    IGNORE_WARNINGS: False,
    IGNORE_WHITESPACE: False,
    NORMALIZE_REPR: True,
    NORMALIZE_WHITESPACE: True,
    REPORT_CDIFF: False,
    REPORT_NDIFF: False,
    REPORT_UDIFF: True,
    REQUIRES: set(...),
    REQUIRE_WANT: False,
    SHOW_WARNINGS: False,
    SKIP: False
})>
Parameters:

default_state (None | dict) – starting default state, if unspecified falls back to the global DEFAULT_RUNTIME_STATE

class xdoctest.stdlib_doctest.DocTest(docsrc: str, modpath: str | PathLike[str] | ModuleType | None = None, callname: str | None = None, num: int = 0, lineno: int = 1, fpath: str | PathLike[str] | None = None, block_type: str | None = None, mode: str = 'pytest')[source]

Bases: object

Holds information necessary to execute and verify a doctest

Variables:
  • docsrc (str) – doctest source code

  • modpath (str | PathLike | ModuleType | None) – 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 | tuple[type[BaseException], BaseException, types.TracebackType] | tuple[None, None, None]) – 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 | ModuleType | None)

  • callname (str | None)

  • num (int)

  • lineno (int)

  • fpath (str | None)

  • block_type (str | None)

  • mode (str)

class xdoctest.stdlib_doctest.OutputChecker[source]

Bases: OutputChecker

Default xdoctest checker exposed through a stdlib-doctest interface.

Subclasses can wrap or extend xdoctest’s matching by calling super().check_output(want, got, optionflags) to delegate the base comparison while adding their own pre-/post-processing.

Note

This class intentionally accepts the same (want, got, optionflags) signature as doctest.OutputChecker so that it is a drop-in replacement for stdlib-shaped consumers.

Example

>>> from xdoctest.stdlib_doctest import ELLIPSIS, FLOAT_CMP
>>> output_checker = OutputChecker()
>>> output_checker.check_output(
>>>     'prefix ... value=1\n',
>>>     'prefix middle value=1.0000001\n',
>>>     ELLIPSIS | FLOAT_CMP,
>>> )
True

Registration

xdoctest.stdlib_doctest.register_optionflag(name: str, runtime_state_key: str | None = None) → int[source]

Register an optionflag with xdoctest. See RuntimeFlagFacade.register_optionflag().

Calling this with an existing name is idempotent.

Example

>>> register_optionflag('FLOAT_CMP') == FLOAT_CMP
True
xdoctest.stdlib_doctest.register_checker(name: str, checker_: OutputChecker | type[OutputChecker]) → None[source]

Register a foreign output checker under a configuration name.

Parameters:
  • name – selection key used in configs and runtime state. 'xdoctest' is reserved for the native checker and cannot be replaced.

  • checker_ – either an doctest.OutputChecker instance or a class with a no-argument constructor that returns one. Instances are explicitly process-shared. Classes retain factory semantics and are materialized at most once for each RuntimeState run.

Example

>>> import doctest
>>> name = '_xdoctest_example_checker'
>>> instance = doctest.OutputChecker()
>>> register_checker(name, instance)
>>> resolve_checker(name) is instance
True
>>> del _REGISTERED_CHECKERS[name]
xdoctest.stdlib_doctest.resolve_checker(name: str, runstate: RuntimeState | None = None) → OutputChecker[source]

Resolve an output checker using the documented registration lifecycle.

The reserved native checker is constructed directly and is never stored in the mutable foreign registry. Registered instances are returned as-is. Registered classes are factories when no runtime state is supplied. With a runtime state, one instance is cached for that run and reused by matching and failure rendering. A fresh registration record invalidates an existing per-run cache even when the same class is registered again.

Raises:

KeyError – if a foreign name has not been registered.

Example

>>> isinstance(resolve_checker('xdoctest'), OutputChecker)
True

Example

>>> class ExampleChecker(doctest.OutputChecker):
>>>     pass
>>> name = '_xdoctest_per_run_checker_example'
>>> register_checker(name, ExampleChecker)
>>> resolve_checker(name) is resolve_checker(name)
False
>>> state = directive.RuntimeState()
>>> state.set_output_checker(name)
>>> resolve_checker(name, state) is resolve_checker(name, state)
True
>>> del _REGISTERED_CHECKERS[name]

Conversion

xdoctest.stdlib_doctest.optionflags_to_runtime_state(optionflags: int, default_state: RuntimeStateDict | None = None) → RuntimeState[source]

Unpack a complete stdlib optionflag mask into runtime state.

Example

>>> state = optionflags_to_runtime_state(0)
>>> state['ELLIPSIS'], state['NORMALIZE_WHITESPACE']
(False, False)
>>> optionflags_to_runtime_state(SKIP)['SKIP']
True
xdoctest.stdlib_doctest.runtime_state_to_optionflags(runstate: RuntimeState | Mapping[str, object] | None) → int[source]

Pack structured runtime state into a stdlib optionflag mask.

Example

>>> state = directive.RuntimeState({'ELLIPSIS': True})
>>> bool(runtime_state_to_optionflags(state) & ELLIPSIS)
True
xdoctest.stdlib_doctest.from_examples(examples: Iterable[StdlibExampleLike], *, globs: Mapping[str, Any] | None = None, name: str = '<doctest>', filename: str | PathLike[str] | None = None, lineno: int | None = None, optionflags: int | None = 0, config: Mapping[str, object] | None = None) → DocTest[source]

Build a runnable xdoctest DocTest from a sequence of stdlib-like example objects.

Parameters:
  • examples – iterable of objects each with source, want, lineno and (optionally) options attributes — i.e. the stdlib doctest.Example shape.

  • globs – namespace dict for the doctest. Mirrors stdlib DocTest.globs. Defaults to {'__name__': '__main__'}.

  • name – human-readable test name; mirrors stdlib DocTest.name.

  • filename – source file path; mirrors stdlib DocTest.filename. Used by xdoctest for failure reporting.

  • lineno – explicit one-based source line for the first example. If None, the first example’s zero-based lineno is converted to one-based form.

  • optionflags – complete stdlib-doctest optionflags mask applying to the whole test. Every integer, including 0, replaces mapped runtime flags and checker-only bits. Pass None to retain the corresponding values supplied through config.

  • config – optional mapping of DoctestConfig keys to merge into the resulting DocTest.config. Most useful for setting output_checker to select a registered checker.

Returns:

configured to run via DocTest.run().

Return type:

DocTest

Notes

Per-example options are attached as structured per-part directives (see module docstring); the source text is never rewritten.

Example

>>> import doctest
>>> examples = [
>>>     doctest.Example('value = 3\n', '', lineno=0),
>>>     doctest.Example('value * 2\n', '6\n', lineno=1),
>>> ]
>>> dtest = from_examples(examples, name='double')
>>> result = dtest.run(verbose=0, on_error='return')
>>> result['passed']
True
xdoctest.stdlib_doctest.from_stdlib_doctest(stdlib_test: DocTest, *, optionflags: int | None = 0, config: Mapping[str, object] | None = None) → DocTest[source]

Convenience: convert a stdlib doctest.DocTest directly. The metadata (name, filename, lineno, globs) is taken from the input.

Example

>>> import doctest
>>> example = doctest.Example('answer\n', '42\n', lineno=2)
>>> stdlib_test = doctest.DocTest(
>>>     [example], {'answer': 42}, 'demo', 'demo.py', 10, '',
>>> )
>>> dtest = from_stdlib_doctest(stdlib_test)
>>> dtest.lineno
13
>>> dtest.run(verbose=0, on_error='return')['passed']
True