blob: 3bce66e82867c742c7d113336ef26611ff1534a4 [file] [log] [blame]
Georg Brandlb533e262008-05-25 18:19:30 +00001import os
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002import sys
Éric Araujoe64e51b2011-07-29 17:03:55 +02003import builtins
Antoine Pitrou916fc7b2013-05-19 15:44:54 +02004import contextlib
Georg Brandlb533e262008-05-25 18:19:30 +00005import difflib
Georg Brandlb533e262008-05-25 18:19:30 +00006import inspect
Nick Coghlan7bb30b72010-12-03 09:29:11 +00007import pydoc
Ezio Melottib185a042011-04-28 07:42:55 +03008import keyword
Larry Hastings24a882b2014-02-20 23:34:46 -08009import _pickle
Antoine Pitrou916fc7b2013-05-19 15:44:54 +020010import pkgutil
Nick Coghlan7bb30b72010-12-03 09:29:11 +000011import re
12import string
Georg Brandlb533e262008-05-25 18:19:30 +000013import test.support
Nick Coghlan7bb30b72010-12-03 09:29:11 +000014import time
Ethan Furmanb0c84cd2013-10-20 22:37:39 -070015import types
Nick Coghlan7bb30b72010-12-03 09:29:11 +000016import unittest
Brian Curtin49c284c2010-03-31 03:19:28 +000017import xml.etree
Georg Brandld80d5f42010-12-03 07:47:22 +000018import textwrap
19from io import StringIO
Raymond Hettinger1103d052011-03-25 14:15:24 -070020from collections import namedtuple
Antoine Pitrouf7f54752011-07-15 22:42:12 +020021from test.script_helper import assert_python_ok
Antoine Pitroua6e81a22011-07-15 22:32:25 +020022from test.support import (
Ned Deily92a81a12011-10-06 14:19:03 -070023 TESTFN, rmtree,
Antoine Pitrou916fc7b2013-05-19 15:44:54 +020024 reap_children, reap_threads, captured_output, captured_stdout,
Stefan Krah5de32782014-01-18 23:18:39 +010025 captured_stderr, unlink, requires_docstrings
Antoine Pitroua6e81a22011-07-15 22:32:25 +020026)
Georg Brandlb533e262008-05-25 18:19:30 +000027from test import pydoc_mod
28
Victor Stinner62a68f22011-05-20 02:29:13 +020029try:
30 import threading
31except ImportError:
32 threading = None
33
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020034if test.support.HAVE_DOCSTRINGS:
35 expected_data_docstrings = (
36 'dictionary for instance variables (if defined)',
37 'list of weak references to the object (if defined)',
38 ) * 2
39else:
40 expected_data_docstrings = ('', '', '', '')
41
Barry Warsaw28a691b2010-04-17 00:19:56 +000042expected_text_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000043NAME
44 test.pydoc_mod - This is a test module for test_pydoc
Georg Brandlb533e262008-05-25 18:19:30 +000045%s
46CLASSES
47 builtins.object
48 A
49 B
Benjamin Petersoned1160b2014-06-07 16:44:00 -070050 C
Georg Brandlb533e262008-05-25 18:19:30 +000051\x20\x20\x20\x20
52 class A(builtins.object)
53 | Hello and goodbye
54 |\x20\x20
55 | Methods defined here:
56 |\x20\x20
57 | __init__()
58 | Wow, I have no function!
59 |\x20\x20
60 | ----------------------------------------------------------------------
61 | Data descriptors defined here:
62 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020063 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000064 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020065 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000066\x20\x20\x20\x20
67 class B(builtins.object)
68 | Data descriptors defined here:
69 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020070 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000071 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020072 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000073 |\x20\x20
74 | ----------------------------------------------------------------------
75 | Data and other attributes defined here:
76 |\x20\x20
77 | NO_MEANING = 'eggs'
Benjamin Petersoned1160b2014-06-07 16:44:00 -070078\x20\x20\x20\x20
79 class C(builtins.object)
80 | Methods defined here:
81 |\x20\x20
82 | get_answer(self)
83 | Return say_no()
84 |\x20\x20
85 | is_it_true(self)
86 | Return self.get_answer()
87 |\x20\x20
88 | say_no(self)
89 |\x20\x20
90 | ----------------------------------------------------------------------
91 | Data descriptors defined here:
92 |\x20\x20
93 | __dict__
94 | dictionary for instance variables (if defined)
95 |\x20\x20
96 | __weakref__
97 | list of weak references to the object (if defined)
Georg Brandlb533e262008-05-25 18:19:30 +000098
99FUNCTIONS
100 doc_func()
101 This function solves all of the world's problems:
102 hunger
103 lack of Python
104 war
105\x20\x20\x20\x20
106 nodoc_func()
107
108DATA
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000109 __xyz__ = 'X, Y and Z'
Georg Brandlb533e262008-05-25 18:19:30 +0000110
111VERSION
112 1.2.3.4
113
114AUTHOR
115 Benjamin Peterson
116
117CREDITS
118 Nobody
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000119
120FILE
121 %s
Georg Brandlb533e262008-05-25 18:19:30 +0000122""".strip()
123
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200124expected_text_data_docstrings = tuple('\n | ' + s if s else ''
125 for s in expected_data_docstrings)
126
Barry Warsaw28a691b2010-04-17 00:19:56 +0000127expected_html_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +0000128<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
129<tr bgcolor="#7799ee">
130<td valign=bottom>&nbsp;<br>
131<font color="#ffffff" face="helvetica, arial">&nbsp;<br><big><big><strong><a href="test.html"><font color="#ffffff">test</font></a>.pydoc_mod</strong></big></big> (version 1.2.3.4)</font></td
132><td align=right valign=bottom
133><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
134 <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
135<p>
136<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
137<tr bgcolor="#ee77aa">
138<td colspan=3 valign=bottom>&nbsp;<br>
139<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
140\x20\x20\x20\x20
141<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
142<td width="100%%"><dl>
143<dt><font face="helvetica, arial"><a href="builtins.html#object">builtins.object</a>
144</font></dt><dd>
145<dl>
146<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
147</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700148</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#C">C</a>
Georg Brandlb533e262008-05-25 18:19:30 +0000149</font></dt></dl>
150</dd>
151</dl>
152 <p>
153<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
154<tr bgcolor="#ffc8d8">
155<td colspan=3 valign=bottom>&nbsp;<br>
156<font color="#000000" face="helvetica, arial"><a name="A">class <strong>A</strong></a>(<a href="builtins.html#object">builtins.object</a>)</font></td></tr>
157\x20\x20\x20\x20
158<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
159<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
160<tr><td>&nbsp;</td>
161<td width="100%%">Methods defined here:<br>
162<dl><dt><a name="A-__init__"><strong>__init__</strong></a>()</dt><dd><tt>Wow,&nbsp;I&nbsp;have&nbsp;no&nbsp;function!</tt></dd></dl>
163
164<hr>
165Data descriptors defined here:<br>
166<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200167<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000168</dl>
169<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200170<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000171</dl>
172</td></tr></table> <p>
173<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
174<tr bgcolor="#ffc8d8">
175<td colspan=3 valign=bottom>&nbsp;<br>
176<font color="#000000" face="helvetica, arial"><a name="B">class <strong>B</strong></a>(<a href="builtins.html#object">builtins.object</a>)</font></td></tr>
177\x20\x20\x20\x20
178<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
179<td width="100%%">Data descriptors defined here:<br>
180<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200181<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000182</dl>
183<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200184<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000185</dl>
186<hr>
187Data and other attributes defined here:<br>
188<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
189
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700190</td></tr></table> <p>
191<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
192<tr bgcolor="#ffc8d8">
193<td colspan=3 valign=bottom>&nbsp;<br>
194<font color="#000000" face="helvetica, arial"><a name="C">class <strong>C</strong></a>(<a href="builtins.html#object">builtins.object</a>)</font></td></tr>
195\x20\x20\x20\x20
196<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
197<td width="100%%">Methods defined here:<br>
198<dl><dt><a name="C-get_answer"><strong>get_answer</strong></a>(self)</dt><dd><tt>Return&nbsp;<a href="#C-say_no">say_no</a>()</tt></dd></dl>
199
200<dl><dt><a name="C-is_it_true"><strong>is_it_true</strong></a>(self)</dt><dd><tt>Return&nbsp;self.<a href="#C-get_answer">get_answer</a>()</tt></dd></dl>
201
202<dl><dt><a name="C-say_no"><strong>say_no</strong></a>(self)</dt></dl>
203
204<hr>
205Data descriptors defined here:<br>
206<dl><dt><strong>__dict__</strong></dt>
207<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
208</dl>
209<dl><dt><strong>__weakref__</strong></dt>
210<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
211</dl>
Georg Brandlb533e262008-05-25 18:19:30 +0000212</td></tr></table></td></tr></table><p>
213<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
214<tr bgcolor="#eeaa77">
215<td colspan=3 valign=bottom>&nbsp;<br>
216<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
217\x20\x20\x20\x20
218<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
219<td width="100%%"><dl><dt><a name="-doc_func"><strong>doc_func</strong></a>()</dt><dd><tt>This&nbsp;function&nbsp;solves&nbsp;all&nbsp;of&nbsp;the&nbsp;world's&nbsp;problems:<br>
220hunger<br>
221lack&nbsp;of&nbsp;Python<br>
222war</tt></dd></dl>
223 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
224</td></tr></table><p>
225<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
226<tr bgcolor="#55aa55">
227<td colspan=3 valign=bottom>&nbsp;<br>
228<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
229\x20\x20\x20\x20
230<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000231<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p>
Georg Brandlb533e262008-05-25 18:19:30 +0000232<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
233<tr bgcolor="#7799ee">
234<td colspan=3 valign=bottom>&nbsp;<br>
235<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
236\x20\x20\x20\x20
237<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
238<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
239<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
240<tr bgcolor="#7799ee">
241<td colspan=3 valign=bottom>&nbsp;<br>
242<font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
243\x20\x20\x20\x20
244<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
245<td width="100%%">Nobody</td></tr></table>
Barry Warsaw28a691b2010-04-17 00:19:56 +0000246""".strip() # ' <- emacs turd
Georg Brandlb533e262008-05-25 18:19:30 +0000247
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200248expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;')
249 for s in expected_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000250
251# output pattern for missing module
252missing_pattern = "no Python documentation found for '%s'"
253
Benjamin Peterson0289b152009-06-28 17:22:03 +0000254# output pattern for module with bad imports
Brett Cannon679ecb52013-07-04 17:51:50 -0400255badimport_pattern = "problem in %s - ImportError: No module named %r"
Benjamin Peterson0289b152009-06-28 17:22:03 +0000256
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700257expected_dynamicattribute_pattern = """
258Help on class DA in module %s:
259
260class DA(builtins.object)
261 | Data descriptors defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200262 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700263 | __dict__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200264 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700265 | __weakref__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200266 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700267 | ham
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200268 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700269 | ----------------------------------------------------------------------
270 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200271 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700272 | ham = 'spam'
273""".strip()
274
275expected_virtualattribute_pattern1 = """
276Help on class Class in module %s:
277
278class Class(builtins.object)
279 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200280 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700281 | LIFE = 42
282""".strip()
283
284expected_virtualattribute_pattern2 = """
285Help on class Class1 in module %s:
286
287class Class1(builtins.object)
288 | Data and other attributes inherited from Meta1:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200289 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700290 | one = 1
291""".strip()
292
293expected_virtualattribute_pattern3 = """
294Help on class Class2 in module %s:
295
296class Class2(Class1)
297 | Method resolution order:
298 | Class2
299 | Class1
300 | builtins.object
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200301 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700302 | Data and other attributes inherited from Meta1:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200303 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700304 | one = 1
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200305 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700306 | ----------------------------------------------------------------------
307 | Data and other attributes inherited from Meta3:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200308 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700309 | three = 3
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200310 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700311 | ----------------------------------------------------------------------
312 | Data and other attributes inherited from Meta2:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200313 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700314 | two = 2
315""".strip()
316
317expected_missingattribute_pattern = """
318Help on class C in module %s:
319
320class C(builtins.object)
321 | Data and other attributes defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200322 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700323 | here = 'present!'
324""".strip()
325
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200326def run_pydoc(module_name, *args, **env):
Georg Brandlb533e262008-05-25 18:19:30 +0000327 """
328 Runs pydoc on the specified module. Returns the stripped
329 output of pydoc.
330 """
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200331 args = args + (module_name,)
Ned Deily92a81a12011-10-06 14:19:03 -0700332 # do not write bytecode files to avoid caching errors
333 rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200334 return out.strip()
Georg Brandlb533e262008-05-25 18:19:30 +0000335
336def get_pydoc_html(module):
337 "Returns pydoc generated output as html"
338 doc = pydoc.HTMLDoc()
339 output = doc.docmodule(module)
340 loc = doc.getdocloc(pydoc_mod) or ""
341 if loc:
342 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
343 return output.strip(), loc
344
345def get_pydoc_text(module):
346 "Returns pydoc generated output as text"
347 doc = pydoc.TextDoc()
348 loc = doc.getdocloc(pydoc_mod) or ""
349 if loc:
350 loc = "\nMODULE DOCS\n " + loc + "\n"
351
352 output = doc.docmodule(module)
353
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000354 # clean up the extra text formatting that pydoc performs
Georg Brandlb533e262008-05-25 18:19:30 +0000355 patt = re.compile('\b.')
356 output = patt.sub('', output)
357 return output.strip(), loc
358
359def print_diffs(text1, text2):
360 "Prints unified diffs for two texts"
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000361 # XXX now obsolete, use unittest built-in support
Ezio Melottid8b509b2011-09-28 17:37:55 +0300362 lines1 = text1.splitlines(keepends=True)
363 lines2 = text2.splitlines(keepends=True)
Georg Brandlb533e262008-05-25 18:19:30 +0000364 diffs = difflib.unified_diff(lines1, lines2, n=0, fromfile='expected',
365 tofile='got')
366 print('\n' + ''.join(diffs))
367
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000368def get_html_title(text):
Nick Coghlanecace282010-12-03 16:08:46 +0000369 # Bit of hack, but good enough for test purposes
370 header, _, _ = text.partition("</head>")
371 _, _, title = header.partition("<title>")
372 title, _, _ = title.partition("</title>")
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000373 return title
374
Georg Brandlb533e262008-05-25 18:19:30 +0000375
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200376class PydocBaseTest(unittest.TestCase):
377
378 def _restricted_walk_packages(self, walk_packages, path=None):
379 """
380 A version of pkgutil.walk_packages() that will restrict itself to
381 a given path.
382 """
383 default_path = path or [os.path.dirname(__file__)]
384 def wrapper(path=None, prefix='', onerror=None):
385 return walk_packages(path or default_path, prefix, onerror)
386 return wrapper
387
388 @contextlib.contextmanager
389 def restrict_walk_packages(self, path=None):
390 walk_packages = pkgutil.walk_packages
391 pkgutil.walk_packages = self._restricted_walk_packages(walk_packages,
392 path)
393 try:
394 yield
395 finally:
396 pkgutil.walk_packages = walk_packages
397
398
Georg Brandld2f38572011-01-30 08:37:19 +0000399class PydocDocTest(unittest.TestCase):
Georg Brandlb533e262008-05-25 18:19:30 +0000400
R. David Murray378c0cf2010-02-24 01:46:21 +0000401 @unittest.skipIf(sys.flags.optimize >= 2,
402 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000403 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
404 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100405 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000406 def test_html_doc(self):
407 result, doc_loc = get_pydoc_html(pydoc_mod)
408 mod_file = inspect.getabsfile(pydoc_mod)
Benjamin Petersonc5e94642008-06-14 23:04:46 +0000409 if sys.platform == 'win32':
410 import nturl2path
411 mod_url = nturl2path.pathname2url(mod_file)
412 else:
413 mod_url = mod_file
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200414 expected_html = expected_html_pattern % (
415 (mod_url, mod_file, doc_loc) +
416 expected_html_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000417 if result != expected_html:
418 print_diffs(expected_html, result)
419 self.fail("outputs are not equal, see diff above")
420
R. David Murray378c0cf2010-02-24 01:46:21 +0000421 @unittest.skipIf(sys.flags.optimize >= 2,
422 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000423 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
424 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100425 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000426 def test_text_doc(self):
427 result, doc_loc = get_pydoc_text(pydoc_mod)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200428 expected_text = expected_text_pattern % (
429 (doc_loc,) +
430 expected_text_data_docstrings +
431 (inspect.getabsfile(pydoc_mod),))
Georg Brandlb533e262008-05-25 18:19:30 +0000432 if result != expected_text:
433 print_diffs(expected_text, result)
434 self.fail("outputs are not equal, see diff above")
435
Serhiy Storchaka056eb022014-02-19 23:05:12 +0200436 def test_text_enum_member_with_value_zero(self):
437 # Test issue #20654 to ensure enum member with value 0 can be
438 # displayed. It used to throw KeyError: 'zero'.
439 import enum
440 class BinaryInteger(enum.IntEnum):
441 zero = 0
442 one = 1
443 doc = pydoc.render_doc(BinaryInteger)
444 self.assertIn('<BinaryInteger.zero: 0>', doc)
445
Brian Curtin49c284c2010-03-31 03:19:28 +0000446 def test_issue8225(self):
447 # Test issue8225 to ensure no doc link appears for xml.etree
448 result, doc_loc = get_pydoc_text(xml.etree)
449 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
450
Benjamin Peterson159824e2014-06-07 20:14:26 -0700451 def test_getpager_with_stdin_none(self):
452 previous_stdin = sys.stdin
453 try:
454 sys.stdin = None
455 pydoc.getpager() # Shouldn't fail.
456 finally:
457 sys.stdin = previous_stdin
458
R David Murrayc43125a2012-04-23 13:23:57 -0400459 def test_non_str_name(self):
460 # issue14638
461 # Treat illegal (non-str) name like no name
462 class A:
463 __name__ = 42
464 class B:
465 pass
466 adoc = pydoc.render_doc(A())
467 bdoc = pydoc.render_doc(B())
468 self.assertEqual(adoc.replace("A", "B"), bdoc)
469
Georg Brandlb533e262008-05-25 18:19:30 +0000470 def test_not_here(self):
471 missing_module = "test.i_am_not_here"
472 result = str(run_pydoc(missing_module), 'ascii')
473 expected = missing_pattern % missing_module
474 self.assertEqual(expected, result,
475 "documentation for missing module found")
476
R. David Murray1f1b9d32009-05-27 20:56:59 +0000477 def test_input_strip(self):
478 missing_module = " test.i_am_not_here "
479 result = str(run_pydoc(missing_module), 'ascii')
480 expected = missing_pattern % missing_module.strip()
481 self.assertEqual(expected, result)
482
Ezio Melotti412c95a2010-02-16 23:31:04 +0000483 def test_stripid(self):
484 # test with strings, other implementations might have different repr()
485 stripid = pydoc.stripid
486 # strip the id
487 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
488 '<function stripid>')
489 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
490 '<function stripid>')
491 # nothing to strip, return the same text
492 self.assertEqual(stripid('42'), '42')
493 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
494 "<type 'exceptions.Exception'>")
495
Georg Brandld80d5f42010-12-03 07:47:22 +0000496 @unittest.skipIf(sys.flags.optimize >= 2,
497 'Docstrings are omitted with -O2 and above')
Brett Cannon7a540732011-02-22 03:04:06 +0000498 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
499 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100500 @requires_docstrings
Georg Brandld80d5f42010-12-03 07:47:22 +0000501 def test_help_output_redirect(self):
502 # issue 940286, if output is set in Helper, then all output from
503 # Helper.help should be redirected
504 old_pattern = expected_text_pattern
505 getpager_old = pydoc.getpager
506 getpager_new = lambda: (lambda x: x)
507 self.maxDiff = None
508
509 buf = StringIO()
510 helper = pydoc.Helper(output=buf)
511 unused, doc_loc = get_pydoc_text(pydoc_mod)
512 module = "test.pydoc_mod"
513 help_header = """
514 Help on module test.pydoc_mod in test:
515
516 """.lstrip()
517 help_header = textwrap.dedent(help_header)
518 expected_help_pattern = help_header + expected_text_pattern
519
520 pydoc.getpager = getpager_new
521 try:
522 with captured_output('stdout') as output, \
523 captured_output('stderr') as err:
524 helper.help(module)
525 result = buf.getvalue().strip()
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200526 expected_text = expected_help_pattern % (
527 (doc_loc,) +
528 expected_text_data_docstrings +
529 (inspect.getabsfile(pydoc_mod),))
Georg Brandld80d5f42010-12-03 07:47:22 +0000530 self.assertEqual('', output.getvalue())
531 self.assertEqual('', err.getvalue())
532 self.assertEqual(expected_text, result)
533 finally:
534 pydoc.getpager = getpager_old
535
Raymond Hettinger1103d052011-03-25 14:15:24 -0700536 def test_namedtuple_public_underscore(self):
537 NT = namedtuple('NT', ['abc', 'def'], rename=True)
538 with captured_stdout() as help_io:
Terry Jan Reedy5c811642013-11-04 21:43:26 -0500539 pydoc.help(NT)
Raymond Hettinger1103d052011-03-25 14:15:24 -0700540 helptext = help_io.getvalue()
541 self.assertIn('_1', helptext)
542 self.assertIn('_replace', helptext)
543 self.assertIn('_asdict', helptext)
544
Victor Stinnere6c910e2011-06-30 15:55:43 +0200545 def test_synopsis(self):
546 self.addCleanup(unlink, TESTFN)
547 for encoding in ('ISO-8859-1', 'UTF-8'):
548 with open(TESTFN, 'w', encoding=encoding) as script:
549 if encoding != 'UTF-8':
550 print('#coding: {}'.format(encoding), file=script)
551 print('"""line 1: h\xe9', file=script)
552 print('line 2: hi"""', file=script)
553 synopsis = pydoc.synopsis(TESTFN, {})
554 self.assertEqual(synopsis, 'line 1: h\xe9')
555
Eric Snowaed5b222014-01-04 20:38:11 -0700556 def test_synopsis_sourceless(self):
557 expected = os.__doc__.splitlines()[0]
558 filename = os.__cached__
559 synopsis = pydoc.synopsis(filename)
560
561 self.assertEqual(synopsis, expected)
562
R David Murray455f2962013-03-19 00:00:33 -0400563 def test_splitdoc_with_description(self):
564 example_string = "I Am A Doc\n\n\nHere is my description"
565 self.assertEqual(pydoc.splitdoc(example_string),
566 ('I Am A Doc', '\nHere is my description'))
567
568 def test_is_object_or_method(self):
569 doc = pydoc.Doc()
570 # Bound Method
571 self.assertTrue(pydoc._is_some_method(doc.fail))
572 # Method Descriptor
573 self.assertTrue(pydoc._is_some_method(int.__add__))
574 # String
575 self.assertFalse(pydoc._is_some_method("I am not a method"))
576
577 def test_is_package_when_not_package(self):
578 with test.support.temp_cwd() as test_dir:
579 self.assertFalse(pydoc.ispackage(test_dir))
580
581 def test_is_package_when_is_package(self):
582 with test.support.temp_cwd() as test_dir:
583 init_path = os.path.join(test_dir, '__init__.py')
584 open(init_path, 'w').close()
585 self.assertTrue(pydoc.ispackage(test_dir))
586 os.remove(init_path)
587
R David Murrayac0cea52013-03-19 02:47:44 -0400588 def test_allmethods(self):
589 # issue 17476: allmethods was no longer returning unbound methods.
590 # This test is a bit fragile in the face of changes to object and type,
591 # but I can't think of a better way to do it without duplicating the
592 # logic of the function under test.
593
594 class TestClass(object):
595 def method_returning_true(self):
596 return True
597
598 # What we expect to get back: everything on object...
599 expected = dict(vars(object))
600 # ...plus our unbound method...
601 expected['method_returning_true'] = TestClass.method_returning_true
602 # ...but not the non-methods on object.
603 del expected['__doc__']
604 del expected['__class__']
605 # inspect resolves descriptors on type into methods, but vars doesn't,
606 # so we need to update __subclasshook__.
607 expected['__subclasshook__'] = TestClass.__subclasshook__
608
609 methods = pydoc.allmethods(TestClass)
610 self.assertDictEqual(methods, expected)
611
Georg Brandlb533e262008-05-25 18:19:30 +0000612
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200613class PydocImportTest(PydocBaseTest):
Ned Deily92a81a12011-10-06 14:19:03 -0700614
615 def setUp(self):
616 self.test_dir = os.mkdir(TESTFN)
617 self.addCleanup(rmtree, TESTFN)
618
619 def test_badimport(self):
620 # This tests the fix for issue 5230, where if pydoc found the module
621 # but the module had an internal import error pydoc would report no doc
622 # found.
623 modname = 'testmod_xyzzy'
624 testpairs = (
625 ('i_am_not_here', 'i_am_not_here'),
Brett Cannonfd074152012-04-14 14:10:13 -0400626 ('test.i_am_not_here_either', 'test.i_am_not_here_either'),
627 ('test.i_am_not_here.neither_am_i', 'test.i_am_not_here'),
628 ('i_am_not_here.{}'.format(modname), 'i_am_not_here'),
629 ('test.{}'.format(modname), 'test.{}'.format(modname)),
Ned Deily92a81a12011-10-06 14:19:03 -0700630 )
631
632 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
633 for importstring, expectedinmsg in testpairs:
634 with open(sourcefn, 'w') as f:
635 f.write("import {}\n".format(importstring))
636 result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii")
637 expected = badimport_pattern % (modname, expectedinmsg)
638 self.assertEqual(expected, result)
639
640 def test_apropos_with_bad_package(self):
641 # Issue 7425 - pydoc -k failed when bad package on path
642 pkgdir = os.path.join(TESTFN, "syntaxerr")
643 os.mkdir(pkgdir)
644 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
645 with open(badsyntax, 'w') as f:
646 f.write("invalid python syntax = $1\n")
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200647 with self.restrict_walk_packages(path=[TESTFN]):
648 with captured_stdout() as out:
649 with captured_stderr() as err:
650 pydoc.apropos('xyzzy')
651 # No result, no error
652 self.assertEqual(out.getvalue(), '')
653 self.assertEqual(err.getvalue(), '')
654 # The package name is still matched
655 with captured_stdout() as out:
656 with captured_stderr() as err:
657 pydoc.apropos('syntaxerr')
658 self.assertEqual(out.getvalue().strip(), 'syntaxerr')
659 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700660
661 def test_apropos_with_unreadable_dir(self):
662 # Issue 7367 - pydoc -k failed when unreadable dir on path
663 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
664 os.mkdir(self.unreadable_dir, 0)
665 self.addCleanup(os.rmdir, self.unreadable_dir)
666 # Note, on Windows the directory appears to be still
667 # readable so this is not really testing the issue there
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200668 with self.restrict_walk_packages(path=[TESTFN]):
669 with captured_stdout() as out:
670 with captured_stderr() as err:
671 pydoc.apropos('SOMEKEY')
672 # No result, no error
673 self.assertEqual(out.getvalue(), '')
674 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700675
Eric Snowa46ef702014-02-22 13:57:08 -0700676 @unittest.skip('causes undesireable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700677 def test_modules(self):
678 # See Helper.listmodules().
679 num_header_lines = 2
680 num_module_lines_min = 5 # Playing it safe.
681 num_footer_lines = 3
682 expected = num_header_lines + num_module_lines_min + num_footer_lines
683
684 output = StringIO()
685 helper = pydoc.Helper(output=output)
686 helper('modules')
687 result = output.getvalue().strip()
688 num_lines = len(result.splitlines())
689
690 self.assertGreaterEqual(num_lines, expected)
691
Eric Snowa46ef702014-02-22 13:57:08 -0700692 @unittest.skip('causes undesireable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700693 def test_modules_search(self):
694 # See Helper.listmodules().
695 expected = 'pydoc - '
696
697 output = StringIO()
698 helper = pydoc.Helper(output=output)
699 with captured_stdout() as help_io:
700 helper('modules pydoc')
701 result = help_io.getvalue()
702
703 self.assertIn(expected, result)
704
Eric Snowa46ef702014-02-22 13:57:08 -0700705 @unittest.skip('some buildbots are not cooperating (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700706 def test_modules_search_builtin(self):
Eric Snow5ea97502014-01-04 23:04:27 -0700707 expected = 'gc - '
Eric Snowaed5b222014-01-04 20:38:11 -0700708
709 output = StringIO()
710 helper = pydoc.Helper(output=output)
711 with captured_stdout() as help_io:
Eric Snow5ea97502014-01-04 23:04:27 -0700712 helper('modules garbage')
Eric Snowaed5b222014-01-04 20:38:11 -0700713 result = help_io.getvalue()
714
715 self.assertTrue(result.startswith(expected))
716
717 def test_importfile(self):
718 loaded_pydoc = pydoc.importfile(pydoc.__file__)
719
Eric Snow3a62d142014-01-06 20:42:59 -0700720 self.assertIsNot(loaded_pydoc, pydoc)
Eric Snowaed5b222014-01-04 20:38:11 -0700721 self.assertEqual(loaded_pydoc.__name__, 'pydoc')
722 self.assertEqual(loaded_pydoc.__file__, pydoc.__file__)
Eric Snow3a62d142014-01-06 20:42:59 -0700723 self.assertEqual(loaded_pydoc.__spec__, pydoc.__spec__)
Eric Snowaed5b222014-01-04 20:38:11 -0700724
Ned Deily92a81a12011-10-06 14:19:03 -0700725
Georg Brandlb533e262008-05-25 18:19:30 +0000726class TestDescriptions(unittest.TestCase):
727
728 def test_module(self):
729 # Check that pydocfodder module can be described
730 from test import pydocfodder
731 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000732 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000733
Georg Brandlb533e262008-05-25 18:19:30 +0000734 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000735 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +0000736 c = C()
737
738 self.assertEqual(pydoc.describe(C), 'class C')
739 self.assertEqual(pydoc.describe(c), 'C')
740 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000741 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000742
Éric Araujoe64e51b2011-07-29 17:03:55 +0200743 def test_builtin(self):
744 for name in ('str', 'str.translate', 'builtins.str',
745 'builtins.str.translate'):
746 # test low-level function
747 self.assertIsNotNone(pydoc.locate(name))
748 # test high-level function
749 try:
750 pydoc.render_doc(name)
751 except ImportError:
Terry Jan Reedyfe928de2014-06-20 14:59:11 -0400752 self.fail('finding the doc of {!r} failed'.format(name))
Éric Araujoe64e51b2011-07-29 17:03:55 +0200753
754 for name in ('notbuiltins', 'strrr', 'strr.translate',
755 'str.trrrranslate', 'builtins.strrr',
756 'builtins.str.trrranslate'):
757 self.assertIsNone(pydoc.locate(name))
758 self.assertRaises(ImportError, pydoc.render_doc, name)
759
Larry Hastings24a882b2014-02-20 23:34:46 -0800760 @staticmethod
761 def _get_summary_line(o):
762 text = pydoc.plain(pydoc.render_doc(o))
763 lines = text.split('\n')
764 assert len(lines) >= 2
765 return lines[2]
766
767 # these should include "self"
768 def test_unbound_python_method(self):
769 self.assertEqual(self._get_summary_line(textwrap.TextWrapper.wrap),
770 "wrap(self, text)")
771
Stefan Krah5de32782014-01-18 23:18:39 +0100772 @requires_docstrings
Larry Hastings24a882b2014-02-20 23:34:46 -0800773 def test_unbound_builtin_method(self):
774 self.assertEqual(self._get_summary_line(_pickle.Pickler.dump),
775 "dump(self, obj, /)")
776
777 # these no longer include "self"
778 def test_bound_python_method(self):
779 t = textwrap.TextWrapper()
780 self.assertEqual(self._get_summary_line(t.wrap),
781 "wrap(text) method of textwrap.TextWrapper instance")
782
783 @requires_docstrings
784 def test_bound_builtin_method(self):
785 s = StringIO()
786 p = _pickle.Pickler(s)
787 self.assertEqual(self._get_summary_line(p.dump),
788 "dump(obj, /) method of _pickle.Pickler instance")
789
790 # this should *never* include self!
791 @requires_docstrings
792 def test_module_level_callable(self):
793 self.assertEqual(self._get_summary_line(os.stat),
794 "stat(path, *, dir_fd=None, follow_symlinks=True)")
Larry Hastings1abd7082014-01-16 14:15:03 -0800795
Georg Brandlb533e262008-05-25 18:19:30 +0000796
Victor Stinner62a68f22011-05-20 02:29:13 +0200797@unittest.skipUnless(threading, 'Threading required for this test.')
Georg Brandld2f38572011-01-30 08:37:19 +0000798class PydocServerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000799 """Tests for pydoc._start_server"""
800
801 def test_server(self):
802
803 # Minimal test that starts the server, then stops it.
804 def my_url_handler(url, content_type):
805 text = 'the URL sent was: (%s, %s)' % (url, content_type)
806 return text
807
808 serverthread = pydoc._start_server(my_url_handler, port=0)
809 starttime = time.time()
810 timeout = 1 #seconds
811
812 while serverthread.serving:
813 time.sleep(.01)
814 if serverthread.serving and time.time() - starttime > timeout:
815 serverthread.stop()
816 break
817
818 self.assertEqual(serverthread.error, None)
819
820
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200821class PydocUrlHandlerTest(PydocBaseTest):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000822 """Tests for pydoc._url_handler"""
823
824 def test_content_type_err(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000825 f = pydoc._url_handler
Georg Brandld2f38572011-01-30 08:37:19 +0000826 self.assertRaises(TypeError, f, 'A', '')
827 self.assertRaises(TypeError, f, 'B', 'foobar')
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000828
829 def test_url_requests(self):
830 # Test for the correct title in the html pages returned.
831 # This tests the different parts of the URL handler without
832 # getting too picky about the exact html.
833 requests = [
Georg Brandld2f38572011-01-30 08:37:19 +0000834 ("", "Pydoc: Index of Modules"),
835 ("get?key=", "Pydoc: Index of Modules"),
836 ("index", "Pydoc: Index of Modules"),
837 ("topics", "Pydoc: Topics"),
838 ("keywords", "Pydoc: Keywords"),
839 ("pydoc", "Pydoc: module pydoc"),
840 ("get?key=pydoc", "Pydoc: module pydoc"),
841 ("search?key=pydoc", "Pydoc: Search Results"),
842 ("topic?key=def", "Pydoc: KEYWORD def"),
843 ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
844 ("foobar", "Pydoc: Error - foobar"),
845 ("getfile?key=foobar", "Pydoc: Error - getfile?key=foobar"),
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000846 ]
847
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200848 with self.restrict_walk_packages():
849 for url, title in requests:
850 text = pydoc._url_handler(url, "text/html")
851 result = get_html_title(text)
852 self.assertEqual(result, title, text)
853
854 path = string.__file__
855 title = "Pydoc: getfile " + path
856 url = "getfile?key=" + path
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000857 text = pydoc._url_handler(url, "text/html")
858 result = get_html_title(text)
859 self.assertEqual(result, title)
860
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000861
Ezio Melottib185a042011-04-28 07:42:55 +0300862class TestHelper(unittest.TestCase):
863 def test_keywords(self):
864 self.assertEqual(sorted(pydoc.Helper.keywords),
865 sorted(keyword.kwlist))
866
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700867class PydocWithMetaClasses(unittest.TestCase):
Ethan Furman3f2f1922013-10-22 07:30:24 -0700868 @unittest.skipIf(sys.flags.optimize >= 2,
869 "Docstrings are omitted with -O2 and above")
870 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
871 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700872 def test_DynamicClassAttribute(self):
873 class Meta(type):
874 def __getattr__(self, name):
875 if name == 'ham':
876 return 'spam'
877 return super().__getattr__(name)
878 class DA(metaclass=Meta):
879 @types.DynamicClassAttribute
880 def ham(self):
881 return 'eggs'
Ethan Furman3f2f1922013-10-22 07:30:24 -0700882 expected_text_data_docstrings = tuple('\n | ' + s if s else ''
883 for s in expected_data_docstrings)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700884 output = StringIO()
885 helper = pydoc.Helper(output=output)
886 helper(DA)
Ethan Furman3f2f1922013-10-22 07:30:24 -0700887 expected_text = expected_dynamicattribute_pattern % (
888 (__name__,) + expected_text_data_docstrings[:2])
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700889 result = output.getvalue().strip()
890 if result != expected_text:
891 print_diffs(expected_text, result)
892 self.fail("outputs are not equal, see diff above")
893
Ethan Furman3f2f1922013-10-22 07:30:24 -0700894 @unittest.skipIf(sys.flags.optimize >= 2,
895 "Docstrings are omitted with -O2 and above")
896 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
897 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700898 def test_virtualClassAttributeWithOneMeta(self):
899 class Meta(type):
900 def __dir__(cls):
901 return ['__class__', '__module__', '__name__', 'LIFE']
902 def __getattr__(self, name):
903 if name =='LIFE':
904 return 42
905 return super().__getattr(name)
906 class Class(metaclass=Meta):
907 pass
908 output = StringIO()
909 helper = pydoc.Helper(output=output)
910 helper(Class)
911 expected_text = expected_virtualattribute_pattern1 % __name__
912 result = output.getvalue().strip()
913 if result != expected_text:
914 print_diffs(expected_text, result)
915 self.fail("outputs are not equal, see diff above")
916
Ethan Furman3f2f1922013-10-22 07:30:24 -0700917 @unittest.skipIf(sys.flags.optimize >= 2,
918 "Docstrings are omitted with -O2 and above")
919 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
920 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700921 def test_virtualClassAttributeWithTwoMeta(self):
922 class Meta1(type):
923 def __dir__(cls):
924 return ['__class__', '__module__', '__name__', 'one']
925 def __getattr__(self, name):
926 if name =='one':
927 return 1
928 return super().__getattr__(name)
929 class Meta2(type):
930 def __dir__(cls):
931 return ['__class__', '__module__', '__name__', 'two']
932 def __getattr__(self, name):
933 if name =='two':
934 return 2
935 return super().__getattr__(name)
936 class Meta3(Meta1, Meta2):
937 def __dir__(cls):
938 return list(sorted(set(
939 ['__class__', '__module__', '__name__', 'three'] +
940 Meta1.__dir__(cls) + Meta2.__dir__(cls))))
941 def __getattr__(self, name):
942 if name =='three':
943 return 3
944 return super().__getattr__(name)
945 class Class1(metaclass=Meta1):
946 pass
947 class Class2(Class1, metaclass=Meta3):
948 pass
949 fail1 = fail2 = False
950 output = StringIO()
951 helper = pydoc.Helper(output=output)
952 helper(Class1)
953 expected_text1 = expected_virtualattribute_pattern2 % __name__
954 result1 = output.getvalue().strip()
955 if result1 != expected_text1:
956 print_diffs(expected_text1, result1)
957 fail1 = True
958 output = StringIO()
959 helper = pydoc.Helper(output=output)
960 helper(Class2)
961 expected_text2 = expected_virtualattribute_pattern3 % __name__
962 result2 = output.getvalue().strip()
963 if result2 != expected_text2:
964 print_diffs(expected_text2, result2)
965 fail2 = True
966 if fail1 or fail2:
967 self.fail("outputs are not equal, see diff above")
968
Ethan Furman3f2f1922013-10-22 07:30:24 -0700969 @unittest.skipIf(sys.flags.optimize >= 2,
970 "Docstrings are omitted with -O2 and above")
971 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
972 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700973 def test_buggy_dir(self):
974 class M(type):
975 def __dir__(cls):
976 return ['__class__', '__name__', 'missing', 'here']
977 class C(metaclass=M):
978 here = 'present!'
979 output = StringIO()
980 helper = pydoc.Helper(output=output)
981 helper(C)
982 expected_text = expected_missingattribute_pattern % __name__
983 result = output.getvalue().strip()
984 if result != expected_text:
985 print_diffs(expected_text, result)
986 self.fail("outputs are not equal, see diff above")
987
Eric Snowaed5b222014-01-04 20:38:11 -0700988
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200989@reap_threads
Georg Brandlb533e262008-05-25 18:19:30 +0000990def test_main():
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200991 try:
992 test.support.run_unittest(PydocDocTest,
Ned Deily92a81a12011-10-06 14:19:03 -0700993 PydocImportTest,
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200994 TestDescriptions,
995 PydocServerTest,
996 PydocUrlHandlerTest,
997 TestHelper,
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700998 PydocWithMetaClasses,
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200999 )
1000 finally:
1001 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +00001002
1003if __name__ == "__main__":
1004 test_main()