Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/src/_pytest/doctest.py

raw
1 # mypy: allow-untyped-defs
2 """Discover and run doctests in modules and test files."""
3
4 import bdb
5 from contextlib import contextmanager
6 import functools
7 import inspect
8 import os
9 from pathlib import Path
10 import platform
11 import sys
12 import traceback
13 import types
14 from typing import Any
15 from typing import Callable
16 from typing import Dict
17 from typing import Generator
18 from typing import Iterable
19 from typing import List
20 from typing import Optional
21 from typing import Pattern
22 from typing import Sequence
23 from typing import Tuple
24 from typing import Type
25 from typing import TYPE_CHECKING
26 from typing import Union
27 import warnings
28
29 from _pytest import outcomes
30 from _pytest._code.code import ExceptionInfo
31 from _pytest._code.code import ReprFileLocation
32 from _pytest._code.code import TerminalRepr
33 from _pytest._io import TerminalWriter
34 from _pytest.compat import safe_getattr
35 from _pytest.config import Config
36 from _pytest.config.argparsing import Parser
37 from _pytest.fixtures import fixture
38 from _pytest.fixtures import TopRequest
39 from _pytest.nodes import Collector
40 from _pytest.nodes import Item
41 from _pytest.outcomes import OutcomeException
42 from _pytest.outcomes import skip
43 from _pytest.pathlib import fnmatch_ex
44 from _pytest.python import Module
45 from _pytest.python_api import approx
46 from _pytest.warning_types import PytestWarning
47
48
49 if TYPE_CHECKING:
50 import doctest
51 from typing import Self
52
53 DOCTEST_REPORT_CHOICE_NONE = "none"
54 DOCTEST_REPORT_CHOICE_CDIFF = "cdiff"
55 DOCTEST_REPORT_CHOICE_NDIFF = "ndiff"
56 DOCTEST_REPORT_CHOICE_UDIFF = "udiff"
57 DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE = "only_first_failure"
58
59 DOCTEST_REPORT_CHOICES = (
60 DOCTEST_REPORT_CHOICE_NONE,
61 DOCTEST_REPORT_CHOICE_CDIFF,
62 DOCTEST_REPORT_CHOICE_NDIFF,
63 DOCTEST_REPORT_CHOICE_UDIFF,
64 DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE,
65 )
66
67 # Lazy definition of runner class
68 RUNNER_CLASS = None
69 # Lazy definition of output checker class
70 CHECKER_CLASS: Optional[Type["doctest.OutputChecker"]] = None
71
72
73 def pytest_addoption(parser: Parser) -> None:
74 parser.addini(
75 "doctest_optionflags",
76 "Option flags for doctests",
77 type="args",
78 default=["ELLIPSIS"],
79 )
80 parser.addini(
81 "doctest_encoding", "Encoding used for doctest files", default="utf-8"
82 )
83 group = parser.getgroup("collect")
84 group.addoption(
85 "--doctest-modules",
86 action="store_true",
87 default=False,
88 help="Run doctests in all .py modules",
89 dest="doctestmodules",
90 )
91 group.addoption(
92 "--doctest-report",
93 type=str.lower,
94 default="udiff",
95 help="Choose another output format for diffs on doctest failure",
96 choices=DOCTEST_REPORT_CHOICES,
97 dest="doctestreport",
98 )
99 group.addoption(
100 "--doctest-glob",
101 action="append",
102 default=[],
103 metavar="pat",
104 help="Doctests file matching pattern, default: test*.txt",
105 dest="doctestglob",
106 )
107 group.addoption(
108 "--doctest-ignore-import-errors",
109 action="store_true",
110 default=False,
111 help="Ignore doctest collection errors",
112 dest="doctest_ignore_import_errors",
113 )
114 group.addoption(
115 "--doctest-continue-on-failure",
116 action="store_true",
117 default=False,
118 help="For a given doctest, continue to run after the first failure",
119 dest="doctest_continue_on_failure",
120 )
121
122
123 def pytest_unconfigure() -> None:
124 global RUNNER_CLASS
125
126 RUNNER_CLASS = None
127
128
129 def pytest_collect_file(
130 file_path: Path,
131 parent: Collector,
132 ) -> Optional[Union["DoctestModule", "DoctestTextfile"]]:
133 config = parent.config
134 if file_path.suffix == ".py":
135 if config.option.doctestmodules and not any(
136 (_is_setup_py(file_path), _is_main_py(file_path))
137 ):
138 return DoctestModule.from_parent(parent, path=file_path)
139 elif _is_doctest(config, file_path, parent):
140 return DoctestTextfile.from_parent(parent, path=file_path)
141 return None
142
143
144 def _is_setup_py(path: Path) -> bool:
145 if path.name != "setup.py":
146 return False
147 contents = path.read_bytes()
148 return b"setuptools" in contents or b"distutils" in contents
149
150
151 def _is_doctest(config: Config, path: Path, parent: Collector) -> bool:
152 if path.suffix in (".txt", ".rst") and parent.session.isinitpath(path):
153 return True
154 globs = config.getoption("doctestglob") or ["test*.txt"]
155 return any(fnmatch_ex(glob, path) for glob in globs)
156
157
158 def _is_main_py(path: Path) -> bool:
159 return path.name == "__main__.py"
160
161
162 class ReprFailDoctest(TerminalRepr):
163 def __init__(
164 self, reprlocation_lines: Sequence[Tuple[ReprFileLocation, Sequence[str]]]
165 ) -> None:
166 self.reprlocation_lines = reprlocation_lines
167
168 def toterminal(self, tw: TerminalWriter) -> None:
169 for reprlocation, lines in self.reprlocation_lines:
170 for line in lines:
171 tw.line(line)
172 reprlocation.toterminal(tw)
173
174
175 class MultipleDoctestFailures(Exception):
176 def __init__(self, failures: Sequence["doctest.DocTestFailure"]) -> None:
177 super().__init__()
178 self.failures = failures
179
180
181 def _init_runner_class() -> Type["doctest.DocTestRunner"]:
182 import doctest
183
184 class PytestDoctestRunner(doctest.DebugRunner):
185 """Runner to collect failures.
186
187 Note that the out variable in this case is a list instead of a
188 stdout-like object.
189 """
190
191 def __init__(
192 self,
193 checker: Optional["doctest.OutputChecker"] = None,
194 verbose: Optional[bool] = None,
195 optionflags: int = 0,
196 continue_on_failure: bool = True,
197 ) -> None:
198 super().__init__(checker=checker, verbose=verbose, optionflags=optionflags)
199 self.continue_on_failure = continue_on_failure
200
201 def report_failure(
202 self,
203 out,
204 test: "doctest.DocTest",
205 example: "doctest.Example",
206 got: str,
207 ) -> None:
208 failure = doctest.DocTestFailure(test, example, got)
209 if self.continue_on_failure:
210 out.append(failure)
211 else:
212 raise failure
213
214 def report_unexpected_exception(
215 self,
216 out,
217 test: "doctest.DocTest",
218 example: "doctest.Example",
219 exc_info: Tuple[Type[BaseException], BaseException, types.TracebackType],
220 ) -> None:
221 if isinstance(exc_info[1], OutcomeException):
222 raise exc_info[1]
223 if isinstance(exc_info[1], bdb.BdbQuit):
224 outcomes.exit("Quitting debugger")
225 failure = doctest.UnexpectedException(test, example, exc_info)
226 if self.continue_on_failure:
227 out.append(failure)
228 else:
229 raise failure
230
231 return PytestDoctestRunner
232
233
234 def _get_runner(
235 checker: Optional["doctest.OutputChecker"] = None,
236 verbose: Optional[bool] = None,
237 optionflags: int = 0,
238 continue_on_failure: bool = True,
239 ) -> "doctest.DocTestRunner":
240 # We need this in order to do a lazy import on doctest
241 global RUNNER_CLASS
242 if RUNNER_CLASS is None:
243 RUNNER_CLASS = _init_runner_class()
244 # Type ignored because the continue_on_failure argument is only defined on
245 # PytestDoctestRunner, which is lazily defined so can't be used as a type.
246 return RUNNER_CLASS( # type: ignore
247 checker=checker,
248 verbose=verbose,
249 optionflags=optionflags,
250 continue_on_failure=continue_on_failure,
251 )
252
253
254 class DoctestItem(Item):
255 def __init__(
256 self,
257 name: str,
258 parent: "Union[DoctestTextfile, DoctestModule]",
259 runner: "doctest.DocTestRunner",
260 dtest: "doctest.DocTest",
261 ) -> None:
262 super().__init__(name, parent)
263 self.runner = runner
264 self.dtest = dtest
265
266 # Stuff needed for fixture support.
267 self.obj = None
268 fm = self.session._fixturemanager
269 fixtureinfo = fm.getfixtureinfo(node=self, func=None, cls=None)
270 self._fixtureinfo = fixtureinfo
271 self.fixturenames = fixtureinfo.names_closure
272 self._initrequest()
273
274 @classmethod
275 def from_parent( # type: ignore[override]
276 cls,
277 parent: "Union[DoctestTextfile, DoctestModule]",
278 *,
279 name: str,
280 runner: "doctest.DocTestRunner",
281 dtest: "doctest.DocTest",
282 ) -> "Self":
283 # incompatible signature due to imposed limits on subclass
284 """The public named constructor."""
285 return super().from_parent(name=name, parent=parent, runner=runner, dtest=dtest)
286
287 def _initrequest(self) -> None:
288 self.funcargs: Dict[str, object] = {}
289 self._request = TopRequest(self, _ispytest=True) # type: ignore[arg-type]
290
291 def setup(self) -> None:
292 self._request._fillfixtures()
293 globs = dict(getfixture=self._request.getfixturevalue)
294 for name, value in self._request.getfixturevalue("doctest_namespace").items():
295 globs[name] = value
296 self.dtest.globs.update(globs)
297
298 def runtest(self) -> None:
299 _check_all_skipped(self.dtest)
300 self._disable_output_capturing_for_darwin()
301 failures: List["doctest.DocTestFailure"] = []
302 # Type ignored because we change the type of `out` from what
303 # doctest expects.
304 self.runner.run(self.dtest, out=failures) # type: ignore[arg-type]
305 if failures:
306 raise MultipleDoctestFailures(failures)
307
308 def _disable_output_capturing_for_darwin(self) -> None:
309 """Disable output capturing. Otherwise, stdout is lost to doctest (#985)."""
310 if platform.system() != "Darwin":
311 return
312 capman = self.config.pluginmanager.getplugin("capturemanager")
313 if capman:
314 capman.suspend_global_capture(in_=True)
315 out, err = capman.read_global_capture()
316 sys.stdout.write(out)
317 sys.stderr.write(err)
318
319 # TODO: Type ignored -- breaks Liskov Substitution.
320 def repr_failure( # type: ignore[override]
321 self,
322 excinfo: ExceptionInfo[BaseException],
323 ) -> Union[str, TerminalRepr]:
324 import doctest
325
326 failures: Optional[
327 Sequence[Union[doctest.DocTestFailure, doctest.UnexpectedException]]
328 ] = None
329 if isinstance(
330 excinfo.value, (doctest.DocTestFailure, doctest.UnexpectedException)
331 ):
332 failures = [excinfo.value]
333 elif isinstance(excinfo.value, MultipleDoctestFailures):
334 failures = excinfo.value.failures
335
336 if failures is None:
337 return super().repr_failure(excinfo)
338
339 reprlocation_lines = []
340 for failure in failures:
341 example = failure.example
342 test = failure.test
343 filename = test.filename
344 if test.lineno is None:
345 lineno = None
346 else:
347 lineno = test.lineno + example.lineno + 1
348 message = type(failure).__name__
349 # TODO: ReprFileLocation doesn't expect a None lineno.
350 reprlocation = ReprFileLocation(filename, lineno, message) # type: ignore[arg-type]
351 checker = _get_checker()
352 report_choice = _get_report_choice(self.config.getoption("doctestreport"))
353 if lineno is not None:
354 assert failure.test.docstring is not None
355 lines = failure.test.docstring.splitlines(False)
356 # add line numbers to the left of the error message
357 assert test.lineno is not None
358 lines = [
359 "%03d %s" % (i + test.lineno + 1, x) for (i, x) in enumerate(lines)
360 ]
361 # trim docstring error lines to 10
362 lines = lines[max(example.lineno - 9, 0) : example.lineno + 1]
363 else:
364 lines = [
365 "EXAMPLE LOCATION UNKNOWN, not showing all tests of that example"
366 ]
367 indent = ">>>"
368 for line in example.source.splitlines():
369 lines.append(f"??? {indent} {line}")
370 indent = "..."
371 if isinstance(failure, doctest.DocTestFailure):
372 lines += checker.output_difference(
373 example, failure.got, report_choice
374 ).split("\n")
375 else:
376 inner_excinfo = ExceptionInfo.from_exc_info(failure.exc_info)
377 lines += ["UNEXPECTED EXCEPTION: %s" % repr(inner_excinfo.value)]
378 lines += [
379 x.strip("\n") for x in traceback.format_exception(*failure.exc_info)
380 ]
381 reprlocation_lines.append((reprlocation, lines))
382 return ReprFailDoctest(reprlocation_lines)
383
384 def reportinfo(self) -> Tuple[Union["os.PathLike[str]", str], Optional[int], str]:
385 return self.path, self.dtest.lineno, "[doctest] %s" % self.name
386
387
388 def _get_flag_lookup() -> Dict[str, int]:
389 import doctest
390
391 return dict(
392 DONT_ACCEPT_TRUE_FOR_1=doctest.DONT_ACCEPT_TRUE_FOR_1,
393 DONT_ACCEPT_BLANKLINE=doctest.DONT_ACCEPT_BLANKLINE,
394 NORMALIZE_WHITESPACE=doctest.NORMALIZE_WHITESPACE,
395 ELLIPSIS=doctest.ELLIPSIS,
396 IGNORE_EXCEPTION_DETAIL=doctest.IGNORE_EXCEPTION_DETAIL,
397 COMPARISON_FLAGS=doctest.COMPARISON_FLAGS,
398 ALLOW_UNICODE=_get_allow_unicode_flag(),
399 ALLOW_BYTES=_get_allow_bytes_flag(),
400 NUMBER=_get_number_flag(),
401 )
402
403
404 def get_optionflags(config: Config) -> int:
405 optionflags_str = config.getini("doctest_optionflags")
406 flag_lookup_table = _get_flag_lookup()
407 flag_acc = 0
408 for flag in optionflags_str:
409 flag_acc |= flag_lookup_table[flag]
410 return flag_acc
411
412
413 def _get_continue_on_failure(config: Config) -> bool:
414 continue_on_failure: bool = config.getvalue("doctest_continue_on_failure")
415 if continue_on_failure:
416 # We need to turn off this if we use pdb since we should stop at
417 # the first failure.
418 if config.getvalue("usepdb"):
419 continue_on_failure = False
420 return continue_on_failure
421
422
423 class DoctestTextfile(Module):
424 obj = None
425
426 def collect(self) -> Iterable[DoctestItem]:
427 import doctest
428
429 # Inspired by doctest.testfile; ideally we would use it directly,
430 # but it doesn't support passing a custom checker.
431 encoding = self.config.getini("doctest_encoding")
432 text = self.path.read_text(encoding)
433 filename = str(self.path)
434 name = self.path.name
435 globs = {"__name__": "__main__"}
436
437 optionflags = get_optionflags(self.config)
438
439 runner = _get_runner(
440 verbose=False,
441 optionflags=optionflags,
442 checker=_get_checker(),
443 continue_on_failure=_get_continue_on_failure(self.config),
444 )
445
446 parser = doctest.DocTestParser()
447 test = parser.get_doctest(text, globs, name, filename, 0)
448 if test.examples:
449 yield DoctestItem.from_parent(
450 self, name=test.name, runner=runner, dtest=test
451 )
452
453
454 def _check_all_skipped(test: "doctest.DocTest") -> None:
455 """Raise pytest.skip() if all examples in the given DocTest have the SKIP
456 option set."""
457 import doctest
458
459 all_skipped = all(x.options.get(doctest.SKIP, False) for x in test.examples)
460 if all_skipped:
461 skip("all tests skipped by +SKIP option")
462
463
464 def _is_mocked(obj: object) -> bool:
465 """Return if an object is possibly a mock object by checking the
466 existence of a highly improbable attribute."""
467 return (
468 safe_getattr(obj, "pytest_mock_example_attribute_that_shouldnt_exist", None)
469 is not None
470 )
471
472
473 @contextmanager
474 def _patch_unwrap_mock_aware() -> Generator[None, None, None]:
475 """Context manager which replaces ``inspect.unwrap`` with a version
476 that's aware of mock objects and doesn't recurse into them."""
477 real_unwrap = inspect.unwrap
478
479 def _mock_aware_unwrap(
480 func: Callable[..., Any], *, stop: Optional[Callable[[Any], Any]] = None
481 ) -> Any:
482 try:
483 if stop is None or stop is _is_mocked:
484 return real_unwrap(func, stop=_is_mocked)
485 _stop = stop
486 return real_unwrap(func, stop=lambda obj: _is_mocked(obj) or _stop(func))
487 except Exception as e:
488 warnings.warn(
489 f"Got {e!r} when unwrapping {func!r}. This is usually caused "
490 "by a violation of Python's object protocol; see e.g. "
491 "https://github.com/pytest-dev/pytest/issues/5080",
492 PytestWarning,
493 )
494 raise
495
496 inspect.unwrap = _mock_aware_unwrap
497 try:
498 yield
499 finally:
500 inspect.unwrap = real_unwrap
501
502
503 class DoctestModule(Module):
504 def collect(self) -> Iterable[DoctestItem]:
505 import doctest
506
507 class MockAwareDocTestFinder(doctest.DocTestFinder):
508 """A hackish doctest finder that overrides stdlib internals to fix a stdlib bug.
509
510 https://github.com/pytest-dev/pytest/issues/3456
511 https://bugs.python.org/issue25532
512 """
513
514 def _find_lineno(self, obj, source_lines):
515 """Doctest code does not take into account `@property`, this
516 is a hackish way to fix it. https://bugs.python.org/issue17446
517
518 Wrapped Doctests will need to be unwrapped so the correct
519 line number is returned. This will be reported upstream. #8796
520 """
521 if isinstance(obj, property):
522 obj = getattr(obj, "fget", obj)
523
524 if hasattr(obj, "__wrapped__"):
525 # Get the main obj in case of it being wrapped
526 obj = inspect.unwrap(obj)
527
528 # Type ignored because this is a private function.
529 return super()._find_lineno( # type:ignore[misc]
530 obj,
531 source_lines,
532 )
533
534 def _find(
535 self, tests, obj, name, module, source_lines, globs, seen
536 ) -> None:
537 if _is_mocked(obj):
538 return
539 with _patch_unwrap_mock_aware():
540 # Type ignored because this is a private function.
541 super()._find( # type:ignore[misc]
542 tests, obj, name, module, source_lines, globs, seen
543 )
544
545 if sys.version_info < (3, 13):
546
547 def _from_module(self, module, object):
548 """`cached_property` objects are never considered a part
549 of the 'current module'. As such they are skipped by doctest.
550 Here we override `_from_module` to check the underlying
551 function instead. https://github.com/python/cpython/issues/107995
552 """
553 if isinstance(object, functools.cached_property):
554 object = object.func
555
556 # Type ignored because this is a private function.
557 return super()._from_module(module, object) # type: ignore[misc]
558
559 else: # pragma: no cover
560 pass
561
562 try:
563 module = self.obj
564 except Collector.CollectError:
565 if self.config.getvalue("doctest_ignore_import_errors"):
566 skip("unable to import module %r" % self.path)
567 else:
568 raise
569
570 # While doctests currently don't support fixtures directly, we still
571 # need to pick up autouse fixtures.
572 self.session._fixturemanager.parsefactories(self)
573
574 # Uses internal doctest module parsing mechanism.
575 finder = MockAwareDocTestFinder()
576 optionflags = get_optionflags(self.config)
577 runner = _get_runner(
578 verbose=False,
579 optionflags=optionflags,
580 checker=_get_checker(),
581 continue_on_failure=_get_continue_on_failure(self.config),
582 )
583
584 for test in finder.find(module, module.__name__):
585 if test.examples: # skip empty doctests
586 yield DoctestItem.from_parent(
587 self, name=test.name, runner=runner, dtest=test
588 )
589
590
591 def _init_checker_class() -> Type["doctest.OutputChecker"]:
592 import doctest
593 import re
594
595 class LiteralsOutputChecker(doctest.OutputChecker):
596 # Based on doctest_nose_plugin.py from the nltk project
597 # (https://github.com/nltk/nltk) and on the "numtest" doctest extension
598 # by Sebastien Boisgerault (https://github.com/boisgera/numtest).
599
600 _unicode_literal_re = re.compile(r"(\W|^)[uU]([rR]?[\'\"])", re.UNICODE)
601 _bytes_literal_re = re.compile(r"(\W|^)[bB]([rR]?[\'\"])", re.UNICODE)
602 _number_re = re.compile(
603 r"""
604 (?P<number>
605 (?P<mantissa>
606 (?P<integer1> [+-]?\d*)\.(?P<fraction>\d+)
607 |
608 (?P<integer2> [+-]?\d+)\.
609 )
610 (?:
611 [Ee]
612 (?P<exponent1> [+-]?\d+)
613 )?
614 |
615 (?P<integer3> [+-]?\d+)
616 (?:
617 [Ee]
618 (?P<exponent2> [+-]?\d+)
619 )
620 )
621 """,
622 re.VERBOSE,
623 )
624
625 def check_output(self, want: str, got: str, optionflags: int) -> bool:
626 if super().check_output(want, got, optionflags):
627 return True
628
629 allow_unicode = optionflags & _get_allow_unicode_flag()
630 allow_bytes = optionflags & _get_allow_bytes_flag()
631 allow_number = optionflags & _get_number_flag()
632
633 if not allow_unicode and not allow_bytes and not allow_number:
634 return False
635
636 def remove_prefixes(regex: Pattern[str], txt: str) -> str:
637 return re.sub(regex, r"\1\2", txt)
638
639 if allow_unicode:
640 want = remove_prefixes(self._unicode_literal_re, want)
641 got = remove_prefixes(self._unicode_literal_re, got)
642
643 if allow_bytes:
644 want = remove_prefixes(self._bytes_literal_re, want)
645 got = remove_prefixes(self._bytes_literal_re, got)
646
647 if allow_number:
648 got = self._remove_unwanted_precision(want, got)
649
650 return super().check_output(want, got, optionflags)
651
652 def _remove_unwanted_precision(self, want: str, got: str) -> str:
653 wants = list(self._number_re.finditer(want))
654 gots = list(self._number_re.finditer(got))
655 if len(wants) != len(gots):
656 return got
657 offset = 0
658 for w, g in zip(wants, gots):
659 fraction: Optional[str] = w.group("fraction")
660 exponent: Optional[str] = w.group("exponent1")
661 if exponent is None:
662 exponent = w.group("exponent2")
663 precision = 0 if fraction is None else len(fraction)
664 if exponent is not None:
665 precision -= int(exponent)
666 if float(w.group()) == approx(float(g.group()), abs=10**-precision):
667 # They're close enough. Replace the text we actually
668 # got with the text we want, so that it will match when we
669 # check the string literally.
670 got = (
671 got[: g.start() + offset] + w.group() + got[g.end() + offset :]
672 )
673 offset += w.end() - w.start() - (g.end() - g.start())
674 return got
675
676 return LiteralsOutputChecker
677
678
679 def _get_checker() -> "doctest.OutputChecker":
680 """Return a doctest.OutputChecker subclass that supports some
681 additional options:
682
683 * ALLOW_UNICODE and ALLOW_BYTES options to ignore u'' and b''
684 prefixes (respectively) in string literals. Useful when the same
685 doctest should run in Python 2 and Python 3.
686
687 * NUMBER to ignore floating-point differences smaller than the
688 precision of the literal number in the doctest.
689
690 An inner class is used to avoid importing "doctest" at the module
691 level.
692 """
693 global CHECKER_CLASS
694 if CHECKER_CLASS is None:
695 CHECKER_CLASS = _init_checker_class()
696 return CHECKER_CLASS()
697
698
699 def _get_allow_unicode_flag() -> int:
700 """Register and return the ALLOW_UNICODE flag."""
701 import doctest
702
703 return doctest.register_optionflag("ALLOW_UNICODE")
704
705
706 def _get_allow_bytes_flag() -> int:
707 """Register and return the ALLOW_BYTES flag."""
708 import doctest
709
710 return doctest.register_optionflag("ALLOW_BYTES")
711
712
713 def _get_number_flag() -> int:
714 """Register and return the NUMBER flag."""
715 import doctest
716
717 return doctest.register_optionflag("NUMBER")
718
719
720 def _get_report_choice(key: str) -> int:
721 """Return the actual `doctest` module flag value.
722
723 We want to do it as late as possible to avoid importing `doctest` and all
724 its dependencies when parsing options, as it adds overhead and breaks tests.
725 """
726 import doctest
727
728 return {
729 DOCTEST_REPORT_CHOICE_UDIFF: doctest.REPORT_UDIFF,
730 DOCTEST_REPORT_CHOICE_CDIFF: doctest.REPORT_CDIFF,
731 DOCTEST_REPORT_CHOICE_NDIFF: doctest.REPORT_NDIFF,
732 DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE: doctest.REPORT_ONLY_FIRST_FAILURE,
733 DOCTEST_REPORT_CHOICE_NONE: 0,
734 }[key]
735
736
737 @fixture(scope="session")
738 def doctest_namespace() -> Dict[str, Any]:
739 """Fixture that returns a :py:class:`dict` that will be injected into the
740 namespace of doctests.
741
742 Usually this fixture is used in conjunction with another ``autouse`` fixture:
743
744 .. code-block:: python
745
746 @pytest.fixture(autouse=True)
747 def add_np(doctest_namespace):
748 doctest_namespace["np"] = numpy
749
750 For more details: :ref:`doctest_namespace`.
751 """
752 return dict()