Debian Codegraph @

IPython/testing/plugin/pytest_ipdoctest.py

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