blob: 8bf9b20ce91bf957abeddd822fd6295c6639c98c [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
Zachary Wareeb432142014-07-10 11:18:00 -050017import urllib.parse
Brian Curtin49c284c2010-03-31 03:19:28 +000018import xml.etree
Georg Brandld80d5f42010-12-03 07:47:22 +000019import textwrap
20from io import StringIO
Raymond Hettinger1103d052011-03-25 14:15:24 -070021from collections import namedtuple
Antoine Pitrouf7f54752011-07-15 22:42:12 +020022from test.script_helper import assert_python_ok
Antoine Pitroua6e81a22011-07-15 22:32:25 +020023from test.support import (
Ned Deily92a81a12011-10-06 14:19:03 -070024 TESTFN, rmtree,
Antoine Pitrou916fc7b2013-05-19 15:44:54 +020025 reap_children, reap_threads, captured_output, captured_stdout,
Stefan Krah5de32782014-01-18 23:18:39 +010026 captured_stderr, unlink, requires_docstrings
Antoine Pitroua6e81a22011-07-15 22:32:25 +020027)
Georg Brandlb533e262008-05-25 18:19:30 +000028from test import pydoc_mod
29
Victor Stinner62a68f22011-05-20 02:29:13 +020030try:
31 import threading
32except ImportError:
33 threading = None
34
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020035if test.support.HAVE_DOCSTRINGS:
36 expected_data_docstrings = (
37 'dictionary for instance variables (if defined)',
38 'list of weak references to the object (if defined)',
39 ) * 2
40else:
41 expected_data_docstrings = ('', '', '', '')
42
Barry Warsaw28a691b2010-04-17 00:19:56 +000043expected_text_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000044NAME
45 test.pydoc_mod - This is a test module for test_pydoc
Georg Brandlb533e262008-05-25 18:19:30 +000046%s
47CLASSES
48 builtins.object
49 A
50 B
Benjamin Petersoned1160b2014-06-07 16:44:00 -070051 C
Georg Brandlb533e262008-05-25 18:19:30 +000052\x20\x20\x20\x20
53 class A(builtins.object)
54 | Hello and goodbye
55 |\x20\x20
56 | Methods defined here:
57 |\x20\x20
58 | __init__()
59 | Wow, I have no function!
60 |\x20\x20
61 | ----------------------------------------------------------------------
62 | Data descriptors defined here:
63 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020064 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000065 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020066 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000067\x20\x20\x20\x20
68 class B(builtins.object)
69 | Data descriptors defined here:
70 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020071 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000072 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020073 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000074 |\x20\x20
75 | ----------------------------------------------------------------------
76 | Data and other attributes defined here:
77 |\x20\x20
78 | NO_MEANING = 'eggs'
Benjamin Petersoned1160b2014-06-07 16:44:00 -070079\x20\x20\x20\x20
80 class C(builtins.object)
81 | Methods defined here:
82 |\x20\x20
83 | get_answer(self)
84 | Return say_no()
85 |\x20\x20
86 | is_it_true(self)
87 | Return self.get_answer()
88 |\x20\x20
89 | say_no(self)
90 |\x20\x20
91 | ----------------------------------------------------------------------
92 | Data descriptors defined here:
93 |\x20\x20
94 | __dict__
95 | dictionary for instance variables (if defined)
96 |\x20\x20
97 | __weakref__
98 | list of weak references to the object (if defined)
Georg Brandlb533e262008-05-25 18:19:30 +000099
100FUNCTIONS
101 doc_func()
102 This function solves all of the world's problems:
103 hunger
104 lack of Python
105 war
106\x20\x20\x20\x20
107 nodoc_func()
108
109DATA
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000110 __xyz__ = 'X, Y and Z'
Georg Brandlb533e262008-05-25 18:19:30 +0000111
112VERSION
113 1.2.3.4
114
115AUTHOR
116 Benjamin Peterson
117
118CREDITS
119 Nobody
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000120
121FILE
122 %s
Georg Brandlb533e262008-05-25 18:19:30 +0000123""".strip()
124
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200125expected_text_data_docstrings = tuple('\n | ' + s if s else ''
126 for s in expected_data_docstrings)
127
Barry Warsaw28a691b2010-04-17 00:19:56 +0000128expected_html_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +0000129<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
130<tr bgcolor="#7799ee">
131<td valign=bottom>&nbsp;<br>
132<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
133><td align=right valign=bottom
134><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
135 <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
136<p>
137<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
138<tr bgcolor="#ee77aa">
139<td colspan=3 valign=bottom>&nbsp;<br>
140<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
141\x20\x20\x20\x20
142<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
143<td width="100%%"><dl>
144<dt><font face="helvetica, arial"><a href="builtins.html#object">builtins.object</a>
145</font></dt><dd>
146<dl>
147<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
148</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700149</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#C">C</a>
Georg Brandlb533e262008-05-25 18:19:30 +0000150</font></dt></dl>
151</dd>
152</dl>
153 <p>
154<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
155<tr bgcolor="#ffc8d8">
156<td colspan=3 valign=bottom>&nbsp;<br>
157<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>
158\x20\x20\x20\x20
159<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
160<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
161<tr><td>&nbsp;</td>
162<td width="100%%">Methods defined here:<br>
163<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>
164
165<hr>
166Data descriptors defined here:<br>
167<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200168<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000169</dl>
170<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200171<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000172</dl>
173</td></tr></table> <p>
174<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
175<tr bgcolor="#ffc8d8">
176<td colspan=3 valign=bottom>&nbsp;<br>
177<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>
178\x20\x20\x20\x20
179<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
180<td width="100%%">Data descriptors defined here:<br>
181<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200182<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000183</dl>
184<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200185<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000186</dl>
187<hr>
188Data and other attributes defined here:<br>
189<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
190
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700191</td></tr></table> <p>
192<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
193<tr bgcolor="#ffc8d8">
194<td colspan=3 valign=bottom>&nbsp;<br>
195<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>
196\x20\x20\x20\x20
197<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
198<td width="100%%">Methods defined here:<br>
199<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>
200
201<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>
202
203<dl><dt><a name="C-say_no"><strong>say_no</strong></a>(self)</dt></dl>
204
205<hr>
206Data descriptors defined here:<br>
207<dl><dt><strong>__dict__</strong></dt>
208<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
209</dl>
210<dl><dt><strong>__weakref__</strong></dt>
211<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
212</dl>
Georg Brandlb533e262008-05-25 18:19:30 +0000213</td></tr></table></td></tr></table><p>
214<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
215<tr bgcolor="#eeaa77">
216<td colspan=3 valign=bottom>&nbsp;<br>
217<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
218\x20\x20\x20\x20
219<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
220<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>
221hunger<br>
222lack&nbsp;of&nbsp;Python<br>
223war</tt></dd></dl>
224 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
225</td></tr></table><p>
226<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
227<tr bgcolor="#55aa55">
228<td colspan=3 valign=bottom>&nbsp;<br>
229<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
230\x20\x20\x20\x20
231<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000232<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p>
Georg Brandlb533e262008-05-25 18:19:30 +0000233<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
234<tr bgcolor="#7799ee">
235<td colspan=3 valign=bottom>&nbsp;<br>
236<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
237\x20\x20\x20\x20
238<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
239<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
240<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
241<tr bgcolor="#7799ee">
242<td colspan=3 valign=bottom>&nbsp;<br>
243<font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
244\x20\x20\x20\x20
245<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
246<td width="100%%">Nobody</td></tr></table>
Barry Warsaw28a691b2010-04-17 00:19:56 +0000247""".strip() # ' <- emacs turd
Georg Brandlb533e262008-05-25 18:19:30 +0000248
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200249expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;')
250 for s in expected_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000251
252# output pattern for missing module
253missing_pattern = "no Python documentation found for '%s'"
254
Benjamin Peterson0289b152009-06-28 17:22:03 +0000255# output pattern for module with bad imports
Brett Cannon679ecb52013-07-04 17:51:50 -0400256badimport_pattern = "problem in %s - ImportError: No module named %r"
Benjamin Peterson0289b152009-06-28 17:22:03 +0000257
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700258expected_dynamicattribute_pattern = """
259Help on class DA in module %s:
260
261class DA(builtins.object)
262 | Data descriptors defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200263 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700264 | __dict__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200265 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700266 | __weakref__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200267 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700268 | ham
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200269 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700270 | ----------------------------------------------------------------------
271 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200272 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700273 | ham = 'spam'
274""".strip()
275
276expected_virtualattribute_pattern1 = """
277Help on class Class in module %s:
278
279class Class(builtins.object)
280 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200281 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700282 | LIFE = 42
283""".strip()
284
285expected_virtualattribute_pattern2 = """
286Help on class Class1 in module %s:
287
288class Class1(builtins.object)
289 | Data and other attributes inherited from Meta1:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200290 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700291 | one = 1
292""".strip()
293
294expected_virtualattribute_pattern3 = """
295Help on class Class2 in module %s:
296
297class Class2(Class1)
298 | Method resolution order:
299 | Class2
300 | Class1
301 | builtins.object
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200302 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700303 | Data and other attributes inherited from Meta1:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200304 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700305 | one = 1
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200306 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700307 | ----------------------------------------------------------------------
308 | Data and other attributes inherited from Meta3:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200309 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700310 | three = 3
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200311 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700312 | ----------------------------------------------------------------------
313 | Data and other attributes inherited from Meta2:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200314 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700315 | two = 2
316""".strip()
317
318expected_missingattribute_pattern = """
319Help on class C in module %s:
320
321class C(builtins.object)
322 | Data and other attributes defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200323 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700324 | here = 'present!'
325""".strip()
326
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200327def run_pydoc(module_name, *args, **env):
Georg Brandlb533e262008-05-25 18:19:30 +0000328 """
329 Runs pydoc on the specified module. Returns the stripped
330 output of pydoc.
331 """
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200332 args = args + (module_name,)
Ned Deily92a81a12011-10-06 14:19:03 -0700333 # do not write bytecode files to avoid caching errors
334 rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200335 return out.strip()
Georg Brandlb533e262008-05-25 18:19:30 +0000336
337def get_pydoc_html(module):
338 "Returns pydoc generated output as html"
339 doc = pydoc.HTMLDoc()
340 output = doc.docmodule(module)
341 loc = doc.getdocloc(pydoc_mod) or ""
342 if loc:
343 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
344 return output.strip(), loc
345
346def get_pydoc_text(module):
347 "Returns pydoc generated output as text"
348 doc = pydoc.TextDoc()
349 loc = doc.getdocloc(pydoc_mod) or ""
350 if loc:
351 loc = "\nMODULE DOCS\n " + loc + "\n"
352
353 output = doc.docmodule(module)
354
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000355 # clean up the extra text formatting that pydoc performs
Georg Brandlb533e262008-05-25 18:19:30 +0000356 patt = re.compile('\b.')
357 output = patt.sub('', output)
358 return output.strip(), loc
359
360def print_diffs(text1, text2):
361 "Prints unified diffs for two texts"
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000362 # XXX now obsolete, use unittest built-in support
Ezio Melottid8b509b2011-09-28 17:37:55 +0300363 lines1 = text1.splitlines(keepends=True)
364 lines2 = text2.splitlines(keepends=True)
Georg Brandlb533e262008-05-25 18:19:30 +0000365 diffs = difflib.unified_diff(lines1, lines2, n=0, fromfile='expected',
366 tofile='got')
367 print('\n' + ''.join(diffs))
368
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000369def get_html_title(text):
Nick Coghlanecace282010-12-03 16:08:46 +0000370 # Bit of hack, but good enough for test purposes
371 header, _, _ = text.partition("</head>")
372 _, _, title = header.partition("<title>")
373 title, _, _ = title.partition("</title>")
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000374 return title
375
Georg Brandlb533e262008-05-25 18:19:30 +0000376
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200377class PydocBaseTest(unittest.TestCase):
378
379 def _restricted_walk_packages(self, walk_packages, path=None):
380 """
381 A version of pkgutil.walk_packages() that will restrict itself to
382 a given path.
383 """
384 default_path = path or [os.path.dirname(__file__)]
385 def wrapper(path=None, prefix='', onerror=None):
386 return walk_packages(path or default_path, prefix, onerror)
387 return wrapper
388
389 @contextlib.contextmanager
390 def restrict_walk_packages(self, path=None):
391 walk_packages = pkgutil.walk_packages
392 pkgutil.walk_packages = self._restricted_walk_packages(walk_packages,
393 path)
394 try:
395 yield
396 finally:
397 pkgutil.walk_packages = walk_packages
398
399
Georg Brandld2f38572011-01-30 08:37:19 +0000400class PydocDocTest(unittest.TestCase):
Georg Brandlb533e262008-05-25 18:19:30 +0000401
R. David Murray378c0cf2010-02-24 01:46:21 +0000402 @unittest.skipIf(sys.flags.optimize >= 2,
403 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000404 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
405 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100406 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000407 def test_html_doc(self):
408 result, doc_loc = get_pydoc_html(pydoc_mod)
409 mod_file = inspect.getabsfile(pydoc_mod)
Zachary Wareeb432142014-07-10 11:18:00 -0500410 mod_url = urllib.parse.quote(mod_file)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200411 expected_html = expected_html_pattern % (
412 (mod_url, mod_file, doc_loc) +
413 expected_html_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000414 if result != expected_html:
415 print_diffs(expected_html, result)
416 self.fail("outputs are not equal, see diff above")
417
R. David Murray378c0cf2010-02-24 01:46:21 +0000418 @unittest.skipIf(sys.flags.optimize >= 2,
419 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000420 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
421 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100422 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000423 def test_text_doc(self):
424 result, doc_loc = get_pydoc_text(pydoc_mod)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200425 expected_text = expected_text_pattern % (
426 (doc_loc,) +
427 expected_text_data_docstrings +
428 (inspect.getabsfile(pydoc_mod),))
Georg Brandlb533e262008-05-25 18:19:30 +0000429 if result != expected_text:
430 print_diffs(expected_text, result)
431 self.fail("outputs are not equal, see diff above")
432
Serhiy Storchaka056eb022014-02-19 23:05:12 +0200433 def test_text_enum_member_with_value_zero(self):
434 # Test issue #20654 to ensure enum member with value 0 can be
435 # displayed. It used to throw KeyError: 'zero'.
436 import enum
437 class BinaryInteger(enum.IntEnum):
438 zero = 0
439 one = 1
440 doc = pydoc.render_doc(BinaryInteger)
441 self.assertIn('<BinaryInteger.zero: 0>', doc)
442
Brian Curtin49c284c2010-03-31 03:19:28 +0000443 def test_issue8225(self):
444 # Test issue8225 to ensure no doc link appears for xml.etree
445 result, doc_loc = get_pydoc_text(xml.etree)
446 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
447
Benjamin Peterson159824e2014-06-07 20:14:26 -0700448 def test_getpager_with_stdin_none(self):
449 previous_stdin = sys.stdin
450 try:
451 sys.stdin = None
452 pydoc.getpager() # Shouldn't fail.
453 finally:
454 sys.stdin = previous_stdin
455
R David Murrayc43125a2012-04-23 13:23:57 -0400456 def test_non_str_name(self):
457 # issue14638
458 # Treat illegal (non-str) name like no name
459 class A:
460 __name__ = 42
461 class B:
462 pass
463 adoc = pydoc.render_doc(A())
464 bdoc = pydoc.render_doc(B())
465 self.assertEqual(adoc.replace("A", "B"), bdoc)
466
Georg Brandlb533e262008-05-25 18:19:30 +0000467 def test_not_here(self):
468 missing_module = "test.i_am_not_here"
469 result = str(run_pydoc(missing_module), 'ascii')
470 expected = missing_pattern % missing_module
471 self.assertEqual(expected, result,
472 "documentation for missing module found")
473
R. David Murray1f1b9d32009-05-27 20:56:59 +0000474 def test_input_strip(self):
475 missing_module = " test.i_am_not_here "
476 result = str(run_pydoc(missing_module), 'ascii')
477 expected = missing_pattern % missing_module.strip()
478 self.assertEqual(expected, result)
479
Ezio Melotti412c95a2010-02-16 23:31:04 +0000480 def test_stripid(self):
481 # test with strings, other implementations might have different repr()
482 stripid = pydoc.stripid
483 # strip the id
484 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
485 '<function stripid>')
486 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
487 '<function stripid>')
488 # nothing to strip, return the same text
489 self.assertEqual(stripid('42'), '42')
490 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
491 "<type 'exceptions.Exception'>")
492
Georg Brandld80d5f42010-12-03 07:47:22 +0000493 @unittest.skipIf(sys.flags.optimize >= 2,
494 'Docstrings are omitted with -O2 and above')
Brett Cannon7a540732011-02-22 03:04:06 +0000495 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
496 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100497 @requires_docstrings
Georg Brandld80d5f42010-12-03 07:47:22 +0000498 def test_help_output_redirect(self):
499 # issue 940286, if output is set in Helper, then all output from
500 # Helper.help should be redirected
501 old_pattern = expected_text_pattern
502 getpager_old = pydoc.getpager
503 getpager_new = lambda: (lambda x: x)
504 self.maxDiff = None
505
506 buf = StringIO()
507 helper = pydoc.Helper(output=buf)
508 unused, doc_loc = get_pydoc_text(pydoc_mod)
509 module = "test.pydoc_mod"
510 help_header = """
511 Help on module test.pydoc_mod in test:
512
513 """.lstrip()
514 help_header = textwrap.dedent(help_header)
515 expected_help_pattern = help_header + expected_text_pattern
516
517 pydoc.getpager = getpager_new
518 try:
519 with captured_output('stdout') as output, \
520 captured_output('stderr') as err:
521 helper.help(module)
522 result = buf.getvalue().strip()
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200523 expected_text = expected_help_pattern % (
524 (doc_loc,) +
525 expected_text_data_docstrings +
526 (inspect.getabsfile(pydoc_mod),))
Georg Brandld80d5f42010-12-03 07:47:22 +0000527 self.assertEqual('', output.getvalue())
528 self.assertEqual('', err.getvalue())
529 self.assertEqual(expected_text, result)
530 finally:
531 pydoc.getpager = getpager_old
532
Raymond Hettinger1103d052011-03-25 14:15:24 -0700533 def test_namedtuple_public_underscore(self):
534 NT = namedtuple('NT', ['abc', 'def'], rename=True)
535 with captured_stdout() as help_io:
Terry Jan Reedy5c811642013-11-04 21:43:26 -0500536 pydoc.help(NT)
Raymond Hettinger1103d052011-03-25 14:15:24 -0700537 helptext = help_io.getvalue()
538 self.assertIn('_1', helptext)
539 self.assertIn('_replace', helptext)
540 self.assertIn('_asdict', helptext)
541
Victor Stinnere6c910e2011-06-30 15:55:43 +0200542 def test_synopsis(self):
543 self.addCleanup(unlink, TESTFN)
544 for encoding in ('ISO-8859-1', 'UTF-8'):
545 with open(TESTFN, 'w', encoding=encoding) as script:
546 if encoding != 'UTF-8':
547 print('#coding: {}'.format(encoding), file=script)
548 print('"""line 1: h\xe9', file=script)
549 print('line 2: hi"""', file=script)
550 synopsis = pydoc.synopsis(TESTFN, {})
551 self.assertEqual(synopsis, 'line 1: h\xe9')
552
Eric Snowaed5b222014-01-04 20:38:11 -0700553 def test_synopsis_sourceless(self):
554 expected = os.__doc__.splitlines()[0]
555 filename = os.__cached__
556 synopsis = pydoc.synopsis(filename)
557
558 self.assertEqual(synopsis, expected)
559
R David Murray455f2962013-03-19 00:00:33 -0400560 def test_splitdoc_with_description(self):
561 example_string = "I Am A Doc\n\n\nHere is my description"
562 self.assertEqual(pydoc.splitdoc(example_string),
563 ('I Am A Doc', '\nHere is my description'))
564
565 def test_is_object_or_method(self):
566 doc = pydoc.Doc()
567 # Bound Method
568 self.assertTrue(pydoc._is_some_method(doc.fail))
569 # Method Descriptor
570 self.assertTrue(pydoc._is_some_method(int.__add__))
571 # String
572 self.assertFalse(pydoc._is_some_method("I am not a method"))
573
574 def test_is_package_when_not_package(self):
575 with test.support.temp_cwd() as test_dir:
576 self.assertFalse(pydoc.ispackage(test_dir))
577
578 def test_is_package_when_is_package(self):
579 with test.support.temp_cwd() as test_dir:
580 init_path = os.path.join(test_dir, '__init__.py')
581 open(init_path, 'w').close()
582 self.assertTrue(pydoc.ispackage(test_dir))
583 os.remove(init_path)
584
R David Murrayac0cea52013-03-19 02:47:44 -0400585 def test_allmethods(self):
586 # issue 17476: allmethods was no longer returning unbound methods.
587 # This test is a bit fragile in the face of changes to object and type,
588 # but I can't think of a better way to do it without duplicating the
589 # logic of the function under test.
590
591 class TestClass(object):
592 def method_returning_true(self):
593 return True
594
595 # What we expect to get back: everything on object...
596 expected = dict(vars(object))
597 # ...plus our unbound method...
598 expected['method_returning_true'] = TestClass.method_returning_true
599 # ...but not the non-methods on object.
600 del expected['__doc__']
601 del expected['__class__']
602 # inspect resolves descriptors on type into methods, but vars doesn't,
603 # so we need to update __subclasshook__.
604 expected['__subclasshook__'] = TestClass.__subclasshook__
605
606 methods = pydoc.allmethods(TestClass)
607 self.assertDictEqual(methods, expected)
608
Georg Brandlb533e262008-05-25 18:19:30 +0000609
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200610class PydocImportTest(PydocBaseTest):
Ned Deily92a81a12011-10-06 14:19:03 -0700611
612 def setUp(self):
613 self.test_dir = os.mkdir(TESTFN)
614 self.addCleanup(rmtree, TESTFN)
615
616 def test_badimport(self):
617 # This tests the fix for issue 5230, where if pydoc found the module
618 # but the module had an internal import error pydoc would report no doc
619 # found.
620 modname = 'testmod_xyzzy'
621 testpairs = (
622 ('i_am_not_here', 'i_am_not_here'),
Brett Cannonfd074152012-04-14 14:10:13 -0400623 ('test.i_am_not_here_either', 'test.i_am_not_here_either'),
624 ('test.i_am_not_here.neither_am_i', 'test.i_am_not_here'),
625 ('i_am_not_here.{}'.format(modname), 'i_am_not_here'),
626 ('test.{}'.format(modname), 'test.{}'.format(modname)),
Ned Deily92a81a12011-10-06 14:19:03 -0700627 )
628
629 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
630 for importstring, expectedinmsg in testpairs:
631 with open(sourcefn, 'w') as f:
632 f.write("import {}\n".format(importstring))
633 result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii")
634 expected = badimport_pattern % (modname, expectedinmsg)
635 self.assertEqual(expected, result)
636
637 def test_apropos_with_bad_package(self):
638 # Issue 7425 - pydoc -k failed when bad package on path
639 pkgdir = os.path.join(TESTFN, "syntaxerr")
640 os.mkdir(pkgdir)
641 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
642 with open(badsyntax, 'w') as f:
643 f.write("invalid python syntax = $1\n")
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200644 with self.restrict_walk_packages(path=[TESTFN]):
645 with captured_stdout() as out:
646 with captured_stderr() as err:
647 pydoc.apropos('xyzzy')
648 # No result, no error
649 self.assertEqual(out.getvalue(), '')
650 self.assertEqual(err.getvalue(), '')
651 # The package name is still matched
652 with captured_stdout() as out:
653 with captured_stderr() as err:
654 pydoc.apropos('syntaxerr')
655 self.assertEqual(out.getvalue().strip(), 'syntaxerr')
656 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700657
658 def test_apropos_with_unreadable_dir(self):
659 # Issue 7367 - pydoc -k failed when unreadable dir on path
660 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
661 os.mkdir(self.unreadable_dir, 0)
662 self.addCleanup(os.rmdir, self.unreadable_dir)
663 # Note, on Windows the directory appears to be still
664 # readable so this is not really testing the issue there
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200665 with self.restrict_walk_packages(path=[TESTFN]):
666 with captured_stdout() as out:
667 with captured_stderr() as err:
668 pydoc.apropos('SOMEKEY')
669 # No result, no error
670 self.assertEqual(out.getvalue(), '')
671 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700672
Eric Snowa46ef702014-02-22 13:57:08 -0700673 @unittest.skip('causes undesireable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700674 def test_modules(self):
675 # See Helper.listmodules().
676 num_header_lines = 2
677 num_module_lines_min = 5 # Playing it safe.
678 num_footer_lines = 3
679 expected = num_header_lines + num_module_lines_min + num_footer_lines
680
681 output = StringIO()
682 helper = pydoc.Helper(output=output)
683 helper('modules')
684 result = output.getvalue().strip()
685 num_lines = len(result.splitlines())
686
687 self.assertGreaterEqual(num_lines, expected)
688
Eric Snowa46ef702014-02-22 13:57:08 -0700689 @unittest.skip('causes undesireable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700690 def test_modules_search(self):
691 # See Helper.listmodules().
692 expected = 'pydoc - '
693
694 output = StringIO()
695 helper = pydoc.Helper(output=output)
696 with captured_stdout() as help_io:
697 helper('modules pydoc')
698 result = help_io.getvalue()
699
700 self.assertIn(expected, result)
701
Eric Snowa46ef702014-02-22 13:57:08 -0700702 @unittest.skip('some buildbots are not cooperating (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700703 def test_modules_search_builtin(self):
Eric Snow5ea97502014-01-04 23:04:27 -0700704 expected = 'gc - '
Eric Snowaed5b222014-01-04 20:38:11 -0700705
706 output = StringIO()
707 helper = pydoc.Helper(output=output)
708 with captured_stdout() as help_io:
Eric Snow5ea97502014-01-04 23:04:27 -0700709 helper('modules garbage')
Eric Snowaed5b222014-01-04 20:38:11 -0700710 result = help_io.getvalue()
711
712 self.assertTrue(result.startswith(expected))
713
714 def test_importfile(self):
715 loaded_pydoc = pydoc.importfile(pydoc.__file__)
716
Eric Snow3a62d142014-01-06 20:42:59 -0700717 self.assertIsNot(loaded_pydoc, pydoc)
Eric Snowaed5b222014-01-04 20:38:11 -0700718 self.assertEqual(loaded_pydoc.__name__, 'pydoc')
719 self.assertEqual(loaded_pydoc.__file__, pydoc.__file__)
Eric Snow3a62d142014-01-06 20:42:59 -0700720 self.assertEqual(loaded_pydoc.__spec__, pydoc.__spec__)
Eric Snowaed5b222014-01-04 20:38:11 -0700721
Ned Deily92a81a12011-10-06 14:19:03 -0700722
Georg Brandlb533e262008-05-25 18:19:30 +0000723class TestDescriptions(unittest.TestCase):
724
725 def test_module(self):
726 # Check that pydocfodder module can be described
727 from test import pydocfodder
728 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000729 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000730
Georg Brandlb533e262008-05-25 18:19:30 +0000731 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000732 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +0000733 c = C()
734
735 self.assertEqual(pydoc.describe(C), 'class C')
736 self.assertEqual(pydoc.describe(c), 'C')
737 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000738 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000739
Éric Araujoe64e51b2011-07-29 17:03:55 +0200740 def test_builtin(self):
741 for name in ('str', 'str.translate', 'builtins.str',
742 'builtins.str.translate'):
743 # test low-level function
744 self.assertIsNotNone(pydoc.locate(name))
745 # test high-level function
746 try:
747 pydoc.render_doc(name)
748 except ImportError:
Terry Jan Reedyfe928de2014-06-20 14:59:11 -0400749 self.fail('finding the doc of {!r} failed'.format(name))
Éric Araujoe64e51b2011-07-29 17:03:55 +0200750
751 for name in ('notbuiltins', 'strrr', 'strr.translate',
752 'str.trrrranslate', 'builtins.strrr',
753 'builtins.str.trrranslate'):
754 self.assertIsNone(pydoc.locate(name))
755 self.assertRaises(ImportError, pydoc.render_doc, name)
756
Larry Hastings24a882b2014-02-20 23:34:46 -0800757 @staticmethod
758 def _get_summary_line(o):
759 text = pydoc.plain(pydoc.render_doc(o))
760 lines = text.split('\n')
761 assert len(lines) >= 2
762 return lines[2]
763
764 # these should include "self"
765 def test_unbound_python_method(self):
766 self.assertEqual(self._get_summary_line(textwrap.TextWrapper.wrap),
767 "wrap(self, text)")
768
Stefan Krah5de32782014-01-18 23:18:39 +0100769 @requires_docstrings
Larry Hastings24a882b2014-02-20 23:34:46 -0800770 def test_unbound_builtin_method(self):
771 self.assertEqual(self._get_summary_line(_pickle.Pickler.dump),
772 "dump(self, obj, /)")
773
774 # these no longer include "self"
775 def test_bound_python_method(self):
776 t = textwrap.TextWrapper()
777 self.assertEqual(self._get_summary_line(t.wrap),
778 "wrap(text) method of textwrap.TextWrapper instance")
779
780 @requires_docstrings
781 def test_bound_builtin_method(self):
782 s = StringIO()
783 p = _pickle.Pickler(s)
784 self.assertEqual(self._get_summary_line(p.dump),
785 "dump(obj, /) method of _pickle.Pickler instance")
786
787 # this should *never* include self!
788 @requires_docstrings
789 def test_module_level_callable(self):
790 self.assertEqual(self._get_summary_line(os.stat),
791 "stat(path, *, dir_fd=None, follow_symlinks=True)")
Larry Hastings1abd7082014-01-16 14:15:03 -0800792
Georg Brandlb533e262008-05-25 18:19:30 +0000793
Victor Stinner62a68f22011-05-20 02:29:13 +0200794@unittest.skipUnless(threading, 'Threading required for this test.')
Georg Brandld2f38572011-01-30 08:37:19 +0000795class PydocServerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000796 """Tests for pydoc._start_server"""
797
798 def test_server(self):
799
800 # Minimal test that starts the server, then stops it.
801 def my_url_handler(url, content_type):
802 text = 'the URL sent was: (%s, %s)' % (url, content_type)
803 return text
804
805 serverthread = pydoc._start_server(my_url_handler, port=0)
Senthil Kumaran2a42a0b2014-09-17 13:17:58 +0800806 self.assertIn('localhost', serverthread.docserver.address)
807
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000808 starttime = time.time()
809 timeout = 1 #seconds
810
811 while serverthread.serving:
812 time.sleep(.01)
813 if serverthread.serving and time.time() - starttime > timeout:
814 serverthread.stop()
815 break
816
817 self.assertEqual(serverthread.error, None)
818
819
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200820class PydocUrlHandlerTest(PydocBaseTest):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000821 """Tests for pydoc._url_handler"""
822
823 def test_content_type_err(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000824 f = pydoc._url_handler
Georg Brandld2f38572011-01-30 08:37:19 +0000825 self.assertRaises(TypeError, f, 'A', '')
826 self.assertRaises(TypeError, f, 'B', 'foobar')
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000827
828 def test_url_requests(self):
829 # Test for the correct title in the html pages returned.
830 # This tests the different parts of the URL handler without
831 # getting too picky about the exact html.
832 requests = [
Georg Brandld2f38572011-01-30 08:37:19 +0000833 ("", "Pydoc: Index of Modules"),
834 ("get?key=", "Pydoc: Index of Modules"),
835 ("index", "Pydoc: Index of Modules"),
836 ("topics", "Pydoc: Topics"),
837 ("keywords", "Pydoc: Keywords"),
838 ("pydoc", "Pydoc: module pydoc"),
839 ("get?key=pydoc", "Pydoc: module pydoc"),
840 ("search?key=pydoc", "Pydoc: Search Results"),
841 ("topic?key=def", "Pydoc: KEYWORD def"),
842 ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
843 ("foobar", "Pydoc: Error - foobar"),
844 ("getfile?key=foobar", "Pydoc: Error - getfile?key=foobar"),
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000845 ]
846
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200847 with self.restrict_walk_packages():
848 for url, title in requests:
849 text = pydoc._url_handler(url, "text/html")
850 result = get_html_title(text)
851 self.assertEqual(result, title, text)
852
853 path = string.__file__
854 title = "Pydoc: getfile " + path
855 url = "getfile?key=" + path
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000856 text = pydoc._url_handler(url, "text/html")
857 result = get_html_title(text)
858 self.assertEqual(result, title)
859
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000860
Ezio Melottib185a042011-04-28 07:42:55 +0300861class TestHelper(unittest.TestCase):
862 def test_keywords(self):
863 self.assertEqual(sorted(pydoc.Helper.keywords),
864 sorted(keyword.kwlist))
865
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700866class PydocWithMetaClasses(unittest.TestCase):
Ethan Furman3f2f1922013-10-22 07:30:24 -0700867 @unittest.skipIf(sys.flags.optimize >= 2,
868 "Docstrings are omitted with -O2 and above")
869 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
870 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700871 def test_DynamicClassAttribute(self):
872 class Meta(type):
873 def __getattr__(self, name):
874 if name == 'ham':
875 return 'spam'
876 return super().__getattr__(name)
877 class DA(metaclass=Meta):
878 @types.DynamicClassAttribute
879 def ham(self):
880 return 'eggs'
Ethan Furman3f2f1922013-10-22 07:30:24 -0700881 expected_text_data_docstrings = tuple('\n | ' + s if s else ''
882 for s in expected_data_docstrings)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700883 output = StringIO()
884 helper = pydoc.Helper(output=output)
885 helper(DA)
Ethan Furman3f2f1922013-10-22 07:30:24 -0700886 expected_text = expected_dynamicattribute_pattern % (
887 (__name__,) + expected_text_data_docstrings[:2])
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700888 result = output.getvalue().strip()
889 if result != expected_text:
890 print_diffs(expected_text, result)
891 self.fail("outputs are not equal, see diff above")
892
Ethan Furman3f2f1922013-10-22 07:30:24 -0700893 @unittest.skipIf(sys.flags.optimize >= 2,
894 "Docstrings are omitted with -O2 and above")
895 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
896 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700897 def test_virtualClassAttributeWithOneMeta(self):
898 class Meta(type):
899 def __dir__(cls):
900 return ['__class__', '__module__', '__name__', 'LIFE']
901 def __getattr__(self, name):
902 if name =='LIFE':
903 return 42
904 return super().__getattr(name)
905 class Class(metaclass=Meta):
906 pass
907 output = StringIO()
908 helper = pydoc.Helper(output=output)
909 helper(Class)
910 expected_text = expected_virtualattribute_pattern1 % __name__
911 result = output.getvalue().strip()
912 if result != expected_text:
913 print_diffs(expected_text, result)
914 self.fail("outputs are not equal, see diff above")
915
Ethan Furman3f2f1922013-10-22 07:30:24 -0700916 @unittest.skipIf(sys.flags.optimize >= 2,
917 "Docstrings are omitted with -O2 and above")
918 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
919 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700920 def test_virtualClassAttributeWithTwoMeta(self):
921 class Meta1(type):
922 def __dir__(cls):
923 return ['__class__', '__module__', '__name__', 'one']
924 def __getattr__(self, name):
925 if name =='one':
926 return 1
927 return super().__getattr__(name)
928 class Meta2(type):
929 def __dir__(cls):
930 return ['__class__', '__module__', '__name__', 'two']
931 def __getattr__(self, name):
932 if name =='two':
933 return 2
934 return super().__getattr__(name)
935 class Meta3(Meta1, Meta2):
936 def __dir__(cls):
937 return list(sorted(set(
938 ['__class__', '__module__', '__name__', 'three'] +
939 Meta1.__dir__(cls) + Meta2.__dir__(cls))))
940 def __getattr__(self, name):
941 if name =='three':
942 return 3
943 return super().__getattr__(name)
944 class Class1(metaclass=Meta1):
945 pass
946 class Class2(Class1, metaclass=Meta3):
947 pass
948 fail1 = fail2 = False
949 output = StringIO()
950 helper = pydoc.Helper(output=output)
951 helper(Class1)
952 expected_text1 = expected_virtualattribute_pattern2 % __name__
953 result1 = output.getvalue().strip()
954 if result1 != expected_text1:
955 print_diffs(expected_text1, result1)
956 fail1 = True
957 output = StringIO()
958 helper = pydoc.Helper(output=output)
959 helper(Class2)
960 expected_text2 = expected_virtualattribute_pattern3 % __name__
961 result2 = output.getvalue().strip()
962 if result2 != expected_text2:
963 print_diffs(expected_text2, result2)
964 fail2 = True
965 if fail1 or fail2:
966 self.fail("outputs are not equal, see diff above")
967
Ethan Furman3f2f1922013-10-22 07:30:24 -0700968 @unittest.skipIf(sys.flags.optimize >= 2,
969 "Docstrings are omitted with -O2 and above")
970 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
971 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700972 def test_buggy_dir(self):
973 class M(type):
974 def __dir__(cls):
975 return ['__class__', '__name__', 'missing', 'here']
976 class C(metaclass=M):
977 here = 'present!'
978 output = StringIO()
979 helper = pydoc.Helper(output=output)
980 helper(C)
981 expected_text = expected_missingattribute_pattern % __name__
982 result = output.getvalue().strip()
983 if result != expected_text:
984 print_diffs(expected_text, result)
985 self.fail("outputs are not equal, see diff above")
986
Eric Snowaed5b222014-01-04 20:38:11 -0700987
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200988@reap_threads
Georg Brandlb533e262008-05-25 18:19:30 +0000989def test_main():
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200990 try:
991 test.support.run_unittest(PydocDocTest,
Ned Deily92a81a12011-10-06 14:19:03 -0700992 PydocImportTest,
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200993 TestDescriptions,
994 PydocServerTest,
995 PydocUrlHandlerTest,
996 TestHelper,
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700997 PydocWithMetaClasses,
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200998 )
999 finally:
1000 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +00001001
1002if __name__ == "__main__":
1003 test_main()