Debian Codegraph @

src/_pytest/doctest.py

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