blob: e5794c8844760db7bbe4376744868f8631b02408 [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 inspect
Nick Coghlan7bb30b72010-12-03 09:29:11 +00006import pydoc
Ezio Melottib185a042011-04-28 07:42:55 +03007import keyword
Larry Hastings24a882b2014-02-20 23:34:46 -08008import _pickle
Antoine Pitrou916fc7b2013-05-19 15:44:54 +02009import pkgutil
Nick Coghlan7bb30b72010-12-03 09:29:11 +000010import re
11import string
Georg Brandlb533e262008-05-25 18:19:30 +000012import test.support
Nick Coghlan7bb30b72010-12-03 09:29:11 +000013import time
Ethan Furmanb0c84cd2013-10-20 22:37:39 -070014import types
Nick Coghlan7bb30b72010-12-03 09:29:11 +000015import unittest
Brian Curtin49c284c2010-03-31 03:19:28 +000016import xml.etree
Georg Brandld80d5f42010-12-03 07:47:22 +000017import textwrap
18from io import StringIO
Raymond Hettinger1103d052011-03-25 14:15:24 -070019from collections import namedtuple
Antoine Pitrouf7f54752011-07-15 22:42:12 +020020from test.script_helper import assert_python_ok
Antoine Pitroua6e81a22011-07-15 22:32:25 +020021from test.support import (
Ned Deily92a81a12011-10-06 14:19:03 -070022 TESTFN, rmtree,
Antoine Pitrou916fc7b2013-05-19 15:44:54 +020023 reap_children, reap_threads, captured_output, captured_stdout,
Stefan Krah5de32782014-01-18 23:18:39 +010024 captured_stderr, unlink, requires_docstrings
Antoine Pitroua6e81a22011-07-15 22:32:25 +020025)
Georg Brandlb533e262008-05-25 18:19:30 +000026from test import pydoc_mod
27
Victor Stinner62a68f22011-05-20 02:29:13 +020028try:
29 import threading
30except ImportError:
31 threading = None
32
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020033if test.support.HAVE_DOCSTRINGS:
34 expected_data_docstrings = (
35 'dictionary for instance variables (if defined)',
36 'list of weak references to the object (if defined)',
37 ) * 2
38else:
39 expected_data_docstrings = ('', '', '', '')
40
Barry Warsaw28a691b2010-04-17 00:19:56 +000041expected_text_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000042NAME
43 test.pydoc_mod - This is a test module for test_pydoc
Georg Brandlb533e262008-05-25 18:19:30 +000044%s
45CLASSES
46 builtins.object
47 A
48 B
Benjamin Petersoned1160b2014-06-07 16:44:00 -070049 C
Georg Brandlb533e262008-05-25 18:19:30 +000050\x20\x20\x20\x20
51 class A(builtins.object)
52 | Hello and goodbye
53 |\x20\x20
54 | Methods defined here:
55 |\x20\x20
56 | __init__()
57 | Wow, I have no function!
58 |\x20\x20
59 | ----------------------------------------------------------------------
60 | Data descriptors defined here:
61 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020062 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000063 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020064 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000065\x20\x20\x20\x20
66 class B(builtins.object)
67 | Data descriptors defined here:
68 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020069 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000070 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020071 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000072 |\x20\x20
73 | ----------------------------------------------------------------------
74 | Data and other attributes defined here:
75 |\x20\x20
76 | NO_MEANING = 'eggs'
Benjamin Petersoned1160b2014-06-07 16:44:00 -070077\x20\x20\x20\x20
78 class C(builtins.object)
79 | Methods defined here:
80 |\x20\x20
81 | get_answer(self)
82 | Return say_no()
83 |\x20\x20
84 | is_it_true(self)
85 | Return self.get_answer()
86 |\x20\x20
87 | say_no(self)
88 |\x20\x20
89 | ----------------------------------------------------------------------
90 | Data descriptors defined here:
91 |\x20\x20
92 | __dict__
93 | dictionary for instance variables (if defined)
94 |\x20\x20
95 | __weakref__
96 | list of weak references to the object (if defined)
Georg Brandlb533e262008-05-25 18:19:30 +000097
98FUNCTIONS
99 doc_func()
100 This function solves all of the world's problems:
101 hunger
102 lack of Python
103 war
104\x20\x20\x20\x20
105 nodoc_func()
106
107DATA
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000108 __xyz__ = 'X, Y and Z'
Georg Brandlb533e262008-05-25 18:19:30 +0000109
110VERSION
111 1.2.3.4
112
113AUTHOR
114 Benjamin Peterson
115
116CREDITS
117 Nobody
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000118
119FILE
120 %s
Georg Brandlb533e262008-05-25 18:19:30 +0000121""".strip()
122
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200123expected_text_data_docstrings = tuple('\n | ' + s if s else ''
124 for s in expected_data_docstrings)
125
Barry Warsaw28a691b2010-04-17 00:19:56 +0000126expected_html_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +0000127<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
128<tr bgcolor="#7799ee">
129<td valign=bottom>&nbsp;<br>
130<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
131><td align=right valign=bottom
132><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
133 <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
134<p>
135<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
136<tr bgcolor="#ee77aa">
137<td colspan=3 valign=bottom>&nbsp;<br>
138<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
139\x20\x20\x20\x20
140<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
141<td width="100%%"><dl>
142<dt><font face="helvetica, arial"><a href="builtins.html#object">builtins.object</a>
143</font></dt><dd>
144<dl>
145<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
146</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700147</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#C">C</a>
Georg Brandlb533e262008-05-25 18:19:30 +0000148</font></dt></dl>
149</dd>
150</dl>
151 <p>
152<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
153<tr bgcolor="#ffc8d8">
154<td colspan=3 valign=bottom>&nbsp;<br>
155<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>
156\x20\x20\x20\x20
157<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
158<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
159<tr><td>&nbsp;</td>
160<td width="100%%">Methods defined here:<br>
161<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>
162
163<hr>
164Data descriptors defined here:<br>
165<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200166<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000167</dl>
168<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200169<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000170</dl>
171</td></tr></table> <p>
172<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
173<tr bgcolor="#ffc8d8">
174<td colspan=3 valign=bottom>&nbsp;<br>
175<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>
176\x20\x20\x20\x20
177<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
178<td width="100%%">Data descriptors defined here:<br>
179<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200180<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000181</dl>
182<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200183<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000184</dl>
185<hr>
186Data and other attributes defined here:<br>
187<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
188
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700189</td></tr></table> <p>
190<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
191<tr bgcolor="#ffc8d8">
192<td colspan=3 valign=bottom>&nbsp;<br>
193<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>
194\x20\x20\x20\x20
195<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
196<td width="100%%">Methods defined here:<br>
197<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>
198
199<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>
200
201<dl><dt><a name="C-say_no"><strong>say_no</strong></a>(self)</dt></dl>
202
203<hr>
204Data descriptors defined here:<br>
205<dl><dt><strong>__dict__</strong></dt>
206<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
207</dl>
208<dl><dt><strong>__weakref__</strong></dt>
209<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
210</dl>
Georg Brandlb533e262008-05-25 18:19:30 +0000211</td></tr></table></td></tr></table><p>
212<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
213<tr bgcolor="#eeaa77">
214<td colspan=3 valign=bottom>&nbsp;<br>
215<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
216\x20\x20\x20\x20
217<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
218<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>
219hunger<br>
220lack&nbsp;of&nbsp;Python<br>
221war</tt></dd></dl>
222 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
223</td></tr></table><p>
224<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
225<tr bgcolor="#55aa55">
226<td colspan=3 valign=bottom>&nbsp;<br>
227<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
228\x20\x20\x20\x20
229<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000230<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p>
Georg Brandlb533e262008-05-25 18:19:30 +0000231<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
232<tr bgcolor="#7799ee">
233<td colspan=3 valign=bottom>&nbsp;<br>
234<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
235\x20\x20\x20\x20
236<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
237<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
238<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
239<tr bgcolor="#7799ee">
240<td colspan=3 valign=bottom>&nbsp;<br>
241<font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
242\x20\x20\x20\x20
243<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
244<td width="100%%">Nobody</td></tr></table>
Barry Warsaw28a691b2010-04-17 00:19:56 +0000245""".strip() # ' <- emacs turd
Georg Brandlb533e262008-05-25 18:19:30 +0000246
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200247expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;')
248 for s in expected_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000249
250# output pattern for missing module
251missing_pattern = "no Python documentation found for '%s'"
252
Benjamin Peterson0289b152009-06-28 17:22:03 +0000253# output pattern for module with bad imports
Brett Cannon679ecb52013-07-04 17:51:50 -0400254badimport_pattern = "problem in %s - ImportError: No module named %r"
Benjamin Peterson0289b152009-06-28 17:22:03 +0000255
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700256expected_dynamicattribute_pattern = """
257Help on class DA in module %s:
258
259class DA(builtins.object)
260 | Data descriptors defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200261 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700262 | __dict__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200263 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700264 | __weakref__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200265 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700266 | ham
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200267 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700268 | ----------------------------------------------------------------------
269 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200270 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700271 | ham = 'spam'
272""".strip()
273
274expected_virtualattribute_pattern1 = """
275Help on class Class in module %s:
276
277class Class(builtins.object)
278 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200279 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700280 | LIFE = 42
281""".strip()
282
283expected_virtualattribute_pattern2 = """
284Help on class Class1 in module %s:
285
286class Class1(builtins.object)
287 | Data and other attributes inherited from Meta1:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200288 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700289 | one = 1
290""".strip()
291
292expected_virtualattribute_pattern3 = """
293Help on class Class2 in module %s:
294
295class Class2(Class1)
296 | Method resolution order:
297 | Class2
298 | Class1
299 | builtins.object
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200300 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700301 | Data and other attributes inherited from Meta1:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200302 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700303 | one = 1
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200304 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700305 | ----------------------------------------------------------------------
306 | Data and other attributes inherited from Meta3:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200307 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700308 | three = 3
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200309 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700310 | ----------------------------------------------------------------------
311 | Data and other attributes inherited from Meta2:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200312 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700313 | two = 2
314""".strip()
315
316expected_missingattribute_pattern = """
317Help on class C in module %s:
318
319class C(builtins.object)
320 | Data and other attributes defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200321 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700322 | here = 'present!'
323""".strip()
324
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200325def run_pydoc(module_name, *args, **env):
Georg Brandlb533e262008-05-25 18:19:30 +0000326 """
327 Runs pydoc on the specified module. Returns the stripped
328 output of pydoc.
329 """
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200330 args = args + (module_name,)
Ned Deily92a81a12011-10-06 14:19:03 -0700331 # do not write bytecode files to avoid caching errors
332 rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200333 return out.strip()
Georg Brandlb533e262008-05-25 18:19:30 +0000334
335def get_pydoc_html(module):
336 "Returns pydoc generated output as html"
337 doc = pydoc.HTMLDoc()
338 output = doc.docmodule(module)
339 loc = doc.getdocloc(pydoc_mod) or ""
340 if loc:
341 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
342 return output.strip(), loc
343
344def get_pydoc_text(module):
345 "Returns pydoc generated output as text"
346 doc = pydoc.TextDoc()
347 loc = doc.getdocloc(pydoc_mod) or ""
348 if loc:
349 loc = "\nMODULE DOCS\n " + loc + "\n"
350
351 output = doc.docmodule(module)
352
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000353 # clean up the extra text formatting that pydoc performs
Georg Brandlb533e262008-05-25 18:19:30 +0000354 patt = re.compile('\b.')
355 output = patt.sub('', output)
356 return output.strip(), loc
357
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000358def get_html_title(text):
Nick Coghlanecace282010-12-03 16:08:46 +0000359 # Bit of hack, but good enough for test purposes
360 header, _, _ = text.partition("</head>")
361 _, _, title = header.partition("<title>")
362 title, _, _ = title.partition("</title>")
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000363 return title
364
Georg Brandlb533e262008-05-25 18:19:30 +0000365
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200366class PydocBaseTest(unittest.TestCase):
367
368 def _restricted_walk_packages(self, walk_packages, path=None):
369 """
370 A version of pkgutil.walk_packages() that will restrict itself to
371 a given path.
372 """
373 default_path = path or [os.path.dirname(__file__)]
374 def wrapper(path=None, prefix='', onerror=None):
375 return walk_packages(path or default_path, prefix, onerror)
376 return wrapper
377
378 @contextlib.contextmanager
379 def restrict_walk_packages(self, path=None):
380 walk_packages = pkgutil.walk_packages
381 pkgutil.walk_packages = self._restricted_walk_packages(walk_packages,
382 path)
383 try:
384 yield
385 finally:
386 pkgutil.walk_packages = walk_packages
387
388
Georg Brandld2f38572011-01-30 08:37:19 +0000389class PydocDocTest(unittest.TestCase):
Georg Brandlb533e262008-05-25 18:19:30 +0000390
R. David Murray378c0cf2010-02-24 01:46:21 +0000391 @unittest.skipIf(sys.flags.optimize >= 2,
392 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000393 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
394 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100395 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000396 def test_html_doc(self):
397 result, doc_loc = get_pydoc_html(pydoc_mod)
398 mod_file = inspect.getabsfile(pydoc_mod)
Benjamin Petersonc5e94642008-06-14 23:04:46 +0000399 if sys.platform == 'win32':
400 import nturl2path
401 mod_url = nturl2path.pathname2url(mod_file)
402 else:
403 mod_url = mod_file
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200404 expected_html = expected_html_pattern % (
405 (mod_url, mod_file, doc_loc) +
406 expected_html_data_docstrings)
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700407 self.assertEqual(result, expected_html)
Georg Brandlb533e262008-05-25 18:19:30 +0000408
R. David Murray378c0cf2010-02-24 01:46:21 +0000409 @unittest.skipIf(sys.flags.optimize >= 2,
410 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000411 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
412 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100413 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000414 def test_text_doc(self):
415 result, doc_loc = get_pydoc_text(pydoc_mod)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200416 expected_text = expected_text_pattern % (
417 (doc_loc,) +
418 expected_text_data_docstrings +
419 (inspect.getabsfile(pydoc_mod),))
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700420 self.assertEqual(expected_text, result)
Georg Brandlb533e262008-05-25 18:19:30 +0000421
Serhiy Storchaka056eb022014-02-19 23:05:12 +0200422 def test_text_enum_member_with_value_zero(self):
423 # Test issue #20654 to ensure enum member with value 0 can be
424 # displayed. It used to throw KeyError: 'zero'.
425 import enum
426 class BinaryInteger(enum.IntEnum):
427 zero = 0
428 one = 1
429 doc = pydoc.render_doc(BinaryInteger)
430 self.assertIn('<BinaryInteger.zero: 0>', doc)
431
Brian Curtin49c284c2010-03-31 03:19:28 +0000432 def test_issue8225(self):
433 # Test issue8225 to ensure no doc link appears for xml.etree
434 result, doc_loc = get_pydoc_text(xml.etree)
435 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
436
Benjamin Peterson159824e2014-06-07 20:14:26 -0700437 def test_getpager_with_stdin_none(self):
438 previous_stdin = sys.stdin
439 try:
440 sys.stdin = None
441 pydoc.getpager() # Shouldn't fail.
442 finally:
443 sys.stdin = previous_stdin
444
R David Murrayc43125a2012-04-23 13:23:57 -0400445 def test_non_str_name(self):
446 # issue14638
447 # Treat illegal (non-str) name like no name
448 class A:
449 __name__ = 42
450 class B:
451 pass
452 adoc = pydoc.render_doc(A())
453 bdoc = pydoc.render_doc(B())
454 self.assertEqual(adoc.replace("A", "B"), bdoc)
455
Georg Brandlb533e262008-05-25 18:19:30 +0000456 def test_not_here(self):
457 missing_module = "test.i_am_not_here"
458 result = str(run_pydoc(missing_module), 'ascii')
459 expected = missing_pattern % missing_module
460 self.assertEqual(expected, result,
461 "documentation for missing module found")
462
R. David Murray1f1b9d32009-05-27 20:56:59 +0000463 def test_input_strip(self):
464 missing_module = " test.i_am_not_here "
465 result = str(run_pydoc(missing_module), 'ascii')
466 expected = missing_pattern % missing_module.strip()
467 self.assertEqual(expected, result)
468
Ezio Melotti412c95a2010-02-16 23:31:04 +0000469 def test_stripid(self):
470 # test with strings, other implementations might have different repr()
471 stripid = pydoc.stripid
472 # strip the id
473 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
474 '<function stripid>')
475 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
476 '<function stripid>')
477 # nothing to strip, return the same text
478 self.assertEqual(stripid('42'), '42')
479 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
480 "<type 'exceptions.Exception'>")
481
Georg Brandld80d5f42010-12-03 07:47:22 +0000482 @unittest.skipIf(sys.flags.optimize >= 2,
483 'Docstrings are omitted with -O2 and above')
Brett Cannon7a540732011-02-22 03:04:06 +0000484 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
485 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100486 @requires_docstrings
Georg Brandld80d5f42010-12-03 07:47:22 +0000487 def test_help_output_redirect(self):
488 # issue 940286, if output is set in Helper, then all output from
489 # Helper.help should be redirected
490 old_pattern = expected_text_pattern
491 getpager_old = pydoc.getpager
492 getpager_new = lambda: (lambda x: x)
493 self.maxDiff = None
494
495 buf = StringIO()
496 helper = pydoc.Helper(output=buf)
497 unused, doc_loc = get_pydoc_text(pydoc_mod)
498 module = "test.pydoc_mod"
499 help_header = """
500 Help on module test.pydoc_mod in test:
501
502 """.lstrip()
503 help_header = textwrap.dedent(help_header)
504 expected_help_pattern = help_header + expected_text_pattern
505
506 pydoc.getpager = getpager_new
507 try:
508 with captured_output('stdout') as output, \
509 captured_output('stderr') as err:
510 helper.help(module)
511 result = buf.getvalue().strip()
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200512 expected_text = expected_help_pattern % (
513 (doc_loc,) +
514 expected_text_data_docstrings +
515 (inspect.getabsfile(pydoc_mod),))
Georg Brandld80d5f42010-12-03 07:47:22 +0000516 self.assertEqual('', output.getvalue())
517 self.assertEqual('', err.getvalue())
518 self.assertEqual(expected_text, result)
519 finally:
520 pydoc.getpager = getpager_old
521
Raymond Hettinger1103d052011-03-25 14:15:24 -0700522 def test_namedtuple_public_underscore(self):
523 NT = namedtuple('NT', ['abc', 'def'], rename=True)
524 with captured_stdout() as help_io:
Terry Jan Reedy5c811642013-11-04 21:43:26 -0500525 pydoc.help(NT)
Raymond Hettinger1103d052011-03-25 14:15:24 -0700526 helptext = help_io.getvalue()
527 self.assertIn('_1', helptext)
528 self.assertIn('_replace', helptext)
529 self.assertIn('_asdict', helptext)
530
Victor Stinnere6c910e2011-06-30 15:55:43 +0200531 def test_synopsis(self):
532 self.addCleanup(unlink, TESTFN)
533 for encoding in ('ISO-8859-1', 'UTF-8'):
534 with open(TESTFN, 'w', encoding=encoding) as script:
535 if encoding != 'UTF-8':
536 print('#coding: {}'.format(encoding), file=script)
537 print('"""line 1: h\xe9', file=script)
538 print('line 2: hi"""', file=script)
539 synopsis = pydoc.synopsis(TESTFN, {})
540 self.assertEqual(synopsis, 'line 1: h\xe9')
541
Eric Snowaed5b222014-01-04 20:38:11 -0700542 def test_synopsis_sourceless(self):
543 expected = os.__doc__.splitlines()[0]
544 filename = os.__cached__
545 synopsis = pydoc.synopsis(filename)
546
547 self.assertEqual(synopsis, expected)
548
R David Murray455f2962013-03-19 00:00:33 -0400549 def test_splitdoc_with_description(self):
550 example_string = "I Am A Doc\n\n\nHere is my description"
551 self.assertEqual(pydoc.splitdoc(example_string),
552 ('I Am A Doc', '\nHere is my description'))
553
554 def test_is_object_or_method(self):
555 doc = pydoc.Doc()
556 # Bound Method
557 self.assertTrue(pydoc._is_some_method(doc.fail))
558 # Method Descriptor
559 self.assertTrue(pydoc._is_some_method(int.__add__))
560 # String
561 self.assertFalse(pydoc._is_some_method("I am not a method"))
562
563 def test_is_package_when_not_package(self):
564 with test.support.temp_cwd() as test_dir:
565 self.assertFalse(pydoc.ispackage(test_dir))
566
567 def test_is_package_when_is_package(self):
568 with test.support.temp_cwd() as test_dir:
569 init_path = os.path.join(test_dir, '__init__.py')
570 open(init_path, 'w').close()
571 self.assertTrue(pydoc.ispackage(test_dir))
572 os.remove(init_path)
573
R David Murrayac0cea52013-03-19 02:47:44 -0400574 def test_allmethods(self):
575 # issue 17476: allmethods was no longer returning unbound methods.
576 # This test is a bit fragile in the face of changes to object and type,
577 # but I can't think of a better way to do it without duplicating the
578 # logic of the function under test.
579
580 class TestClass(object):
581 def method_returning_true(self):
582 return True
583
584 # What we expect to get back: everything on object...
585 expected = dict(vars(object))
586 # ...plus our unbound method...
587 expected['method_returning_true'] = TestClass.method_returning_true
588 # ...but not the non-methods on object.
589 del expected['__doc__']
590 del expected['__class__']
591 # inspect resolves descriptors on type into methods, but vars doesn't,
592 # so we need to update __subclasshook__.
593 expected['__subclasshook__'] = TestClass.__subclasshook__
594
595 methods = pydoc.allmethods(TestClass)
596 self.assertDictEqual(methods, expected)
597
Georg Brandlb533e262008-05-25 18:19:30 +0000598
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200599class PydocImportTest(PydocBaseTest):
Ned Deily92a81a12011-10-06 14:19:03 -0700600
601 def setUp(self):
602 self.test_dir = os.mkdir(TESTFN)
603 self.addCleanup(rmtree, TESTFN)
604
605 def test_badimport(self):
606 # This tests the fix for issue 5230, where if pydoc found the module
607 # but the module had an internal import error pydoc would report no doc
608 # found.
609 modname = 'testmod_xyzzy'
610 testpairs = (
611 ('i_am_not_here', 'i_am_not_here'),
Brett Cannonfd074152012-04-14 14:10:13 -0400612 ('test.i_am_not_here_either', 'test.i_am_not_here_either'),
613 ('test.i_am_not_here.neither_am_i', 'test.i_am_not_here'),
614 ('i_am_not_here.{}'.format(modname), 'i_am_not_here'),
615 ('test.{}'.format(modname), 'test.{}'.format(modname)),
Ned Deily92a81a12011-10-06 14:19:03 -0700616 )
617
618 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
619 for importstring, expectedinmsg in testpairs:
620 with open(sourcefn, 'w') as f:
621 f.write("import {}\n".format(importstring))
622 result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii")
623 expected = badimport_pattern % (modname, expectedinmsg)
624 self.assertEqual(expected, result)
625
626 def test_apropos_with_bad_package(self):
627 # Issue 7425 - pydoc -k failed when bad package on path
628 pkgdir = os.path.join(TESTFN, "syntaxerr")
629 os.mkdir(pkgdir)
630 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
631 with open(badsyntax, 'w') as f:
632 f.write("invalid python syntax = $1\n")
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200633 with self.restrict_walk_packages(path=[TESTFN]):
634 with captured_stdout() as out:
635 with captured_stderr() as err:
636 pydoc.apropos('xyzzy')
637 # No result, no error
638 self.assertEqual(out.getvalue(), '')
639 self.assertEqual(err.getvalue(), '')
640 # The package name is still matched
641 with captured_stdout() as out:
642 with captured_stderr() as err:
643 pydoc.apropos('syntaxerr')
644 self.assertEqual(out.getvalue().strip(), 'syntaxerr')
645 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700646
647 def test_apropos_with_unreadable_dir(self):
648 # Issue 7367 - pydoc -k failed when unreadable dir on path
649 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
650 os.mkdir(self.unreadable_dir, 0)
651 self.addCleanup(os.rmdir, self.unreadable_dir)
652 # Note, on Windows the directory appears to be still
653 # readable so this is not really testing the issue there
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200654 with self.restrict_walk_packages(path=[TESTFN]):
655 with captured_stdout() as out:
656 with captured_stderr() as err:
657 pydoc.apropos('SOMEKEY')
658 # No result, no error
659 self.assertEqual(out.getvalue(), '')
660 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700661
Eric Snowa46ef702014-02-22 13:57:08 -0700662 @unittest.skip('causes undesireable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700663 def test_modules(self):
664 # See Helper.listmodules().
665 num_header_lines = 2
666 num_module_lines_min = 5 # Playing it safe.
667 num_footer_lines = 3
668 expected = num_header_lines + num_module_lines_min + num_footer_lines
669
670 output = StringIO()
671 helper = pydoc.Helper(output=output)
672 helper('modules')
673 result = output.getvalue().strip()
674 num_lines = len(result.splitlines())
675
676 self.assertGreaterEqual(num_lines, expected)
677
Eric Snowa46ef702014-02-22 13:57:08 -0700678 @unittest.skip('causes undesireable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700679 def test_modules_search(self):
680 # See Helper.listmodules().
681 expected = 'pydoc - '
682
683 output = StringIO()
684 helper = pydoc.Helper(output=output)
685 with captured_stdout() as help_io:
686 helper('modules pydoc')
687 result = help_io.getvalue()
688
689 self.assertIn(expected, result)
690
Eric Snowa46ef702014-02-22 13:57:08 -0700691 @unittest.skip('some buildbots are not cooperating (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700692 def test_modules_search_builtin(self):
Eric Snow5ea97502014-01-04 23:04:27 -0700693 expected = 'gc - '
Eric Snowaed5b222014-01-04 20:38:11 -0700694
695 output = StringIO()
696 helper = pydoc.Helper(output=output)
697 with captured_stdout() as help_io:
Eric Snow5ea97502014-01-04 23:04:27 -0700698 helper('modules garbage')
Eric Snowaed5b222014-01-04 20:38:11 -0700699 result = help_io.getvalue()
700
701 self.assertTrue(result.startswith(expected))
702
703 def test_importfile(self):
704 loaded_pydoc = pydoc.importfile(pydoc.__file__)
705
Eric Snow3a62d142014-01-06 20:42:59 -0700706 self.assertIsNot(loaded_pydoc, pydoc)
Eric Snowaed5b222014-01-04 20:38:11 -0700707 self.assertEqual(loaded_pydoc.__name__, 'pydoc')
708 self.assertEqual(loaded_pydoc.__file__, pydoc.__file__)
Eric Snow3a62d142014-01-06 20:42:59 -0700709 self.assertEqual(loaded_pydoc.__spec__, pydoc.__spec__)
Eric Snowaed5b222014-01-04 20:38:11 -0700710
Ned Deily92a81a12011-10-06 14:19:03 -0700711
Georg Brandlb533e262008-05-25 18:19:30 +0000712class TestDescriptions(unittest.TestCase):
713
714 def test_module(self):
715 # Check that pydocfodder module can be described
716 from test import pydocfodder
717 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000718 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000719
Georg Brandlb533e262008-05-25 18:19:30 +0000720 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000721 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +0000722 c = C()
723
724 self.assertEqual(pydoc.describe(C), 'class C')
725 self.assertEqual(pydoc.describe(c), 'C')
726 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000727 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000728
Éric Araujoe64e51b2011-07-29 17:03:55 +0200729 def test_builtin(self):
730 for name in ('str', 'str.translate', 'builtins.str',
731 'builtins.str.translate'):
732 # test low-level function
733 self.assertIsNotNone(pydoc.locate(name))
734 # test high-level function
735 try:
736 pydoc.render_doc(name)
737 except ImportError:
Terry Jan Reedyfe928de2014-06-20 14:59:11 -0400738 self.fail('finding the doc of {!r} failed'.format(name))
Éric Araujoe64e51b2011-07-29 17:03:55 +0200739
740 for name in ('notbuiltins', 'strrr', 'strr.translate',
741 'str.trrrranslate', 'builtins.strrr',
742 'builtins.str.trrranslate'):
743 self.assertIsNone(pydoc.locate(name))
744 self.assertRaises(ImportError, pydoc.render_doc, name)
745
Larry Hastings24a882b2014-02-20 23:34:46 -0800746 @staticmethod
747 def _get_summary_line(o):
748 text = pydoc.plain(pydoc.render_doc(o))
749 lines = text.split('\n')
750 assert len(lines) >= 2
751 return lines[2]
752
753 # these should include "self"
754 def test_unbound_python_method(self):
755 self.assertEqual(self._get_summary_line(textwrap.TextWrapper.wrap),
756 "wrap(self, text)")
757
Stefan Krah5de32782014-01-18 23:18:39 +0100758 @requires_docstrings
Larry Hastings24a882b2014-02-20 23:34:46 -0800759 def test_unbound_builtin_method(self):
760 self.assertEqual(self._get_summary_line(_pickle.Pickler.dump),
761 "dump(self, obj, /)")
762
763 # these no longer include "self"
764 def test_bound_python_method(self):
765 t = textwrap.TextWrapper()
766 self.assertEqual(self._get_summary_line(t.wrap),
767 "wrap(text) method of textwrap.TextWrapper instance")
768
769 @requires_docstrings
770 def test_bound_builtin_method(self):
771 s = StringIO()
772 p = _pickle.Pickler(s)
773 self.assertEqual(self._get_summary_line(p.dump),
774 "dump(obj, /) method of _pickle.Pickler instance")
775
776 # this should *never* include self!
777 @requires_docstrings
778 def test_module_level_callable(self):
779 self.assertEqual(self._get_summary_line(os.stat),
780 "stat(path, *, dir_fd=None, follow_symlinks=True)")
Larry Hastings1abd7082014-01-16 14:15:03 -0800781
Georg Brandlb533e262008-05-25 18:19:30 +0000782
Victor Stinner62a68f22011-05-20 02:29:13 +0200783@unittest.skipUnless(threading, 'Threading required for this test.')
Georg Brandld2f38572011-01-30 08:37:19 +0000784class PydocServerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000785 """Tests for pydoc._start_server"""
786
787 def test_server(self):
788
789 # Minimal test that starts the server, then stops it.
790 def my_url_handler(url, content_type):
791 text = 'the URL sent was: (%s, %s)' % (url, content_type)
792 return text
793
794 serverthread = pydoc._start_server(my_url_handler, port=0)
795 starttime = time.time()
796 timeout = 1 #seconds
797
798 while serverthread.serving:
799 time.sleep(.01)
800 if serverthread.serving and time.time() - starttime > timeout:
801 serverthread.stop()
802 break
803
804 self.assertEqual(serverthread.error, None)
805
806
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200807class PydocUrlHandlerTest(PydocBaseTest):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000808 """Tests for pydoc._url_handler"""
809
810 def test_content_type_err(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000811 f = pydoc._url_handler
Georg Brandld2f38572011-01-30 08:37:19 +0000812 self.assertRaises(TypeError, f, 'A', '')
813 self.assertRaises(TypeError, f, 'B', 'foobar')
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000814
815 def test_url_requests(self):
816 # Test for the correct title in the html pages returned.
817 # This tests the different parts of the URL handler without
818 # getting too picky about the exact html.
819 requests = [
Georg Brandld2f38572011-01-30 08:37:19 +0000820 ("", "Pydoc: Index of Modules"),
821 ("get?key=", "Pydoc: Index of Modules"),
822 ("index", "Pydoc: Index of Modules"),
823 ("topics", "Pydoc: Topics"),
824 ("keywords", "Pydoc: Keywords"),
825 ("pydoc", "Pydoc: module pydoc"),
826 ("get?key=pydoc", "Pydoc: module pydoc"),
827 ("search?key=pydoc", "Pydoc: Search Results"),
828 ("topic?key=def", "Pydoc: KEYWORD def"),
829 ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
830 ("foobar", "Pydoc: Error - foobar"),
831 ("getfile?key=foobar", "Pydoc: Error - getfile?key=foobar"),
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000832 ]
833
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200834 with self.restrict_walk_packages():
835 for url, title in requests:
836 text = pydoc._url_handler(url, "text/html")
837 result = get_html_title(text)
838 self.assertEqual(result, title, text)
839
840 path = string.__file__
841 title = "Pydoc: getfile " + path
842 url = "getfile?key=" + path
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000843 text = pydoc._url_handler(url, "text/html")
844 result = get_html_title(text)
845 self.assertEqual(result, title)
846
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000847
Ezio Melottib185a042011-04-28 07:42:55 +0300848class TestHelper(unittest.TestCase):
849 def test_keywords(self):
850 self.assertEqual(sorted(pydoc.Helper.keywords),
851 sorted(keyword.kwlist))
852
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700853class PydocWithMetaClasses(unittest.TestCase):
Ethan Furman3f2f1922013-10-22 07:30:24 -0700854 @unittest.skipIf(sys.flags.optimize >= 2,
855 "Docstrings are omitted with -O2 and above")
856 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
857 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700858 def test_DynamicClassAttribute(self):
859 class Meta(type):
860 def __getattr__(self, name):
861 if name == 'ham':
862 return 'spam'
863 return super().__getattr__(name)
864 class DA(metaclass=Meta):
865 @types.DynamicClassAttribute
866 def ham(self):
867 return 'eggs'
Ethan Furman3f2f1922013-10-22 07:30:24 -0700868 expected_text_data_docstrings = tuple('\n | ' + s if s else ''
869 for s in expected_data_docstrings)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700870 output = StringIO()
871 helper = pydoc.Helper(output=output)
872 helper(DA)
Ethan Furman3f2f1922013-10-22 07:30:24 -0700873 expected_text = expected_dynamicattribute_pattern % (
874 (__name__,) + expected_text_data_docstrings[:2])
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700875 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700876 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700877
Ethan Furman3f2f1922013-10-22 07:30:24 -0700878 @unittest.skipIf(sys.flags.optimize >= 2,
879 "Docstrings are omitted with -O2 and above")
880 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
881 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700882 def test_virtualClassAttributeWithOneMeta(self):
883 class Meta(type):
884 def __dir__(cls):
885 return ['__class__', '__module__', '__name__', 'LIFE']
886 def __getattr__(self, name):
887 if name =='LIFE':
888 return 42
889 return super().__getattr(name)
890 class Class(metaclass=Meta):
891 pass
892 output = StringIO()
893 helper = pydoc.Helper(output=output)
894 helper(Class)
895 expected_text = expected_virtualattribute_pattern1 % __name__
896 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700897 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700898
Ethan Furman3f2f1922013-10-22 07:30:24 -0700899 @unittest.skipIf(sys.flags.optimize >= 2,
900 "Docstrings are omitted with -O2 and above")
901 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
902 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700903 def test_virtualClassAttributeWithTwoMeta(self):
904 class Meta1(type):
905 def __dir__(cls):
906 return ['__class__', '__module__', '__name__', 'one']
907 def __getattr__(self, name):
908 if name =='one':
909 return 1
910 return super().__getattr__(name)
911 class Meta2(type):
912 def __dir__(cls):
913 return ['__class__', '__module__', '__name__', 'two']
914 def __getattr__(self, name):
915 if name =='two':
916 return 2
917 return super().__getattr__(name)
918 class Meta3(Meta1, Meta2):
919 def __dir__(cls):
920 return list(sorted(set(
921 ['__class__', '__module__', '__name__', 'three'] +
922 Meta1.__dir__(cls) + Meta2.__dir__(cls))))
923 def __getattr__(self, name):
924 if name =='three':
925 return 3
926 return super().__getattr__(name)
927 class Class1(metaclass=Meta1):
928 pass
929 class Class2(Class1, metaclass=Meta3):
930 pass
931 fail1 = fail2 = False
932 output = StringIO()
933 helper = pydoc.Helper(output=output)
934 helper(Class1)
935 expected_text1 = expected_virtualattribute_pattern2 % __name__
936 result1 = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700937 self.assertEqual(expected_text1, result1)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700938 output = StringIO()
939 helper = pydoc.Helper(output=output)
940 helper(Class2)
941 expected_text2 = expected_virtualattribute_pattern3 % __name__
942 result2 = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700943 self.assertEqual(expected_text2, result2)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700944
Ethan Furman3f2f1922013-10-22 07:30:24 -0700945 @unittest.skipIf(sys.flags.optimize >= 2,
946 "Docstrings are omitted with -O2 and above")
947 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
948 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700949 def test_buggy_dir(self):
950 class M(type):
951 def __dir__(cls):
952 return ['__class__', '__name__', 'missing', 'here']
953 class C(metaclass=M):
954 here = 'present!'
955 output = StringIO()
956 helper = pydoc.Helper(output=output)
957 helper(C)
958 expected_text = expected_missingattribute_pattern % __name__
959 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700960 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700961
Eric Snowaed5b222014-01-04 20:38:11 -0700962
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200963@reap_threads
Georg Brandlb533e262008-05-25 18:19:30 +0000964def test_main():
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200965 try:
966 test.support.run_unittest(PydocDocTest,
Ned Deily92a81a12011-10-06 14:19:03 -0700967 PydocImportTest,
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200968 TestDescriptions,
969 PydocServerTest,
970 PydocUrlHandlerTest,
971 TestHelper,
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700972 PydocWithMetaClasses,
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200973 )
974 finally:
975 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +0000976
977if __name__ == "__main__":
978 test_main()