PageRenderTime 75ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/test/test_doctest.py

http://github.com/IronLanguages/main
Python | 2756 lines | 2692 code | 10 blank | 54 comment | 0 complexity | 1a1b0d1fc632aa650040ede252f2345d MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. # -*- coding: utf-8 -*-
  2. """
  3. Test script for doctest.
  4. """
  5. import sys
  6. from test import test_support
  7. import doctest
  8. # NOTE: There are some additional tests relating to interaction with
  9. # zipimport in the test_zipimport_support test module.
  10. ######################################################################
  11. ## Sample Objects (used by test cases)
  12. ######################################################################
  13. def sample_func(v):
  14. """
  15. Blah blah
  16. >>> print sample_func(22)
  17. 44
  18. Yee ha!
  19. """
  20. return v+v
  21. class SampleClass:
  22. """
  23. >>> print 1
  24. 1
  25. >>> # comments get ignored. so are empty PS1 and PS2 prompts:
  26. >>>
  27. ...
  28. Multiline example:
  29. >>> sc = SampleClass(3)
  30. >>> for i in range(10):
  31. ... sc = sc.double()
  32. ... print sc.get(),
  33. 6 12 24 48 96 192 384 768 1536 3072
  34. """
  35. def __init__(self, val):
  36. """
  37. >>> print SampleClass(12).get()
  38. 12
  39. """
  40. self.val = val
  41. def double(self):
  42. """
  43. >>> print SampleClass(12).double().get()
  44. 24
  45. """
  46. return SampleClass(self.val + self.val)
  47. def get(self):
  48. """
  49. >>> print SampleClass(-5).get()
  50. -5
  51. """
  52. return self.val
  53. def a_staticmethod(v):
  54. """
  55. >>> print SampleClass.a_staticmethod(10)
  56. 11
  57. """
  58. return v+1
  59. a_staticmethod = staticmethod(a_staticmethod)
  60. def a_classmethod(cls, v):
  61. """
  62. >>> print SampleClass.a_classmethod(10)
  63. 12
  64. >>> print SampleClass(0).a_classmethod(10)
  65. 12
  66. """
  67. return v+2
  68. a_classmethod = classmethod(a_classmethod)
  69. a_property = property(get, doc="""
  70. >>> print SampleClass(22).a_property
  71. 22
  72. """)
  73. class NestedClass:
  74. """
  75. >>> x = SampleClass.NestedClass(5)
  76. >>> y = x.square()
  77. >>> print y.get()
  78. 25
  79. """
  80. def __init__(self, val=0):
  81. """
  82. >>> print SampleClass.NestedClass().get()
  83. 0
  84. """
  85. self.val = val
  86. def square(self):
  87. return SampleClass.NestedClass(self.val*self.val)
  88. def get(self):
  89. return self.val
  90. class SampleNewStyleClass(object):
  91. r"""
  92. >>> print '1\n2\n3'
  93. 1
  94. 2
  95. 3
  96. """
  97. def __init__(self, val):
  98. """
  99. >>> print SampleNewStyleClass(12).get()
  100. 12
  101. """
  102. self.val = val
  103. def double(self):
  104. """
  105. >>> print SampleNewStyleClass(12).double().get()
  106. 24
  107. """
  108. return SampleNewStyleClass(self.val + self.val)
  109. def get(self):
  110. """
  111. >>> print SampleNewStyleClass(-5).get()
  112. -5
  113. """
  114. return self.val
  115. ######################################################################
  116. ## Fake stdin (for testing interactive debugging)
  117. ######################################################################
  118. class _FakeInput:
  119. """
  120. A fake input stream for pdb's interactive debugger. Whenever a
  121. line is read, print it (to simulate the user typing it), and then
  122. return it. The set of lines to return is specified in the
  123. constructor; they should not have trailing newlines.
  124. """
  125. def __init__(self, lines):
  126. self.lines = lines
  127. def readline(self):
  128. line = self.lines.pop(0)
  129. print line
  130. return line+'\n'
  131. ######################################################################
  132. ## Test Cases
  133. ######################################################################
  134. def test_Example(): r"""
  135. Unit tests for the `Example` class.
  136. Example is a simple container class that holds:
  137. - `source`: A source string.
  138. - `want`: An expected output string.
  139. - `exc_msg`: An expected exception message string (or None if no
  140. exception is expected).
  141. - `lineno`: A line number (within the docstring).
  142. - `indent`: The example's indentation in the input string.
  143. - `options`: An option dictionary, mapping option flags to True or
  144. False.
  145. These attributes are set by the constructor. `source` and `want` are
  146. required; the other attributes all have default values:
  147. >>> example = doctest.Example('print 1', '1\n')
  148. >>> (example.source, example.want, example.exc_msg,
  149. ... example.lineno, example.indent, example.options)
  150. ('print 1\n', '1\n', None, 0, 0, {})
  151. The first three attributes (`source`, `want`, and `exc_msg`) may be
  152. specified positionally; the remaining arguments should be specified as
  153. keyword arguments:
  154. >>> exc_msg = 'IndexError: pop from an empty list'
  155. >>> example = doctest.Example('[].pop()', '', exc_msg,
  156. ... lineno=5, indent=4,
  157. ... options={doctest.ELLIPSIS: True})
  158. >>> (example.source, example.want, example.exc_msg,
  159. ... example.lineno, example.indent, example.options)
  160. ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
  161. The constructor normalizes the `source` string to end in a newline:
  162. Source spans a single line: no terminating newline.
  163. >>> e = doctest.Example('print 1', '1\n')
  164. >>> e.source, e.want
  165. ('print 1\n', '1\n')
  166. >>> e = doctest.Example('print 1\n', '1\n')
  167. >>> e.source, e.want
  168. ('print 1\n', '1\n')
  169. Source spans multiple lines: require terminating newline.
  170. >>> e = doctest.Example('print 1;\nprint 2\n', '1\n2\n')
  171. >>> e.source, e.want
  172. ('print 1;\nprint 2\n', '1\n2\n')
  173. >>> e = doctest.Example('print 1;\nprint 2', '1\n2\n')
  174. >>> e.source, e.want
  175. ('print 1;\nprint 2\n', '1\n2\n')
  176. Empty source string (which should never appear in real examples)
  177. >>> e = doctest.Example('', '')
  178. >>> e.source, e.want
  179. ('\n', '')
  180. The constructor normalizes the `want` string to end in a newline,
  181. unless it's the empty string:
  182. >>> e = doctest.Example('print 1', '1\n')
  183. >>> e.source, e.want
  184. ('print 1\n', '1\n')
  185. >>> e = doctest.Example('print 1', '1')
  186. >>> e.source, e.want
  187. ('print 1\n', '1\n')
  188. >>> e = doctest.Example('print', '')
  189. >>> e.source, e.want
  190. ('print\n', '')
  191. The constructor normalizes the `exc_msg` string to end in a newline,
  192. unless it's `None`:
  193. Message spans one line
  194. >>> exc_msg = 'IndexError: pop from an empty list'
  195. >>> e = doctest.Example('[].pop()', '', exc_msg)
  196. >>> e.exc_msg
  197. 'IndexError: pop from an empty list\n'
  198. >>> exc_msg = 'IndexError: pop from an empty list\n'
  199. >>> e = doctest.Example('[].pop()', '', exc_msg)
  200. >>> e.exc_msg
  201. 'IndexError: pop from an empty list\n'
  202. Message spans multiple lines
  203. >>> exc_msg = 'ValueError: 1\n 2'
  204. >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
  205. >>> e.exc_msg
  206. 'ValueError: 1\n 2\n'
  207. >>> exc_msg = 'ValueError: 1\n 2\n'
  208. >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg)
  209. >>> e.exc_msg
  210. 'ValueError: 1\n 2\n'
  211. Empty (but non-None) exception message (which should never appear
  212. in real examples)
  213. >>> exc_msg = ''
  214. >>> e = doctest.Example('raise X()', '', exc_msg)
  215. >>> e.exc_msg
  216. '\n'
  217. Compare `Example`:
  218. >>> example = doctest.Example('print 1', '1\n')
  219. >>> same_example = doctest.Example('print 1', '1\n')
  220. >>> other_example = doctest.Example('print 42', '42\n')
  221. >>> example == same_example
  222. True
  223. >>> example != same_example
  224. False
  225. >>> hash(example) == hash(same_example)
  226. True
  227. >>> example == other_example
  228. False
  229. >>> example != other_example
  230. True
  231. """
  232. def test_DocTest(): r"""
  233. Unit tests for the `DocTest` class.
  234. DocTest is a collection of examples, extracted from a docstring, along
  235. with information about where the docstring comes from (a name,
  236. filename, and line number). The docstring is parsed by the `DocTest`
  237. constructor:
  238. >>> docstring = '''
  239. ... >>> print 12
  240. ... 12
  241. ...
  242. ... Non-example text.
  243. ...
  244. ... >>> print 'another\example'
  245. ... another
  246. ... example
  247. ... '''
  248. >>> globs = {} # globals to run the test in.
  249. >>> parser = doctest.DocTestParser()
  250. >>> test = parser.get_doctest(docstring, globs, 'some_test',
  251. ... 'some_file', 20)
  252. >>> print test
  253. <DocTest some_test from some_file:20 (2 examples)>
  254. >>> len(test.examples)
  255. 2
  256. >>> e1, e2 = test.examples
  257. >>> (e1.source, e1.want, e1.lineno)
  258. ('print 12\n', '12\n', 1)
  259. >>> (e2.source, e2.want, e2.lineno)
  260. ("print 'another\\example'\n", 'another\nexample\n', 6)
  261. Source information (name, filename, and line number) is available as
  262. attributes on the doctest object:
  263. >>> (test.name, test.filename, test.lineno)
  264. ('some_test', 'some_file', 20)
  265. The line number of an example within its containing file is found by
  266. adding the line number of the example and the line number of its
  267. containing test:
  268. >>> test.lineno + e1.lineno
  269. 21
  270. >>> test.lineno + e2.lineno
  271. 26
  272. If the docstring contains inconsistent leading whitespace in the
  273. expected output of an example, then `DocTest` will raise a ValueError:
  274. >>> docstring = r'''
  275. ... >>> print 'bad\nindentation'
  276. ... bad
  277. ... indentation
  278. ... '''
  279. >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
  280. Traceback (most recent call last):
  281. ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
  282. If the docstring contains inconsistent leading whitespace on
  283. continuation lines, then `DocTest` will raise a ValueError:
  284. >>> docstring = r'''
  285. ... >>> print ('bad indentation',
  286. ... ... 2)
  287. ... ('bad', 'indentation')
  288. ... '''
  289. >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
  290. Traceback (most recent call last):
  291. ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2)'
  292. If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
  293. will raise a ValueError:
  294. >>> docstring = '>>>print 1\n1'
  295. >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
  296. Traceback (most recent call last):
  297. ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1'
  298. If there's no blank space after a PS2 prompt ('...'), then `DocTest`
  299. will raise a ValueError:
  300. >>> docstring = '>>> if 1:\n...print 1\n1'
  301. >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
  302. Traceback (most recent call last):
  303. ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1'
  304. Compare `DocTest`:
  305. >>> docstring = '''
  306. ... >>> print 12
  307. ... 12
  308. ... '''
  309. >>> test = parser.get_doctest(docstring, globs, 'some_test',
  310. ... 'some_test', 20)
  311. >>> same_test = parser.get_doctest(docstring, globs, 'some_test',
  312. ... 'some_test', 20)
  313. >>> test == same_test
  314. True
  315. >>> test != same_test
  316. False
  317. >>> hash(test) == hash(same_test)
  318. True
  319. >>> docstring = '''
  320. ... >>> print 42
  321. ... 42
  322. ... '''
  323. >>> other_test = parser.get_doctest(docstring, globs, 'other_test',
  324. ... 'other_file', 10)
  325. >>> test == other_test
  326. False
  327. >>> test != other_test
  328. True
  329. Compare `DocTestCase`:
  330. >>> DocTestCase = doctest.DocTestCase
  331. >>> test_case = DocTestCase(test)
  332. >>> same_test_case = DocTestCase(same_test)
  333. >>> other_test_case = DocTestCase(other_test)
  334. >>> test_case == same_test_case
  335. True
  336. >>> test_case != same_test_case
  337. False
  338. >>> hash(test_case) == hash(same_test_case)
  339. True
  340. >>> test == other_test_case
  341. False
  342. >>> test != other_test_case
  343. True
  344. """
  345. def test_DocTestFinder(): r"""
  346. Unit tests for the `DocTestFinder` class.
  347. DocTestFinder is used to extract DocTests from an object's docstring
  348. and the docstrings of its contained objects. It can be used with
  349. modules, functions, classes, methods, staticmethods, classmethods, and
  350. properties.
  351. Finding Tests in Functions
  352. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  353. For a function whose docstring contains examples, DocTestFinder.find()
  354. will return a single test (for that function's docstring):
  355. >>> finder = doctest.DocTestFinder()
  356. We'll simulate a __file__ attr that ends in pyc:
  357. >>> import test.test_doctest
  358. >>> old = test.test_doctest.__file__
  359. >>> test.test_doctest.__file__ = 'test_doctest.pyc'
  360. >>> tests = finder.find(sample_func)
  361. >>> print tests # doctest: +ELLIPSIS
  362. [<DocTest sample_func from ...:17 (1 example)>]
  363. The exact name depends on how test_doctest was invoked, so allow for
  364. leading path components.
  365. >>> tests[0].filename # doctest: +ELLIPSIS
  366. '...test_doctest.py'
  367. >>> test.test_doctest.__file__ = old
  368. >>> e = tests[0].examples[0]
  369. >>> (e.source, e.want, e.lineno)
  370. ('print sample_func(22)\n', '44\n', 3)
  371. By default, tests are created for objects with no docstring:
  372. >>> def no_docstring(v):
  373. ... pass
  374. >>> finder.find(no_docstring)
  375. []
  376. However, the optional argument `exclude_empty` to the DocTestFinder
  377. constructor can be used to exclude tests for objects with empty
  378. docstrings:
  379. >>> def no_docstring(v):
  380. ... pass
  381. >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
  382. >>> excl_empty_finder.find(no_docstring)
  383. []
  384. If the function has a docstring with no examples, then a test with no
  385. examples is returned. (This lets `DocTestRunner` collect statistics
  386. about which functions have no tests -- but is that useful? And should
  387. an empty test also be created when there's no docstring?)
  388. >>> def no_examples(v):
  389. ... ''' no doctest examples '''
  390. >>> finder.find(no_examples) # doctest: +ELLIPSIS
  391. [<DocTest no_examples from ...:1 (no examples)>]
  392. Finding Tests in Classes
  393. ~~~~~~~~~~~~~~~~~~~~~~~~
  394. For a class, DocTestFinder will create a test for the class's
  395. docstring, and will recursively explore its contents, including
  396. methods, classmethods, staticmethods, properties, and nested classes.
  397. >>> finder = doctest.DocTestFinder()
  398. >>> tests = finder.find(SampleClass)
  399. >>> for t in tests:
  400. ... print '%2s %s' % (len(t.examples), t.name)
  401. 3 SampleClass
  402. 3 SampleClass.NestedClass
  403. 1 SampleClass.NestedClass.__init__
  404. 1 SampleClass.__init__
  405. 2 SampleClass.a_classmethod
  406. 1 SampleClass.a_property
  407. 1 SampleClass.a_staticmethod
  408. 1 SampleClass.double
  409. 1 SampleClass.get
  410. New-style classes are also supported:
  411. >>> tests = finder.find(SampleNewStyleClass)
  412. >>> for t in tests:
  413. ... print '%2s %s' % (len(t.examples), t.name)
  414. 1 SampleNewStyleClass
  415. 1 SampleNewStyleClass.__init__
  416. 1 SampleNewStyleClass.double
  417. 1 SampleNewStyleClass.get
  418. Finding Tests in Modules
  419. ~~~~~~~~~~~~~~~~~~~~~~~~
  420. For a module, DocTestFinder will create a test for the class's
  421. docstring, and will recursively explore its contents, including
  422. functions, classes, and the `__test__` dictionary, if it exists:
  423. >>> # A module
  424. >>> import types
  425. >>> m = types.ModuleType('some_module')
  426. >>> def triple(val):
  427. ... '''
  428. ... >>> print triple(11)
  429. ... 33
  430. ... '''
  431. ... return val*3
  432. >>> m.__dict__.update({
  433. ... 'sample_func': sample_func,
  434. ... 'SampleClass': SampleClass,
  435. ... '__doc__': '''
  436. ... Module docstring.
  437. ... >>> print 'module'
  438. ... module
  439. ... ''',
  440. ... '__test__': {
  441. ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
  442. ... 'c': triple}})
  443. >>> finder = doctest.DocTestFinder()
  444. >>> # Use module=test.test_doctest, to prevent doctest from
  445. >>> # ignoring the objects since they weren't defined in m.
  446. >>> import test.test_doctest
  447. >>> tests = finder.find(m, module=test.test_doctest)
  448. >>> for t in tests:
  449. ... print '%2s %s' % (len(t.examples), t.name)
  450. 1 some_module
  451. 3 some_module.SampleClass
  452. 3 some_module.SampleClass.NestedClass
  453. 1 some_module.SampleClass.NestedClass.__init__
  454. 1 some_module.SampleClass.__init__
  455. 2 some_module.SampleClass.a_classmethod
  456. 1 some_module.SampleClass.a_property
  457. 1 some_module.SampleClass.a_staticmethod
  458. 1 some_module.SampleClass.double
  459. 1 some_module.SampleClass.get
  460. 1 some_module.__test__.c
  461. 2 some_module.__test__.d
  462. 1 some_module.sample_func
  463. Duplicate Removal
  464. ~~~~~~~~~~~~~~~~~
  465. If a single object is listed twice (under different names), then tests
  466. will only be generated for it once:
  467. >>> from test import doctest_aliases
  468. >>> assert doctest_aliases.TwoNames.f
  469. >>> assert doctest_aliases.TwoNames.g
  470. >>> tests = excl_empty_finder.find(doctest_aliases)
  471. >>> print len(tests)
  472. 2
  473. >>> print tests[0].name
  474. test.doctest_aliases.TwoNames
  475. TwoNames.f and TwoNames.g are bound to the same object.
  476. We can't guess which will be found in doctest's traversal of
  477. TwoNames.__dict__ first, so we have to allow for either.
  478. >>> tests[1].name.split('.')[-1] in ['f', 'g']
  479. True
  480. Empty Tests
  481. ~~~~~~~~~~~
  482. By default, an object with no doctests doesn't create any tests:
  483. >>> tests = doctest.DocTestFinder().find(SampleClass)
  484. >>> for t in tests:
  485. ... print '%2s %s' % (len(t.examples), t.name)
  486. 3 SampleClass
  487. 3 SampleClass.NestedClass
  488. 1 SampleClass.NestedClass.__init__
  489. 1 SampleClass.__init__
  490. 2 SampleClass.a_classmethod
  491. 1 SampleClass.a_property
  492. 1 SampleClass.a_staticmethod
  493. 1 SampleClass.double
  494. 1 SampleClass.get
  495. By default, that excluded objects with no doctests. exclude_empty=False
  496. tells it to include (empty) tests for objects with no doctests. This feature
  497. is really to support backward compatibility in what doctest.master.summarize()
  498. displays.
  499. >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
  500. >>> for t in tests:
  501. ... print '%2s %s' % (len(t.examples), t.name)
  502. 3 SampleClass
  503. 3 SampleClass.NestedClass
  504. 1 SampleClass.NestedClass.__init__
  505. 0 SampleClass.NestedClass.get
  506. 0 SampleClass.NestedClass.square
  507. 1 SampleClass.__init__
  508. 2 SampleClass.a_classmethod
  509. 1 SampleClass.a_property
  510. 1 SampleClass.a_staticmethod
  511. 1 SampleClass.double
  512. 1 SampleClass.get
  513. Turning off Recursion
  514. ~~~~~~~~~~~~~~~~~~~~~
  515. DocTestFinder can be told not to look for tests in contained objects
  516. using the `recurse` flag:
  517. >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
  518. >>> for t in tests:
  519. ... print '%2s %s' % (len(t.examples), t.name)
  520. 3 SampleClass
  521. Line numbers
  522. ~~~~~~~~~~~~
  523. DocTestFinder finds the line number of each example:
  524. >>> def f(x):
  525. ... '''
  526. ... >>> x = 12
  527. ...
  528. ... some text
  529. ...
  530. ... >>> # examples are not created for comments & bare prompts.
  531. ... >>>
  532. ... ...
  533. ...
  534. ... >>> for x in range(10):
  535. ... ... print x,
  536. ... 0 1 2 3 4 5 6 7 8 9
  537. ... >>> x//2
  538. ... 6
  539. ... '''
  540. >>> test = doctest.DocTestFinder().find(f)[0]
  541. >>> [e.lineno for e in test.examples]
  542. [1, 9, 12]
  543. """
  544. def test_DocTestParser(): r"""
  545. Unit tests for the `DocTestParser` class.
  546. DocTestParser is used to parse docstrings containing doctest examples.
  547. The `parse` method divides a docstring into examples and intervening
  548. text:
  549. >>> s = '''
  550. ... >>> x, y = 2, 3 # no output expected
  551. ... >>> if 1:
  552. ... ... print x
  553. ... ... print y
  554. ... 2
  555. ... 3
  556. ...
  557. ... Some text.
  558. ... >>> x+y
  559. ... 5
  560. ... '''
  561. >>> parser = doctest.DocTestParser()
  562. >>> for piece in parser.parse(s):
  563. ... if isinstance(piece, doctest.Example):
  564. ... print 'Example:', (piece.source, piece.want, piece.lineno)
  565. ... else:
  566. ... print ' Text:', `piece`
  567. Text: '\n'
  568. Example: ('x, y = 2, 3 # no output expected\n', '', 1)
  569. Text: ''
  570. Example: ('if 1:\n print x\n print y\n', '2\n3\n', 2)
  571. Text: '\nSome text.\n'
  572. Example: ('x+y\n', '5\n', 9)
  573. Text: ''
  574. The `get_examples` method returns just the examples:
  575. >>> for piece in parser.get_examples(s):
  576. ... print (piece.source, piece.want, piece.lineno)
  577. ('x, y = 2, 3 # no output expected\n', '', 1)
  578. ('if 1:\n print x\n print y\n', '2\n3\n', 2)
  579. ('x+y\n', '5\n', 9)
  580. The `get_doctest` method creates a Test from the examples, along with the
  581. given arguments:
  582. >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
  583. >>> (test.name, test.filename, test.lineno)
  584. ('name', 'filename', 5)
  585. >>> for piece in test.examples:
  586. ... print (piece.source, piece.want, piece.lineno)
  587. ('x, y = 2, 3 # no output expected\n', '', 1)
  588. ('if 1:\n print x\n print y\n', '2\n3\n', 2)
  589. ('x+y\n', '5\n', 9)
  590. """
  591. class test_DocTestRunner:
  592. def basics(): r"""
  593. Unit tests for the `DocTestRunner` class.
  594. DocTestRunner is used to run DocTest test cases, and to accumulate
  595. statistics. Here's a simple DocTest case we can use:
  596. >>> def f(x):
  597. ... '''
  598. ... >>> x = 12
  599. ... >>> print x
  600. ... 12
  601. ... >>> x//2
  602. ... 6
  603. ... '''
  604. >>> test = doctest.DocTestFinder().find(f)[0]
  605. The main DocTestRunner interface is the `run` method, which runs a
  606. given DocTest case in a given namespace (globs). It returns a tuple
  607. `(f,t)`, where `f` is the number of failed tests and `t` is the number
  608. of tried tests.
  609. >>> doctest.DocTestRunner(verbose=False).run(test)
  610. TestResults(failed=0, attempted=3)
  611. If any example produces incorrect output, then the test runner reports
  612. the failure and proceeds to the next example:
  613. >>> def f(x):
  614. ... '''
  615. ... >>> x = 12
  616. ... >>> print x
  617. ... 14
  618. ... >>> x//2
  619. ... 6
  620. ... '''
  621. >>> test = doctest.DocTestFinder().find(f)[0]
  622. >>> doctest.DocTestRunner(verbose=True).run(test)
  623. ... # doctest: +ELLIPSIS
  624. Trying:
  625. x = 12
  626. Expecting nothing
  627. ok
  628. Trying:
  629. print x
  630. Expecting:
  631. 14
  632. **********************************************************************
  633. File ..., line 4, in f
  634. Failed example:
  635. print x
  636. Expected:
  637. 14
  638. Got:
  639. 12
  640. Trying:
  641. x//2
  642. Expecting:
  643. 6
  644. ok
  645. TestResults(failed=1, attempted=3)
  646. """
  647. def verbose_flag(): r"""
  648. The `verbose` flag makes the test runner generate more detailed
  649. output:
  650. >>> def f(x):
  651. ... '''
  652. ... >>> x = 12
  653. ... >>> print x
  654. ... 12
  655. ... >>> x//2
  656. ... 6
  657. ... '''
  658. >>> test = doctest.DocTestFinder().find(f)[0]
  659. >>> doctest.DocTestRunner(verbose=True).run(test)
  660. Trying:
  661. x = 12
  662. Expecting nothing
  663. ok
  664. Trying:
  665. print x
  666. Expecting:
  667. 12
  668. ok
  669. Trying:
  670. x//2
  671. Expecting:
  672. 6
  673. ok
  674. TestResults(failed=0, attempted=3)
  675. If the `verbose` flag is unspecified, then the output will be verbose
  676. iff `-v` appears in sys.argv:
  677. >>> # Save the real sys.argv list.
  678. >>> old_argv = sys.argv
  679. >>> # If -v does not appear in sys.argv, then output isn't verbose.
  680. >>> sys.argv = ['test']
  681. >>> doctest.DocTestRunner().run(test)
  682. TestResults(failed=0, attempted=3)
  683. >>> # If -v does appear in sys.argv, then output is verbose.
  684. >>> sys.argv = ['test', '-v']
  685. >>> doctest.DocTestRunner().run(test)
  686. Trying:
  687. x = 12
  688. Expecting nothing
  689. ok
  690. Trying:
  691. print x
  692. Expecting:
  693. 12
  694. ok
  695. Trying:
  696. x//2
  697. Expecting:
  698. 6
  699. ok
  700. TestResults(failed=0, attempted=3)
  701. >>> # Restore sys.argv
  702. >>> sys.argv = old_argv
  703. In the remaining examples, the test runner's verbosity will be
  704. explicitly set, to ensure that the test behavior is consistent.
  705. """
  706. def exceptions(): r"""
  707. Tests of `DocTestRunner`'s exception handling.
  708. An expected exception is specified with a traceback message. The
  709. lines between the first line and the type/value may be omitted or
  710. replaced with any other string:
  711. >>> def f(x):
  712. ... '''
  713. ... >>> x = 12
  714. ... >>> print x//0
  715. ... Traceback (most recent call last):
  716. ... ZeroDivisionError: integer division or modulo by zero
  717. ... '''
  718. >>> test = doctest.DocTestFinder().find(f)[0]
  719. >>> doctest.DocTestRunner(verbose=False).run(test)
  720. TestResults(failed=0, attempted=2)
  721. An example may not generate output before it raises an exception; if
  722. it does, then the traceback message will not be recognized as
  723. signaling an expected exception, so the example will be reported as an
  724. unexpected exception:
  725. >>> def f(x):
  726. ... '''
  727. ... >>> x = 12
  728. ... >>> print 'pre-exception output', x//0
  729. ... pre-exception output
  730. ... Traceback (most recent call last):
  731. ... ZeroDivisionError: integer division or modulo by zero
  732. ... '''
  733. >>> test = doctest.DocTestFinder().find(f)[0]
  734. >>> doctest.DocTestRunner(verbose=False).run(test)
  735. ... # doctest: +ELLIPSIS
  736. **********************************************************************
  737. File ..., line 4, in f
  738. Failed example:
  739. print 'pre-exception output', x//0
  740. Exception raised:
  741. ...
  742. ZeroDivisionError: integer division or modulo by zero
  743. TestResults(failed=1, attempted=2)
  744. Exception messages may contain newlines:
  745. >>> def f(x):
  746. ... r'''
  747. ... >>> raise ValueError, 'multi\nline\nmessage'
  748. ... Traceback (most recent call last):
  749. ... ValueError: multi
  750. ... line
  751. ... message
  752. ... '''
  753. >>> test = doctest.DocTestFinder().find(f)[0]
  754. >>> doctest.DocTestRunner(verbose=False).run(test)
  755. TestResults(failed=0, attempted=1)
  756. If an exception is expected, but an exception with the wrong type or
  757. message is raised, then it is reported as a failure:
  758. >>> def f(x):
  759. ... r'''
  760. ... >>> raise ValueError, 'message'
  761. ... Traceback (most recent call last):
  762. ... ValueError: wrong message
  763. ... '''
  764. >>> test = doctest.DocTestFinder().find(f)[0]
  765. >>> doctest.DocTestRunner(verbose=False).run(test)
  766. ... # doctest: +ELLIPSIS
  767. **********************************************************************
  768. File ..., line 3, in f
  769. Failed example:
  770. raise ValueError, 'message'
  771. Expected:
  772. Traceback (most recent call last):
  773. ValueError: wrong message
  774. Got:
  775. Traceback (most recent call last):
  776. ...
  777. ValueError: message
  778. TestResults(failed=1, attempted=1)
  779. However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
  780. detail:
  781. >>> def f(x):
  782. ... r'''
  783. ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
  784. ... Traceback (most recent call last):
  785. ... ValueError: wrong message
  786. ... '''
  787. >>> test = doctest.DocTestFinder().find(f)[0]
  788. >>> doctest.DocTestRunner(verbose=False).run(test)
  789. TestResults(failed=0, attempted=1)
  790. IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
  791. between Python versions. For example, in Python 3.x, the module path of
  792. the exception is in the output, but this will fail under Python 2:
  793. >>> def f(x):
  794. ... r'''
  795. ... >>> from httplib import HTTPException
  796. ... >>> raise HTTPException('message')
  797. ... Traceback (most recent call last):
  798. ... httplib.HTTPException: message
  799. ... '''
  800. >>> test = doctest.DocTestFinder().find(f)[0]
  801. >>> doctest.DocTestRunner(verbose=False).run(test)
  802. ... # doctest: +ELLIPSIS
  803. **********************************************************************
  804. File ..., line 4, in f
  805. Failed example:
  806. raise HTTPException('message')
  807. Expected:
  808. Traceback (most recent call last):
  809. httplib.HTTPException: message
  810. Got:
  811. Traceback (most recent call last):
  812. ...
  813. HTTPException: message
  814. TestResults(failed=1, attempted=2)
  815. But in Python 2 the module path is not included, and therefore a test must look
  816. like the following test to succeed in Python 2. But that test will fail under
  817. Python 3.
  818. >>> def f(x):
  819. ... r'''
  820. ... >>> from httplib import HTTPException
  821. ... >>> raise HTTPException('message')
  822. ... Traceback (most recent call last):
  823. ... HTTPException: message
  824. ... '''
  825. >>> test = doctest.DocTestFinder().find(f)[0]
  826. >>> doctest.DocTestRunner(verbose=False).run(test)
  827. TestResults(failed=0, attempted=2)
  828. However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
  829. (if any) will be ignored:
  830. >>> def f(x):
  831. ... r'''
  832. ... >>> from httplib import HTTPException
  833. ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
  834. ... Traceback (most recent call last):
  835. ... HTTPException: message
  836. ... '''
  837. >>> test = doctest.DocTestFinder().find(f)[0]
  838. >>> doctest.DocTestRunner(verbose=False).run(test)
  839. TestResults(failed=0, attempted=2)
  840. The module path will be completely ignored, so two different module paths will
  841. still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
  842. be used when exceptions have changed module.
  843. >>> def f(x):
  844. ... r'''
  845. ... >>> from httplib import HTTPException
  846. ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
  847. ... Traceback (most recent call last):
  848. ... foo.bar.HTTPException: message
  849. ... '''
  850. >>> test = doctest.DocTestFinder().find(f)[0]
  851. >>> doctest.DocTestRunner(verbose=False).run(test)
  852. TestResults(failed=0, attempted=2)
  853. But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
  854. >>> def f(x):
  855. ... r'''
  856. ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
  857. ... Traceback (most recent call last):
  858. ... TypeError: wrong type
  859. ... '''
  860. >>> test = doctest.DocTestFinder().find(f)[0]
  861. >>> doctest.DocTestRunner(verbose=False).run(test)
  862. ... # doctest: +ELLIPSIS
  863. **********************************************************************
  864. File ..., line 3, in f
  865. Failed example:
  866. raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
  867. Expected:
  868. Traceback (most recent call last):
  869. TypeError: wrong type
  870. Got:
  871. Traceback (most recent call last):
  872. ...
  873. ValueError: message
  874. TestResults(failed=1, attempted=1)
  875. If the exception does not have a message, you can still use
  876. IGNORE_EXCEPTION_DETAIL to normalize the modules between Python 2 and 3:
  877. >>> def f(x):
  878. ... r'''
  879. ... >>> from Queue import Empty
  880. ... >>> raise Empty() #doctest: +IGNORE_EXCEPTION_DETAIL
  881. ... Traceback (most recent call last):
  882. ... foo.bar.Empty
  883. ... '''
  884. >>> test = doctest.DocTestFinder().find(f)[0]
  885. >>> doctest.DocTestRunner(verbose=False).run(test)
  886. TestResults(failed=0, attempted=2)
  887. Note that a trailing colon doesn't matter either:
  888. >>> def f(x):
  889. ... r'''
  890. ... >>> from Queue import Empty
  891. ... >>> raise Empty() #doctest: +IGNORE_EXCEPTION_DETAIL
  892. ... Traceback (most recent call last):
  893. ... foo.bar.Empty:
  894. ... '''
  895. >>> test = doctest.DocTestFinder().find(f)[0]
  896. >>> doctest.DocTestRunner(verbose=False).run(test)
  897. TestResults(failed=0, attempted=2)
  898. If an exception is raised but not expected, then it is reported as an
  899. unexpected exception:
  900. >>> def f(x):
  901. ... r'''
  902. ... >>> 1//0
  903. ... 0
  904. ... '''
  905. >>> test = doctest.DocTestFinder().find(f)[0]
  906. >>> doctest.DocTestRunner(verbose=False).run(test)
  907. ... # doctest: +ELLIPSIS
  908. **********************************************************************
  909. File ..., line 3, in f
  910. Failed example:
  911. 1//0
  912. Exception raised:
  913. Traceback (most recent call last):
  914. ...
  915. ZeroDivisionError: integer division or modulo by zero
  916. TestResults(failed=1, attempted=1)
  917. """
  918. def displayhook(): r"""
  919. Test that changing sys.displayhook doesn't matter for doctest.
  920. >>> import sys
  921. >>> orig_displayhook = sys.displayhook
  922. >>> def my_displayhook(x):
  923. ... print('hi!')
  924. >>> sys.displayhook = my_displayhook
  925. >>> def f():
  926. ... '''
  927. ... >>> 3
  928. ... 3
  929. ... '''
  930. >>> test = doctest.DocTestFinder().find(f)[0]
  931. >>> r = doctest.DocTestRunner(verbose=False).run(test)
  932. >>> post_displayhook = sys.displayhook
  933. We need to restore sys.displayhook now, so that we'll be able to test
  934. results.
  935. >>> sys.displayhook = orig_displayhook
  936. Ok, now we can check that everything is ok.
  937. >>> r
  938. TestResults(failed=0, attempted=1)
  939. >>> post_displayhook is my_displayhook
  940. True
  941. """
  942. def optionflags(): r"""
  943. Tests of `DocTestRunner`'s option flag handling.
  944. Several option flags can be used to customize the behavior of the test
  945. runner. These are defined as module constants in doctest, and passed
  946. to the DocTestRunner constructor (multiple constants should be ORed
  947. together).
  948. The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
  949. and 1/0:
  950. >>> def f(x):
  951. ... '>>> True\n1\n'
  952. >>> # Without the flag:
  953. >>> test = doctest.DocTestFinder().find(f)[0]
  954. >>> doctest.DocTestRunner(verbose=False).run(test)
  955. TestResults(failed=0, attempted=1)
  956. >>> # With the flag:
  957. >>> test = doctest.DocTestFinder().find(f)[0]
  958. >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
  959. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  960. ... # doctest: +ELLIPSIS
  961. **********************************************************************
  962. File ..., line 2, in f
  963. Failed example:
  964. True
  965. Expected:
  966. 1
  967. Got:
  968. True
  969. TestResults(failed=1, attempted=1)
  970. The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
  971. and the '<BLANKLINE>' marker:
  972. >>> def f(x):
  973. ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
  974. >>> # Without the flag:
  975. >>> test = doctest.DocTestFinder().find(f)[0]
  976. >>> doctest.DocTestRunner(verbose=False).run(test)
  977. TestResults(failed=0, attempted=1)
  978. >>> # With the flag:
  979. >>> test = doctest.DocTestFinder().find(f)[0]
  980. >>> flags = doctest.DONT_ACCEPT_BLANKLINE
  981. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  982. ... # doctest: +ELLIPSIS
  983. **********************************************************************
  984. File ..., line 2, in f
  985. Failed example:
  986. print "a\n\nb"
  987. Expected:
  988. a
  989. <BLANKLINE>
  990. b
  991. Got:
  992. a
  993. <BLANKLINE>
  994. b
  995. TestResults(failed=1, attempted=1)
  996. The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
  997. treated as equal:
  998. >>> def f(x):
  999. ... '>>> print 1, 2, 3\n 1 2\n 3'
  1000. >>> # Without the flag:
  1001. >>> test = doctest.DocTestFinder().find(f)[0]
  1002. >>> doctest.DocTestRunner(verbose=False).run(test)
  1003. ... # doctest: +ELLIPSIS
  1004. **********************************************************************
  1005. File ..., line 2, in f
  1006. Failed example:
  1007. print 1, 2, 3
  1008. Expected:
  1009. 1 2
  1010. 3
  1011. Got:
  1012. 1 2 3
  1013. TestResults(failed=1, attempted=1)
  1014. >>> # With the flag:
  1015. >>> test = doctest.DocTestFinder().find(f)[0]
  1016. >>> flags = doctest.NORMALIZE_WHITESPACE
  1017. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1018. TestResults(failed=0, attempted=1)
  1019. An example from the docs:
  1020. >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
  1021. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
  1022. 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
  1023. The ELLIPSIS flag causes ellipsis marker ("...") in the expected
  1024. output to match any substring in the actual output:
  1025. >>> def f(x):
  1026. ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
  1027. >>> # Without the flag:
  1028. >>> test = doctest.DocTestFinder().find(f)[0]
  1029. >>> doctest.DocTestRunner(verbose=False).run(test)
  1030. ... # doctest: +ELLIPSIS
  1031. **********************************************************************
  1032. File ..., line 2, in f
  1033. Failed example:
  1034. print range(15)
  1035. Expected:
  1036. [0, 1, 2, ..., 14]
  1037. Got:
  1038. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
  1039. TestResults(failed=1, attempted=1)
  1040. >>> # With the flag:
  1041. >>> test = doctest.DocTestFinder().find(f)[0]
  1042. >>> flags = doctest.ELLIPSIS
  1043. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1044. TestResults(failed=0, attempted=1)
  1045. ... also matches nothing:
  1046. >>> for i in range(100):
  1047. ... print i**2, #doctest: +ELLIPSIS
  1048. 0 1...4...9 16 ... 36 49 64 ... 9801
  1049. ... can be surprising; e.g., this test passes:
  1050. >>> for i in range(21): #doctest: +ELLIPSIS
  1051. ... print i,
  1052. 0 1 2 ...1...2...0
  1053. Examples from the docs:
  1054. >>> print range(20) # doctest:+ELLIPSIS
  1055. [0, 1, ..., 18, 19]
  1056. >>> print range(20) # doctest: +ELLIPSIS
  1057. ... # doctest: +NORMALIZE_WHITESPACE
  1058. [0, 1, ..., 18, 19]
  1059. The SKIP flag causes an example to be skipped entirely. I.e., the
  1060. example is not run. It can be useful in contexts where doctest
  1061. examples serve as both documentation and test cases, and an example
  1062. should be included for documentation purposes, but should not be
  1063. checked (e.g., because its output is random, or depends on resources
  1064. which would be unavailable.) The SKIP flag can also be used for
  1065. 'commenting out' broken examples.
  1066. >>> import unavailable_resource # doctest: +SKIP
  1067. >>> unavailable_resource.do_something() # doctest: +SKIP
  1068. >>> unavailable_resource.blow_up() # doctest: +SKIP
  1069. Traceback (most recent call last):
  1070. ...
  1071. UncheckedBlowUpError: Nobody checks me.
  1072. >>> import random
  1073. >>> print random.random() # doctest: +SKIP
  1074. 0.721216923889
  1075. The REPORT_UDIFF flag causes failures that involve multi-line expected
  1076. and actual outputs to be displayed using a unified diff:
  1077. >>> def f(x):
  1078. ... r'''
  1079. ... >>> print '\n'.join('abcdefg')
  1080. ... a
  1081. ... B
  1082. ... c
  1083. ... d
  1084. ... f
  1085. ... g
  1086. ... h
  1087. ... '''
  1088. >>> # Without the flag:
  1089. >>> test = doctest.DocTestFinder().find(f)[0]
  1090. >>> doctest.DocTestRunner(verbose=False).run(test)
  1091. ... # doctest: +ELLIPSIS
  1092. **********************************************************************
  1093. File ..., line 3, in f
  1094. Failed example:
  1095. print '\n'.join('abcdefg')
  1096. Expected:
  1097. a
  1098. B
  1099. c
  1100. d
  1101. f
  1102. g
  1103. h
  1104. Got:
  1105. a
  1106. b
  1107. c
  1108. d
  1109. e
  1110. f
  1111. g
  1112. TestResults(failed=1, attempted=1)
  1113. >>> # With the flag:
  1114. >>> test = doctest.DocTestFinder().find(f)[0]
  1115. >>> flags = doctest.REPORT_UDIFF
  1116. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1117. ... # doctest: +ELLIPSIS
  1118. **********************************************************************
  1119. File ..., line 3, in f
  1120. Failed example:
  1121. print '\n'.join('abcdefg')
  1122. Differences (unified diff with -expected +actual):
  1123. @@ -1,7 +1,7 @@
  1124. a
  1125. -B
  1126. +b
  1127. c
  1128. d
  1129. +e
  1130. f
  1131. g
  1132. -h
  1133. TestResults(failed=1, attempted=1)
  1134. The REPORT_CDIFF flag causes failures that involve multi-line expected
  1135. and actual outputs to be displayed using a context diff:
  1136. >>> # Reuse f() from the REPORT_UDIFF example, above.
  1137. >>> test = doctest.DocTestFinder().find(f)[0]
  1138. >>> flags = doctest.REPORT_CDIFF
  1139. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1140. ... # doctest: +ELLIPSIS
  1141. **********************************************************************
  1142. File ..., line 3, in f
  1143. Failed example:
  1144. print '\n'.join('abcdefg')
  1145. Differences (context diff with expected followed by actual):
  1146. ***************
  1147. *** 1,7 ****
  1148. a
  1149. ! B
  1150. c
  1151. d
  1152. f
  1153. g
  1154. - h
  1155. --- 1,7 ----
  1156. a
  1157. ! b
  1158. c
  1159. d
  1160. + e
  1161. f
  1162. g
  1163. TestResults(failed=1, attempted=1)
  1164. The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
  1165. used by the popular ndiff.py utility. This does intraline difference
  1166. marking, as well as interline differences.
  1167. >>> def f(x):
  1168. ... r'''
  1169. ... >>> print "a b c d e f g h i j k l m"
  1170. ... a b c d e f g h i j k 1 m
  1171. ... '''
  1172. >>> test = doctest.DocTestFinder().find(f)[0]
  1173. >>> flags = doctest.REPORT_NDIFF
  1174. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1175. ... # doctest: +ELLIPSIS
  1176. **********************************************************************
  1177. File ..., line 3, in f
  1178. Failed example:
  1179. print "a b c d e f g h i j k l m"
  1180. Differences (ndiff with -expected +actual):
  1181. - a b c d e f g h i j k 1 m
  1182. ? ^
  1183. + a b c d e f g h i j k l m
  1184. ? + ++ ^
  1185. TestResults(failed=1, attempted=1)
  1186. The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
  1187. failing example:
  1188. >>> def f(x):
  1189. ... r'''
  1190. ... >>> print 1 # first success
  1191. ... 1
  1192. ... >>> print 2 # first failure
  1193. ... 200
  1194. ... >>> print 3 # second failure
  1195. ... 300
  1196. ... >>> print 4 # second success
  1197. ... 4
  1198. ... >>> print 5 # third failure
  1199. ... 500
  1200. ... '''
  1201. >>> test = doctest.DocTestFinder().find(f)[0]
  1202. >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
  1203. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1204. ... # doctest: +ELLIPSIS
  1205. **********************************************************************
  1206. File ..., line 5, in f
  1207. Failed example:
  1208. print 2 # first failure
  1209. Expected:
  1210. 200
  1211. Got:
  1212. 2
  1213. TestResults(failed=3, attempted=5)
  1214. However, output from `report_start` is not suppressed:
  1215. >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
  1216. ... # doctest: +ELLIPSIS
  1217. Trying:
  1218. print 1 # first success
  1219. Expecting:
  1220. 1
  1221. ok
  1222. Trying:
  1223. print 2 # first failure
  1224. Expecting:
  1225. 200
  1226. **********************************************************************
  1227. File ..., line 5, in f
  1228. Failed example:
  1229. print 2 # first failure
  1230. Expected:
  1231. 200
  1232. Got:
  1233. 2
  1234. TestResults(failed=3, attempted=5)
  1235. For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
  1236. count as failures:
  1237. >>> def f(x):
  1238. ... r'''
  1239. ... >>> print 1 # first success
  1240. ... 1
  1241. ... >>> raise ValueError(2) # first failure
  1242. ... 200
  1243. ... >>> print 3 # second failure
  1244. ... 300
  1245. ... >>> print 4 # second success
  1246. ... 4
  1247. ... >>> print 5 # third failure
  1248. ... 500
  1249. ... '''
  1250. >>> test = doctest.DocTestFinder().find(f)[0]
  1251. >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
  1252. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1253. ... # doctest: +ELLIPSIS
  1254. **********************************************************************
  1255. File ..., line 5, in f
  1256. Failed example:
  1257. raise ValueError(2) # first failure
  1258. Exception raised:
  1259. ...
  1260. ValueError: 2
  1261. TestResults(failed=3, attempted=5)
  1262. New option flags can also be registered, via register_optionflag(). Here
  1263. we reach into doctest's internals a bit.
  1264. >>> unlikely = "UNLIKELY_OPTION_NAME"
  1265. >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
  1266. False
  1267. >>> new_flag_value = doctest.register_optionflag(unlikely)
  1268. >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
  1269. True
  1270. Before 2.4.4/2.5, registering a name more than once erroneously created
  1271. more than one flag value. Here we verify that's fixed:
  1272. >>> redundant_flag_value = doctest.register_optionflag(unlikely)
  1273. >>> redundant_flag_value == new_flag_value
  1274. True
  1275. Clean up.
  1276. >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
  1277. """
  1278. def option_directives(): r"""
  1279. Tests of `DocTestRunner`'s option directive mechanism.
  1280. Option directives can be used to turn option flags on or off for a
  1281. single example. To turn an option on for an example, follow that
  1282. example with a comment of the form ``# doctest: +OPTION``:
  1283. >>> def f(x): r'''
  1284. ... >>> print range(10) # should fail: no ellipsis
  1285. ... [0, 1, ..., 9]
  1286. ...
  1287. ... >>> print range(10) # doctest: +ELLIPSIS
  1288. ... [0, 1, ..., 9]
  1289. ... '''
  1290. >>> test = doctest.DocTestFinder().find(f)[0]
  1291. >>> doctest.DocTestRunner(verbose=False).run(test)
  1292. ... # doctest: +ELLIPSIS
  1293. **********************************************************************
  1294. File ..., line 2, in f
  1295. Failed example:
  1296. print range(10) # should fail: no ellipsis
  1297. Expected:
  1298. [0, 1, ..., 9]
  1299. Got:
  1300. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1301. TestResults(failed=1, attempted=2)
  1302. To turn an option off for an example, follow that example with a
  1303. comment of the form ``# doctest: -OPTION``:
  1304. >>> def f(x): r'''
  1305. ... >>> print range(10)
  1306. ... [0, 1, ..., 9]
  1307. ...
  1308. ... >>> # should fail: no ellipsis
  1309. ... >>> print range(10) # doctest: -ELLIPSIS
  1310. ... [0, 1, ..., 9]
  1311. ... '''
  1312. >>> test = doctest.DocTestFinder().find(f)[0]
  1313. >>> doctest.DocTestRunner(verbose=False,
  1314. ... optionflags=doctest.ELLIPSIS).run(test)
  1315. ... # doctest: +ELLIPSIS
  1316. **********************************************************************
  1317. File ..., line 6, in f
  1318. Failed example:
  1319. print range(10) # doctest: -ELLIPSIS
  1320. Expected:
  1321. [0, 1, ..., 9]
  1322. Got:
  1323. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1324. TestResults(failed=1, attempted=2)
  1325. Option directives affect only the example that they appear with; they
  1326. do not change the options for surrounding examples:
  1327. >>> def f(x): r'''
  1328. ... >>> print range(10) # Should fail: no ellipsis
  1329. ... [0, 1, ..., 9]
  1330. ...
  1331. ... >>> print range(10) # doctest: +ELLIPSIS
  1332. ... [0, 1, ..., 9]
  1333. ...
  1334. ... >>> print range(10) # Should fail: no ellipsis
  1335. ... [0, 1, ..., 9]
  1336. ... '''
  1337. >>> test = doctest.DocTestFinder().find(f)[0]
  1338. >>> doctest.DocTestRunner(verbose=False).run(test)
  1339. ... # doctest: +ELLIPSIS
  1340. **********************************************************************
  1341. File ..., line 2, in f
  1342. Failed example:
  1343. print range(10) # Should fail: no ellipsis
  1344. Expected:
  1345. [0, 1, ..., 9]
  1346. Got:
  1347. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1348. **********************************************************************
  1349. File ..., line 8, in f
  1350. Failed example:
  1351. print range(10) # Should fail: no ellipsis
  1352. Expected:
  1353. [0, 1, ..., 9]
  1354. Got:
  1355. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1356. TestResults(failed=2, attempted=3)
  1357. Multiple options may be modified by a single option directive. They
  1358. may be separated by whitespace, commas, or both:
  1359. >>> def f(x): r'''
  1360. ... >>> print range(10) # Should fail
  1361. ... [0, 1, ..., 9]
  1362. ... >>> print range(10) # Should succeed
  1363. ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  1364. ... [0, 1, ..., 9]
  1365. ... '''
  1366. >>> test = doctest.DocTestFinder().find(f)[0]
  1367. >>> doctest.DocTestRunner(verbose=False).run(test)
  1368. ... # doctest: +ELLIPSIS
  1369. **********************************************************************
  1370. File ..., line 2, in f
  1371. Failed example:
  1372. print range(10) # Should fail
  1373. Expected:
  1374. [0, 1, ..., 9]
  1375. Got:
  1376. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1377. TestResults(failed=1, attempted=2)
  1378. >>> def f(x): r'''
  1379. ... >>> print range(10) # Should fail
  1380. ... [0, 1, ..., 9]
  1381. ... >>> print range(10) # Should succeed
  1382. ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
  1383. ... [0, 1, ..., 9]
  1384. ... '''
  1385. >>> test = doctest.DocTestFinder().find(f)[0]
  1386. >>> doctest.DocTestRunner(verbose=False).run(test)
  1387. ... # doctest: +ELLIPSIS
  1388. **********************************************************************
  1389. File ..., line 2, in f
  1390. Failed example:
  1391. print range(10) # Should fail
  1392. Expected:
  1393. [0, 1, ..., 9]
  1394. Got:
  1395. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1396. TestResults(failed=1, attempted=2)
  1397. >>> def f(x): r'''
  1398. ... >>> print range(10) # Should fail
  1399. ... [0, 1, ..., 9]
  1400. ... >>> print range(10) # Should succeed
  1401. ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
  1402. ... [0, 1, ..., 9]
  1403. ... '''
  1404. >>> test = doctest.DocTestFinder().find(f)[0]
  1405. >>> doctest.DocTestRunner(verbose=False).run(test)
  1406. ... # doctest: +ELLIPSIS
  1407. **********************************************************************
  1408. File ..., line 2, in f
  1409. Failed example:
  1410. print range(10) # Should fail
  1411. Expected:
  1412. [0, 1, ..., 9]
  1413. Got:
  1414. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1415. TestResults(failed=1, attempted=2)
  1416. The option directive may be put on the line following the source, as
  1417. long as a continuation prompt is used:
  1418. >>> def f(x): r'''
  1419. ... >>> print range(10)
  1420. ... ... # doctest: +ELLIPSIS
  1421. ... [0, 1, ..., 9]
  1422. ... '''
  1423. >>> test = doctest.DocTestFinder().find(f)[0]
  1424. >>> doctest.DocTestRunner(verbose=False).run(test)
  1425. TestResults(failed=0, attempted=1)
  1426. For examples with multi-line source, the option directive may appear
  1427. at the end of any line:
  1428. >>> def f(x): r'''
  1429. ... >>> for x in range(10): # doctest: +ELLIPSIS
  1430. ... ... print x,
  1431. ... 0 1 2 ... 9
  1432. ...
  1433. ... >>> for x in range(10):
  1434. ... ... print x, # doctest: +ELLIPSIS
  1435. ... 0 1 2 ... 9
  1436. ... '''
  1437. >>> test = doctest.DocTestFinder().find(f)[0]
  1438. >>> doctest.DocTestRunner(verbose=False).run(test)
  1439. TestResults(failed=0, attempted=2)
  1440. If more than one line of an example with multi-line source has an
  1441. option directive, then they are combined:
  1442. >>> def f(x): r'''
  1443. ... Should fail (option directive not on the last line):
  1444. ... >>> for x in range(10): # doctest: +ELLIPSIS
  1445. ... ... print x, # doctest: +NORMALIZE_WHITESPACE
  1446. ... 0 1 2...9
  1447. ... '''
  1448. >>> test = doctest.DocTestFinder().find(f)[0]
  1449. >>> doctest.DocTestRunner(verbose=False).run(test)
  1450. TestResults(failed=0, attempted=1)
  1451. It is an error to have a comment of the form ``# doctest:`` that is
  1452. *not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
  1453. ``OPTION`` is an option that has been registered with
  1454. `register_option`:
  1455. >>> # Error: Option not registered
  1456. >>> s = '>>> print 12 #doctest: +BADOPTION'
  1457. >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
  1458. Traceback (most recent call last):
  1459. ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
  1460. >>> # Error: No + or - prefix
  1461. >>> s = '>>> print 12 #doctest: ELLIPSIS'
  1462. >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
  1463. Traceback (most recent call last):
  1464. ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
  1465. It is an error to use an option directive on a line that contains no
  1466. source:
  1467. >>> s = '>>> # doctest: +ELLIPSIS'
  1468. >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
  1469. Traceback (most recent call last):
  1470. ValueError: line 0 of the doctest for s has an option directive on a line with no example: '# doctest: +ELLIPSIS'
  1471. """
  1472. def test_unicode_output(self): r"""
  1473. Check that unicode output works:
  1474. >>> u'\xe9'
  1475. u'\xe9'
  1476. If we return unicode, SpoofOut's buf variable becomes automagically
  1477. converted to unicode. This means all subsequent output becomes converted
  1478. to unicode, and if the output contains non-ascii characters that failed.
  1479. It used to be that this state change carried on between tests, meaning
  1480. tests would fail if unicode has been output previously in the testrun.
  1481. This test tests that this is no longer so:
  1482. >>> print u'abc'
  1483. abc
  1484. And then return a string with non-ascii characters:
  1485. >>> print u'\xe9'.encode('utf-8')
  1486. é
  1487. """
  1488. def test_testsource(): r"""
  1489. Unit tests for `testsource()`.
  1490. The testsource() function takes a module and a name, finds the (first)
  1491. test with that name in that module, and converts it to a script. The
  1492. example code is converted to regular Python code. The surrounding
  1493. words and expected output are converted to comments:
  1494. >>> import test.test_doctest
  1495. >>> name = 'test.test_doctest.sample_func'
  1496. >>> print doctest.testsource(test.test_doctest, name)
  1497. # Blah blah
  1498. #
  1499. print sample_func(22)
  1500. # Expected:
  1501. ## 44
  1502. #
  1503. # Yee ha!
  1504. <BLANKLINE>
  1505. >>> name = 'test.test_doctest.SampleNewStyleClass'
  1506. >>> print doctest.testsource(test.test_doctest, name)
  1507. print '1\n2\n3'
  1508. # Expected:
  1509. ## 1
  1510. ## 2
  1511. ## 3
  1512. <BLANKLINE>
  1513. >>> name = 'test.test_doctest.SampleClass.a_classmethod'
  1514. >>> print doctest.testsource(test.test_doctest, name)
  1515. print SampleClass.a_classmethod(10)
  1516. # Expected:
  1517. ## 12
  1518. print SampleClass(0).a_classmethod(10)
  1519. # Expected:
  1520. ## 12
  1521. <BLANKLINE>
  1522. """
  1523. def test_debug(): r"""
  1524. Create a docstring that we want to debug:
  1525. >>> s = '''
  1526. ... >>> x = 12
  1527. ... >>> print x
  1528. ... 12
  1529. ... '''
  1530. Create some fake stdin input, to feed to the debugger:
  1531. >>> import tempfile
  1532. >>> real_stdin = sys.stdin
  1533. >>> sys.stdin = _FakeInput(['next', 'print x', 'continue'])
  1534. Run the debugger on the docstring, and then restore sys.stdin.
  1535. >>> try: doctest.debug_src(s)
  1536. ... finally: sys.stdin = real_stdin
  1537. > <string>(1)<module>()
  1538. (Pdb) next
  1539. 12
  1540. --Return--
  1541. > <string>(1)<module>()->None
  1542. (Pdb) print x
  1543. 12
  1544. (Pdb) continue
  1545. """
  1546. def test_pdb_set_trace():
  1547. """Using pdb.set_trace from a doctest.
  1548. You can use pdb.set_trace from a doctest. To do so, you must
  1549. retrieve the set_trace function from the pdb module at the time
  1550. you use it. The doctest module changes sys.stdout so that it can
  1551. capture program output. It also temporarily replaces pdb.set_trace
  1552. with a version that restores stdout. This is necessary for you to
  1553. see debugger output.
  1554. >>> doc = '''
  1555. ... >>> x = 42
  1556. ... >>> raise Exception('clé')
  1557. ... Traceback (most recent call last):
  1558. ... Exception: clé
  1559. ... >>> import pdb; pdb.set_trace()
  1560. ... '''
  1561. >>> parser = doctest.DocTestParser()
  1562. >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
  1563. >>> runner = doctest.DocTestRunner(verbose=False)
  1564. To demonstrate this, we'll create a fake standard input that
  1565. captures our debugger input:
  1566. >>> import tempfile
  1567. >>> real_stdin = sys.stdin
  1568. >>> sys.stdin = _FakeInput([
  1569. ... 'print x', # print data defined by the example
  1570. ... 'continue', # stop debugging
  1571. ... ''])
  1572. >>> try: runner.run(test)
  1573. ... finally: sys.stdin = real_stdin
  1574. --Return--
  1575. > <doctest foo-bär@baz[2]>(1)<module>()->None
  1576. -> import pdb; pdb.set_trace()
  1577. (Pdb) print x
  1578. 42
  1579. (Pdb) continue
  1580. TestResults(failed=0, attempted=3)
  1581. You can also put pdb.set_trace in a function called from a test:
  1582. >>> def calls_set_trace():
  1583. ... y=2
  1584. ... import pdb; pdb.set_trace()
  1585. >>> doc = '''
  1586. ... >>> x=1
  1587. ... >>> calls_set_trace()
  1588. ... '''
  1589. >>> test = parser.get_doctest(doc, globals(), "foo-bär@baz", "foo-bär@baz.py", 0)
  1590. >>> real_stdin = sys.stdin
  1591. >>> sys.stdin = _FakeInput([
  1592. ... 'print y', # print data defined in the function
  1593. ... 'up', # out of function
  1594. ... 'print x', # print data defined by the example
  1595. ... 'continue', # stop debugging
  1596. ... ''])
  1597. >>> try:
  1598. ... runner.run(test)
  1599. ... finally:
  1600. ... sys.stdin = real_stdin
  1601. --Return--
  1602. > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
  1603. -> import pdb; pdb.set_trace()
  1604. (Pdb) print y
  1605. 2
  1606. (Pdb) up
  1607. > <doctest foo-bär@baz[1]>(1)<module>()
  1608. -> calls_set_trace()
  1609. (Pdb) print x
  1610. 1
  1611. (Pdb) continue
  1612. TestResults(failed=0, attempted=2)
  1613. During interactive debugging, source code is shown, even for
  1614. doctest examples:
  1615. >>> doc = '''
  1616. ... >>> def f(x):
  1617. ... ... g(x*2)
  1618. ... >>> def g(x):
  1619. ... ... print x+3
  1620. ... ... import pdb; pdb.set_trace()
  1621. ... >>> f(3)
  1622. ... '''
  1623. >>> test = parser.get_doctest(doc, globals(), "foo-bär@baz", "foo-bär@baz.py", 0)
  1624. >>> real_stdin = sys.stdin
  1625. >>> sys.stdin = _FakeInput([
  1626. ... 'list', # list source from example 2
  1627. ... 'next', # return from g()
  1628. ... 'list', # list source from example 1
  1629. ... 'next', # return from f()
  1630. ... 'list', # list source from example 3
  1631. ... 'continue', # stop debugging
  1632. ... ''])
  1633. >>> try: runner.run(test)
  1634. ... finally: sys.stdin = real_stdin
  1635. ... # doctest: +NORMALIZE_WHITESPACE
  1636. --Return--
  1637. > <doctest foo-bär@baz[1]>(3)g()->None
  1638. -> import pdb; pdb.set_trace()
  1639. (Pdb) list
  1640. 1 def g(x):
  1641. 2 print x+3
  1642. 3 -> import pdb; pdb.set_trace()
  1643. [EOF]
  1644. (Pdb) next
  1645. --Return--
  1646. > <doctest foo-bär@baz[0]>(2)f()->None
  1647. -> g(x*2)
  1648. (Pdb) list
  1649. 1 def f(x):
  1650. 2 -> g(x*2)
  1651. [EOF]
  1652. (Pdb) next
  1653. --Return--
  1654. > <doctest foo-bär@baz[2]>(1)<module>()->None
  1655. -> f(3)
  1656. (Pdb) list
  1657. 1 -> f(3)
  1658. [EOF]
  1659. (Pdb) continue
  1660. **********************************************************************
  1661. File "foo-bär@baz.py", line 7, in foo-bär@baz
  1662. Failed example:
  1663. f(3)
  1664. Expected nothing
  1665. Got:
  1666. 9
  1667. TestResults(failed=1, attempted=3)
  1668. """
  1669. def test_pdb_set_trace_nested():
  1670. """This illustrates more-demanding use of set_trace with nested functions.
  1671. >>> class C(object):
  1672. ... def calls_set_trace(self):
  1673. ... y = 1
  1674. ... import pdb; pdb.set_trace()
  1675. ... self.f1()
  1676. ... y = 2
  1677. ... def f1(self):
  1678. ... x = 1
  1679. ... self.f2()
  1680. ... x = 2
  1681. ... def f2(self):
  1682. ... z = 1
  1683. ... z = 2
  1684. >>> calls_set_trace = C().calls_set_trace
  1685. >>> doc = '''
  1686. ... >>> a = 1
  1687. ... >>> calls_set_trace()
  1688. ... '''
  1689. >>> parser = doctest.DocTestParser()
  1690. >>> runner = doctest.DocTestRunner(verbose=False)
  1691. >>> test = parser.get_doctest(doc, globals(), "foo-bär@baz", "foo-bär@baz.py", 0)
  1692. >>> real_stdin = sys.stdin
  1693. >>> sys.stdin = _FakeInput([
  1694. ... 'print y', # print data defined in the function
  1695. ... 'step', 'step', 'step', 'step', 'step', 'step', 'print z',
  1696. ... 'up', 'print x',
  1697. ... 'up', 'print y',
  1698. ... 'up', 'print foo',
  1699. ... 'continue', # stop debugging
  1700. ... ''])
  1701. >>> try:
  1702. ... runner.run(test)
  1703. ... finally:
  1704. ... sys.stdin = real_stdin
  1705. > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
  1706. -> self.f1()
  1707. (Pdb) print y
  1708. 1
  1709. (Pdb) step
  1710. --Call--
  1711. > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
  1712. -> def f1(self):
  1713. (Pdb) step
  1714. > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
  1715. -> x = 1
  1716. (Pdb) step
  1717. > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
  1718. -> self.f2()
  1719. (Pdb) step
  1720. --Call--
  1721. > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
  1722. -> def f2(self):
  1723. (Pdb) step
  1724. > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
  1725. -> z = 1
  1726. (Pdb) step
  1727. > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
  1728. -> z = 2
  1729. (Pdb) print z
  1730. 1
  1731. (Pdb) up
  1732. > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
  1733. -> self.f2()
  1734. (Pdb) print x
  1735. 1
  1736. (Pdb) up
  1737. > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
  1738. -> self.f1()
  1739. (Pdb) print y
  1740. 1
  1741. (Pdb) up
  1742. > <doctest foo-bär@baz[1]>(1)<module>()
  1743. -> calls_set_trace()
  1744. (Pdb) print foo
  1745. *** NameError: name 'foo' is not defined
  1746. (Pdb) continue
  1747. TestResults(failed=0, attempted=2)
  1748. """
  1749. def test_DocTestSuite():
  1750. """DocTestSuite creates a unittest test suite from a doctest.
  1751. We create a Suite by providing a module. A module can be provided
  1752. by passing a module object:
  1753. >>> import unittest
  1754. >>> import test.sample_doctest
  1755. >>> suite = doctest.DocTestSuite(test.sample_doctest)
  1756. >>> suite.run(unittest.TestResult())
  1757. <unittest.result.TestResult run=9 errors=0 failures=4>
  1758. We can also supply the module by name:
  1759. >>> suite = doctest.DocTestSuite('test.sample_doctest')
  1760. >>> suite.run(unittest.TestResult())
  1761. <unittest.result.TestResult run=9 errors=0 failures=4>
  1762. The module need not contain any doctest examples:
  1763. >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
  1764. >>> suite.run(unittest.TestResult())
  1765. <unittest.result.TestResult run=0 errors=0 failures=0>
  1766. However, if DocTestSuite finds no docstrings, it raises an error:
  1767. >>> try:
  1768. ... doctest.DocTestSuite('test.sample_doctest_no_docstrings')
  1769. ... except ValueError as e:
  1770. ... error = e
  1771. >>> print(error.args[1])
  1772. has no docstrings
  1773. You can prevent this error by passing a DocTestFinder instance with
  1774. the `exclude_empty` keyword argument set to False:
  1775. >>> finder = doctest.DocTestFinder(exclude_empty=False)
  1776. >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
  1777. ... test_finder=finder)
  1778. >>> suite.run(unittest.TestResult())
  1779. <unittest.result.TestResult run=0 errors=0 failures=0>
  1780. We can use the current module:
  1781. >>> suite = test.sample_doctest.test_suite()
  1782. >>> suite.run(unittest.TestResult())
  1783. <unittest.result.TestResult run=9 errors=0 failures=4>
  1784. We can supply global variables. If we pass globs, they will be
  1785. used instead of the module globals. Here we'll pass an empty
  1786. globals, triggering an extra error:
  1787. >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
  1788. >>> suite.run(unittest.TestResult())
  1789. <unittest.result.TestResult run=9 errors=0 failures=5>
  1790. Alternatively, we can provide extra globals. Here we'll make an
  1791. error go away by providing an extra global variable:
  1792. >>> suite = doctest.DocTestSuite('test.sample_doctest',
  1793. ... extraglobs={'y': 1})
  1794. >>> suite.run(unittest.TestResult())
  1795. <unittest.result.TestResult run=9 errors=0 failures=3>
  1796. You can pass option flags. Here we'll cause an extra error
  1797. by disabling the blank-line feature:
  1798. >>> suite = doctest.DocTestSuite('test.sample_doctest',
  1799. ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
  1800. >>> suite.run(unittest.TestResult())
  1801. <unittest.result.TestResult run=9 errors=0 failures=5>
  1802. You can supply setUp and tearDown functions:
  1803. >>> def setUp(t):
  1804. ... import test.test_doctest
  1805. ... test.test_doctest.sillySetup = True
  1806. >>> def tearDown(t):
  1807. ... import test.test_doctest
  1808. ... del test.test_doctest.sillySetup
  1809. Here, we installed a silly variable that the test expects:
  1810. >>> suite = doctest.DocTestSuite('test.sample_doctest',
  1811. ... setUp=setUp, tearDown=tearDown)
  1812. >>> suite.run(unittest.TestResult())
  1813. <unittest.result.TestResult run=9 errors=0 failures=3>
  1814. But the tearDown restores sanity:
  1815. >>> import test.test_doctest
  1816. >>> test.test_doctest.sillySetup
  1817. Traceback (most recent call last):
  1818. ...
  1819. AttributeError: 'module' object has no attribute 'sillySetup'
  1820. The setUp and tearDown funtions are passed test objects. Here
  1821. we'll use the setUp function to supply the missing variable y:
  1822. >>> def setUp(test):
  1823. ... test.globs['y'] = 1
  1824. >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
  1825. >>> suite.run(unittest.TestResult())
  1826. <unittest.result.TestResult run=9 errors=0 failures=3>
  1827. Here, we didn't need to use a tearDown function because we
  1828. modified the test globals, which are a copy of the
  1829. sample_doctest module dictionary. The test globals are
  1830. automatically cleared for us after a test.
  1831. """
  1832. def test_DocFileSuite():
  1833. """We can test tests found in text files using a DocFileSuite.
  1834. We create a suite by providing the names of one or more text
  1835. files that include examples:
  1836. >>> import unittest
  1837. >>> suite = doctest.DocFileSuite('test_doctest.txt',
  1838. ... 'test_doctest2.txt',
  1839. ... 'test_doctest4.txt')
  1840. >>> suite.run(unittest.TestResult())
  1841. <unittest.result.TestResult run=3 errors=0 failures=3>
  1842. The test files are looked for in the directory containing the
  1843. calling module. A package keyword argument can be provided to
  1844. specify a different relative location.
  1845. >>> import unittest
  1846. >>> suite = doctest.DocFileSuite('test_doctest.txt',
  1847. ... 'test_doctest2.txt',
  1848. ... 'test_doctest4.txt',
  1849. ... package='test')
  1850. >>> suite.run(unittest.TestResult())
  1851. <unittest.result.TestResult run=3 errors=0 failures=3>
  1852. Support for using a package's __loader__.get_data() is also
  1853. provided.
  1854. >>> import unittest, pkgutil, test
  1855. >>> added_loader = False
  1856. >>> if not hasattr(test, '__loader__'):
  1857. ... test.__loader__ = pkgutil.get_loader(test)
  1858. ... added_loader = True
  1859. >>> try:
  1860. ... suite = doctest.DocFileSuite('test_doctest.txt',
  1861. ... 'test_doctest2.txt',
  1862. ... 'test_doctest4.txt',
  1863. ... package='test')
  1864. ... suite.run(unittest.TestResult())
  1865. ... finally:
  1866. ... if added_loader:
  1867. ... del test.__loader__
  1868. <unittest.result.TestResult run=3 errors=0 failures=3>
  1869. '/' should be used as a path separator. It will be converted
  1870. to a native separator at run time:
  1871. >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
  1872. >>> suite.run(unittest.TestResult())
  1873. <unittest.result.TestResult run=1 errors=0 failures=1>
  1874. If DocFileSuite is used from an interactive session, then files
  1875. are resolved relative to the directory of sys.argv[0]:
  1876. >>> import types, os.path, test.test_doctest
  1877. >>> save_argv = sys.argv
  1878. >>> sys.argv = [test.test_doctest.__file__]
  1879. >>> suite = doctest.DocFileSuite('test_doctest.txt',
  1880. ... package=types.ModuleType('__main__'))
  1881. >>> sys.argv = save_argv
  1882. By setting `module_relative=False`, os-specific paths may be
  1883. used (including absolute paths and paths relative to the
  1884. working directory):
  1885. >>> # Get the absolute path of the test package.
  1886. >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
  1887. >>> test_pkg_path = os.path.split(test_doctest_path)[0]
  1888. >>> # Use it to find the absolute path of test_doctest.txt.
  1889. >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
  1890. >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
  1891. >>> suite.run(unittest.TestResult())
  1892. <unittest.result.TestResult run=1 errors=0 failures=1>
  1893. It is an error to specify `package` when `module_relative=False`:
  1894. >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
  1895. ... package='test')
  1896. Traceback (most recent call last):
  1897. ValueError: Package may only be specified for module-relative paths.
  1898. You can specify initial global variables:
  1899. >>> suite = doctest.DocFileSuite('test_doctest.txt',
  1900. ... 'test_doctest2.txt',
  1901. ... 'test_doctest4.txt',
  1902. ... globs={'favorite_color': 'blue'})
  1903. >>> suite.run(unittest.TestResult())
  1904. <unittest.result.TestResult run=3 errors=0 failures=2>
  1905. In this case, we supplied a missing favorite color. You can
  1906. provide doctest options:
  1907. >>> suite = doctest.DocFileSuite('test_doctest.txt',
  1908. ... 'test_doctest2.txt',
  1909. ... 'test_doctest4.txt',
  1910. ... optionflags=doctest.DONT_ACCEPT_BLANKLINE,
  1911. ... globs={'favorite_color': 'blue'})
  1912. >>> suite.run(unittest.TestResult())
  1913. <unittest.result.TestResult run=3 errors=0 failures=3>
  1914. And, you can provide setUp and tearDown functions:
  1915. >>> def setUp(t):
  1916. ... import test.test_doctest
  1917. ... test.test_doctest.sillySetup = True
  1918. >>> def tearDown(t):
  1919. ... import test.test_doctest
  1920. ... del test.test_doctest.sillySetup
  1921. Here, we installed a silly variable that the test expects:
  1922. >>> suite = doctest.DocFileSuite('test_doctest.txt',
  1923. ... 'test_doctest2.txt',
  1924. ... 'test_doctest4.txt',
  1925. ... setUp=setUp, tearDown=tearDown)
  1926. >>> suite.run(unittest.TestResult())
  1927. <unittest.result.TestResult run=3 errors=0 failures=2>
  1928. But the tearDown restores sanity:
  1929. >>> import test.test_doctest
  1930. >>> test.test_doctest.sillySetup
  1931. Traceback (most recent call last):
  1932. ...
  1933. AttributeError: 'module' object has no attribute 'sillySetup'
  1934. The setUp and tearDown funtions are passed test objects.
  1935. Here, we'll use a setUp function to set the favorite color in
  1936. test_doctest.txt:
  1937. >>> def setUp(test):
  1938. ... test.globs['favorite_color'] = 'blue'
  1939. >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
  1940. >>> suite.run(unittest.TestResult())
  1941. <unittest.result.TestResult run=1 errors=0 failures=0>
  1942. Here, we didn't need to use a tearDown function because we
  1943. modified the test globals. The test globals are
  1944. automatically cleared for us after a test.
  1945. Tests in a file run using `DocFileSuite` can also access the
  1946. `__file__` global, which is set to the name of the file
  1947. containing the tests:
  1948. >>> suite = doctest.DocFileSuite('test_doctest3.txt')
  1949. >>> suite.run(unittest.TestResult())
  1950. <unittest.result.TestResult run=1 errors=0 failures=0>
  1951. If the tests contain non-ASCII characters, we have to specify which
  1952. encoding the file is encoded with. We do so by using the `encoding`
  1953. parameter:
  1954. >>> suite = doctest.DocFileSuite('test_doctest.txt',
  1955. ... 'test_doctest2.txt',
  1956. ... 'test_doctest4.txt',
  1957. ... encoding='utf-8')
  1958. >>> suite.run(unittest.TestResult())
  1959. <unittest.result.TestResult run=3 errors=0 failures=2>
  1960. """
  1961. def test_trailing_space_in_test():
  1962. """
  1963. Trailing spaces in expected output are significant:
  1964. >>> x, y = 'foo', ''
  1965. >>> print x, y
  1966. foo \n
  1967. """
  1968. def test_unittest_reportflags():
  1969. """Default unittest reporting flags can be set to control reporting
  1970. Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
  1971. only the first failure of each test. First, we'll look at the
  1972. output without the flag. The file test_doctest.txt file has two
  1973. tests. They both fail if blank lines are disabled:
  1974. >>> suite = doctest.DocFileSuite('test_doctest.txt',
  1975. ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
  1976. >>> import unittest
  1977. >>> result = suite.run(unittest.TestResult())
  1978. >>> print result.failures[0][1] # doctest: +ELLIPSIS
  1979. Traceback ...
  1980. Failed example:
  1981. favorite_color
  1982. ...
  1983. Failed example:
  1984. if 1:
  1985. ...
  1986. Note that we see both failures displayed.
  1987. >>> old = doctest.set_unittest_reportflags(
  1988. ... doctest.REPORT_ONLY_FIRST_FAILURE)
  1989. Now, when we run the test:
  1990. >>> result = suite.run(unittest.TestResult())
  1991. >>> print result.failures[0][1] # doctest: +ELLIPSIS
  1992. Traceback ...
  1993. Failed example:
  1994. favorite_color
  1995. Exception raised:
  1996. ...
  1997. NameError: name 'favorite_color' is not defined
  1998. <BLANKLINE>
  1999. <BLANKLINE>
  2000. We get only the first failure.
  2001. If we give any reporting options when we set up the tests,
  2002. however:
  2003. >>> suite = doctest.DocFileSuite('test_doctest.txt',
  2004. ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
  2005. Then the default eporting options are ignored:
  2006. >>> result = suite.run(unittest.TestResult())
  2007. >>> print result.failures[0][1] # doctest: +ELLIPSIS
  2008. Traceback ...
  2009. Failed example:
  2010. favorite_color
  2011. ...
  2012. Failed example:
  2013. if 1:
  2014. print 'a'
  2015. print
  2016. print 'b'
  2017. Differences (ndiff with -expected +actual):
  2018. a
  2019. - <BLANKLINE>
  2020. +
  2021. b
  2022. <BLANKLINE>
  2023. <BLANKLINE>
  2024. Test runners can restore the formatting flags after they run:
  2025. >>> ignored = doctest.set_unittest_reportflags(old)
  2026. """
  2027. def test_testfile(): r"""
  2028. Tests for the `testfile()` function. This function runs all the
  2029. doctest examples in a given file. In its simple invokation, it is
  2030. called with the name of a file, which is taken to be relative to the
  2031. calling module. The return value is (#failures, #tests).
  2032. We don't want `-v` in sys.argv for these tests.
  2033. >>> save_argv = sys.argv
  2034. >>> if '-v' in sys.argv:
  2035. ... sys.argv = [arg for arg in save_argv if arg != '-v']
  2036. >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
  2037. **********************************************************************
  2038. File "...", line 6, in test_doctest.txt
  2039. Failed example:
  2040. favorite_color
  2041. Exception raised:
  2042. ...
  2043. NameError: name 'favorite_color' is not defined
  2044. **********************************************************************
  2045. 1 items had failures:
  2046. 1 of 2 in test_doctest.txt
  2047. ***Test Failed*** 1 failures.
  2048. TestResults(failed=1, attempted=2)
  2049. >>> doctest.master = None # Reset master.
  2050. (Note: we'll be clearing doctest.master after each call to
  2051. `doctest.testfile`, to suppress warnings about multiple tests with the
  2052. same name.)
  2053. Globals may be specified with the `globs` and `extraglobs` parameters:
  2054. >>> globs = {'favorite_color': 'blue'}
  2055. >>> doctest.testfile('test_doctest.txt', globs=globs)
  2056. TestResults(failed=0, attempted=2)
  2057. >>> doctest.master = None # Reset master.
  2058. >>> extraglobs = {'favorite_color': 'red'}
  2059. >>> doctest.testfile('test_doctest.txt', globs=globs,
  2060. ... extraglobs=extraglobs) # doctest: +ELLIPSIS
  2061. **********************************************************************
  2062. File "...", line 6, in test_doctest.txt
  2063. Failed example:
  2064. favorite_color
  2065. Expected:
  2066. 'blue'
  2067. Got:
  2068. 'red'
  2069. **********************************************************************
  2070. 1 items had failures:
  2071. 1 of 2 in test_doctest.txt
  2072. ***Test Failed*** 1 failures.
  2073. TestResults(failed=1, attempted=2)
  2074. >>> doctest.master = None # Reset master.
  2075. The file may be made relative to a given module or package, using the
  2076. optional `module_relative` parameter:
  2077. >>> doctest.testfile('test_doctest.txt', globs=globs,
  2078. ... module_relative='test')
  2079. TestResults(failed=0, attempted=2)
  2080. >>> doctest.master = None # Reset master.
  2081. Verbosity can be increased with the optional `verbose` parameter:
  2082. >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
  2083. Trying:
  2084. favorite_color
  2085. Expecting:
  2086. 'blue'
  2087. ok
  2088. Trying:
  2089. if 1:
  2090. print 'a'
  2091. print
  2092. print 'b'
  2093. Expecting:
  2094. a
  2095. <BLANKLINE>
  2096. b
  2097. ok
  2098. 1 items passed all tests:
  2099. 2 tests in test_doctest.txt
  2100. 2 tests in 1 items.
  2101. 2 passed and 0 failed.
  2102. Test passed.
  2103. TestResults(failed=0, attempted=2)
  2104. >>> doctest.master = None # Reset master.
  2105. The name of the test may be specified with the optional `name`
  2106. parameter:
  2107. >>> doctest.testfile('test_doctest.txt', name='newname')
  2108. ... # doctest: +ELLIPSIS
  2109. **********************************************************************
  2110. File "...", line 6, in newname
  2111. ...
  2112. TestResults(failed=1, attempted=2)
  2113. >>> doctest.master = None # Reset master.
  2114. The summary report may be suppressed with the optional `report`
  2115. parameter:
  2116. >>> doctest.testfile('test_doctest.txt', report=False)
  2117. ... # doctest: +ELLIPSIS
  2118. **********************************************************************
  2119. File "...", line 6, in test_doctest.txt
  2120. Failed example:
  2121. favorite_color
  2122. Exception raised:
  2123. ...
  2124. NameError: name 'favorite_color' is not defined
  2125. TestResults(failed=1, attempted=2)
  2126. >>> doctest.master = None # Reset master.
  2127. The optional keyword argument `raise_on_error` can be used to raise an
  2128. exception on the first error (which may be useful for postmortem
  2129. debugging):
  2130. >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
  2131. ... # doctest: +ELLIPSIS
  2132. Traceback (most recent call last):
  2133. UnexpectedException: ...
  2134. >>> doctest.master = None # Reset master.
  2135. If the tests contain non-ASCII characters, the tests might fail, since
  2136. it's unknown which encoding is used. The encoding can be specified
  2137. using the optional keyword argument `encoding`:
  2138. >>> doctest.testfile('test_doctest4.txt') # doctest: +ELLIPSIS
  2139. **********************************************************************
  2140. File "...", line 7, in test_doctest4.txt
  2141. Failed example:
  2142. u'...'
  2143. Expected:
  2144. u'f\xf6\xf6'
  2145. Got:
  2146. u'f\xc3\xb6\xc3\xb6'
  2147. **********************************************************************
  2148. ...
  2149. **********************************************************************
  2150. 1 items had failures:
  2151. 2 of 4 in test_doctest4.txt
  2152. ***Test Failed*** 2 failures.
  2153. TestResults(failed=2, attempted=4)
  2154. >>> doctest.master = None # Reset master.
  2155. >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
  2156. TestResults(failed=0, attempted=4)
  2157. >>> doctest.master = None # Reset master.
  2158. Switch the module encoding to 'utf-8' to test the verbose output without
  2159. bothering with the current sys.stdout encoding.
  2160. >>> doctest._encoding, saved_encoding = 'utf-8', doctest._encoding
  2161. >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
  2162. Trying:
  2163. u'föö'
  2164. Expecting:
  2165. u'f\xf6\xf6'
  2166. ok
  2167. Trying:
  2168. u'bąr'
  2169. Expecting:
  2170. u'b\u0105r'
  2171. ok
  2172. Trying:
  2173. 'föö'
  2174. Expecting:
  2175. 'f\xc3\xb6\xc3\xb6'
  2176. ok
  2177. Trying:
  2178. 'bąr'
  2179. Expecting:
  2180. 'b\xc4\x85r'
  2181. ok
  2182. 1 items passed all tests:
  2183. 4 tests in test_doctest4.txt
  2184. 4 tests in 1 items.
  2185. 4 passed and 0 failed.
  2186. Test passed.
  2187. TestResults(failed=0, attempted=4)
  2188. >>> doctest._encoding = saved_encoding
  2189. >>> doctest.master = None # Reset master.
  2190. >>> sys.argv = save_argv
  2191. """
  2192. def test_lineendings(): r"""
  2193. *nix systems use \n line endings, while Windows systems use \r\n. Python
  2194. handles this using universal newline mode for reading files. Let's make
  2195. sure doctest does so (issue 8473) by creating temporary test files using each
  2196. of the two line disciplines. One of the two will be the "wrong" one for the
  2197. platform the test is run on.
  2198. Windows line endings first:
  2199. >>> import tempfile, os
  2200. >>> fn = tempfile.mktemp()
  2201. >>> with open(fn, 'wb') as f:
  2202. ... f.write('Test:\r\n\r\n >>> x = 1 + 1\r\n\r\nDone.\r\n')
  2203. >>> doctest.testfile(fn, module_relative=False, verbose=False)
  2204. TestResults(failed=0, attempted=1)
  2205. >>> os.remove(fn)
  2206. And now *nix line endings:
  2207. >>> fn = tempfile.mktemp()
  2208. >>> with open(fn, 'wb') as f:
  2209. ... f.write('Test:\n\n >>> x = 1 + 1\n\nDone.\n')
  2210. >>> doctest.testfile(fn, module_relative=False, verbose=False)
  2211. TestResults(failed=0, attempted=1)
  2212. >>> os.remove(fn)
  2213. """
  2214. # old_test1, ... used to live in doctest.py, but cluttered it. Note
  2215. # that these use the deprecated doctest.Tester, so should go away (or
  2216. # be rewritten) someday.
  2217. def old_test1(): r"""
  2218. >>> from doctest import Tester
  2219. >>> t = Tester(globs={'x': 42}, verbose=0)
  2220. >>> t.runstring(r'''
  2221. ... >>> x = x * 2
  2222. ... >>> print x
  2223. ... 42
  2224. ... ''', 'XYZ')
  2225. **********************************************************************
  2226. Line 3, in XYZ
  2227. Failed example:
  2228. print x
  2229. Expected:
  2230. 42
  2231. Got:
  2232. 84
  2233. TestResults(failed=1, attempted=2)
  2234. >>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
  2235. TestResults(failed=0, attempted=2)
  2236. >>> t.summarize()
  2237. **********************************************************************
  2238. 1 items had failures:
  2239. 1 of 2 in XYZ
  2240. ***Test Failed*** 1 failures.
  2241. TestResults(failed=1, attempted=4)
  2242. >>> t.summarize(verbose=1)
  2243. 1 items passed all tests:
  2244. 2 tests in example2
  2245. **********************************************************************
  2246. 1 items had failures:
  2247. 1 of 2 in XYZ
  2248. 4 tests in 2 items.
  2249. 3 passed and 1 failed.
  2250. ***Test Failed*** 1 failures.
  2251. TestResults(failed=1, attempted=4)
  2252. """
  2253. def old_test2(): r"""
  2254. >>> from doctest import Tester
  2255. >>> t = Tester(globs={}, verbose=1)
  2256. >>> test = r'''
  2257. ... # just an example
  2258. ... >>> x = 1 + 2
  2259. ... >>> x
  2260. ... 3
  2261. ... '''
  2262. >>> t.runstring(test, "Example")
  2263. Running string Example
  2264. Trying:
  2265. x = 1 + 2
  2266. Expecting nothing
  2267. ok
  2268. Trying:
  2269. x
  2270. Expecting:
  2271. 3
  2272. ok
  2273. 0 of 2 examples failed in string Example
  2274. TestResults(failed=0, attempted=2)
  2275. """
  2276. def old_test3(): r"""
  2277. >>> from doctest import Tester
  2278. >>> t = Tester(globs={}, verbose=0)
  2279. >>> def _f():
  2280. ... '''Trivial docstring example.
  2281. ... >>> assert 2 == 2
  2282. ... '''
  2283. ... return 32
  2284. ...
  2285. >>> t.rundoc(_f) # expect 0 failures in 1 example
  2286. TestResults(failed=0, attempted=1)
  2287. """
  2288. def old_test4(): """
  2289. >>> import types
  2290. >>> m1 = types.ModuleType('_m1')
  2291. >>> m2 = types.ModuleType('_m2')
  2292. >>> test_data = \"""
  2293. ... def _f():
  2294. ... '''>>> assert 1 == 1
  2295. ... '''
  2296. ... def g():
  2297. ... '''>>> assert 2 != 1
  2298. ... '''
  2299. ... class H:
  2300. ... '''>>> assert 2 > 1
  2301. ... '''
  2302. ... def bar(self):
  2303. ... '''>>> assert 1 < 2
  2304. ... '''
  2305. ... \"""
  2306. >>> exec test_data in m1.__dict__
  2307. >>> exec test_data in m2.__dict__
  2308. >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
  2309. Tests that objects outside m1 are excluded:
  2310. >>> from doctest import Tester
  2311. >>> t = Tester(globs={}, verbose=0)
  2312. >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
  2313. TestResults(failed=0, attempted=4)
  2314. Once more, not excluding stuff outside m1:
  2315. >>> t = Tester(globs={}, verbose=0)
  2316. >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
  2317. TestResults(failed=0, attempted=8)
  2318. The exclusion of objects from outside the designated module is
  2319. meant to be invoked automagically by testmod.
  2320. >>> doctest.testmod(m1, verbose=False)
  2321. TestResults(failed=0, attempted=4)
  2322. """
  2323. ######################################################################
  2324. ## Main
  2325. ######################################################################
  2326. def test_main():
  2327. # Check the doctest cases in doctest itself:
  2328. test_support.run_doctest(doctest, verbosity=True)
  2329. from test import test_doctest
  2330. # Ignore all warnings about the use of class Tester in this module.
  2331. deprecations = []
  2332. if __debug__:
  2333. deprecations.append(("class Tester is deprecated", DeprecationWarning))
  2334. if sys.py3kwarning:
  2335. deprecations += [("backquote not supported", SyntaxWarning),
  2336. ("execfile.. not supported", DeprecationWarning)]
  2337. with test_support.check_warnings(*deprecations):
  2338. # Check the doctest cases defined here:
  2339. test_support.run_doctest(test_doctest, verbosity=True)
  2340. import sys
  2341. def test_coverage(coverdir):
  2342. trace = test_support.import_module('trace')
  2343. tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
  2344. trace=0, count=1)
  2345. tracer.run('reload(doctest); test_main()')
  2346. r = tracer.results()
  2347. print 'Writing coverage results...'
  2348. r.write_results(show_missing=True, summary=True,
  2349. coverdir=coverdir)
  2350. if __name__ == '__main__':
  2351. if '-c' in sys.argv:
  2352. test_coverage('/tmp/doctest.cover')
  2353. else:
  2354. test_main()