blob: 67424442e68281a3d5e2fda26e78b9640aa2020b [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
Zachary Wareeb432142014-07-10 11:18:00 -050016import urllib.parse
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
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000359def get_html_title(text):
Nick Coghlanecace282010-12-03 16:08:46 +0000360 # Bit of hack, but good enough for test purposes
361 header, _, _ = text.partition("</head>")
362 _, _, title = header.partition("<title>")
363 title, _, _ = title.partition("</title>")
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000364 return title
365
Georg Brandlb533e262008-05-25 18:19:30 +0000366
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200367class PydocBaseTest(unittest.TestCase):
368
369 def _restricted_walk_packages(self, walk_packages, path=None):
370 """
371 A version of pkgutil.walk_packages() that will restrict itself to
372 a given path.
373 """
374 default_path = path or [os.path.dirname(__file__)]
375 def wrapper(path=None, prefix='', onerror=None):
376 return walk_packages(path or default_path, prefix, onerror)
377 return wrapper
378
379 @contextlib.contextmanager
380 def restrict_walk_packages(self, path=None):
381 walk_packages = pkgutil.walk_packages
382 pkgutil.walk_packages = self._restricted_walk_packages(walk_packages,
383 path)
384 try:
385 yield
386 finally:
387 pkgutil.walk_packages = walk_packages
388
389
Georg Brandld2f38572011-01-30 08:37:19 +0000390class PydocDocTest(unittest.TestCase):
Georg Brandlb533e262008-05-25 18:19:30 +0000391
R. David Murray378c0cf2010-02-24 01:46:21 +0000392 @unittest.skipIf(sys.flags.optimize >= 2,
393 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000394 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
395 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100396 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000397 def test_html_doc(self):
398 result, doc_loc = get_pydoc_html(pydoc_mod)
399 mod_file = inspect.getabsfile(pydoc_mod)
Zachary Wareeb432142014-07-10 11:18:00 -0500400 mod_url = urllib.parse.quote(mod_file)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200401 expected_html = expected_html_pattern % (
402 (mod_url, mod_file, doc_loc) +
403 expected_html_data_docstrings)
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700404 self.assertEqual(result, expected_html)
Georg Brandlb533e262008-05-25 18:19:30 +0000405
R. David Murray378c0cf2010-02-24 01:46:21 +0000406 @unittest.skipIf(sys.flags.optimize >= 2,
407 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000408 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
409 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100410 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000411 def test_text_doc(self):
412 result, doc_loc = get_pydoc_text(pydoc_mod)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200413 expected_text = expected_text_pattern % (
414 (doc_loc,) +
415 expected_text_data_docstrings +
416 (inspect.getabsfile(pydoc_mod),))
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700417 self.assertEqual(expected_text, result)
Georg Brandlb533e262008-05-25 18:19:30 +0000418
Serhiy Storchaka056eb022014-02-19 23:05:12 +0200419 def test_text_enum_member_with_value_zero(self):
420 # Test issue #20654 to ensure enum member with value 0 can be
421 # displayed. It used to throw KeyError: 'zero'.
422 import enum
423 class BinaryInteger(enum.IntEnum):
424 zero = 0
425 one = 1
426 doc = pydoc.render_doc(BinaryInteger)
427 self.assertIn('<BinaryInteger.zero: 0>', doc)
428
Brian Curtin49c284c2010-03-31 03:19:28 +0000429 def test_issue8225(self):
430 # Test issue8225 to ensure no doc link appears for xml.etree
431 result, doc_loc = get_pydoc_text(xml.etree)
432 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
433
Benjamin Peterson159824e2014-06-07 20:14:26 -0700434 def test_getpager_with_stdin_none(self):
435 previous_stdin = sys.stdin
436 try:
437 sys.stdin = None
438 pydoc.getpager() # Shouldn't fail.
439 finally:
440 sys.stdin = previous_stdin
441
R David Murrayc43125a2012-04-23 13:23:57 -0400442 def test_non_str_name(self):
443 # issue14638
444 # Treat illegal (non-str) name like no name
445 class A:
446 __name__ = 42
447 class B:
448 pass
449 adoc = pydoc.render_doc(A())
450 bdoc = pydoc.render_doc(B())
451 self.assertEqual(adoc.replace("A", "B"), bdoc)
452
Georg Brandlb533e262008-05-25 18:19:30 +0000453 def test_not_here(self):
454 missing_module = "test.i_am_not_here"
455 result = str(run_pydoc(missing_module), 'ascii')
456 expected = missing_pattern % missing_module
457 self.assertEqual(expected, result,
458 "documentation for missing module found")
459
R. David Murray1f1b9d32009-05-27 20:56:59 +0000460 def test_input_strip(self):
461 missing_module = " test.i_am_not_here "
462 result = str(run_pydoc(missing_module), 'ascii')
463 expected = missing_pattern % missing_module.strip()
464 self.assertEqual(expected, result)
465
Ezio Melotti412c95a2010-02-16 23:31:04 +0000466 def test_stripid(self):
467 # test with strings, other implementations might have different repr()
468 stripid = pydoc.stripid
469 # strip the id
470 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
471 '<function stripid>')
472 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
473 '<function stripid>')
474 # nothing to strip, return the same text
475 self.assertEqual(stripid('42'), '42')
476 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
477 "<type 'exceptions.Exception'>")
478
Georg Brandld80d5f42010-12-03 07:47:22 +0000479 @unittest.skipIf(sys.flags.optimize >= 2,
480 'Docstrings are omitted with -O2 and above')
Brett Cannon7a540732011-02-22 03:04:06 +0000481 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
482 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100483 @requires_docstrings
Georg Brandld80d5f42010-12-03 07:47:22 +0000484 def test_help_output_redirect(self):
485 # issue 940286, if output is set in Helper, then all output from
486 # Helper.help should be redirected
487 old_pattern = expected_text_pattern
488 getpager_old = pydoc.getpager
489 getpager_new = lambda: (lambda x: x)
490 self.maxDiff = None
491
492 buf = StringIO()
493 helper = pydoc.Helper(output=buf)
494 unused, doc_loc = get_pydoc_text(pydoc_mod)
495 module = "test.pydoc_mod"
496 help_header = """
497 Help on module test.pydoc_mod in test:
498
499 """.lstrip()
500 help_header = textwrap.dedent(help_header)
501 expected_help_pattern = help_header + expected_text_pattern
502
503 pydoc.getpager = getpager_new
504 try:
505 with captured_output('stdout') as output, \
506 captured_output('stderr') as err:
507 helper.help(module)
508 result = buf.getvalue().strip()
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200509 expected_text = expected_help_pattern % (
510 (doc_loc,) +
511 expected_text_data_docstrings +
512 (inspect.getabsfile(pydoc_mod),))
Georg Brandld80d5f42010-12-03 07:47:22 +0000513 self.assertEqual('', output.getvalue())
514 self.assertEqual('', err.getvalue())
515 self.assertEqual(expected_text, result)
516 finally:
517 pydoc.getpager = getpager_old
518
Raymond Hettinger1103d052011-03-25 14:15:24 -0700519 def test_namedtuple_public_underscore(self):
520 NT = namedtuple('NT', ['abc', 'def'], rename=True)
521 with captured_stdout() as help_io:
Terry Jan Reedy5c811642013-11-04 21:43:26 -0500522 pydoc.help(NT)
Raymond Hettinger1103d052011-03-25 14:15:24 -0700523 helptext = help_io.getvalue()
524 self.assertIn('_1', helptext)
525 self.assertIn('_replace', helptext)
526 self.assertIn('_asdict', helptext)
527
Victor Stinnere6c910e2011-06-30 15:55:43 +0200528 def test_synopsis(self):
529 self.addCleanup(unlink, TESTFN)
530 for encoding in ('ISO-8859-1', 'UTF-8'):
531 with open(TESTFN, 'w', encoding=encoding) as script:
532 if encoding != 'UTF-8':
533 print('#coding: {}'.format(encoding), file=script)
534 print('"""line 1: h\xe9', file=script)
535 print('line 2: hi"""', file=script)
536 synopsis = pydoc.synopsis(TESTFN, {})
537 self.assertEqual(synopsis, 'line 1: h\xe9')
538
Eric Snowaed5b222014-01-04 20:38:11 -0700539 def test_synopsis_sourceless(self):
540 expected = os.__doc__.splitlines()[0]
541 filename = os.__cached__
542 synopsis = pydoc.synopsis(filename)
543
544 self.assertEqual(synopsis, expected)
545
R David Murray455f2962013-03-19 00:00:33 -0400546 def test_splitdoc_with_description(self):
547 example_string = "I Am A Doc\n\n\nHere is my description"
548 self.assertEqual(pydoc.splitdoc(example_string),
549 ('I Am A Doc', '\nHere is my description'))
550
551 def test_is_object_or_method(self):
552 doc = pydoc.Doc()
553 # Bound Method
554 self.assertTrue(pydoc._is_some_method(doc.fail))
555 # Method Descriptor
556 self.assertTrue(pydoc._is_some_method(int.__add__))
557 # String
558 self.assertFalse(pydoc._is_some_method("I am not a method"))
559
560 def test_is_package_when_not_package(self):
561 with test.support.temp_cwd() as test_dir:
562 self.assertFalse(pydoc.ispackage(test_dir))
563
564 def test_is_package_when_is_package(self):
565 with test.support.temp_cwd() as test_dir:
566 init_path = os.path.join(test_dir, '__init__.py')
567 open(init_path, 'w').close()
568 self.assertTrue(pydoc.ispackage(test_dir))
569 os.remove(init_path)
570
R David Murrayac0cea52013-03-19 02:47:44 -0400571 def test_allmethods(self):
572 # issue 17476: allmethods was no longer returning unbound methods.
573 # This test is a bit fragile in the face of changes to object and type,
574 # but I can't think of a better way to do it without duplicating the
575 # logic of the function under test.
576
577 class TestClass(object):
578 def method_returning_true(self):
579 return True
580
581 # What we expect to get back: everything on object...
582 expected = dict(vars(object))
583 # ...plus our unbound method...
584 expected['method_returning_true'] = TestClass.method_returning_true
585 # ...but not the non-methods on object.
586 del expected['__doc__']
587 del expected['__class__']
588 # inspect resolves descriptors on type into methods, but vars doesn't,
589 # so we need to update __subclasshook__.
590 expected['__subclasshook__'] = TestClass.__subclasshook__
591
592 methods = pydoc.allmethods(TestClass)
593 self.assertDictEqual(methods, expected)
594
Georg Brandlb533e262008-05-25 18:19:30 +0000595
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200596class PydocImportTest(PydocBaseTest):
Ned Deily92a81a12011-10-06 14:19:03 -0700597
598 def setUp(self):
599 self.test_dir = os.mkdir(TESTFN)
600 self.addCleanup(rmtree, TESTFN)
601
602 def test_badimport(self):
603 # This tests the fix for issue 5230, where if pydoc found the module
604 # but the module had an internal import error pydoc would report no doc
605 # found.
606 modname = 'testmod_xyzzy'
607 testpairs = (
608 ('i_am_not_here', 'i_am_not_here'),
Brett Cannonfd074152012-04-14 14:10:13 -0400609 ('test.i_am_not_here_either', 'test.i_am_not_here_either'),
610 ('test.i_am_not_here.neither_am_i', 'test.i_am_not_here'),
611 ('i_am_not_here.{}'.format(modname), 'i_am_not_here'),
612 ('test.{}'.format(modname), 'test.{}'.format(modname)),
Ned Deily92a81a12011-10-06 14:19:03 -0700613 )
614
615 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
616 for importstring, expectedinmsg in testpairs:
617 with open(sourcefn, 'w') as f:
618 f.write("import {}\n".format(importstring))
619 result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii")
620 expected = badimport_pattern % (modname, expectedinmsg)
621 self.assertEqual(expected, result)
622
623 def test_apropos_with_bad_package(self):
624 # Issue 7425 - pydoc -k failed when bad package on path
625 pkgdir = os.path.join(TESTFN, "syntaxerr")
626 os.mkdir(pkgdir)
627 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
628 with open(badsyntax, 'w') as f:
629 f.write("invalid python syntax = $1\n")
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200630 with self.restrict_walk_packages(path=[TESTFN]):
631 with captured_stdout() as out:
632 with captured_stderr() as err:
633 pydoc.apropos('xyzzy')
634 # No result, no error
635 self.assertEqual(out.getvalue(), '')
636 self.assertEqual(err.getvalue(), '')
637 # The package name is still matched
638 with captured_stdout() as out:
639 with captured_stderr() as err:
640 pydoc.apropos('syntaxerr')
641 self.assertEqual(out.getvalue().strip(), 'syntaxerr')
642 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700643
644 def test_apropos_with_unreadable_dir(self):
645 # Issue 7367 - pydoc -k failed when unreadable dir on path
646 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
647 os.mkdir(self.unreadable_dir, 0)
648 self.addCleanup(os.rmdir, self.unreadable_dir)
649 # Note, on Windows the directory appears to be still
650 # readable so this is not really testing the issue there
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200651 with self.restrict_walk_packages(path=[TESTFN]):
652 with captured_stdout() as out:
653 with captured_stderr() as err:
654 pydoc.apropos('SOMEKEY')
655 # No result, no error
656 self.assertEqual(out.getvalue(), '')
657 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700658
Eric Snowa46ef702014-02-22 13:57:08 -0700659 @unittest.skip('causes undesireable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700660 def test_modules(self):
661 # See Helper.listmodules().
662 num_header_lines = 2
663 num_module_lines_min = 5 # Playing it safe.
664 num_footer_lines = 3
665 expected = num_header_lines + num_module_lines_min + num_footer_lines
666
667 output = StringIO()
668 helper = pydoc.Helper(output=output)
669 helper('modules')
670 result = output.getvalue().strip()
671 num_lines = len(result.splitlines())
672
673 self.assertGreaterEqual(num_lines, expected)
674
Eric Snowa46ef702014-02-22 13:57:08 -0700675 @unittest.skip('causes undesireable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700676 def test_modules_search(self):
677 # See Helper.listmodules().
678 expected = 'pydoc - '
679
680 output = StringIO()
681 helper = pydoc.Helper(output=output)
682 with captured_stdout() as help_io:
683 helper('modules pydoc')
684 result = help_io.getvalue()
685
686 self.assertIn(expected, result)
687
Eric Snowa46ef702014-02-22 13:57:08 -0700688 @unittest.skip('some buildbots are not cooperating (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700689 def test_modules_search_builtin(self):
Eric Snow5ea97502014-01-04 23:04:27 -0700690 expected = 'gc - '
Eric Snowaed5b222014-01-04 20:38:11 -0700691
692 output = StringIO()
693 helper = pydoc.Helper(output=output)
694 with captured_stdout() as help_io:
Eric Snow5ea97502014-01-04 23:04:27 -0700695 helper('modules garbage')
Eric Snowaed5b222014-01-04 20:38:11 -0700696 result = help_io.getvalue()
697
698 self.assertTrue(result.startswith(expected))
699
700 def test_importfile(self):
701 loaded_pydoc = pydoc.importfile(pydoc.__file__)
702
Eric Snow3a62d142014-01-06 20:42:59 -0700703 self.assertIsNot(loaded_pydoc, pydoc)
Eric Snowaed5b222014-01-04 20:38:11 -0700704 self.assertEqual(loaded_pydoc.__name__, 'pydoc')
705 self.assertEqual(loaded_pydoc.__file__, pydoc.__file__)
Eric Snow3a62d142014-01-06 20:42:59 -0700706 self.assertEqual(loaded_pydoc.__spec__, pydoc.__spec__)
Eric Snowaed5b222014-01-04 20:38:11 -0700707
Ned Deily92a81a12011-10-06 14:19:03 -0700708
Georg Brandlb533e262008-05-25 18:19:30 +0000709class TestDescriptions(unittest.TestCase):
710
711 def test_module(self):
712 # Check that pydocfodder module can be described
713 from test import pydocfodder
714 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000715 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000716
Georg Brandlb533e262008-05-25 18:19:30 +0000717 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000718 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +0000719 c = C()
720
721 self.assertEqual(pydoc.describe(C), 'class C')
722 self.assertEqual(pydoc.describe(c), 'C')
723 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000724 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000725
Éric Araujoe64e51b2011-07-29 17:03:55 +0200726 def test_builtin(self):
727 for name in ('str', 'str.translate', 'builtins.str',
728 'builtins.str.translate'):
729 # test low-level function
730 self.assertIsNotNone(pydoc.locate(name))
731 # test high-level function
732 try:
733 pydoc.render_doc(name)
734 except ImportError:
Terry Jan Reedyfe928de2014-06-20 14:59:11 -0400735 self.fail('finding the doc of {!r} failed'.format(name))
Éric Araujoe64e51b2011-07-29 17:03:55 +0200736
737 for name in ('notbuiltins', 'strrr', 'strr.translate',
738 'str.trrrranslate', 'builtins.strrr',
739 'builtins.str.trrranslate'):
740 self.assertIsNone(pydoc.locate(name))
741 self.assertRaises(ImportError, pydoc.render_doc, name)
742
Larry Hastings24a882b2014-02-20 23:34:46 -0800743 @staticmethod
744 def _get_summary_line(o):
745 text = pydoc.plain(pydoc.render_doc(o))
746 lines = text.split('\n')
747 assert len(lines) >= 2
748 return lines[2]
749
750 # these should include "self"
751 def test_unbound_python_method(self):
752 self.assertEqual(self._get_summary_line(textwrap.TextWrapper.wrap),
753 "wrap(self, text)")
754
Stefan Krah5de32782014-01-18 23:18:39 +0100755 @requires_docstrings
Larry Hastings24a882b2014-02-20 23:34:46 -0800756 def test_unbound_builtin_method(self):
757 self.assertEqual(self._get_summary_line(_pickle.Pickler.dump),
758 "dump(self, obj, /)")
759
760 # these no longer include "self"
761 def test_bound_python_method(self):
762 t = textwrap.TextWrapper()
763 self.assertEqual(self._get_summary_line(t.wrap),
764 "wrap(text) method of textwrap.TextWrapper instance")
765
766 @requires_docstrings
767 def test_bound_builtin_method(self):
768 s = StringIO()
769 p = _pickle.Pickler(s)
770 self.assertEqual(self._get_summary_line(p.dump),
771 "dump(obj, /) method of _pickle.Pickler instance")
772
773 # this should *never* include self!
774 @requires_docstrings
775 def test_module_level_callable(self):
776 self.assertEqual(self._get_summary_line(os.stat),
777 "stat(path, *, dir_fd=None, follow_symlinks=True)")
Larry Hastings1abd7082014-01-16 14:15:03 -0800778
Georg Brandlb533e262008-05-25 18:19:30 +0000779
Victor Stinner62a68f22011-05-20 02:29:13 +0200780@unittest.skipUnless(threading, 'Threading required for this test.')
Georg Brandld2f38572011-01-30 08:37:19 +0000781class PydocServerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000782 """Tests for pydoc._start_server"""
783
784 def test_server(self):
785
786 # Minimal test that starts the server, then stops it.
787 def my_url_handler(url, content_type):
788 text = 'the URL sent was: (%s, %s)' % (url, content_type)
789 return text
790
791 serverthread = pydoc._start_server(my_url_handler, port=0)
Senthil Kumaran2a42a0b2014-09-17 13:17:58 +0800792 self.assertIn('localhost', serverthread.docserver.address)
793
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000794 starttime = time.time()
795 timeout = 1 #seconds
796
797 while serverthread.serving:
798 time.sleep(.01)
799 if serverthread.serving and time.time() - starttime > timeout:
800 serverthread.stop()
801 break
802
803 self.assertEqual(serverthread.error, None)
804
805
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200806class PydocUrlHandlerTest(PydocBaseTest):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000807 """Tests for pydoc._url_handler"""
808
809 def test_content_type_err(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000810 f = pydoc._url_handler
Georg Brandld2f38572011-01-30 08:37:19 +0000811 self.assertRaises(TypeError, f, 'A', '')
812 self.assertRaises(TypeError, f, 'B', 'foobar')
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000813
814 def test_url_requests(self):
815 # Test for the correct title in the html pages returned.
816 # This tests the different parts of the URL handler without
817 # getting too picky about the exact html.
818 requests = [
Georg Brandld2f38572011-01-30 08:37:19 +0000819 ("", "Pydoc: Index of Modules"),
820 ("get?key=", "Pydoc: Index of Modules"),
821 ("index", "Pydoc: Index of Modules"),
822 ("topics", "Pydoc: Topics"),
823 ("keywords", "Pydoc: Keywords"),
824 ("pydoc", "Pydoc: module pydoc"),
825 ("get?key=pydoc", "Pydoc: module pydoc"),
826 ("search?key=pydoc", "Pydoc: Search Results"),
827 ("topic?key=def", "Pydoc: KEYWORD def"),
828 ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
829 ("foobar", "Pydoc: Error - foobar"),
830 ("getfile?key=foobar", "Pydoc: Error - getfile?key=foobar"),
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000831 ]
832
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200833 with self.restrict_walk_packages():
834 for url, title in requests:
835 text = pydoc._url_handler(url, "text/html")
836 result = get_html_title(text)
837 self.assertEqual(result, title, text)
838
839 path = string.__file__
840 title = "Pydoc: getfile " + path
841 url = "getfile?key=" + path
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000842 text = pydoc._url_handler(url, "text/html")
843 result = get_html_title(text)
844 self.assertEqual(result, title)
845
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000846
Ezio Melottib185a042011-04-28 07:42:55 +0300847class TestHelper(unittest.TestCase):
848 def test_keywords(self):
849 self.assertEqual(sorted(pydoc.Helper.keywords),
850 sorted(keyword.kwlist))
851
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700852class PydocWithMetaClasses(unittest.TestCase):
Ethan Furman3f2f1922013-10-22 07:30:24 -0700853 @unittest.skipIf(sys.flags.optimize >= 2,
854 "Docstrings are omitted with -O2 and above")
855 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
856 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700857 def test_DynamicClassAttribute(self):
858 class Meta(type):
859 def __getattr__(self, name):
860 if name == 'ham':
861 return 'spam'
862 return super().__getattr__(name)
863 class DA(metaclass=Meta):
864 @types.DynamicClassAttribute
865 def ham(self):
866 return 'eggs'
Ethan Furman3f2f1922013-10-22 07:30:24 -0700867 expected_text_data_docstrings = tuple('\n | ' + s if s else ''
868 for s in expected_data_docstrings)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700869 output = StringIO()
870 helper = pydoc.Helper(output=output)
871 helper(DA)
Ethan Furman3f2f1922013-10-22 07:30:24 -0700872 expected_text = expected_dynamicattribute_pattern % (
873 (__name__,) + expected_text_data_docstrings[:2])
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700874 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700875 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700876
Ethan Furman3f2f1922013-10-22 07:30:24 -0700877 @unittest.skipIf(sys.flags.optimize >= 2,
878 "Docstrings are omitted with -O2 and above")
879 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
880 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700881 def test_virtualClassAttributeWithOneMeta(self):
882 class Meta(type):
883 def __dir__(cls):
884 return ['__class__', '__module__', '__name__', 'LIFE']
885 def __getattr__(self, name):
886 if name =='LIFE':
887 return 42
888 return super().__getattr(name)
889 class Class(metaclass=Meta):
890 pass
891 output = StringIO()
892 helper = pydoc.Helper(output=output)
893 helper(Class)
894 expected_text = expected_virtualattribute_pattern1 % __name__
895 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700896 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700897
Ethan Furman3f2f1922013-10-22 07:30:24 -0700898 @unittest.skipIf(sys.flags.optimize >= 2,
899 "Docstrings are omitted with -O2 and above")
900 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
901 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700902 def test_virtualClassAttributeWithTwoMeta(self):
903 class Meta1(type):
904 def __dir__(cls):
905 return ['__class__', '__module__', '__name__', 'one']
906 def __getattr__(self, name):
907 if name =='one':
908 return 1
909 return super().__getattr__(name)
910 class Meta2(type):
911 def __dir__(cls):
912 return ['__class__', '__module__', '__name__', 'two']
913 def __getattr__(self, name):
914 if name =='two':
915 return 2
916 return super().__getattr__(name)
917 class Meta3(Meta1, Meta2):
918 def __dir__(cls):
919 return list(sorted(set(
920 ['__class__', '__module__', '__name__', 'three'] +
921 Meta1.__dir__(cls) + Meta2.__dir__(cls))))
922 def __getattr__(self, name):
923 if name =='three':
924 return 3
925 return super().__getattr__(name)
926 class Class1(metaclass=Meta1):
927 pass
928 class Class2(Class1, metaclass=Meta3):
929 pass
930 fail1 = fail2 = False
931 output = StringIO()
932 helper = pydoc.Helper(output=output)
933 helper(Class1)
934 expected_text1 = expected_virtualattribute_pattern2 % __name__
935 result1 = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700936 self.assertEqual(expected_text1, result1)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700937 output = StringIO()
938 helper = pydoc.Helper(output=output)
939 helper(Class2)
940 expected_text2 = expected_virtualattribute_pattern3 % __name__
941 result2 = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700942 self.assertEqual(expected_text2, result2)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700943
Ethan Furman3f2f1922013-10-22 07:30:24 -0700944 @unittest.skipIf(sys.flags.optimize >= 2,
945 "Docstrings are omitted with -O2 and above")
946 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
947 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700948 def test_buggy_dir(self):
949 class M(type):
950 def __dir__(cls):
951 return ['__class__', '__name__', 'missing', 'here']
952 class C(metaclass=M):
953 here = 'present!'
954 output = StringIO()
955 helper = pydoc.Helper(output=output)
956 helper(C)
957 expected_text = expected_missingattribute_pattern % __name__
958 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700959 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700960
Eric Snowaed5b222014-01-04 20:38:11 -0700961
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200962@reap_threads
Georg Brandlb533e262008-05-25 18:19:30 +0000963def test_main():
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200964 try:
965 test.support.run_unittest(PydocDocTest,
Ned Deily92a81a12011-10-06 14:19:03 -0700966 PydocImportTest,
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200967 TestDescriptions,
968 PydocServerTest,
969 PydocUrlHandlerTest,
970 TestHelper,
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700971 PydocWithMetaClasses,
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200972 )
973 finally:
974 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +0000975
976if __name__ == "__main__":
977 test_main()