blob: d68ab5595e877b6e7db839c90ca5307a79d679c1 [file] [log] [blame]
Georg Brandlb533e262008-05-25 18:19:30 +00001import os
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002import sys
Antoine Pitrou916fc7b2013-05-19 15:44:54 +02003import contextlib
Benjamin Peterson54237f92015-02-16 19:45:01 -05004import importlib.util
Georg Brandlb533e262008-05-25 18:19:30 +00005import inspect
Nick Coghlan7bb30b72010-12-03 09:29:11 +00006import pydoc
Benjamin Peterson54237f92015-02-16 19:45:01 -05007import py_compile
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
Benjamin Peterson54237f92015-02-16 19:45:01 -050012import stat
Nick Coghlan7bb30b72010-12-03 09:29:11 +000013import string
Georg Brandlb533e262008-05-25 18:19:30 +000014import test.support
Nick Coghlan7bb30b72010-12-03 09:29:11 +000015import time
Ethan Furmanb0c84cd2013-10-20 22:37:39 -070016import types
Guido van Rossum52e50042016-10-22 07:55:18 -070017import typing
Nick Coghlan7bb30b72010-12-03 09:29:11 +000018import unittest
Zachary Wareeb432142014-07-10 11:18:00 -050019import urllib.parse
Brian Curtin49c284c2010-03-31 03:19:28 +000020import xml.etree
R David Murrayead9bfc2016-06-03 19:28:35 -040021import xml.etree.ElementTree
Georg Brandld80d5f42010-12-03 07:47:22 +000022import textwrap
23from io import StringIO
Raymond Hettinger1103d052011-03-25 14:15:24 -070024from collections import namedtuple
Berker Peksagce643912015-05-06 06:33:17 +030025from test.support.script_helper import assert_python_ok
Antoine Pitroua6e81a22011-07-15 22:32:25 +020026from test.support import (
Ned Deily92a81a12011-10-06 14:19:03 -070027 TESTFN, rmtree,
Antoine Pitrou916fc7b2013-05-19 15:44:54 +020028 reap_children, reap_threads, captured_output, captured_stdout,
Stefan Krah5de32782014-01-18 23:18:39 +010029 captured_stderr, unlink, requires_docstrings
Antoine Pitroua6e81a22011-07-15 22:32:25 +020030)
Georg Brandlb533e262008-05-25 18:19:30 +000031from test import pydoc_mod
32
Victor Stinner62a68f22011-05-20 02:29:13 +020033try:
34 import threading
35except ImportError:
36 threading = None
37
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +020038class nonascii:
39 'Це не латиниця'
40 pass
41
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020042if test.support.HAVE_DOCSTRINGS:
43 expected_data_docstrings = (
44 'dictionary for instance variables (if defined)',
45 'list of weak references to the object (if defined)',
46 ) * 2
47else:
48 expected_data_docstrings = ('', '', '', '')
49
Barry Warsaw28a691b2010-04-17 00:19:56 +000050expected_text_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000051NAME
52 test.pydoc_mod - This is a test module for test_pydoc
Georg Brandlb533e262008-05-25 18:19:30 +000053%s
54CLASSES
55 builtins.object
56 A
57 B
Benjamin Petersoned1160b2014-06-07 16:44:00 -070058 C
Georg Brandlb533e262008-05-25 18:19:30 +000059\x20\x20\x20\x20
60 class A(builtins.object)
61 | Hello and goodbye
62 |\x20\x20
63 | Methods defined here:
64 |\x20\x20
65 | __init__()
66 | Wow, I have no function!
67 |\x20\x20
68 | ----------------------------------------------------------------------
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\x20\x20
75 class B(builtins.object)
76 | Data descriptors defined here:
77 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020078 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000079 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020080 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000081 |\x20\x20
82 | ----------------------------------------------------------------------
83 | Data and other attributes defined here:
84 |\x20\x20
85 | NO_MEANING = 'eggs'
Yury Selivanovf8cb8a12016-09-08 20:50:03 -070086 |\x20\x20
87 | __annotations__ = {'NO_MEANING': <class 'str'>}
Benjamin Petersoned1160b2014-06-07 16:44:00 -070088\x20\x20\x20\x20
89 class C(builtins.object)
90 | Methods defined here:
91 |\x20\x20
92 | get_answer(self)
93 | Return say_no()
94 |\x20\x20
95 | is_it_true(self)
96 | Return self.get_answer()
97 |\x20\x20
98 | say_no(self)
99 |\x20\x20
100 | ----------------------------------------------------------------------
101 | Data descriptors defined here:
102 |\x20\x20
103 | __dict__
104 | dictionary for instance variables (if defined)
105 |\x20\x20
106 | __weakref__
107 | list of weak references to the object (if defined)
Georg Brandlb533e262008-05-25 18:19:30 +0000108
109FUNCTIONS
110 doc_func()
111 This function solves all of the world's problems:
112 hunger
113 lack of Python
114 war
115\x20\x20\x20\x20
116 nodoc_func()
117
118DATA
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000119 __xyz__ = 'X, Y and Z'
Georg Brandlb533e262008-05-25 18:19:30 +0000120
121VERSION
122 1.2.3.4
123
124AUTHOR
125 Benjamin Peterson
126
127CREDITS
128 Nobody
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000129
130FILE
131 %s
Georg Brandlb533e262008-05-25 18:19:30 +0000132""".strip()
133
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200134expected_text_data_docstrings = tuple('\n | ' + s if s else ''
135 for s in expected_data_docstrings)
136
Barry Warsaw28a691b2010-04-17 00:19:56 +0000137expected_html_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +0000138<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
139<tr bgcolor="#7799ee">
140<td valign=bottom>&nbsp;<br>
141<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
142><td align=right valign=bottom
143><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
144 <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
145<p>
146<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
147<tr bgcolor="#ee77aa">
148<td colspan=3 valign=bottom>&nbsp;<br>
149<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
150\x20\x20\x20\x20
151<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
152<td width="100%%"><dl>
153<dt><font face="helvetica, arial"><a href="builtins.html#object">builtins.object</a>
154</font></dt><dd>
155<dl>
156<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
157</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700158</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#C">C</a>
Georg Brandlb533e262008-05-25 18:19:30 +0000159</font></dt></dl>
160</dd>
161</dl>
162 <p>
163<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
164<tr bgcolor="#ffc8d8">
165<td colspan=3 valign=bottom>&nbsp;<br>
166<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>
167\x20\x20\x20\x20
168<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
169<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
170<tr><td>&nbsp;</td>
171<td width="100%%">Methods defined here:<br>
172<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>
173
174<hr>
175Data descriptors defined here:<br>
176<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200177<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000178</dl>
179<dl><dt><strong>__weakref__</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</td></tr></table> <p>
183<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
184<tr bgcolor="#ffc8d8">
185<td colspan=3 valign=bottom>&nbsp;<br>
186<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>
187\x20\x20\x20\x20
188<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
189<td width="100%%">Data descriptors defined here:<br>
190<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200191<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000192</dl>
193<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200194<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000195</dl>
196<hr>
197Data and other attributes defined here:<br>
198<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
199
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700200<dl><dt><strong>__annotations__</strong> = {'NO_MEANING': &lt;class 'str'&gt;}</dl>
201
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700202</td></tr></table> <p>
203<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
204<tr bgcolor="#ffc8d8">
205<td colspan=3 valign=bottom>&nbsp;<br>
206<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>
207\x20\x20\x20\x20
208<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
209<td width="100%%">Methods defined here:<br>
210<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>
211
212<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>
213
214<dl><dt><a name="C-say_no"><strong>say_no</strong></a>(self)</dt></dl>
215
216<hr>
217Data descriptors defined here:<br>
218<dl><dt><strong>__dict__</strong></dt>
219<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
220</dl>
221<dl><dt><strong>__weakref__</strong></dt>
222<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
223</dl>
Georg Brandlb533e262008-05-25 18:19:30 +0000224</td></tr></table></td></tr></table><p>
225<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
226<tr bgcolor="#eeaa77">
227<td colspan=3 valign=bottom>&nbsp;<br>
228<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
229\x20\x20\x20\x20
230<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
231<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>
232hunger<br>
233lack&nbsp;of&nbsp;Python<br>
234war</tt></dd></dl>
235 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
236</td></tr></table><p>
237<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
238<tr bgcolor="#55aa55">
239<td colspan=3 valign=bottom>&nbsp;<br>
240<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
241\x20\x20\x20\x20
242<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000243<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p>
Georg Brandlb533e262008-05-25 18:19:30 +0000244<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
245<tr bgcolor="#7799ee">
246<td colspan=3 valign=bottom>&nbsp;<br>
247<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
248\x20\x20\x20\x20
249<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
250<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
251<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
252<tr bgcolor="#7799ee">
253<td colspan=3 valign=bottom>&nbsp;<br>
254<font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
255\x20\x20\x20\x20
256<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
257<td width="100%%">Nobody</td></tr></table>
Barry Warsaw28a691b2010-04-17 00:19:56 +0000258""".strip() # ' <- emacs turd
Georg Brandlb533e262008-05-25 18:19:30 +0000259
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200260expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;')
261 for s in expected_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000262
263# output pattern for missing module
Serhiy Storchaka1c205512015-03-01 00:42:54 +0200264missing_pattern = '''\
265No Python documentation found for %r.
266Use help() to get the interactive help utility.
267Use help(str) for help on the str class.'''.replace('\n', os.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000268
Benjamin Peterson0289b152009-06-28 17:22:03 +0000269# output pattern for module with bad imports
Eric Snow46f97b82016-09-07 16:56:15 -0700270badimport_pattern = "problem in %s - ModuleNotFoundError: No module named %r"
Benjamin Peterson0289b152009-06-28 17:22:03 +0000271
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700272expected_dynamicattribute_pattern = """
273Help on class DA in module %s:
274
275class DA(builtins.object)
276 | Data descriptors defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200277 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700278 | __dict__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200279 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700280 | __weakref__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200281 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700282 | ham
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200283 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700284 | ----------------------------------------------------------------------
285 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200286 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700287 | ham = 'spam'
288""".strip()
289
290expected_virtualattribute_pattern1 = """
291Help on class Class in module %s:
292
293class Class(builtins.object)
294 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200295 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700296 | LIFE = 42
297""".strip()
298
299expected_virtualattribute_pattern2 = """
300Help on class Class1 in module %s:
301
302class Class1(builtins.object)
303 | 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
306""".strip()
307
308expected_virtualattribute_pattern3 = """
309Help on class Class2 in module %s:
310
311class Class2(Class1)
312 | Method resolution order:
313 | Class2
314 | Class1
315 | builtins.object
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200316 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700317 | Data and other attributes inherited from Meta1:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200318 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700319 | one = 1
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200320 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700321 | ----------------------------------------------------------------------
322 | Data and other attributes inherited from Meta3:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200323 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700324 | three = 3
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200325 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700326 | ----------------------------------------------------------------------
327 | Data and other attributes inherited from Meta2:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200328 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700329 | two = 2
330""".strip()
331
332expected_missingattribute_pattern = """
333Help on class C in module %s:
334
335class C(builtins.object)
336 | Data and other attributes defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200337 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700338 | here = 'present!'
339""".strip()
340
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200341def run_pydoc(module_name, *args, **env):
Georg Brandlb533e262008-05-25 18:19:30 +0000342 """
343 Runs pydoc on the specified module. Returns the stripped
344 output of pydoc.
345 """
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200346 args = args + (module_name,)
Ned Deily92a81a12011-10-06 14:19:03 -0700347 # do not write bytecode files to avoid caching errors
348 rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200349 return out.strip()
Georg Brandlb533e262008-05-25 18:19:30 +0000350
351def get_pydoc_html(module):
352 "Returns pydoc generated output as html"
353 doc = pydoc.HTMLDoc()
354 output = doc.docmodule(module)
355 loc = doc.getdocloc(pydoc_mod) or ""
356 if loc:
357 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
358 return output.strip(), loc
359
R David Murrayead9bfc2016-06-03 19:28:35 -0400360def get_pydoc_link(module):
361 "Returns a documentation web link of a module"
362 dirname = os.path.dirname
Victor Stinnerfd465612017-07-27 11:21:26 +0200363 basedir = dirname(dirname(os.path.realpath(__file__)))
R David Murrayead9bfc2016-06-03 19:28:35 -0400364 doc = pydoc.TextDoc()
365 loc = doc.getdocloc(module, basedir=basedir)
366 return loc
367
Georg Brandlb533e262008-05-25 18:19:30 +0000368def get_pydoc_text(module):
369 "Returns pydoc generated output as text"
370 doc = pydoc.TextDoc()
371 loc = doc.getdocloc(pydoc_mod) or ""
372 if loc:
373 loc = "\nMODULE DOCS\n " + loc + "\n"
374
375 output = doc.docmodule(module)
376
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000377 # clean up the extra text formatting that pydoc performs
Georg Brandlb533e262008-05-25 18:19:30 +0000378 patt = re.compile('\b.')
379 output = patt.sub('', output)
380 return output.strip(), loc
381
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000382def get_html_title(text):
Nick Coghlanecace282010-12-03 16:08:46 +0000383 # Bit of hack, but good enough for test purposes
384 header, _, _ = text.partition("</head>")
385 _, _, title = header.partition("<title>")
386 title, _, _ = title.partition("</title>")
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000387 return title
388
Georg Brandlb533e262008-05-25 18:19:30 +0000389
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200390class PydocBaseTest(unittest.TestCase):
391
392 def _restricted_walk_packages(self, walk_packages, path=None):
393 """
394 A version of pkgutil.walk_packages() that will restrict itself to
395 a given path.
396 """
397 default_path = path or [os.path.dirname(__file__)]
398 def wrapper(path=None, prefix='', onerror=None):
399 return walk_packages(path or default_path, prefix, onerror)
400 return wrapper
401
402 @contextlib.contextmanager
403 def restrict_walk_packages(self, path=None):
404 walk_packages = pkgutil.walk_packages
405 pkgutil.walk_packages = self._restricted_walk_packages(walk_packages,
406 path)
407 try:
408 yield
409 finally:
410 pkgutil.walk_packages = walk_packages
411
Martin Panter9ad0aae2015-11-06 00:27:14 +0000412 def call_url_handler(self, url, expected_title):
413 text = pydoc._url_handler(url, "text/html")
414 result = get_html_title(text)
415 # Check the title to ensure an unexpected error page was not returned
416 self.assertEqual(result, expected_title, text)
417 return text
418
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200419
Georg Brandld2f38572011-01-30 08:37:19 +0000420class PydocDocTest(unittest.TestCase):
Georg Brandlb533e262008-05-25 18:19:30 +0000421
R. David Murray378c0cf2010-02-24 01:46:21 +0000422 @unittest.skipIf(sys.flags.optimize >= 2,
423 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000424 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
425 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100426 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000427 def test_html_doc(self):
428 result, doc_loc = get_pydoc_html(pydoc_mod)
429 mod_file = inspect.getabsfile(pydoc_mod)
Zachary Wareeb432142014-07-10 11:18:00 -0500430 mod_url = urllib.parse.quote(mod_file)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200431 expected_html = expected_html_pattern % (
432 (mod_url, mod_file, doc_loc) +
433 expected_html_data_docstrings)
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700434 self.assertEqual(result, expected_html)
Georg Brandlb533e262008-05-25 18:19:30 +0000435
R. David Murray378c0cf2010-02-24 01:46:21 +0000436 @unittest.skipIf(sys.flags.optimize >= 2,
437 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000438 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
439 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100440 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000441 def test_text_doc(self):
442 result, doc_loc = get_pydoc_text(pydoc_mod)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200443 expected_text = expected_text_pattern % (
444 (doc_loc,) +
445 expected_text_data_docstrings +
446 (inspect.getabsfile(pydoc_mod),))
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700447 self.assertEqual(expected_text, result)
Georg Brandlb533e262008-05-25 18:19:30 +0000448
Serhiy Storchaka056eb022014-02-19 23:05:12 +0200449 def test_text_enum_member_with_value_zero(self):
450 # Test issue #20654 to ensure enum member with value 0 can be
451 # displayed. It used to throw KeyError: 'zero'.
452 import enum
453 class BinaryInteger(enum.IntEnum):
454 zero = 0
455 one = 1
456 doc = pydoc.render_doc(BinaryInteger)
457 self.assertIn('<BinaryInteger.zero: 0>', doc)
458
R David Murrayead9bfc2016-06-03 19:28:35 -0400459 def test_mixed_case_module_names_are_lower_cased(self):
460 # issue16484
461 doc_link = get_pydoc_link(xml.etree.ElementTree)
462 self.assertIn('xml.etree.elementtree', doc_link)
463
Brian Curtin49c284c2010-03-31 03:19:28 +0000464 def test_issue8225(self):
465 # Test issue8225 to ensure no doc link appears for xml.etree
466 result, doc_loc = get_pydoc_text(xml.etree)
467 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
468
Benjamin Peterson159824e2014-06-07 20:14:26 -0700469 def test_getpager_with_stdin_none(self):
470 previous_stdin = sys.stdin
471 try:
472 sys.stdin = None
473 pydoc.getpager() # Shouldn't fail.
474 finally:
475 sys.stdin = previous_stdin
476
R David Murrayc43125a2012-04-23 13:23:57 -0400477 def test_non_str_name(self):
478 # issue14638
479 # Treat illegal (non-str) name like no name
480 class A:
481 __name__ = 42
482 class B:
483 pass
484 adoc = pydoc.render_doc(A())
485 bdoc = pydoc.render_doc(B())
Eric Snow4f29e752016-09-08 15:11:11 -0700486 self.assertEqual(adoc.replace("A", "B"), bdoc)
R David Murrayc43125a2012-04-23 13:23:57 -0400487
Georg Brandlb533e262008-05-25 18:19:30 +0000488 def test_not_here(self):
489 missing_module = "test.i_am_not_here"
490 result = str(run_pydoc(missing_module), 'ascii')
491 expected = missing_pattern % missing_module
492 self.assertEqual(expected, result,
493 "documentation for missing module found")
494
Serhiy Storchaka4c094e52015-03-01 15:31:36 +0200495 @unittest.skipIf(sys.flags.optimize >= 2,
496 'Docstrings are omitted with -OO and above')
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +0200497 def test_not_ascii(self):
498 result = run_pydoc('test.test_pydoc.nonascii', PYTHONIOENCODING='ascii')
499 encoded = nonascii.__doc__.encode('ascii', 'backslashreplace')
500 self.assertIn(encoded, result)
501
R. David Murray1f1b9d32009-05-27 20:56:59 +0000502 def test_input_strip(self):
503 missing_module = " test.i_am_not_here "
504 result = str(run_pydoc(missing_module), 'ascii')
505 expected = missing_pattern % missing_module.strip()
506 self.assertEqual(expected, result)
507
Ezio Melotti412c95a2010-02-16 23:31:04 +0000508 def test_stripid(self):
509 # test with strings, other implementations might have different repr()
510 stripid = pydoc.stripid
511 # strip the id
512 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
513 '<function stripid>')
514 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
515 '<function stripid>')
516 # nothing to strip, return the same text
517 self.assertEqual(stripid('42'), '42')
518 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
519 "<type 'exceptions.Exception'>")
520
Georg Brandld80d5f42010-12-03 07:47:22 +0000521 @unittest.skipIf(sys.flags.optimize >= 2,
522 'Docstrings are omitted with -O2 and above')
Brett Cannon7a540732011-02-22 03:04:06 +0000523 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
524 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100525 @requires_docstrings
Georg Brandld80d5f42010-12-03 07:47:22 +0000526 def test_help_output_redirect(self):
527 # issue 940286, if output is set in Helper, then all output from
528 # Helper.help should be redirected
529 old_pattern = expected_text_pattern
530 getpager_old = pydoc.getpager
531 getpager_new = lambda: (lambda x: x)
532 self.maxDiff = None
533
534 buf = StringIO()
535 helper = pydoc.Helper(output=buf)
536 unused, doc_loc = get_pydoc_text(pydoc_mod)
537 module = "test.pydoc_mod"
538 help_header = """
539 Help on module test.pydoc_mod in test:
540
541 """.lstrip()
542 help_header = textwrap.dedent(help_header)
543 expected_help_pattern = help_header + expected_text_pattern
544
545 pydoc.getpager = getpager_new
546 try:
547 with captured_output('stdout') as output, \
548 captured_output('stderr') as err:
549 helper.help(module)
550 result = buf.getvalue().strip()
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200551 expected_text = expected_help_pattern % (
552 (doc_loc,) +
553 expected_text_data_docstrings +
554 (inspect.getabsfile(pydoc_mod),))
Georg Brandld80d5f42010-12-03 07:47:22 +0000555 self.assertEqual('', output.getvalue())
556 self.assertEqual('', err.getvalue())
557 self.assertEqual(expected_text, result)
558 finally:
559 pydoc.getpager = getpager_old
560
Raymond Hettinger1103d052011-03-25 14:15:24 -0700561 def test_namedtuple_public_underscore(self):
562 NT = namedtuple('NT', ['abc', 'def'], rename=True)
563 with captured_stdout() as help_io:
Terry Jan Reedy5c811642013-11-04 21:43:26 -0500564 pydoc.help(NT)
Raymond Hettinger1103d052011-03-25 14:15:24 -0700565 helptext = help_io.getvalue()
566 self.assertIn('_1', helptext)
567 self.assertIn('_replace', helptext)
568 self.assertIn('_asdict', helptext)
569
Victor Stinnere6c910e2011-06-30 15:55:43 +0200570 def test_synopsis(self):
571 self.addCleanup(unlink, TESTFN)
572 for encoding in ('ISO-8859-1', 'UTF-8'):
573 with open(TESTFN, 'w', encoding=encoding) as script:
574 if encoding != 'UTF-8':
575 print('#coding: {}'.format(encoding), file=script)
576 print('"""line 1: h\xe9', file=script)
577 print('line 2: hi"""', file=script)
578 synopsis = pydoc.synopsis(TESTFN, {})
579 self.assertEqual(synopsis, 'line 1: h\xe9')
580
Serhiy Storchaka4c094e52015-03-01 15:31:36 +0200581 @unittest.skipIf(sys.flags.optimize >= 2,
582 'Docstrings are omitted with -OO and above')
Eric Snowaed5b222014-01-04 20:38:11 -0700583 def test_synopsis_sourceless(self):
584 expected = os.__doc__.splitlines()[0]
585 filename = os.__cached__
586 synopsis = pydoc.synopsis(filename)
587
588 self.assertEqual(synopsis, expected)
589
Benjamin Peterson54237f92015-02-16 19:45:01 -0500590 def test_synopsis_sourceless_empty_doc(self):
591 with test.support.temp_cwd() as test_dir:
592 init_path = os.path.join(test_dir, 'foomod42.py')
593 cached_path = importlib.util.cache_from_source(init_path)
594 with open(init_path, 'w') as fobj:
595 fobj.write("foo = 1")
596 py_compile.compile(init_path)
597 synopsis = pydoc.synopsis(init_path, {})
598 self.assertIsNone(synopsis)
599 synopsis_cached = pydoc.synopsis(cached_path, {})
600 self.assertIsNone(synopsis_cached)
601
R David Murray455f2962013-03-19 00:00:33 -0400602 def test_splitdoc_with_description(self):
603 example_string = "I Am A Doc\n\n\nHere is my description"
604 self.assertEqual(pydoc.splitdoc(example_string),
605 ('I Am A Doc', '\nHere is my description'))
606
607 def test_is_object_or_method(self):
608 doc = pydoc.Doc()
609 # Bound Method
610 self.assertTrue(pydoc._is_some_method(doc.fail))
611 # Method Descriptor
612 self.assertTrue(pydoc._is_some_method(int.__add__))
613 # String
614 self.assertFalse(pydoc._is_some_method("I am not a method"))
615
616 def test_is_package_when_not_package(self):
617 with test.support.temp_cwd() as test_dir:
618 self.assertFalse(pydoc.ispackage(test_dir))
619
620 def test_is_package_when_is_package(self):
621 with test.support.temp_cwd() as test_dir:
622 init_path = os.path.join(test_dir, '__init__.py')
623 open(init_path, 'w').close()
624 self.assertTrue(pydoc.ispackage(test_dir))
625 os.remove(init_path)
626
R David Murrayac0cea52013-03-19 02:47:44 -0400627 def test_allmethods(self):
628 # issue 17476: allmethods was no longer returning unbound methods.
629 # This test is a bit fragile in the face of changes to object and type,
630 # but I can't think of a better way to do it without duplicating the
631 # logic of the function under test.
632
633 class TestClass(object):
634 def method_returning_true(self):
635 return True
636
637 # What we expect to get back: everything on object...
638 expected = dict(vars(object))
639 # ...plus our unbound method...
640 expected['method_returning_true'] = TestClass.method_returning_true
641 # ...but not the non-methods on object.
642 del expected['__doc__']
643 del expected['__class__']
644 # inspect resolves descriptors on type into methods, but vars doesn't,
Nick Coghland78448e2016-07-30 16:26:03 +1000645 # so we need to update __subclasshook__ and __init_subclass__.
R David Murrayac0cea52013-03-19 02:47:44 -0400646 expected['__subclasshook__'] = TestClass.__subclasshook__
Nick Coghland78448e2016-07-30 16:26:03 +1000647 expected['__init_subclass__'] = TestClass.__init_subclass__
R David Murrayac0cea52013-03-19 02:47:44 -0400648
649 methods = pydoc.allmethods(TestClass)
650 self.assertDictEqual(methods, expected)
651
Georg Brandlb533e262008-05-25 18:19:30 +0000652
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200653class PydocImportTest(PydocBaseTest):
Ned Deily92a81a12011-10-06 14:19:03 -0700654
655 def setUp(self):
656 self.test_dir = os.mkdir(TESTFN)
657 self.addCleanup(rmtree, TESTFN)
Benjamin Peterson54237f92015-02-16 19:45:01 -0500658 importlib.invalidate_caches()
Ned Deily92a81a12011-10-06 14:19:03 -0700659
660 def test_badimport(self):
661 # This tests the fix for issue 5230, where if pydoc found the module
662 # but the module had an internal import error pydoc would report no doc
663 # found.
664 modname = 'testmod_xyzzy'
665 testpairs = (
666 ('i_am_not_here', 'i_am_not_here'),
Brett Cannonfd074152012-04-14 14:10:13 -0400667 ('test.i_am_not_here_either', 'test.i_am_not_here_either'),
668 ('test.i_am_not_here.neither_am_i', 'test.i_am_not_here'),
669 ('i_am_not_here.{}'.format(modname), 'i_am_not_here'),
670 ('test.{}'.format(modname), 'test.{}'.format(modname)),
Ned Deily92a81a12011-10-06 14:19:03 -0700671 )
672
673 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
674 for importstring, expectedinmsg in testpairs:
675 with open(sourcefn, 'w') as f:
676 f.write("import {}\n".format(importstring))
677 result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii")
678 expected = badimport_pattern % (modname, expectedinmsg)
679 self.assertEqual(expected, result)
680
681 def test_apropos_with_bad_package(self):
682 # Issue 7425 - pydoc -k failed when bad package on path
683 pkgdir = os.path.join(TESTFN, "syntaxerr")
684 os.mkdir(pkgdir)
685 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
686 with open(badsyntax, 'w') as f:
687 f.write("invalid python syntax = $1\n")
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200688 with self.restrict_walk_packages(path=[TESTFN]):
689 with captured_stdout() as out:
690 with captured_stderr() as err:
691 pydoc.apropos('xyzzy')
692 # No result, no error
693 self.assertEqual(out.getvalue(), '')
694 self.assertEqual(err.getvalue(), '')
695 # The package name is still matched
696 with captured_stdout() as out:
697 with captured_stderr() as err:
698 pydoc.apropos('syntaxerr')
699 self.assertEqual(out.getvalue().strip(), 'syntaxerr')
700 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700701
702 def test_apropos_with_unreadable_dir(self):
703 # Issue 7367 - pydoc -k failed when unreadable dir on path
704 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
705 os.mkdir(self.unreadable_dir, 0)
706 self.addCleanup(os.rmdir, self.unreadable_dir)
707 # Note, on Windows the directory appears to be still
708 # readable so this is not really testing the issue there
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200709 with self.restrict_walk_packages(path=[TESTFN]):
710 with captured_stdout() as out:
711 with captured_stderr() as err:
712 pydoc.apropos('SOMEKEY')
713 # No result, no error
714 self.assertEqual(out.getvalue(), '')
715 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700716
Benjamin Peterson54237f92015-02-16 19:45:01 -0500717 def test_apropos_empty_doc(self):
718 pkgdir = os.path.join(TESTFN, 'walkpkg')
719 os.mkdir(pkgdir)
720 self.addCleanup(rmtree, pkgdir)
721 init_path = os.path.join(pkgdir, '__init__.py')
722 with open(init_path, 'w') as fobj:
723 fobj.write("foo = 1")
724 current_mode = stat.S_IMODE(os.stat(pkgdir).st_mode)
725 try:
726 os.chmod(pkgdir, current_mode & ~stat.S_IEXEC)
727 with self.restrict_walk_packages(path=[TESTFN]), captured_stdout() as stdout:
728 pydoc.apropos('')
729 self.assertIn('walkpkg', stdout.getvalue())
730 finally:
731 os.chmod(pkgdir, current_mode)
732
Martin Panter9ad0aae2015-11-06 00:27:14 +0000733 def test_url_search_package_error(self):
734 # URL handler search should cope with packages that raise exceptions
735 pkgdir = os.path.join(TESTFN, "test_error_package")
736 os.mkdir(pkgdir)
737 init = os.path.join(pkgdir, "__init__.py")
738 with open(init, "wt", encoding="ascii") as f:
739 f.write("""raise ValueError("ouch")\n""")
740 with self.restrict_walk_packages(path=[TESTFN]):
741 # Package has to be importable for the error to have any effect
742 saved_paths = tuple(sys.path)
743 sys.path.insert(0, TESTFN)
744 try:
745 with self.assertRaisesRegex(ValueError, "ouch"):
746 import test_error_package # Sanity check
747
748 text = self.call_url_handler("search?key=test_error_package",
749 "Pydoc: Search Results")
750 found = ('<a href="test_error_package.html">'
751 'test_error_package</a>')
752 self.assertIn(found, text)
753 finally:
754 sys.path[:] = saved_paths
755
Martin Panter46f50722016-05-26 05:35:26 +0000756 @unittest.skip('causes undesirable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700757 def test_modules(self):
758 # See Helper.listmodules().
759 num_header_lines = 2
760 num_module_lines_min = 5 # Playing it safe.
761 num_footer_lines = 3
762 expected = num_header_lines + num_module_lines_min + num_footer_lines
763
764 output = StringIO()
765 helper = pydoc.Helper(output=output)
766 helper('modules')
767 result = output.getvalue().strip()
768 num_lines = len(result.splitlines())
769
770 self.assertGreaterEqual(num_lines, expected)
771
Martin Panter46f50722016-05-26 05:35:26 +0000772 @unittest.skip('causes undesirable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700773 def test_modules_search(self):
774 # See Helper.listmodules().
775 expected = 'pydoc - '
776
777 output = StringIO()
778 helper = pydoc.Helper(output=output)
779 with captured_stdout() as help_io:
780 helper('modules pydoc')
781 result = help_io.getvalue()
782
783 self.assertIn(expected, result)
784
Eric Snowa46ef702014-02-22 13:57:08 -0700785 @unittest.skip('some buildbots are not cooperating (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700786 def test_modules_search_builtin(self):
Eric Snow5ea97502014-01-04 23:04:27 -0700787 expected = 'gc - '
Eric Snowaed5b222014-01-04 20:38:11 -0700788
789 output = StringIO()
790 helper = pydoc.Helper(output=output)
791 with captured_stdout() as help_io:
Eric Snow5ea97502014-01-04 23:04:27 -0700792 helper('modules garbage')
Eric Snowaed5b222014-01-04 20:38:11 -0700793 result = help_io.getvalue()
794
795 self.assertTrue(result.startswith(expected))
796
797 def test_importfile(self):
798 loaded_pydoc = pydoc.importfile(pydoc.__file__)
799
Eric Snow3a62d142014-01-06 20:42:59 -0700800 self.assertIsNot(loaded_pydoc, pydoc)
Eric Snowaed5b222014-01-04 20:38:11 -0700801 self.assertEqual(loaded_pydoc.__name__, 'pydoc')
802 self.assertEqual(loaded_pydoc.__file__, pydoc.__file__)
Eric Snow3a62d142014-01-06 20:42:59 -0700803 self.assertEqual(loaded_pydoc.__spec__, pydoc.__spec__)
Eric Snowaed5b222014-01-04 20:38:11 -0700804
Ned Deily92a81a12011-10-06 14:19:03 -0700805
Georg Brandlb533e262008-05-25 18:19:30 +0000806class TestDescriptions(unittest.TestCase):
807
808 def test_module(self):
809 # Check that pydocfodder module can be described
810 from test import pydocfodder
811 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000812 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000813
Georg Brandlb533e262008-05-25 18:19:30 +0000814 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000815 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +0000816 c = C()
817
818 self.assertEqual(pydoc.describe(C), 'class C')
819 self.assertEqual(pydoc.describe(c), 'C')
820 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000821 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000822
Guido van Rossum52e50042016-10-22 07:55:18 -0700823 def test_typing_pydoc(self):
824 def foo(data: typing.List[typing.Any],
825 x: int) -> typing.Iterator[typing.Tuple[int, typing.Any]]:
826 ...
827 T = typing.TypeVar('T')
828 class C(typing.Generic[T], typing.Mapping[int, str]): ...
829 self.assertEqual(pydoc.render_doc(foo).splitlines()[-1],
830 'f\x08fo\x08oo\x08o(data:List[Any], x:int)'
831 ' -> Iterator[Tuple[int, Any]]')
832 self.assertEqual(pydoc.render_doc(C).splitlines()[2],
833 'class C\x08C(typing.Mapping)')
834
Éric Araujoe64e51b2011-07-29 17:03:55 +0200835 def test_builtin(self):
836 for name in ('str', 'str.translate', 'builtins.str',
837 'builtins.str.translate'):
838 # test low-level function
839 self.assertIsNotNone(pydoc.locate(name))
840 # test high-level function
841 try:
842 pydoc.render_doc(name)
843 except ImportError:
Terry Jan Reedyfe928de2014-06-20 14:59:11 -0400844 self.fail('finding the doc of {!r} failed'.format(name))
Éric Araujoe64e51b2011-07-29 17:03:55 +0200845
846 for name in ('notbuiltins', 'strrr', 'strr.translate',
847 'str.trrrranslate', 'builtins.strrr',
848 'builtins.str.trrranslate'):
849 self.assertIsNone(pydoc.locate(name))
850 self.assertRaises(ImportError, pydoc.render_doc, name)
851
Larry Hastings24a882b2014-02-20 23:34:46 -0800852 @staticmethod
853 def _get_summary_line(o):
854 text = pydoc.plain(pydoc.render_doc(o))
855 lines = text.split('\n')
856 assert len(lines) >= 2
857 return lines[2]
858
859 # these should include "self"
860 def test_unbound_python_method(self):
861 self.assertEqual(self._get_summary_line(textwrap.TextWrapper.wrap),
862 "wrap(self, text)")
863
Stefan Krah5de32782014-01-18 23:18:39 +0100864 @requires_docstrings
Larry Hastings24a882b2014-02-20 23:34:46 -0800865 def test_unbound_builtin_method(self):
866 self.assertEqual(self._get_summary_line(_pickle.Pickler.dump),
867 "dump(self, obj, /)")
868
869 # these no longer include "self"
870 def test_bound_python_method(self):
871 t = textwrap.TextWrapper()
872 self.assertEqual(self._get_summary_line(t.wrap),
873 "wrap(text) method of textwrap.TextWrapper instance")
874
Raymond Hettinger95801bb2015-08-18 22:25:16 -0700875 def test_field_order_for_named_tuples(self):
876 Person = namedtuple('Person', ['nickname', 'firstname', 'agegroup'])
877 s = pydoc.render_doc(Person)
878 self.assertLess(s.index('nickname'), s.index('firstname'))
879 self.assertLess(s.index('firstname'), s.index('agegroup'))
880
881 class NonIterableFields:
882 _fields = None
883
884 class NonHashableFields:
885 _fields = [[]]
886
887 # Make sure these doesn't fail
888 pydoc.render_doc(NonIterableFields)
889 pydoc.render_doc(NonHashableFields)
890
Larry Hastings24a882b2014-02-20 23:34:46 -0800891 @requires_docstrings
892 def test_bound_builtin_method(self):
893 s = StringIO()
894 p = _pickle.Pickler(s)
895 self.assertEqual(self._get_summary_line(p.dump),
896 "dump(obj, /) method of _pickle.Pickler instance")
897
898 # this should *never* include self!
899 @requires_docstrings
900 def test_module_level_callable(self):
901 self.assertEqual(self._get_summary_line(os.stat),
902 "stat(path, *, dir_fd=None, follow_symlinks=True)")
Larry Hastings1abd7082014-01-16 14:15:03 -0800903
Georg Brandlb533e262008-05-25 18:19:30 +0000904
Victor Stinner62a68f22011-05-20 02:29:13 +0200905@unittest.skipUnless(threading, 'Threading required for this test.')
Georg Brandld2f38572011-01-30 08:37:19 +0000906class PydocServerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000907 """Tests for pydoc._start_server"""
908
909 def test_server(self):
910
911 # Minimal test that starts the server, then stops it.
912 def my_url_handler(url, content_type):
913 text = 'the URL sent was: (%s, %s)' % (url, content_type)
914 return text
915
916 serverthread = pydoc._start_server(my_url_handler, port=0)
Senthil Kumaran2a42a0b2014-09-17 13:17:58 +0800917 self.assertIn('localhost', serverthread.docserver.address)
918
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000919 starttime = time.time()
920 timeout = 1 #seconds
921
922 while serverthread.serving:
923 time.sleep(.01)
924 if serverthread.serving and time.time() - starttime > timeout:
925 serverthread.stop()
926 break
927
928 self.assertEqual(serverthread.error, None)
929
930
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200931class PydocUrlHandlerTest(PydocBaseTest):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000932 """Tests for pydoc._url_handler"""
933
934 def test_content_type_err(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000935 f = pydoc._url_handler
Georg Brandld2f38572011-01-30 08:37:19 +0000936 self.assertRaises(TypeError, f, 'A', '')
937 self.assertRaises(TypeError, f, 'B', 'foobar')
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000938
939 def test_url_requests(self):
940 # Test for the correct title in the html pages returned.
941 # This tests the different parts of the URL handler without
942 # getting too picky about the exact html.
943 requests = [
Georg Brandld2f38572011-01-30 08:37:19 +0000944 ("", "Pydoc: Index of Modules"),
945 ("get?key=", "Pydoc: Index of Modules"),
946 ("index", "Pydoc: Index of Modules"),
947 ("topics", "Pydoc: Topics"),
948 ("keywords", "Pydoc: Keywords"),
949 ("pydoc", "Pydoc: module pydoc"),
950 ("get?key=pydoc", "Pydoc: module pydoc"),
951 ("search?key=pydoc", "Pydoc: Search Results"),
952 ("topic?key=def", "Pydoc: KEYWORD def"),
953 ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
954 ("foobar", "Pydoc: Error - foobar"),
955 ("getfile?key=foobar", "Pydoc: Error - getfile?key=foobar"),
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000956 ]
957
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200958 with self.restrict_walk_packages():
959 for url, title in requests:
Martin Panter9ad0aae2015-11-06 00:27:14 +0000960 self.call_url_handler(url, title)
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200961
962 path = string.__file__
963 title = "Pydoc: getfile " + path
964 url = "getfile?key=" + path
Martin Panter9ad0aae2015-11-06 00:27:14 +0000965 self.call_url_handler(url, title)
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000966
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000967
Ezio Melottib185a042011-04-28 07:42:55 +0300968class TestHelper(unittest.TestCase):
969 def test_keywords(self):
970 self.assertEqual(sorted(pydoc.Helper.keywords),
971 sorted(keyword.kwlist))
972
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700973class PydocWithMetaClasses(unittest.TestCase):
Ethan Furman3f2f1922013-10-22 07:30:24 -0700974 @unittest.skipIf(sys.flags.optimize >= 2,
975 "Docstrings are omitted with -O2 and above")
976 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
977 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700978 def test_DynamicClassAttribute(self):
979 class Meta(type):
980 def __getattr__(self, name):
981 if name == 'ham':
982 return 'spam'
983 return super().__getattr__(name)
984 class DA(metaclass=Meta):
985 @types.DynamicClassAttribute
986 def ham(self):
987 return 'eggs'
Ethan Furman3f2f1922013-10-22 07:30:24 -0700988 expected_text_data_docstrings = tuple('\n | ' + s if s else ''
989 for s in expected_data_docstrings)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700990 output = StringIO()
991 helper = pydoc.Helper(output=output)
992 helper(DA)
Ethan Furman3f2f1922013-10-22 07:30:24 -0700993 expected_text = expected_dynamicattribute_pattern % (
994 (__name__,) + expected_text_data_docstrings[:2])
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700995 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700996 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700997
Ethan Furman3f2f1922013-10-22 07:30:24 -0700998 @unittest.skipIf(sys.flags.optimize >= 2,
999 "Docstrings are omitted with -O2 and above")
1000 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
1001 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001002 def test_virtualClassAttributeWithOneMeta(self):
1003 class Meta(type):
1004 def __dir__(cls):
1005 return ['__class__', '__module__', '__name__', 'LIFE']
1006 def __getattr__(self, name):
1007 if name =='LIFE':
1008 return 42
1009 return super().__getattr(name)
1010 class Class(metaclass=Meta):
1011 pass
1012 output = StringIO()
1013 helper = pydoc.Helper(output=output)
1014 helper(Class)
1015 expected_text = expected_virtualattribute_pattern1 % __name__
1016 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -07001017 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001018
Ethan Furman3f2f1922013-10-22 07:30:24 -07001019 @unittest.skipIf(sys.flags.optimize >= 2,
1020 "Docstrings are omitted with -O2 and above")
1021 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
1022 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001023 def test_virtualClassAttributeWithTwoMeta(self):
1024 class Meta1(type):
1025 def __dir__(cls):
1026 return ['__class__', '__module__', '__name__', 'one']
1027 def __getattr__(self, name):
1028 if name =='one':
1029 return 1
1030 return super().__getattr__(name)
1031 class Meta2(type):
1032 def __dir__(cls):
1033 return ['__class__', '__module__', '__name__', 'two']
1034 def __getattr__(self, name):
1035 if name =='two':
1036 return 2
1037 return super().__getattr__(name)
1038 class Meta3(Meta1, Meta2):
1039 def __dir__(cls):
1040 return list(sorted(set(
1041 ['__class__', '__module__', '__name__', 'three'] +
1042 Meta1.__dir__(cls) + Meta2.__dir__(cls))))
1043 def __getattr__(self, name):
1044 if name =='three':
1045 return 3
1046 return super().__getattr__(name)
1047 class Class1(metaclass=Meta1):
1048 pass
1049 class Class2(Class1, metaclass=Meta3):
1050 pass
1051 fail1 = fail2 = False
1052 output = StringIO()
1053 helper = pydoc.Helper(output=output)
1054 helper(Class1)
1055 expected_text1 = expected_virtualattribute_pattern2 % __name__
1056 result1 = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -07001057 self.assertEqual(expected_text1, result1)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001058 output = StringIO()
1059 helper = pydoc.Helper(output=output)
1060 helper(Class2)
1061 expected_text2 = expected_virtualattribute_pattern3 % __name__
1062 result2 = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -07001063 self.assertEqual(expected_text2, result2)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001064
Ethan Furman3f2f1922013-10-22 07:30:24 -07001065 @unittest.skipIf(sys.flags.optimize >= 2,
1066 "Docstrings are omitted with -O2 and above")
1067 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
1068 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001069 def test_buggy_dir(self):
1070 class M(type):
1071 def __dir__(cls):
1072 return ['__class__', '__name__', 'missing', 'here']
1073 class C(metaclass=M):
1074 here = 'present!'
1075 output = StringIO()
1076 helper = pydoc.Helper(output=output)
1077 helper(C)
1078 expected_text = expected_missingattribute_pattern % __name__
1079 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -07001080 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001081
Serhiy Storchakab6076fb2015-04-21 21:09:48 +03001082 def test_resolve_false(self):
1083 # Issue #23008: pydoc enum.{,Int}Enum failed
1084 # because bool(enum.Enum) is False.
1085 with captured_stdout() as help_io:
1086 pydoc.help('enum.Enum')
1087 helptext = help_io.getvalue()
1088 self.assertIn('class Enum', helptext)
1089
Eric Snowaed5b222014-01-04 20:38:11 -07001090
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001091@reap_threads
Georg Brandlb533e262008-05-25 18:19:30 +00001092def test_main():
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001093 try:
1094 test.support.run_unittest(PydocDocTest,
Ned Deily92a81a12011-10-06 14:19:03 -07001095 PydocImportTest,
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001096 TestDescriptions,
1097 PydocServerTest,
1098 PydocUrlHandlerTest,
1099 TestHelper,
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001100 PydocWithMetaClasses,
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001101 )
1102 finally:
1103 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +00001104
1105if __name__ == "__main__":
1106 test_main()