PageRenderTime 95ms CodeModel.GetById 19ms RepoModel.GetById 4ms app.codeStats 0ms

/lib-python/2.7/test/test_doctest.py

https://bitbucket.org/dac_io/pypy
Python | 2615 lines | 2551 code | 10 blank | 54 comment | 0 complexity | f30b5ede17a0a2a4ba138954cee2a722 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  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. """
  218. def test_DocTest(): r"""
  219. Unit tests for the `DocTest` class.
  220. DocTest is a collection of examples, extracted from a docstring, along
  221. with information about where the docstring comes from (a name,
  222. filename, and line number). The docstring is parsed by the `DocTest`
  223. constructor:
  224. >>> docstring = '''
  225. ... >>> print 12
  226. ... 12
  227. ...
  228. ... Non-example text.
  229. ...
  230. ... >>> print 'another\example'
  231. ... another
  232. ... example
  233. ... '''
  234. >>> globs = {} # globals to run the test in.
  235. >>> parser = doctest.DocTestParser()
  236. >>> test = parser.get_doctest(docstring, globs, 'some_test',
  237. ... 'some_file', 20)
  238. >>> print test
  239. <DocTest some_test from some_file:20 (2 examples)>
  240. >>> len(test.examples)
  241. 2
  242. >>> e1, e2 = test.examples
  243. >>> (e1.source, e1.want, e1.lineno)
  244. ('print 12\n', '12\n', 1)
  245. >>> (e2.source, e2.want, e2.lineno)
  246. ("print 'another\\example'\n", 'another\nexample\n', 6)
  247. Source information (name, filename, and line number) is available as
  248. attributes on the doctest object:
  249. >>> (test.name, test.filename, test.lineno)
  250. ('some_test', 'some_file', 20)
  251. The line number of an example within its containing file is found by
  252. adding the line number of the example and the line number of its
  253. containing test:
  254. >>> test.lineno + e1.lineno
  255. 21
  256. >>> test.lineno + e2.lineno
  257. 26
  258. If the docstring contains inconsistant leading whitespace in the
  259. expected output of an example, then `DocTest` will raise a ValueError:
  260. >>> docstring = r'''
  261. ... >>> print 'bad\nindentation'
  262. ... bad
  263. ... indentation
  264. ... '''
  265. >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
  266. Traceback (most recent call last):
  267. ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
  268. If the docstring contains inconsistent leading whitespace on
  269. continuation lines, then `DocTest` will raise a ValueError:
  270. >>> docstring = r'''
  271. ... >>> print ('bad indentation',
  272. ... ... 2)
  273. ... ('bad', 'indentation')
  274. ... '''
  275. >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
  276. Traceback (most recent call last):
  277. ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2)'
  278. If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
  279. will raise a ValueError:
  280. >>> docstring = '>>>print 1\n1'
  281. >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
  282. Traceback (most recent call last):
  283. ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1'
  284. If there's no blank space after a PS2 prompt ('...'), then `DocTest`
  285. will raise a ValueError:
  286. >>> docstring = '>>> if 1:\n...print 1\n1'
  287. >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
  288. Traceback (most recent call last):
  289. ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1'
  290. """
  291. def test_DocTestFinder(): r"""
  292. Unit tests for the `DocTestFinder` class.
  293. DocTestFinder is used to extract DocTests from an object's docstring
  294. and the docstrings of its contained objects. It can be used with
  295. modules, functions, classes, methods, staticmethods, classmethods, and
  296. properties.
  297. Finding Tests in Functions
  298. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  299. For a function whose docstring contains examples, DocTestFinder.find()
  300. will return a single test (for that function's docstring):
  301. >>> finder = doctest.DocTestFinder()
  302. We'll simulate a __file__ attr that ends in pyc:
  303. >>> import test.test_doctest
  304. >>> old = test.test_doctest.__file__
  305. >>> test.test_doctest.__file__ = 'test_doctest.pyc'
  306. >>> tests = finder.find(sample_func)
  307. >>> print tests # doctest: +ELLIPSIS
  308. [<DocTest sample_func from ...:17 (1 example)>]
  309. The exact name depends on how test_doctest was invoked, so allow for
  310. leading path components.
  311. >>> tests[0].filename # doctest: +ELLIPSIS
  312. '...test_doctest.py'
  313. >>> test.test_doctest.__file__ = old
  314. >>> e = tests[0].examples[0]
  315. >>> (e.source, e.want, e.lineno)
  316. ('print sample_func(22)\n', '44\n', 3)
  317. By default, tests are created for objects with no docstring:
  318. >>> def no_docstring(v):
  319. ... pass
  320. >>> finder.find(no_docstring)
  321. []
  322. However, the optional argument `exclude_empty` to the DocTestFinder
  323. constructor can be used to exclude tests for objects with empty
  324. docstrings:
  325. >>> def no_docstring(v):
  326. ... pass
  327. >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
  328. >>> excl_empty_finder.find(no_docstring)
  329. []
  330. If the function has a docstring with no examples, then a test with no
  331. examples is returned. (This lets `DocTestRunner` collect statistics
  332. about which functions have no tests -- but is that useful? And should
  333. an empty test also be created when there's no docstring?)
  334. >>> def no_examples(v):
  335. ... ''' no doctest examples '''
  336. >>> finder.find(no_examples) # doctest: +ELLIPSIS
  337. [<DocTest no_examples from ...:1 (no examples)>]
  338. Finding Tests in Classes
  339. ~~~~~~~~~~~~~~~~~~~~~~~~
  340. For a class, DocTestFinder will create a test for the class's
  341. docstring, and will recursively explore its contents, including
  342. methods, classmethods, staticmethods, properties, and nested classes.
  343. >>> finder = doctest.DocTestFinder()
  344. >>> tests = finder.find(SampleClass)
  345. >>> for t in tests:
  346. ... print '%2s %s' % (len(t.examples), t.name)
  347. 3 SampleClass
  348. 3 SampleClass.NestedClass
  349. 1 SampleClass.NestedClass.__init__
  350. 1 SampleClass.__init__
  351. 2 SampleClass.a_classmethod
  352. 1 SampleClass.a_property
  353. 1 SampleClass.a_staticmethod
  354. 1 SampleClass.double
  355. 1 SampleClass.get
  356. New-style classes are also supported:
  357. >>> tests = finder.find(SampleNewStyleClass)
  358. >>> for t in tests:
  359. ... print '%2s %s' % (len(t.examples), t.name)
  360. 1 SampleNewStyleClass
  361. 1 SampleNewStyleClass.__init__
  362. 1 SampleNewStyleClass.double
  363. 1 SampleNewStyleClass.get
  364. Finding Tests in Modules
  365. ~~~~~~~~~~~~~~~~~~~~~~~~
  366. For a module, DocTestFinder will create a test for the class's
  367. docstring, and will recursively explore its contents, including
  368. functions, classes, and the `__test__` dictionary, if it exists:
  369. >>> # A module
  370. >>> import types
  371. >>> m = types.ModuleType('some_module')
  372. >>> def triple(val):
  373. ... '''
  374. ... >>> print triple(11)
  375. ... 33
  376. ... '''
  377. ... return val*3
  378. >>> m.__dict__.update({
  379. ... 'sample_func': sample_func,
  380. ... 'SampleClass': SampleClass,
  381. ... '__doc__': '''
  382. ... Module docstring.
  383. ... >>> print 'module'
  384. ... module
  385. ... ''',
  386. ... '__test__': {
  387. ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
  388. ... 'c': triple}})
  389. >>> finder = doctest.DocTestFinder()
  390. >>> # Use module=test.test_doctest, to prevent doctest from
  391. >>> # ignoring the objects since they weren't defined in m.
  392. >>> import test.test_doctest
  393. >>> tests = finder.find(m, module=test.test_doctest)
  394. >>> for t in tests:
  395. ... print '%2s %s' % (len(t.examples), t.name)
  396. 1 some_module
  397. 3 some_module.SampleClass
  398. 3 some_module.SampleClass.NestedClass
  399. 1 some_module.SampleClass.NestedClass.__init__
  400. 1 some_module.SampleClass.__init__
  401. 2 some_module.SampleClass.a_classmethod
  402. 1 some_module.SampleClass.a_property
  403. 1 some_module.SampleClass.a_staticmethod
  404. 1 some_module.SampleClass.double
  405. 1 some_module.SampleClass.get
  406. 1 some_module.__test__.c
  407. 2 some_module.__test__.d
  408. 1 some_module.sample_func
  409. Duplicate Removal
  410. ~~~~~~~~~~~~~~~~~
  411. If a single object is listed twice (under different names), then tests
  412. will only be generated for it once:
  413. >>> from test import doctest_aliases
  414. >>> assert doctest_aliases.TwoNames.f
  415. >>> assert doctest_aliases.TwoNames.g
  416. >>> tests = excl_empty_finder.find(doctest_aliases)
  417. >>> print len(tests)
  418. 2
  419. >>> print tests[0].name
  420. test.doctest_aliases.TwoNames
  421. TwoNames.f and TwoNames.g are bound to the same object.
  422. We can't guess which will be found in doctest's traversal of
  423. TwoNames.__dict__ first, so we have to allow for either.
  424. >>> tests[1].name.split('.')[-1] in ['f', 'g']
  425. True
  426. Empty Tests
  427. ~~~~~~~~~~~
  428. By default, an object with no doctests doesn't create any tests:
  429. >>> tests = doctest.DocTestFinder().find(SampleClass)
  430. >>> for t in tests:
  431. ... print '%2s %s' % (len(t.examples), t.name)
  432. 3 SampleClass
  433. 3 SampleClass.NestedClass
  434. 1 SampleClass.NestedClass.__init__
  435. 1 SampleClass.__init__
  436. 2 SampleClass.a_classmethod
  437. 1 SampleClass.a_property
  438. 1 SampleClass.a_staticmethod
  439. 1 SampleClass.double
  440. 1 SampleClass.get
  441. By default, that excluded objects with no doctests. exclude_empty=False
  442. tells it to include (empty) tests for objects with no doctests. This feature
  443. is really to support backward compatibility in what doctest.master.summarize()
  444. displays.
  445. >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
  446. >>> for t in tests:
  447. ... print '%2s %s' % (len(t.examples), t.name)
  448. 3 SampleClass
  449. 3 SampleClass.NestedClass
  450. 1 SampleClass.NestedClass.__init__
  451. 0 SampleClass.NestedClass.get
  452. 0 SampleClass.NestedClass.square
  453. 1 SampleClass.__init__
  454. 2 SampleClass.a_classmethod
  455. 1 SampleClass.a_property
  456. 1 SampleClass.a_staticmethod
  457. 1 SampleClass.double
  458. 1 SampleClass.get
  459. Turning off Recursion
  460. ~~~~~~~~~~~~~~~~~~~~~
  461. DocTestFinder can be told not to look for tests in contained objects
  462. using the `recurse` flag:
  463. >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
  464. >>> for t in tests:
  465. ... print '%2s %s' % (len(t.examples), t.name)
  466. 3 SampleClass
  467. Line numbers
  468. ~~~~~~~~~~~~
  469. DocTestFinder finds the line number of each example:
  470. >>> def f(x):
  471. ... '''
  472. ... >>> x = 12
  473. ...
  474. ... some text
  475. ...
  476. ... >>> # examples are not created for comments & bare prompts.
  477. ... >>>
  478. ... ...
  479. ...
  480. ... >>> for x in range(10):
  481. ... ... print x,
  482. ... 0 1 2 3 4 5 6 7 8 9
  483. ... >>> x//2
  484. ... 6
  485. ... '''
  486. >>> test = doctest.DocTestFinder().find(f)[0]
  487. >>> [e.lineno for e in test.examples]
  488. [1, 9, 12]
  489. """
  490. def test_DocTestParser(): r"""
  491. Unit tests for the `DocTestParser` class.
  492. DocTestParser is used to parse docstrings containing doctest examples.
  493. The `parse` method divides a docstring into examples and intervening
  494. text:
  495. >>> s = '''
  496. ... >>> x, y = 2, 3 # no output expected
  497. ... >>> if 1:
  498. ... ... print x
  499. ... ... print y
  500. ... 2
  501. ... 3
  502. ...
  503. ... Some text.
  504. ... >>> x+y
  505. ... 5
  506. ... '''
  507. >>> parser = doctest.DocTestParser()
  508. >>> for piece in parser.parse(s):
  509. ... if isinstance(piece, doctest.Example):
  510. ... print 'Example:', (piece.source, piece.want, piece.lineno)
  511. ... else:
  512. ... print ' Text:', `piece`
  513. Text: '\n'
  514. Example: ('x, y = 2, 3 # no output expected\n', '', 1)
  515. Text: ''
  516. Example: ('if 1:\n print x\n print y\n', '2\n3\n', 2)
  517. Text: '\nSome text.\n'
  518. Example: ('x+y\n', '5\n', 9)
  519. Text: ''
  520. The `get_examples` method returns just the examples:
  521. >>> for piece in parser.get_examples(s):
  522. ... print (piece.source, piece.want, piece.lineno)
  523. ('x, y = 2, 3 # no output expected\n', '', 1)
  524. ('if 1:\n print x\n print y\n', '2\n3\n', 2)
  525. ('x+y\n', '5\n', 9)
  526. The `get_doctest` method creates a Test from the examples, along with the
  527. given arguments:
  528. >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
  529. >>> (test.name, test.filename, test.lineno)
  530. ('name', 'filename', 5)
  531. >>> for piece in test.examples:
  532. ... print (piece.source, piece.want, piece.lineno)
  533. ('x, y = 2, 3 # no output expected\n', '', 1)
  534. ('if 1:\n print x\n print y\n', '2\n3\n', 2)
  535. ('x+y\n', '5\n', 9)
  536. """
  537. class test_DocTestRunner:
  538. def basics(): r"""
  539. Unit tests for the `DocTestRunner` class.
  540. DocTestRunner is used to run DocTest test cases, and to accumulate
  541. statistics. Here's a simple DocTest case we can use:
  542. >>> def f(x):
  543. ... '''
  544. ... >>> x = 12
  545. ... >>> print x
  546. ... 12
  547. ... >>> x//2
  548. ... 6
  549. ... '''
  550. >>> test = doctest.DocTestFinder().find(f)[0]
  551. The main DocTestRunner interface is the `run` method, which runs a
  552. given DocTest case in a given namespace (globs). It returns a tuple
  553. `(f,t)`, where `f` is the number of failed tests and `t` is the number
  554. of tried tests.
  555. >>> doctest.DocTestRunner(verbose=False).run(test)
  556. TestResults(failed=0, attempted=3)
  557. If any example produces incorrect output, then the test runner reports
  558. the failure and proceeds to the next example:
  559. >>> def f(x):
  560. ... '''
  561. ... >>> x = 12
  562. ... >>> print x
  563. ... 14
  564. ... >>> x//2
  565. ... 6
  566. ... '''
  567. >>> test = doctest.DocTestFinder().find(f)[0]
  568. >>> doctest.DocTestRunner(verbose=True).run(test)
  569. ... # doctest: +ELLIPSIS
  570. Trying:
  571. x = 12
  572. Expecting nothing
  573. ok
  574. Trying:
  575. print x
  576. Expecting:
  577. 14
  578. **********************************************************************
  579. File ..., line 4, in f
  580. Failed example:
  581. print x
  582. Expected:
  583. 14
  584. Got:
  585. 12
  586. Trying:
  587. x//2
  588. Expecting:
  589. 6
  590. ok
  591. TestResults(failed=1, attempted=3)
  592. """
  593. def verbose_flag(): r"""
  594. The `verbose` flag makes the test runner generate more detailed
  595. output:
  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. >>> doctest.DocTestRunner(verbose=True).run(test)
  606. Trying:
  607. x = 12
  608. Expecting nothing
  609. ok
  610. Trying:
  611. print x
  612. Expecting:
  613. 12
  614. ok
  615. Trying:
  616. x//2
  617. Expecting:
  618. 6
  619. ok
  620. TestResults(failed=0, attempted=3)
  621. If the `verbose` flag is unspecified, then the output will be verbose
  622. iff `-v` appears in sys.argv:
  623. >>> # Save the real sys.argv list.
  624. >>> old_argv = sys.argv
  625. >>> # If -v does not appear in sys.argv, then output isn't verbose.
  626. >>> sys.argv = ['test']
  627. >>> doctest.DocTestRunner().run(test)
  628. TestResults(failed=0, attempted=3)
  629. >>> # If -v does appear in sys.argv, then output is verbose.
  630. >>> sys.argv = ['test', '-v']
  631. >>> doctest.DocTestRunner().run(test)
  632. Trying:
  633. x = 12
  634. Expecting nothing
  635. ok
  636. Trying:
  637. print x
  638. Expecting:
  639. 12
  640. ok
  641. Trying:
  642. x//2
  643. Expecting:
  644. 6
  645. ok
  646. TestResults(failed=0, attempted=3)
  647. >>> # Restore sys.argv
  648. >>> sys.argv = old_argv
  649. In the remaining examples, the test runner's verbosity will be
  650. explicitly set, to ensure that the test behavior is consistent.
  651. """
  652. def exceptions(): r"""
  653. Tests of `DocTestRunner`'s exception handling.
  654. An expected exception is specified with a traceback message. The
  655. lines between the first line and the type/value may be omitted or
  656. replaced with any other string:
  657. >>> def f(x):
  658. ... '''
  659. ... >>> x = 12
  660. ... >>> print x//0
  661. ... Traceback (most recent call last):
  662. ... ZeroDivisionError: integer division or modulo by zero
  663. ... '''
  664. >>> test = doctest.DocTestFinder().find(f)[0]
  665. >>> doctest.DocTestRunner(verbose=False).run(test)
  666. TestResults(failed=0, attempted=2)
  667. An example may not generate output before it raises an exception; if
  668. it does, then the traceback message will not be recognized as
  669. signaling an expected exception, so the example will be reported as an
  670. unexpected exception:
  671. >>> def f(x):
  672. ... '''
  673. ... >>> x = 12
  674. ... >>> print 'pre-exception output', x//0
  675. ... pre-exception output
  676. ... Traceback (most recent call last):
  677. ... ZeroDivisionError: integer division or modulo by zero
  678. ... '''
  679. >>> test = doctest.DocTestFinder().find(f)[0]
  680. >>> doctest.DocTestRunner(verbose=False).run(test)
  681. ... # doctest: +ELLIPSIS
  682. **********************************************************************
  683. File ..., line 4, in f
  684. Failed example:
  685. print 'pre-exception output', x//0
  686. Exception raised:
  687. ...
  688. ZeroDivisionError: integer division or modulo by zero
  689. TestResults(failed=1, attempted=2)
  690. Exception messages may contain newlines:
  691. >>> def f(x):
  692. ... r'''
  693. ... >>> raise ValueError, 'multi\nline\nmessage'
  694. ... Traceback (most recent call last):
  695. ... ValueError: multi
  696. ... line
  697. ... message
  698. ... '''
  699. >>> test = doctest.DocTestFinder().find(f)[0]
  700. >>> doctest.DocTestRunner(verbose=False).run(test)
  701. TestResults(failed=0, attempted=1)
  702. If an exception is expected, but an exception with the wrong type or
  703. message is raised, then it is reported as a failure:
  704. >>> def f(x):
  705. ... r'''
  706. ... >>> raise ValueError, 'message'
  707. ... Traceback (most recent call last):
  708. ... ValueError: wrong message
  709. ... '''
  710. >>> test = doctest.DocTestFinder().find(f)[0]
  711. >>> doctest.DocTestRunner(verbose=False).run(test)
  712. ... # doctest: +ELLIPSIS
  713. **********************************************************************
  714. File ..., line 3, in f
  715. Failed example:
  716. raise ValueError, 'message'
  717. Expected:
  718. Traceback (most recent call last):
  719. ValueError: wrong message
  720. Got:
  721. Traceback (most recent call last):
  722. ...
  723. ValueError: message
  724. TestResults(failed=1, attempted=1)
  725. However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
  726. detail:
  727. >>> def f(x):
  728. ... r'''
  729. ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
  730. ... Traceback (most recent call last):
  731. ... ValueError: wrong message
  732. ... '''
  733. >>> test = doctest.DocTestFinder().find(f)[0]
  734. >>> doctest.DocTestRunner(verbose=False).run(test)
  735. TestResults(failed=0, attempted=1)
  736. IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
  737. between Python versions. For example, in Python 3.x, the module path of
  738. the exception is in the output, but this will fail under Python 2:
  739. >>> def f(x):
  740. ... r'''
  741. ... >>> from httplib import HTTPException
  742. ... >>> raise HTTPException('message')
  743. ... Traceback (most recent call last):
  744. ... httplib.HTTPException: message
  745. ... '''
  746. >>> test = doctest.DocTestFinder().find(f)[0]
  747. >>> doctest.DocTestRunner(verbose=False).run(test)
  748. ... # doctest: +ELLIPSIS
  749. **********************************************************************
  750. File ..., line 4, in f
  751. Failed example:
  752. raise HTTPException('message')
  753. Expected:
  754. Traceback (most recent call last):
  755. httplib.HTTPException: message
  756. Got:
  757. Traceback (most recent call last):
  758. ...
  759. HTTPException: message
  760. TestResults(failed=1, attempted=2)
  761. But in Python 2 the module path is not included, an therefore a test must look
  762. like the following test to succeed in Python 2. But that test will fail under
  763. Python 3.
  764. >>> def f(x):
  765. ... r'''
  766. ... >>> from httplib import HTTPException
  767. ... >>> raise HTTPException('message')
  768. ... Traceback (most recent call last):
  769. ... HTTPException: message
  770. ... '''
  771. >>> test = doctest.DocTestFinder().find(f)[0]
  772. >>> doctest.DocTestRunner(verbose=False).run(test)
  773. TestResults(failed=0, attempted=2)
  774. However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
  775. (if any) will be ignored:
  776. >>> def f(x):
  777. ... r'''
  778. ... >>> from httplib import HTTPException
  779. ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
  780. ... Traceback (most recent call last):
  781. ... HTTPException: message
  782. ... '''
  783. >>> test = doctest.DocTestFinder().find(f)[0]
  784. >>> doctest.DocTestRunner(verbose=False).run(test)
  785. TestResults(failed=0, attempted=2)
  786. The module path will be completely ignored, so two different module paths will
  787. still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
  788. be used when exceptions have changed module.
  789. >>> def f(x):
  790. ... r'''
  791. ... >>> from httplib import HTTPException
  792. ... >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
  793. ... Traceback (most recent call last):
  794. ... foo.bar.HTTPException: message
  795. ... '''
  796. >>> test = doctest.DocTestFinder().find(f)[0]
  797. >>> doctest.DocTestRunner(verbose=False).run(test)
  798. TestResults(failed=0, attempted=2)
  799. But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
  800. >>> def f(x):
  801. ... r'''
  802. ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
  803. ... Traceback (most recent call last):
  804. ... TypeError: wrong type
  805. ... '''
  806. >>> test = doctest.DocTestFinder().find(f)[0]
  807. >>> doctest.DocTestRunner(verbose=False).run(test)
  808. ... # doctest: +ELLIPSIS
  809. **********************************************************************
  810. File ..., line 3, in f
  811. Failed example:
  812. raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
  813. Expected:
  814. Traceback (most recent call last):
  815. TypeError: wrong type
  816. Got:
  817. Traceback (most recent call last):
  818. ...
  819. ValueError: message
  820. TestResults(failed=1, attempted=1)
  821. If an exception is raised but not expected, then it is reported as an
  822. unexpected exception:
  823. >>> def f(x):
  824. ... r'''
  825. ... >>> 1//0
  826. ... 0
  827. ... '''
  828. >>> test = doctest.DocTestFinder().find(f)[0]
  829. >>> doctest.DocTestRunner(verbose=False).run(test)
  830. ... # doctest: +ELLIPSIS
  831. **********************************************************************
  832. File ..., line 3, in f
  833. Failed example:
  834. 1//0
  835. Exception raised:
  836. Traceback (most recent call last):
  837. ...
  838. ZeroDivisionError: integer division or modulo by zero
  839. TestResults(failed=1, attempted=1)
  840. """
  841. def displayhook(): r"""
  842. Test that changing sys.displayhook doesn't matter for doctest.
  843. >>> import sys
  844. >>> orig_displayhook = sys.displayhook
  845. >>> def my_displayhook(x):
  846. ... print('hi!')
  847. >>> sys.displayhook = my_displayhook
  848. >>> def f():
  849. ... '''
  850. ... >>> 3
  851. ... 3
  852. ... '''
  853. >>> test = doctest.DocTestFinder().find(f)[0]
  854. >>> r = doctest.DocTestRunner(verbose=False).run(test)
  855. >>> post_displayhook = sys.displayhook
  856. We need to restore sys.displayhook now, so that we'll be able to test
  857. results.
  858. >>> sys.displayhook = orig_displayhook
  859. Ok, now we can check that everything is ok.
  860. >>> r
  861. TestResults(failed=0, attempted=1)
  862. >>> post_displayhook is my_displayhook
  863. True
  864. """
  865. def optionflags(): r"""
  866. Tests of `DocTestRunner`'s option flag handling.
  867. Several option flags can be used to customize the behavior of the test
  868. runner. These are defined as module constants in doctest, and passed
  869. to the DocTestRunner constructor (multiple constants should be ORed
  870. together).
  871. The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
  872. and 1/0:
  873. >>> def f(x):
  874. ... '>>> True\n1\n'
  875. >>> # Without the flag:
  876. >>> test = doctest.DocTestFinder().find(f)[0]
  877. >>> doctest.DocTestRunner(verbose=False).run(test)
  878. TestResults(failed=0, attempted=1)
  879. >>> # With the flag:
  880. >>> test = doctest.DocTestFinder().find(f)[0]
  881. >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
  882. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  883. ... # doctest: +ELLIPSIS
  884. **********************************************************************
  885. File ..., line 2, in f
  886. Failed example:
  887. True
  888. Expected:
  889. 1
  890. Got:
  891. True
  892. TestResults(failed=1, attempted=1)
  893. The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
  894. and the '<BLANKLINE>' marker:
  895. >>> def f(x):
  896. ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
  897. >>> # Without the flag:
  898. >>> test = doctest.DocTestFinder().find(f)[0]
  899. >>> doctest.DocTestRunner(verbose=False).run(test)
  900. TestResults(failed=0, attempted=1)
  901. >>> # With the flag:
  902. >>> test = doctest.DocTestFinder().find(f)[0]
  903. >>> flags = doctest.DONT_ACCEPT_BLANKLINE
  904. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  905. ... # doctest: +ELLIPSIS
  906. **********************************************************************
  907. File ..., line 2, in f
  908. Failed example:
  909. print "a\n\nb"
  910. Expected:
  911. a
  912. <BLANKLINE>
  913. b
  914. Got:
  915. a
  916. <BLANKLINE>
  917. b
  918. TestResults(failed=1, attempted=1)
  919. The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
  920. treated as equal:
  921. >>> def f(x):
  922. ... '>>> print 1, 2, 3\n 1 2\n 3'
  923. >>> # Without the flag:
  924. >>> test = doctest.DocTestFinder().find(f)[0]
  925. >>> doctest.DocTestRunner(verbose=False).run(test)
  926. ... # doctest: +ELLIPSIS
  927. **********************************************************************
  928. File ..., line 2, in f
  929. Failed example:
  930. print 1, 2, 3
  931. Expected:
  932. 1 2
  933. 3
  934. Got:
  935. 1 2 3
  936. TestResults(failed=1, attempted=1)
  937. >>> # With the flag:
  938. >>> test = doctest.DocTestFinder().find(f)[0]
  939. >>> flags = doctest.NORMALIZE_WHITESPACE
  940. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  941. TestResults(failed=0, attempted=1)
  942. An example from the docs:
  943. >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
  944. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
  945. 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
  946. The ELLIPSIS flag causes ellipsis marker ("...") in the expected
  947. output to match any substring in the actual output:
  948. >>> def f(x):
  949. ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
  950. >>> # Without the flag:
  951. >>> test = doctest.DocTestFinder().find(f)[0]
  952. >>> doctest.DocTestRunner(verbose=False).run(test)
  953. ... # doctest: +ELLIPSIS
  954. **********************************************************************
  955. File ..., line 2, in f
  956. Failed example:
  957. print range(15)
  958. Expected:
  959. [0, 1, 2, ..., 14]
  960. Got:
  961. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
  962. TestResults(failed=1, attempted=1)
  963. >>> # With the flag:
  964. >>> test = doctest.DocTestFinder().find(f)[0]
  965. >>> flags = doctest.ELLIPSIS
  966. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  967. TestResults(failed=0, attempted=1)
  968. ... also matches nothing:
  969. >>> for i in range(100):
  970. ... print i**2, #doctest: +ELLIPSIS
  971. 0 1...4...9 16 ... 36 49 64 ... 9801
  972. ... can be surprising; e.g., this test passes:
  973. >>> for i in range(21): #doctest: +ELLIPSIS
  974. ... print i,
  975. 0 1 2 ...1...2...0
  976. Examples from the docs:
  977. >>> print range(20) # doctest:+ELLIPSIS
  978. [0, 1, ..., 18, 19]
  979. >>> print range(20) # doctest: +ELLIPSIS
  980. ... # doctest: +NORMALIZE_WHITESPACE
  981. [0, 1, ..., 18, 19]
  982. The SKIP flag causes an example to be skipped entirely. I.e., the
  983. example is not run. It can be useful in contexts where doctest
  984. examples serve as both documentation and test cases, and an example
  985. should be included for documentation purposes, but should not be
  986. checked (e.g., because its output is random, or depends on resources
  987. which would be unavailable.) The SKIP flag can also be used for
  988. 'commenting out' broken examples.
  989. >>> import unavailable_resource # doctest: +SKIP
  990. >>> unavailable_resource.do_something() # doctest: +SKIP
  991. >>> unavailable_resource.blow_up() # doctest: +SKIP
  992. Traceback (most recent call last):
  993. ...
  994. UncheckedBlowUpError: Nobody checks me.
  995. >>> import random
  996. >>> print random.random() # doctest: +SKIP
  997. 0.721216923889
  998. The REPORT_UDIFF flag causes failures that involve multi-line expected
  999. and actual outputs to be displayed using a unified diff:
  1000. >>> def f(x):
  1001. ... r'''
  1002. ... >>> print '\n'.join('abcdefg')
  1003. ... a
  1004. ... B
  1005. ... c
  1006. ... d
  1007. ... f
  1008. ... g
  1009. ... h
  1010. ... '''
  1011. >>> # Without the flag:
  1012. >>> test = doctest.DocTestFinder().find(f)[0]
  1013. >>> doctest.DocTestRunner(verbose=False).run(test)
  1014. ... # doctest: +ELLIPSIS
  1015. **********************************************************************
  1016. File ..., line 3, in f
  1017. Failed example:
  1018. print '\n'.join('abcdefg')
  1019. Expected:
  1020. a
  1021. B
  1022. c
  1023. d
  1024. f
  1025. g
  1026. h
  1027. Got:
  1028. a
  1029. b
  1030. c
  1031. d
  1032. e
  1033. f
  1034. g
  1035. TestResults(failed=1, attempted=1)
  1036. >>> # With the flag:
  1037. >>> test = doctest.DocTestFinder().find(f)[0]
  1038. >>> flags = doctest.REPORT_UDIFF
  1039. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1040. ... # doctest: +ELLIPSIS
  1041. **********************************************************************
  1042. File ..., line 3, in f
  1043. Failed example:
  1044. print '\n'.join('abcdefg')
  1045. Differences (unified diff with -expected +actual):
  1046. @@ -1,7 +1,7 @@
  1047. a
  1048. -B
  1049. +b
  1050. c
  1051. d
  1052. +e
  1053. f
  1054. g
  1055. -h
  1056. TestResults(failed=1, attempted=1)
  1057. The REPORT_CDIFF flag causes failures that involve multi-line expected
  1058. and actual outputs to be displayed using a context diff:
  1059. >>> # Reuse f() from the REPORT_UDIFF example, above.
  1060. >>> test = doctest.DocTestFinder().find(f)[0]
  1061. >>> flags = doctest.REPORT_CDIFF
  1062. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1063. ... # doctest: +ELLIPSIS
  1064. **********************************************************************
  1065. File ..., line 3, in f
  1066. Failed example:
  1067. print '\n'.join('abcdefg')
  1068. Differences (context diff with expected followed by actual):
  1069. ***************
  1070. *** 1,7 ****
  1071. a
  1072. ! B
  1073. c
  1074. d
  1075. f
  1076. g
  1077. - h
  1078. --- 1,7 ----
  1079. a
  1080. ! b
  1081. c
  1082. d
  1083. + e
  1084. f
  1085. g
  1086. TestResults(failed=1, attempted=1)
  1087. The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
  1088. used by the popular ndiff.py utility. This does intraline difference
  1089. marking, as well as interline differences.
  1090. >>> def f(x):
  1091. ... r'''
  1092. ... >>> print "a b c d e f g h i j k l m"
  1093. ... a b c d e f g h i j k 1 m
  1094. ... '''
  1095. >>> test = doctest.DocTestFinder().find(f)[0]
  1096. >>> flags = doctest.REPORT_NDIFF
  1097. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1098. ... # doctest: +ELLIPSIS
  1099. **********************************************************************
  1100. File ..., line 3, in f
  1101. Failed example:
  1102. print "a b c d e f g h i j k l m"
  1103. Differences (ndiff with -expected +actual):
  1104. - a b c d e f g h i j k 1 m
  1105. ? ^
  1106. + a b c d e f g h i j k l m
  1107. ? + ++ ^
  1108. TestResults(failed=1, attempted=1)
  1109. The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
  1110. failing example:
  1111. >>> def f(x):
  1112. ... r'''
  1113. ... >>> print 1 # first success
  1114. ... 1
  1115. ... >>> print 2 # first failure
  1116. ... 200
  1117. ... >>> print 3 # second failure
  1118. ... 300
  1119. ... >>> print 4 # second success
  1120. ... 4
  1121. ... >>> print 5 # third failure
  1122. ... 500
  1123. ... '''
  1124. >>> test = doctest.DocTestFinder().find(f)[0]
  1125. >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
  1126. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1127. ... # doctest: +ELLIPSIS
  1128. **********************************************************************
  1129. File ..., line 5, in f
  1130. Failed example:
  1131. print 2 # first failure
  1132. Expected:
  1133. 200
  1134. Got:
  1135. 2
  1136. TestResults(failed=3, attempted=5)
  1137. However, output from `report_start` is not suppressed:
  1138. >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
  1139. ... # doctest: +ELLIPSIS
  1140. Trying:
  1141. print 1 # first success
  1142. Expecting:
  1143. 1
  1144. ok
  1145. Trying:
  1146. print 2 # first failure
  1147. Expecting:
  1148. 200
  1149. **********************************************************************
  1150. File ..., line 5, in f
  1151. Failed example:
  1152. print 2 # first failure
  1153. Expected:
  1154. 200
  1155. Got:
  1156. 2
  1157. TestResults(failed=3, attempted=5)
  1158. For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
  1159. count as failures:
  1160. >>> def f(x):
  1161. ... r'''
  1162. ... >>> print 1 # first success
  1163. ... 1
  1164. ... >>> raise ValueError(2) # first failure
  1165. ... 200
  1166. ... >>> print 3 # second failure
  1167. ... 300
  1168. ... >>> print 4 # second success
  1169. ... 4
  1170. ... >>> print 5 # third failure
  1171. ... 500
  1172. ... '''
  1173. >>> test = doctest.DocTestFinder().find(f)[0]
  1174. >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
  1175. >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
  1176. ... # doctest: +ELLIPSIS
  1177. **********************************************************************
  1178. File ..., line 5, in f
  1179. Failed example:
  1180. raise ValueError(2) # first failure
  1181. Exception raised:
  1182. ...
  1183. ValueError: 2
  1184. TestResults(failed=3, attempted=5)
  1185. New option flags can also be registered, via register_optionflag(). Here
  1186. we reach into doctest's internals a bit.
  1187. >>> unlikely = "UNLIKELY_OPTION_NAME"
  1188. >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
  1189. False
  1190. >>> new_flag_value = doctest.register_optionflag(unlikely)
  1191. >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
  1192. True
  1193. Before 2.4.4/2.5, registering a name more than once erroneously created
  1194. more than one flag value. Here we verify that's fixed:
  1195. >>> redundant_flag_value = doctest.register_optionflag(unlikely)
  1196. >>> redundant_flag_value == new_flag_value
  1197. True
  1198. Clean up.
  1199. >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
  1200. """
  1201. def option_directives(): r"""
  1202. Tests of `DocTestRunner`'s option directive mechanism.
  1203. Option directives can be used to turn option flags on or off for a
  1204. single example. To turn an option on for an example, follow that
  1205. example with a comment of the form ``# doctest: +OPTION``:
  1206. >>> def f(x): r'''
  1207. ... >>> print range(10) # should fail: no ellipsis
  1208. ... [0, 1, ..., 9]
  1209. ...
  1210. ... >>> print range(10) # doctest: +ELLIPSIS
  1211. ... [0, 1, ..., 9]
  1212. ... '''
  1213. >>> test = doctest.DocTestFinder().find(f)[0]
  1214. >>> doctest.DocTestRunner(verbose=False).run(test)
  1215. ... # doctest: +ELLIPSIS
  1216. **********************************************************************
  1217. File ..., line 2, in f
  1218. Failed example:
  1219. print range(10) # should fail: no ellipsis
  1220. Expected:
  1221. [0, 1, ..., 9]
  1222. Got:
  1223. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1224. TestResults(failed=1, attempted=2)
  1225. To turn an option off for an example, follow that example with a
  1226. comment of the form ``# doctest: -OPTION``:
  1227. >>> def f(x): r'''
  1228. ... >>> print range(10)
  1229. ... [0, 1, ..., 9]
  1230. ...
  1231. ... >>> # should fail: no ellipsis
  1232. ... >>> print range(10) # doctest: -ELLIPSIS
  1233. ... [0, 1, ..., 9]
  1234. ... '''
  1235. >>> test = doctest.DocTestFinder().find(f)[0]
  1236. >>> doctest.DocTestRunner(verbose=False,
  1237. ... optionflags=doctest.ELLIPSIS).run(test)
  1238. ... # doctest: +ELLIPSIS
  1239. **********************************************************************
  1240. File ..., line 6, in f
  1241. Failed example:
  1242. print range(10) # doctest: -ELLIPSIS
  1243. Expected:
  1244. [0, 1, ..., 9]
  1245. Got:
  1246. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1247. TestResults(failed=1, attempted=2)
  1248. Option directives affect only the example that they appear with; they
  1249. do not change the options for surrounding examples:
  1250. >>> def f(x): r'''
  1251. ... >>> print range(10) # Should fail: no ellipsis
  1252. ... [0, 1, ..., 9]
  1253. ...
  1254. ... >>> print range(10) # doctest: +ELLIPSIS
  1255. ... [0, 1, ..., 9]
  1256. ...
  1257. ... >>> print range(10) # Should fail: no ellipsis
  1258. ... [0, 1, ..., 9]
  1259. ... '''
  1260. >>> test = doctest.DocTestFinder().find(f)[0]
  1261. >>> doctest.DocTestRunner(verbose=False).run(test)
  1262. ... # doctest: +ELLIPSIS
  1263. **********************************************************************
  1264. File ..., line 2, in f
  1265. Failed example:
  1266. print range(10) # Should fail: no ellipsis
  1267. Expected:
  1268. [0, 1, ..., 9]
  1269. Got:
  1270. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1271. **********************************************************************
  1272. File ..., line 8, in f
  1273. Failed example:
  1274. print range(10) # Should fail: no ellipsis
  1275. Expected:
  1276. [0, 1, ..., 9]
  1277. Got:
  1278. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1279. TestResults(failed=2, attempted=3)
  1280. Multiple options may be modified by a single option directive. They
  1281. may be separated by whitespace, commas, or both:
  1282. >>> def f(x): r'''
  1283. ... >>> print range(10) # Should fail
  1284. ... [0, 1, ..., 9]
  1285. ... >>> print range(10) # Should succeed
  1286. ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  1287. ... [0, 1, ..., 9]
  1288. ... '''
  1289. >>> test = doctest.DocTestFinder().find(f)[0]
  1290. >>> doctest.DocTestRunner(verbose=False).run(test)
  1291. ... # doctest: +ELLIPSIS
  1292. **********************************************************************
  1293. File ..., line 2, in f
  1294. Failed example:
  1295. print range(10) # Should fail
  1296. Expected:
  1297. [0, 1, ..., 9]
  1298. Got:
  1299. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1300. TestResults(failed=1, attempted=2)
  1301. >>> def f(x): r'''
  1302. ... >>> print range(10) # Should fail
  1303. ... [0, 1, ..., 9]
  1304. ... >>> print range(10) # Should succeed
  1305. ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
  1306. ... [0, 1, ..., 9]
  1307. ... '''
  1308. >>> test = doctest.DocTestFinder().find(f)[0]
  1309. >>> doctest.DocTestRunner(verbose=False).run(test)
  1310. ... # doctest: +ELLIPSIS
  1311. **********************************************************************
  1312. File ..., line 2, in f
  1313. Failed example:
  1314. print range(10) # Should fail
  1315. Expected:
  1316. [0, 1, ..., 9]
  1317. Got:
  1318. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1319. TestResults(failed=1, attempted=2)
  1320. >>> def f(x): r'''
  1321. ... >>> print range(10) # Should fail
  1322. ... [0, 1, ..., 9]
  1323. ... >>> print range(10) # Should succeed
  1324. ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
  1325. ... [0, 1, ..., 9]
  1326. ... '''
  1327. >>> test = doctest.DocTestFinder().find(f)[0]
  1328. >>> doctest.DocTestRunner(verbose=False).run(test)
  1329. ... # doctest: +ELLIPSIS
  1330. **********************************************************************
  1331. File ..., line 2, in f
  1332. Failed example:
  1333. print range(10) # Should fail
  1334. Expected:
  1335. [0, 1, ..., 9]
  1336. Got:
  1337. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1338. TestResults(failed=1, attempted=2)
  1339. The option directive may be put on the line following the source, as
  1340. long as a continuation prompt is used:
  1341. >>> def f(x): r'''
  1342. ... >>> print range(10)
  1343. ... ... # doctest: +ELLIPSIS
  1344. ... [0, 1, ..., 9]
  1345. ... '''
  1346. >>> test = doctest.DocTestFinder().find(f)[0]
  1347. >>> doctest.DocTestRunner(verbose=False).run(test)
  1348. TestResults(failed=0, attempted=1)
  1349. For examples with multi-line source, the option directive may appear
  1350. at the end of any line:
  1351. >>> def f(x): r'''
  1352. ... >>> for x in range(10): # doctest: +ELLIPSIS
  1353. ... ... print x,
  1354. ... 0 1 2 ... 9
  1355. ...
  1356. ... >>> for x in range(10):
  1357. ... ... print x, # doctest: +ELLIPSIS
  1358. ... 0 1 2 ... 9
  1359. ... '''
  1360. >>> test = doctest.DocTestFinder().find(f)[0]
  1361. >>> doctest.DocTestRunner(verbose=False).run(test)
  1362. TestResults(failed=0, attempted=2)
  1363. If more than one line of an example with multi-line source has an
  1364. option directive, then they are combined:
  1365. >>> def f(x): r'''
  1366. ... Should fail (option directive not on the last line):
  1367. ... >>> for x in range(10): # doctest: +ELLIPSIS
  1368. ... ... print x, # doctest: +NORMALIZE_WHITESPACE
  1369. ... 0 1 2...9
  1370. ... '''
  1371. >>> test = doctest.DocTestFinder().find(f)[0]
  1372. >>> doctest.DocTestRunner(verbose=False).run(test)
  1373. TestResults(failed=0, attempted=1)
  1374. It is an error to have a comment of the form ``# doctest:`` that is
  1375. *not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
  1376. ``OPTION`` is an option that has been registered with
  1377. `register_option`:
  1378. >>> # Error: Option not registered
  1379. >>> s = '>>> print 12 #doctest: +BADOPTION'
  1380. >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
  1381. Traceback (most recent call last):
  1382. ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
  1383. >>> # Error: No + or - prefix
  1384. >>> s = '>>> print 12 #doctest: ELLIPSIS'
  1385. >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
  1386. Traceback (most recent call last):
  1387. ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
  1388. It is an error to use an option directive on a line that contains no
  1389. source:
  1390. >>> s = '>>> # doctest: +ELLIPSIS'
  1391. >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
  1392. Traceback (most recent call last):
  1393. ValueError: line 0 of the doctest for s has an option directive on a line with no example: '# doctest: +ELLIPSIS'
  1394. """
  1395. def test_unicode_output(self): r"""
  1396. Check that unicode output works:
  1397. >>> u'\xe9'
  1398. u'\xe9'
  1399. If we return unicode, SpoofOut's buf variable becomes automagically
  1400. converted to unicode. This means all subsequent output becomes converted
  1401. to unicode, and if the output contains non-ascii characters that failed.
  1402. It used to be that this state change carried on between tests, meaning
  1403. tests would fail if unicode has been output previously in the testrun.
  1404. This test tests that this is no longer so:
  1405. >>> print u'abc'
  1406. abc
  1407. And the

Large files files are truncated, but you can click here to view the full file