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