doctest.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. # -*- coding: utf-8 -*-
  2. """ discover and run doctests in modules and test files."""
  3. from __future__ import absolute_import
  4. from __future__ import division
  5. from __future__ import print_function
  6. import inspect
  7. import platform
  8. import sys
  9. import traceback
  10. import warnings
  11. from contextlib import contextmanager
  12. import pytest
  13. from _pytest._code.code import ExceptionInfo
  14. from _pytest._code.code import ReprFileLocation
  15. from _pytest._code.code import TerminalRepr
  16. from _pytest.compat import safe_getattr
  17. from _pytest.fixtures import FixtureRequest
  18. from _pytest.outcomes import Skipped
  19. from _pytest.warning_types import PytestWarning
  20. DOCTEST_REPORT_CHOICE_NONE = "none"
  21. DOCTEST_REPORT_CHOICE_CDIFF = "cdiff"
  22. DOCTEST_REPORT_CHOICE_NDIFF = "ndiff"
  23. DOCTEST_REPORT_CHOICE_UDIFF = "udiff"
  24. DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE = "only_first_failure"
  25. DOCTEST_REPORT_CHOICES = (
  26. DOCTEST_REPORT_CHOICE_NONE,
  27. DOCTEST_REPORT_CHOICE_CDIFF,
  28. DOCTEST_REPORT_CHOICE_NDIFF,
  29. DOCTEST_REPORT_CHOICE_UDIFF,
  30. DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE,
  31. )
  32. # Lazy definition of runner class
  33. RUNNER_CLASS = None
  34. def pytest_addoption(parser):
  35. parser.addini(
  36. "doctest_optionflags",
  37. "option flags for doctests",
  38. type="args",
  39. default=["ELLIPSIS"],
  40. )
  41. parser.addini(
  42. "doctest_encoding", "encoding used for doctest files", default="utf-8"
  43. )
  44. group = parser.getgroup("collect")
  45. group.addoption(
  46. "--doctest-modules",
  47. action="store_true",
  48. default=False,
  49. help="run doctests in all .py modules",
  50. dest="doctestmodules",
  51. )
  52. group.addoption(
  53. "--doctest-report",
  54. type=str.lower,
  55. default="udiff",
  56. help="choose another output format for diffs on doctest failure",
  57. choices=DOCTEST_REPORT_CHOICES,
  58. dest="doctestreport",
  59. )
  60. group.addoption(
  61. "--doctest-glob",
  62. action="append",
  63. default=[],
  64. metavar="pat",
  65. help="doctests file matching pattern, default: test*.txt",
  66. dest="doctestglob",
  67. )
  68. group.addoption(
  69. "--doctest-ignore-import-errors",
  70. action="store_true",
  71. default=False,
  72. help="ignore doctest ImportErrors",
  73. dest="doctest_ignore_import_errors",
  74. )
  75. group.addoption(
  76. "--doctest-continue-on-failure",
  77. action="store_true",
  78. default=False,
  79. help="for a given doctest, continue to run after the first failure",
  80. dest="doctest_continue_on_failure",
  81. )
  82. def pytest_collect_file(path, parent):
  83. config = parent.config
  84. if path.ext == ".py":
  85. if config.option.doctestmodules and not _is_setup_py(config, path, parent):
  86. return DoctestModule(path, parent)
  87. elif _is_doctest(config, path, parent):
  88. return DoctestTextfile(path, parent)
  89. def _is_setup_py(config, path, parent):
  90. if path.basename != "setup.py":
  91. return False
  92. contents = path.read()
  93. return "setuptools" in contents or "distutils" in contents
  94. def _is_doctest(config, path, parent):
  95. if path.ext in (".txt", ".rst") and parent.session.isinitpath(path):
  96. return True
  97. globs = config.getoption("doctestglob") or ["test*.txt"]
  98. for glob in globs:
  99. if path.check(fnmatch=glob):
  100. return True
  101. return False
  102. class ReprFailDoctest(TerminalRepr):
  103. def __init__(self, reprlocation_lines):
  104. # List of (reprlocation, lines) tuples
  105. self.reprlocation_lines = reprlocation_lines
  106. def toterminal(self, tw):
  107. for reprlocation, lines in self.reprlocation_lines:
  108. for line in lines:
  109. tw.line(line)
  110. reprlocation.toterminal(tw)
  111. class MultipleDoctestFailures(Exception):
  112. def __init__(self, failures):
  113. super(MultipleDoctestFailures, self).__init__()
  114. self.failures = failures
  115. def _init_runner_class():
  116. import doctest
  117. class PytestDoctestRunner(doctest.DebugRunner):
  118. """
  119. Runner to collect failures. Note that the out variable in this case is
  120. a list instead of a stdout-like object
  121. """
  122. def __init__(
  123. self, checker=None, verbose=None, optionflags=0, continue_on_failure=True
  124. ):
  125. doctest.DebugRunner.__init__(
  126. self, checker=checker, verbose=verbose, optionflags=optionflags
  127. )
  128. self.continue_on_failure = continue_on_failure
  129. def report_failure(self, out, test, example, got):
  130. failure = doctest.DocTestFailure(test, example, got)
  131. if self.continue_on_failure:
  132. out.append(failure)
  133. else:
  134. raise failure
  135. def report_unexpected_exception(self, out, test, example, exc_info):
  136. if isinstance(exc_info[1], Skipped):
  137. raise exc_info[1]
  138. failure = doctest.UnexpectedException(test, example, exc_info)
  139. if self.continue_on_failure:
  140. out.append(failure)
  141. else:
  142. raise failure
  143. return PytestDoctestRunner
  144. def _get_runner(checker=None, verbose=None, optionflags=0, continue_on_failure=True):
  145. # We need this in order to do a lazy import on doctest
  146. global RUNNER_CLASS
  147. if RUNNER_CLASS is None:
  148. RUNNER_CLASS = _init_runner_class()
  149. return RUNNER_CLASS(
  150. checker=checker,
  151. verbose=verbose,
  152. optionflags=optionflags,
  153. continue_on_failure=continue_on_failure,
  154. )
  155. class DoctestItem(pytest.Item):
  156. def __init__(self, name, parent, runner=None, dtest=None):
  157. super(DoctestItem, self).__init__(name, parent)
  158. self.runner = runner
  159. self.dtest = dtest
  160. self.obj = None
  161. self.fixture_request = None
  162. def setup(self):
  163. if self.dtest is not None:
  164. self.fixture_request = _setup_fixtures(self)
  165. globs = dict(getfixture=self.fixture_request.getfixturevalue)
  166. for name, value in self.fixture_request.getfixturevalue(
  167. "doctest_namespace"
  168. ).items():
  169. globs[name] = value
  170. self.dtest.globs.update(globs)
  171. def runtest(self):
  172. _check_all_skipped(self.dtest)
  173. self._disable_output_capturing_for_darwin()
  174. failures = []
  175. self.runner.run(self.dtest, out=failures)
  176. if failures:
  177. raise MultipleDoctestFailures(failures)
  178. def _disable_output_capturing_for_darwin(self):
  179. """
  180. Disable output capturing. Otherwise, stdout is lost to doctest (#985)
  181. """
  182. if platform.system() != "Darwin":
  183. return
  184. capman = self.config.pluginmanager.getplugin("capturemanager")
  185. if capman:
  186. capman.suspend_global_capture(in_=True)
  187. out, err = capman.read_global_capture()
  188. sys.stdout.write(out)
  189. sys.stderr.write(err)
  190. def repr_failure(self, excinfo):
  191. import doctest
  192. failures = None
  193. if excinfo.errisinstance((doctest.DocTestFailure, doctest.UnexpectedException)):
  194. failures = [excinfo.value]
  195. elif excinfo.errisinstance(MultipleDoctestFailures):
  196. failures = excinfo.value.failures
  197. if failures is not None:
  198. reprlocation_lines = []
  199. for failure in failures:
  200. example = failure.example
  201. test = failure.test
  202. filename = test.filename
  203. if test.lineno is None:
  204. lineno = None
  205. else:
  206. lineno = test.lineno + example.lineno + 1
  207. message = type(failure).__name__
  208. reprlocation = ReprFileLocation(filename, lineno, message)
  209. checker = _get_checker()
  210. report_choice = _get_report_choice(
  211. self.config.getoption("doctestreport")
  212. )
  213. if lineno is not None:
  214. lines = failure.test.docstring.splitlines(False)
  215. # add line numbers to the left of the error message
  216. lines = [
  217. "%03d %s" % (i + test.lineno + 1, x)
  218. for (i, x) in enumerate(lines)
  219. ]
  220. # trim docstring error lines to 10
  221. lines = lines[max(example.lineno - 9, 0) : example.lineno + 1]
  222. else:
  223. lines = [
  224. "EXAMPLE LOCATION UNKNOWN, not showing all tests of that example"
  225. ]
  226. indent = ">>>"
  227. for line in example.source.splitlines():
  228. lines.append("??? %s %s" % (indent, line))
  229. indent = "..."
  230. if isinstance(failure, doctest.DocTestFailure):
  231. lines += checker.output_difference(
  232. example, failure.got, report_choice
  233. ).split("\n")
  234. else:
  235. inner_excinfo = ExceptionInfo(failure.exc_info)
  236. lines += ["UNEXPECTED EXCEPTION: %s" % repr(inner_excinfo.value)]
  237. lines += traceback.format_exception(*failure.exc_info)
  238. reprlocation_lines.append((reprlocation, lines))
  239. return ReprFailDoctest(reprlocation_lines)
  240. else:
  241. return super(DoctestItem, self).repr_failure(excinfo)
  242. def reportinfo(self):
  243. return self.fspath, self.dtest.lineno, "[doctest] %s" % self.name
  244. def _get_flag_lookup():
  245. import doctest
  246. return dict(
  247. DONT_ACCEPT_TRUE_FOR_1=doctest.DONT_ACCEPT_TRUE_FOR_1,
  248. DONT_ACCEPT_BLANKLINE=doctest.DONT_ACCEPT_BLANKLINE,
  249. NORMALIZE_WHITESPACE=doctest.NORMALIZE_WHITESPACE,
  250. ELLIPSIS=doctest.ELLIPSIS,
  251. IGNORE_EXCEPTION_DETAIL=doctest.IGNORE_EXCEPTION_DETAIL,
  252. COMPARISON_FLAGS=doctest.COMPARISON_FLAGS,
  253. ALLOW_UNICODE=_get_allow_unicode_flag(),
  254. ALLOW_BYTES=_get_allow_bytes_flag(),
  255. )
  256. def get_optionflags(parent):
  257. optionflags_str = parent.config.getini("doctest_optionflags")
  258. flag_lookup_table = _get_flag_lookup()
  259. flag_acc = 0
  260. for flag in optionflags_str:
  261. flag_acc |= flag_lookup_table[flag]
  262. return flag_acc
  263. def _get_continue_on_failure(config):
  264. continue_on_failure = config.getvalue("doctest_continue_on_failure")
  265. if continue_on_failure:
  266. # We need to turn off this if we use pdb since we should stop at
  267. # the first failure
  268. if config.getvalue("usepdb"):
  269. continue_on_failure = False
  270. return continue_on_failure
  271. class DoctestTextfile(pytest.Module):
  272. obj = None
  273. def collect(self):
  274. import doctest
  275. # inspired by doctest.testfile; ideally we would use it directly,
  276. # but it doesn't support passing a custom checker
  277. encoding = self.config.getini("doctest_encoding")
  278. text = self.fspath.read_text(encoding)
  279. filename = str(self.fspath)
  280. name = self.fspath.basename
  281. globs = {"__name__": "__main__"}
  282. optionflags = get_optionflags(self)
  283. runner = _get_runner(
  284. verbose=0,
  285. optionflags=optionflags,
  286. checker=_get_checker(),
  287. continue_on_failure=_get_continue_on_failure(self.config),
  288. )
  289. _fix_spoof_python2(runner, encoding)
  290. parser = doctest.DocTestParser()
  291. test = parser.get_doctest(text, globs, name, filename, 0)
  292. if test.examples:
  293. yield DoctestItem(test.name, self, runner, test)
  294. def _check_all_skipped(test):
  295. """raises pytest.skip() if all examples in the given DocTest have the SKIP
  296. option set.
  297. """
  298. import doctest
  299. all_skipped = all(x.options.get(doctest.SKIP, False) for x in test.examples)
  300. if all_skipped:
  301. pytest.skip("all tests skipped by +SKIP option")
  302. def _is_mocked(obj):
  303. """
  304. returns if a object is possibly a mock object by checking the existence of a highly improbable attribute
  305. """
  306. return (
  307. safe_getattr(obj, "pytest_mock_example_attribute_that_shouldnt_exist", None)
  308. is not None
  309. )
  310. @contextmanager
  311. def _patch_unwrap_mock_aware():
  312. """
  313. contextmanager which replaces ``inspect.unwrap`` with a version
  314. that's aware of mock objects and doesn't recurse on them
  315. """
  316. real_unwrap = getattr(inspect, "unwrap", None)
  317. if real_unwrap is None:
  318. yield
  319. else:
  320. def _mock_aware_unwrap(obj, stop=None):
  321. try:
  322. if stop is None or stop is _is_mocked:
  323. return real_unwrap(obj, stop=_is_mocked)
  324. return real_unwrap(obj, stop=lambda obj: _is_mocked(obj) or stop(obj))
  325. except Exception as e:
  326. warnings.warn(
  327. "Got %r when unwrapping %r. This is usually caused "
  328. "by a violation of Python's object protocol; see e.g. "
  329. "https://github.com/pytest-dev/pytest/issues/5080" % (e, obj),
  330. PytestWarning,
  331. )
  332. raise
  333. inspect.unwrap = _mock_aware_unwrap
  334. try:
  335. yield
  336. finally:
  337. inspect.unwrap = real_unwrap
  338. class DoctestModule(pytest.Module):
  339. def collect(self):
  340. import doctest
  341. class MockAwareDocTestFinder(doctest.DocTestFinder):
  342. """
  343. a hackish doctest finder that overrides stdlib internals to fix a stdlib bug
  344. https://github.com/pytest-dev/pytest/issues/3456
  345. https://bugs.python.org/issue25532
  346. """
  347. def _find(self, tests, obj, name, module, source_lines, globs, seen):
  348. if _is_mocked(obj):
  349. return
  350. with _patch_unwrap_mock_aware():
  351. doctest.DocTestFinder._find(
  352. self, tests, obj, name, module, source_lines, globs, seen
  353. )
  354. if self.fspath.basename == "conftest.py":
  355. module = self.config.pluginmanager._importconftest(self.fspath)
  356. else:
  357. try:
  358. module = self.fspath.pyimport()
  359. except ImportError:
  360. if self.config.getvalue("doctest_ignore_import_errors"):
  361. pytest.skip("unable to import module %r" % self.fspath)
  362. else:
  363. raise
  364. # uses internal doctest module parsing mechanism
  365. finder = MockAwareDocTestFinder()
  366. optionflags = get_optionflags(self)
  367. runner = _get_runner(
  368. verbose=0,
  369. optionflags=optionflags,
  370. checker=_get_checker(),
  371. continue_on_failure=_get_continue_on_failure(self.config),
  372. )
  373. for test in finder.find(module, module.__name__):
  374. if test.examples: # skip empty doctests
  375. yield DoctestItem(test.name, self, runner, test)
  376. def _setup_fixtures(doctest_item):
  377. """
  378. Used by DoctestTextfile and DoctestItem to setup fixture information.
  379. """
  380. def func():
  381. pass
  382. doctest_item.funcargs = {}
  383. fm = doctest_item.session._fixturemanager
  384. doctest_item._fixtureinfo = fm.getfixtureinfo(
  385. node=doctest_item, func=func, cls=None, funcargs=False
  386. )
  387. fixture_request = FixtureRequest(doctest_item)
  388. fixture_request._fillfixtures()
  389. return fixture_request
  390. def _get_checker():
  391. """
  392. Returns a doctest.OutputChecker subclass that takes in account the
  393. ALLOW_UNICODE option to ignore u'' prefixes in strings and ALLOW_BYTES
  394. to strip b'' prefixes.
  395. Useful when the same doctest should run in Python 2 and Python 3.
  396. An inner class is used to avoid importing "doctest" at the module
  397. level.
  398. """
  399. if hasattr(_get_checker, "LiteralsOutputChecker"):
  400. return _get_checker.LiteralsOutputChecker()
  401. import doctest
  402. import re
  403. class LiteralsOutputChecker(doctest.OutputChecker):
  404. """
  405. Copied from doctest_nose_plugin.py from the nltk project:
  406. https://github.com/nltk/nltk
  407. Further extended to also support byte literals.
  408. """
  409. _unicode_literal_re = re.compile(r"(\W|^)[uU]([rR]?[\'\"])", re.UNICODE)
  410. _bytes_literal_re = re.compile(r"(\W|^)[bB]([rR]?[\'\"])", re.UNICODE)
  411. def check_output(self, want, got, optionflags):
  412. res = doctest.OutputChecker.check_output(self, want, got, optionflags)
  413. if res:
  414. return True
  415. allow_unicode = optionflags & _get_allow_unicode_flag()
  416. allow_bytes = optionflags & _get_allow_bytes_flag()
  417. if not allow_unicode and not allow_bytes:
  418. return False
  419. else: # pragma: no cover
  420. def remove_prefixes(regex, txt):
  421. return re.sub(regex, r"\1\2", txt)
  422. if allow_unicode:
  423. want = remove_prefixes(self._unicode_literal_re, want)
  424. got = remove_prefixes(self._unicode_literal_re, got)
  425. if allow_bytes:
  426. want = remove_prefixes(self._bytes_literal_re, want)
  427. got = remove_prefixes(self._bytes_literal_re, got)
  428. res = doctest.OutputChecker.check_output(self, want, got, optionflags)
  429. return res
  430. _get_checker.LiteralsOutputChecker = LiteralsOutputChecker
  431. return _get_checker.LiteralsOutputChecker()
  432. def _get_allow_unicode_flag():
  433. """
  434. Registers and returns the ALLOW_UNICODE flag.
  435. """
  436. import doctest
  437. return doctest.register_optionflag("ALLOW_UNICODE")
  438. def _get_allow_bytes_flag():
  439. """
  440. Registers and returns the ALLOW_BYTES flag.
  441. """
  442. import doctest
  443. return doctest.register_optionflag("ALLOW_BYTES")
  444. def _get_report_choice(key):
  445. """
  446. This function returns the actual `doctest` module flag value, we want to do it as late as possible to avoid
  447. importing `doctest` and all its dependencies when parsing options, as it adds overhead and breaks tests.
  448. """
  449. import doctest
  450. return {
  451. DOCTEST_REPORT_CHOICE_UDIFF: doctest.REPORT_UDIFF,
  452. DOCTEST_REPORT_CHOICE_CDIFF: doctest.REPORT_CDIFF,
  453. DOCTEST_REPORT_CHOICE_NDIFF: doctest.REPORT_NDIFF,
  454. DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE: doctest.REPORT_ONLY_FIRST_FAILURE,
  455. DOCTEST_REPORT_CHOICE_NONE: 0,
  456. }[key]
  457. def _fix_spoof_python2(runner, encoding):
  458. """
  459. Installs a "SpoofOut" into the given DebugRunner so it properly deals with unicode output. This
  460. should patch only doctests for text files because they don't have a way to declare their
  461. encoding. Doctests in docstrings from Python modules don't have the same problem given that
  462. Python already decoded the strings.
  463. This fixes the problem related in issue #2434.
  464. """
  465. from _pytest.compat import _PY2
  466. if not _PY2:
  467. return
  468. from doctest import _SpoofOut
  469. class UnicodeSpoof(_SpoofOut):
  470. def getvalue(self):
  471. result = _SpoofOut.getvalue(self)
  472. if encoding and isinstance(result, bytes):
  473. result = result.decode(encoding)
  474. return result
  475. runner._fakeout = UnicodeSpoof()
  476. @pytest.fixture(scope="session")
  477. def doctest_namespace():
  478. """
  479. Fixture that returns a :py:class:`dict` that will be injected into the namespace of doctests.
  480. """
  481. return dict()