blob: 1f7ab7ffa14dd13e293a7e9677d1e5806f1151b9 [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
Benjamin Peterson54237f92015-02-16 19:45:01 -05005import importlib.util
Georg Brandlb533e262008-05-25 18:19:30 +00006import inspect
Nick Coghlan7bb30b72010-12-03 09:29:11 +00007import pydoc
Benjamin Peterson54237f92015-02-16 19:45:01 -05008import py_compile
Ezio Melottib185a042011-04-28 07:42:55 +03009import keyword
Larry Hastings24a882b2014-02-20 23:34:46 -080010import _pickle
Antoine Pitrou916fc7b2013-05-19 15:44:54 +020011import pkgutil
Nick Coghlan7bb30b72010-12-03 09:29:11 +000012import re
Benjamin Peterson54237f92015-02-16 19:45:01 -050013import stat
Nick Coghlan7bb30b72010-12-03 09:29:11 +000014import string
Georg Brandlb533e262008-05-25 18:19:30 +000015import test.support
Nick Coghlan7bb30b72010-12-03 09:29:11 +000016import time
Ethan Furmanb0c84cd2013-10-20 22:37:39 -070017import types
Guido van Rossum52e50042016-10-22 07:55:18 -070018import typing
Nick Coghlan7bb30b72010-12-03 09:29:11 +000019import unittest
Zachary Wareeb432142014-07-10 11:18:00 -050020import urllib.parse
Brian Curtin49c284c2010-03-31 03:19:28 +000021import xml.etree
R David Murrayead9bfc2016-06-03 19:28:35 -040022import xml.etree.ElementTree
Georg Brandld80d5f42010-12-03 07:47:22 +000023import textwrap
24from io import StringIO
Raymond Hettinger1103d052011-03-25 14:15:24 -070025from collections import namedtuple
Berker Peksagce643912015-05-06 06:33:17 +030026from test.support.script_helper import assert_python_ok
Antoine Pitroua6e81a22011-07-15 22:32:25 +020027from test.support import (
Ned Deily92a81a12011-10-06 14:19:03 -070028 TESTFN, rmtree,
Antoine Pitrou916fc7b2013-05-19 15:44:54 +020029 reap_children, reap_threads, captured_output, captured_stdout,
Stefan Krah5de32782014-01-18 23:18:39 +010030 captured_stderr, unlink, requires_docstrings
Antoine Pitroua6e81a22011-07-15 22:32:25 +020031)
Georg Brandlb533e262008-05-25 18:19:30 +000032from test import pydoc_mod
33
Victor Stinner62a68f22011-05-20 02:29:13 +020034try:
35 import threading
36except ImportError:
37 threading = None
38
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +020039class nonascii:
40 'Це не латиниця'
41 pass
42
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020043if test.support.HAVE_DOCSTRINGS:
44 expected_data_docstrings = (
45 'dictionary for instance variables (if defined)',
46 'list of weak references to the object (if defined)',
47 ) * 2
48else:
49 expected_data_docstrings = ('', '', '', '')
50
Barry Warsaw28a691b2010-04-17 00:19:56 +000051expected_text_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000052NAME
53 test.pydoc_mod - This is a test module for test_pydoc
Georg Brandlb533e262008-05-25 18:19:30 +000054%s
55CLASSES
56 builtins.object
57 A
58 B
Benjamin Petersoned1160b2014-06-07 16:44:00 -070059 C
Georg Brandlb533e262008-05-25 18:19:30 +000060\x20\x20\x20\x20
61 class A(builtins.object)
62 | Hello and goodbye
63 |\x20\x20
64 | Methods defined here:
65 |\x20\x20
66 | __init__()
67 | Wow, I have no function!
68 |\x20\x20
69 | ----------------------------------------------------------------------
70 | Data descriptors defined here:
71 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020072 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000073 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020074 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000075\x20\x20\x20\x20
76 class B(builtins.object)
77 | Data descriptors defined here:
78 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020079 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000080 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020081 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000082 |\x20\x20
83 | ----------------------------------------------------------------------
84 | Data and other attributes defined here:
85 |\x20\x20
86 | NO_MEANING = 'eggs'
Benjamin Petersoned1160b2014-06-07 16:44:00 -070087\x20\x20\x20\x20
88 class C(builtins.object)
89 | Methods defined here:
90 |\x20\x20
91 | get_answer(self)
92 | Return say_no()
93 |\x20\x20
94 | is_it_true(self)
95 | Return self.get_answer()
96 |\x20\x20
97 | say_no(self)
98 |\x20\x20
99 | ----------------------------------------------------------------------
100 | Data descriptors defined here:
101 |\x20\x20
102 | __dict__
103 | dictionary for instance variables (if defined)
104 |\x20\x20
105 | __weakref__
106 | list of weak references to the object (if defined)
Georg Brandlb533e262008-05-25 18:19:30 +0000107
108FUNCTIONS
109 doc_func()
110 This function solves all of the world's problems:
111 hunger
112 lack of Python
113 war
114\x20\x20\x20\x20
115 nodoc_func()
116
117DATA
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000118 __xyz__ = 'X, Y and Z'
Georg Brandlb533e262008-05-25 18:19:30 +0000119
120VERSION
121 1.2.3.4
122
123AUTHOR
124 Benjamin Peterson
125
126CREDITS
127 Nobody
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000128
129FILE
130 %s
Georg Brandlb533e262008-05-25 18:19:30 +0000131""".strip()
132
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200133expected_text_data_docstrings = tuple('\n | ' + s if s else ''
134 for s in expected_data_docstrings)
135
Barry Warsaw28a691b2010-04-17 00:19:56 +0000136expected_html_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +0000137<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
138<tr bgcolor="#7799ee">
139<td valign=bottom>&nbsp;<br>
140<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
141><td align=right valign=bottom
142><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
143 <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
144<p>
145<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
146<tr bgcolor="#ee77aa">
147<td colspan=3 valign=bottom>&nbsp;<br>
148<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
149\x20\x20\x20\x20
150<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
151<td width="100%%"><dl>
152<dt><font face="helvetica, arial"><a href="builtins.html#object">builtins.object</a>
153</font></dt><dd>
154<dl>
155<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
156</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700157</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#C">C</a>
Georg Brandlb533e262008-05-25 18:19:30 +0000158</font></dt></dl>
159</dd>
160</dl>
161 <p>
162<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
163<tr bgcolor="#ffc8d8">
164<td colspan=3 valign=bottom>&nbsp;<br>
165<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>
166\x20\x20\x20\x20
167<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
168<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
169<tr><td>&nbsp;</td>
170<td width="100%%">Methods defined here:<br>
171<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>
172
173<hr>
174Data descriptors defined here:<br>
175<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200176<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000177</dl>
178<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200179<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000180</dl>
181</td></tr></table> <p>
182<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
183<tr bgcolor="#ffc8d8">
184<td colspan=3 valign=bottom>&nbsp;<br>
185<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>
186\x20\x20\x20\x20
187<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
188<td width="100%%">Data descriptors defined here:<br>
189<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200190<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000191</dl>
192<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200193<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000194</dl>
195<hr>
196Data and other attributes defined here:<br>
197<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
198
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700199</td></tr></table> <p>
200<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
201<tr bgcolor="#ffc8d8">
202<td colspan=3 valign=bottom>&nbsp;<br>
203<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>
204\x20\x20\x20\x20
205<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
206<td width="100%%">Methods defined here:<br>
207<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>
208
209<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>
210
211<dl><dt><a name="C-say_no"><strong>say_no</strong></a>(self)</dt></dl>
212
213<hr>
214Data descriptors defined here:<br>
215<dl><dt><strong>__dict__</strong></dt>
216<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
217</dl>
218<dl><dt><strong>__weakref__</strong></dt>
219<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
220</dl>
Georg Brandlb533e262008-05-25 18:19:30 +0000221</td></tr></table></td></tr></table><p>
222<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
223<tr bgcolor="#eeaa77">
224<td colspan=3 valign=bottom>&nbsp;<br>
225<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
226\x20\x20\x20\x20
227<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
228<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>
229hunger<br>
230lack&nbsp;of&nbsp;Python<br>
231war</tt></dd></dl>
232 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
233</td></tr></table><p>
234<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
235<tr bgcolor="#55aa55">
236<td colspan=3 valign=bottom>&nbsp;<br>
237<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
238\x20\x20\x20\x20
239<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000240<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p>
Georg Brandlb533e262008-05-25 18:19:30 +0000241<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
242<tr bgcolor="#7799ee">
243<td colspan=3 valign=bottom>&nbsp;<br>
244<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
245\x20\x20\x20\x20
246<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
247<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
248<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
249<tr bgcolor="#7799ee">
250<td colspan=3 valign=bottom>&nbsp;<br>
251<font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
252\x20\x20\x20\x20
253<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
254<td width="100%%">Nobody</td></tr></table>
Barry Warsaw28a691b2010-04-17 00:19:56 +0000255""".strip() # ' <- emacs turd
Georg Brandlb533e262008-05-25 18:19:30 +0000256
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200257expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;')
258 for s in expected_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000259
260# output pattern for missing module
Serhiy Storchaka1c205512015-03-01 00:42:54 +0200261missing_pattern = '''\
262No Python documentation found for %r.
263Use help() to get the interactive help utility.
264Use help(str) for help on the str class.'''.replace('\n', os.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000265
Benjamin Peterson0289b152009-06-28 17:22:03 +0000266# output pattern for module with bad imports
Brett Cannon679ecb52013-07-04 17:51:50 -0400267badimport_pattern = "problem in %s - ImportError: No module named %r"
Benjamin Peterson0289b152009-06-28 17:22:03 +0000268
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700269expected_dynamicattribute_pattern = """
270Help on class DA in module %s:
271
272class DA(builtins.object)
273 | Data descriptors defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200274 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700275 | __dict__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200276 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700277 | __weakref__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200278 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700279 | ham
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200280 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700281 | ----------------------------------------------------------------------
282 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200283 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700284 | ham = 'spam'
285""".strip()
286
287expected_virtualattribute_pattern1 = """
288Help on class Class in module %s:
289
290class Class(builtins.object)
291 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200292 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700293 | LIFE = 42
294""".strip()
295
296expected_virtualattribute_pattern2 = """
297Help on class Class1 in module %s:
298
299class Class1(builtins.object)
300 | Data and other attributes inherited from Meta1:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200301 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700302 | one = 1
303""".strip()
304
305expected_virtualattribute_pattern3 = """
306Help on class Class2 in module %s:
307
308class Class2(Class1)
309 | Method resolution order:
310 | Class2
311 | Class1
312 | builtins.object
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200313 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700314 | Data and other attributes inherited from Meta1:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200315 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700316 | one = 1
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200317 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700318 | ----------------------------------------------------------------------
319 | Data and other attributes inherited from Meta3:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200320 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700321 | three = 3
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200322 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700323 | ----------------------------------------------------------------------
324 | Data and other attributes inherited from Meta2:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200325 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700326 | two = 2
327""".strip()
328
329expected_missingattribute_pattern = """
330Help on class C in module %s:
331
332class C(builtins.object)
333 | Data and other attributes defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200334 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700335 | here = 'present!'
336""".strip()
337
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200338def run_pydoc(module_name, *args, **env):
Georg Brandlb533e262008-05-25 18:19:30 +0000339 """
340 Runs pydoc on the specified module. Returns the stripped
341 output of pydoc.
342 """
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200343 args = args + (module_name,)
Ned Deily92a81a12011-10-06 14:19:03 -0700344 # do not write bytecode files to avoid caching errors
345 rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200346 return out.strip()
Georg Brandlb533e262008-05-25 18:19:30 +0000347
348def get_pydoc_html(module):
349 "Returns pydoc generated output as html"
350 doc = pydoc.HTMLDoc()
351 output = doc.docmodule(module)
352 loc = doc.getdocloc(pydoc_mod) or ""
353 if loc:
354 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
355 return output.strip(), loc
356
R David Murrayead9bfc2016-06-03 19:28:35 -0400357def get_pydoc_link(module):
358 "Returns a documentation web link of a module"
359 dirname = os.path.dirname
Martin Panter4f8aaf62016-06-12 04:24:06 +0000360 basedir = dirname(dirname(__file__))
R David Murrayead9bfc2016-06-03 19:28:35 -0400361 doc = pydoc.TextDoc()
362 loc = doc.getdocloc(module, basedir=basedir)
363 return loc
364
Georg Brandlb533e262008-05-25 18:19:30 +0000365def get_pydoc_text(module):
366 "Returns pydoc generated output as text"
367 doc = pydoc.TextDoc()
368 loc = doc.getdocloc(pydoc_mod) or ""
369 if loc:
370 loc = "\nMODULE DOCS\n " + loc + "\n"
371
372 output = doc.docmodule(module)
373
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000374 # clean up the extra text formatting that pydoc performs
Georg Brandlb533e262008-05-25 18:19:30 +0000375 patt = re.compile('\b.')
376 output = patt.sub('', output)
377 return output.strip(), loc
378
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000379def get_html_title(text):
Nick Coghlanecace282010-12-03 16:08:46 +0000380 # Bit of hack, but good enough for test purposes
381 header, _, _ = text.partition("</head>")
382 _, _, title = header.partition("<title>")
383 title, _, _ = title.partition("</title>")
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000384 return title
385
Georg Brandlb533e262008-05-25 18:19:30 +0000386
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200387class PydocBaseTest(unittest.TestCase):
388
389 def _restricted_walk_packages(self, walk_packages, path=None):
390 """
391 A version of pkgutil.walk_packages() that will restrict itself to
392 a given path.
393 """
394 default_path = path or [os.path.dirname(__file__)]
395 def wrapper(path=None, prefix='', onerror=None):
396 return walk_packages(path or default_path, prefix, onerror)
397 return wrapper
398
399 @contextlib.contextmanager
400 def restrict_walk_packages(self, path=None):
401 walk_packages = pkgutil.walk_packages
402 pkgutil.walk_packages = self._restricted_walk_packages(walk_packages,
403 path)
404 try:
405 yield
406 finally:
407 pkgutil.walk_packages = walk_packages
408
Martin Panter9ad0aae2015-11-06 00:27:14 +0000409 def call_url_handler(self, url, expected_title):
410 text = pydoc._url_handler(url, "text/html")
411 result = get_html_title(text)
412 # Check the title to ensure an unexpected error page was not returned
413 self.assertEqual(result, expected_title, text)
414 return text
415
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200416
Georg Brandld2f38572011-01-30 08:37:19 +0000417class PydocDocTest(unittest.TestCase):
Georg Brandlb533e262008-05-25 18:19:30 +0000418
R. David Murray378c0cf2010-02-24 01:46:21 +0000419 @unittest.skipIf(sys.flags.optimize >= 2,
420 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000421 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
422 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100423 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000424 def test_html_doc(self):
425 result, doc_loc = get_pydoc_html(pydoc_mod)
426 mod_file = inspect.getabsfile(pydoc_mod)
Zachary Wareeb432142014-07-10 11:18:00 -0500427 mod_url = urllib.parse.quote(mod_file)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200428 expected_html = expected_html_pattern % (
429 (mod_url, mod_file, doc_loc) +
430 expected_html_data_docstrings)
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700431 self.assertEqual(result, expected_html)
Georg Brandlb533e262008-05-25 18:19:30 +0000432
R. David Murray378c0cf2010-02-24 01:46:21 +0000433 @unittest.skipIf(sys.flags.optimize >= 2,
434 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000435 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
436 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100437 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000438 def test_text_doc(self):
439 result, doc_loc = get_pydoc_text(pydoc_mod)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200440 expected_text = expected_text_pattern % (
441 (doc_loc,) +
442 expected_text_data_docstrings +
443 (inspect.getabsfile(pydoc_mod),))
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700444 self.assertEqual(expected_text, result)
Georg Brandlb533e262008-05-25 18:19:30 +0000445
Serhiy Storchaka056eb022014-02-19 23:05:12 +0200446 def test_text_enum_member_with_value_zero(self):
447 # Test issue #20654 to ensure enum member with value 0 can be
448 # displayed. It used to throw KeyError: 'zero'.
449 import enum
450 class BinaryInteger(enum.IntEnum):
451 zero = 0
452 one = 1
453 doc = pydoc.render_doc(BinaryInteger)
454 self.assertIn('<BinaryInteger.zero: 0>', doc)
455
R David Murrayead9bfc2016-06-03 19:28:35 -0400456 def test_mixed_case_module_names_are_lower_cased(self):
457 # issue16484
458 doc_link = get_pydoc_link(xml.etree.ElementTree)
459 self.assertIn('xml.etree.elementtree', doc_link)
460
Brian Curtin49c284c2010-03-31 03:19:28 +0000461 def test_issue8225(self):
462 # Test issue8225 to ensure no doc link appears for xml.etree
463 result, doc_loc = get_pydoc_text(xml.etree)
464 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
465
Benjamin Peterson159824e2014-06-07 20:14:26 -0700466 def test_getpager_with_stdin_none(self):
467 previous_stdin = sys.stdin
468 try:
469 sys.stdin = None
470 pydoc.getpager() # Shouldn't fail.
471 finally:
472 sys.stdin = previous_stdin
473
R David Murrayc43125a2012-04-23 13:23:57 -0400474 def test_non_str_name(self):
475 # issue14638
476 # Treat illegal (non-str) name like no name
477 class A:
478 __name__ = 42
479 class B:
480 pass
481 adoc = pydoc.render_doc(A())
482 bdoc = pydoc.render_doc(B())
483 self.assertEqual(adoc.replace("A", "B"), bdoc)
484
Georg Brandlb533e262008-05-25 18:19:30 +0000485 def test_not_here(self):
486 missing_module = "test.i_am_not_here"
487 result = str(run_pydoc(missing_module), 'ascii')
488 expected = missing_pattern % missing_module
489 self.assertEqual(expected, result,
490 "documentation for missing module found")
491
Serhiy Storchaka4c094e52015-03-01 15:31:36 +0200492 @unittest.skipIf(sys.flags.optimize >= 2,
493 'Docstrings are omitted with -OO and above')
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +0200494 def test_not_ascii(self):
495 result = run_pydoc('test.test_pydoc.nonascii', PYTHONIOENCODING='ascii')
496 encoded = nonascii.__doc__.encode('ascii', 'backslashreplace')
497 self.assertIn(encoded, result)
498
R. David Murray1f1b9d32009-05-27 20:56:59 +0000499 def test_input_strip(self):
500 missing_module = " test.i_am_not_here "
501 result = str(run_pydoc(missing_module), 'ascii')
502 expected = missing_pattern % missing_module.strip()
503 self.assertEqual(expected, result)
504
Ezio Melotti412c95a2010-02-16 23:31:04 +0000505 def test_stripid(self):
506 # test with strings, other implementations might have different repr()
507 stripid = pydoc.stripid
508 # strip the id
509 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
510 '<function stripid>')
511 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
512 '<function stripid>')
513 # nothing to strip, return the same text
514 self.assertEqual(stripid('42'), '42')
515 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
516 "<type 'exceptions.Exception'>")
517
Georg Brandld80d5f42010-12-03 07:47:22 +0000518 @unittest.skipIf(sys.flags.optimize >= 2,
519 'Docstrings are omitted with -O2 and above')
Brett Cannon7a540732011-02-22 03:04:06 +0000520 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
521 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100522 @requires_docstrings
Georg Brandld80d5f42010-12-03 07:47:22 +0000523 def test_help_output_redirect(self):
524 # issue 940286, if output is set in Helper, then all output from
525 # Helper.help should be redirected
526 old_pattern = expected_text_pattern
527 getpager_old = pydoc.getpager
528 getpager_new = lambda: (lambda x: x)
529 self.maxDiff = None
530
531 buf = StringIO()
532 helper = pydoc.Helper(output=buf)
533 unused, doc_loc = get_pydoc_text(pydoc_mod)
534 module = "test.pydoc_mod"
535 help_header = """
536 Help on module test.pydoc_mod in test:
537
538 """.lstrip()
539 help_header = textwrap.dedent(help_header)
540 expected_help_pattern = help_header + expected_text_pattern
541
542 pydoc.getpager = getpager_new
543 try:
544 with captured_output('stdout') as output, \
545 captured_output('stderr') as err:
546 helper.help(module)
547 result = buf.getvalue().strip()
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200548 expected_text = expected_help_pattern % (
549 (doc_loc,) +
550 expected_text_data_docstrings +
551 (inspect.getabsfile(pydoc_mod),))
Georg Brandld80d5f42010-12-03 07:47:22 +0000552 self.assertEqual('', output.getvalue())
553 self.assertEqual('', err.getvalue())
554 self.assertEqual(expected_text, result)
555 finally:
556 pydoc.getpager = getpager_old
557
Raymond Hettinger1103d052011-03-25 14:15:24 -0700558 def test_namedtuple_public_underscore(self):
559 NT = namedtuple('NT', ['abc', 'def'], rename=True)
560 with captured_stdout() as help_io:
Terry Jan Reedy5c811642013-11-04 21:43:26 -0500561 pydoc.help(NT)
Raymond Hettinger1103d052011-03-25 14:15:24 -0700562 helptext = help_io.getvalue()
563 self.assertIn('_1', helptext)
564 self.assertIn('_replace', helptext)
565 self.assertIn('_asdict', helptext)
566
Victor Stinnere6c910e2011-06-30 15:55:43 +0200567 def test_synopsis(self):
568 self.addCleanup(unlink, TESTFN)
569 for encoding in ('ISO-8859-1', 'UTF-8'):
570 with open(TESTFN, 'w', encoding=encoding) as script:
571 if encoding != 'UTF-8':
572 print('#coding: {}'.format(encoding), file=script)
573 print('"""line 1: h\xe9', file=script)
574 print('line 2: hi"""', file=script)
575 synopsis = pydoc.synopsis(TESTFN, {})
576 self.assertEqual(synopsis, 'line 1: h\xe9')
577
Serhiy Storchaka4c094e52015-03-01 15:31:36 +0200578 @unittest.skipIf(sys.flags.optimize >= 2,
579 'Docstrings are omitted with -OO and above')
Eric Snowaed5b222014-01-04 20:38:11 -0700580 def test_synopsis_sourceless(self):
581 expected = os.__doc__.splitlines()[0]
582 filename = os.__cached__
583 synopsis = pydoc.synopsis(filename)
584
585 self.assertEqual(synopsis, expected)
586
Benjamin Peterson54237f92015-02-16 19:45:01 -0500587 def test_synopsis_sourceless_empty_doc(self):
588 with test.support.temp_cwd() as test_dir:
589 init_path = os.path.join(test_dir, 'foomod42.py')
590 cached_path = importlib.util.cache_from_source(init_path)
591 with open(init_path, 'w') as fobj:
592 fobj.write("foo = 1")
593 py_compile.compile(init_path)
594 synopsis = pydoc.synopsis(init_path, {})
595 self.assertIsNone(synopsis)
596 synopsis_cached = pydoc.synopsis(cached_path, {})
597 self.assertIsNone(synopsis_cached)
598
R David Murray455f2962013-03-19 00:00:33 -0400599 def test_splitdoc_with_description(self):
600 example_string = "I Am A Doc\n\n\nHere is my description"
601 self.assertEqual(pydoc.splitdoc(example_string),
602 ('I Am A Doc', '\nHere is my description'))
603
604 def test_is_object_or_method(self):
605 doc = pydoc.Doc()
606 # Bound Method
607 self.assertTrue(pydoc._is_some_method(doc.fail))
608 # Method Descriptor
609 self.assertTrue(pydoc._is_some_method(int.__add__))
610 # String
611 self.assertFalse(pydoc._is_some_method("I am not a method"))
612
613 def test_is_package_when_not_package(self):
614 with test.support.temp_cwd() as test_dir:
615 self.assertFalse(pydoc.ispackage(test_dir))
616
617 def test_is_package_when_is_package(self):
618 with test.support.temp_cwd() as test_dir:
619 init_path = os.path.join(test_dir, '__init__.py')
620 open(init_path, 'w').close()
621 self.assertTrue(pydoc.ispackage(test_dir))
622 os.remove(init_path)
623
R David Murrayac0cea52013-03-19 02:47:44 -0400624 def test_allmethods(self):
625 # issue 17476: allmethods was no longer returning unbound methods.
626 # This test is a bit fragile in the face of changes to object and type,
627 # but I can't think of a better way to do it without duplicating the
628 # logic of the function under test.
629
630 class TestClass(object):
631 def method_returning_true(self):
632 return True
633
634 # What we expect to get back: everything on object...
635 expected = dict(vars(object))
636 # ...plus our unbound method...
637 expected['method_returning_true'] = TestClass.method_returning_true
638 # ...but not the non-methods on object.
639 del expected['__doc__']
640 del expected['__class__']
641 # inspect resolves descriptors on type into methods, but vars doesn't,
642 # so we need to update __subclasshook__.
643 expected['__subclasshook__'] = TestClass.__subclasshook__
644
645 methods = pydoc.allmethods(TestClass)
646 self.assertDictEqual(methods, expected)
647
Georg Brandlb533e262008-05-25 18:19:30 +0000648
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200649class PydocImportTest(PydocBaseTest):
Ned Deily92a81a12011-10-06 14:19:03 -0700650
651 def setUp(self):
652 self.test_dir = os.mkdir(TESTFN)
653 self.addCleanup(rmtree, TESTFN)
Benjamin Peterson54237f92015-02-16 19:45:01 -0500654 importlib.invalidate_caches()
Ned Deily92a81a12011-10-06 14:19:03 -0700655
656 def test_badimport(self):
657 # This tests the fix for issue 5230, where if pydoc found the module
658 # but the module had an internal import error pydoc would report no doc
659 # found.
660 modname = 'testmod_xyzzy'
661 testpairs = (
662 ('i_am_not_here', 'i_am_not_here'),
Brett Cannonfd074152012-04-14 14:10:13 -0400663 ('test.i_am_not_here_either', 'test.i_am_not_here_either'),
664 ('test.i_am_not_here.neither_am_i', 'test.i_am_not_here'),
665 ('i_am_not_here.{}'.format(modname), 'i_am_not_here'),
666 ('test.{}'.format(modname), 'test.{}'.format(modname)),
Ned Deily92a81a12011-10-06 14:19:03 -0700667 )
668
669 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
670 for importstring, expectedinmsg in testpairs:
671 with open(sourcefn, 'w') as f:
672 f.write("import {}\n".format(importstring))
673 result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii")
674 expected = badimport_pattern % (modname, expectedinmsg)
675 self.assertEqual(expected, result)
676
677 def test_apropos_with_bad_package(self):
678 # Issue 7425 - pydoc -k failed when bad package on path
679 pkgdir = os.path.join(TESTFN, "syntaxerr")
680 os.mkdir(pkgdir)
681 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
682 with open(badsyntax, 'w') as f:
683 f.write("invalid python syntax = $1\n")
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200684 with self.restrict_walk_packages(path=[TESTFN]):
685 with captured_stdout() as out:
686 with captured_stderr() as err:
687 pydoc.apropos('xyzzy')
688 # No result, no error
689 self.assertEqual(out.getvalue(), '')
690 self.assertEqual(err.getvalue(), '')
691 # The package name is still matched
692 with captured_stdout() as out:
693 with captured_stderr() as err:
694 pydoc.apropos('syntaxerr')
695 self.assertEqual(out.getvalue().strip(), 'syntaxerr')
696 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700697
698 def test_apropos_with_unreadable_dir(self):
699 # Issue 7367 - pydoc -k failed when unreadable dir on path
700 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
701 os.mkdir(self.unreadable_dir, 0)
702 self.addCleanup(os.rmdir, self.unreadable_dir)
703 # Note, on Windows the directory appears to be still
704 # readable so this is not really testing the issue there
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200705 with self.restrict_walk_packages(path=[TESTFN]):
706 with captured_stdout() as out:
707 with captured_stderr() as err:
708 pydoc.apropos('SOMEKEY')
709 # No result, no error
710 self.assertEqual(out.getvalue(), '')
711 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700712
Benjamin Peterson54237f92015-02-16 19:45:01 -0500713 def test_apropos_empty_doc(self):
714 pkgdir = os.path.join(TESTFN, 'walkpkg')
715 os.mkdir(pkgdir)
716 self.addCleanup(rmtree, pkgdir)
717 init_path = os.path.join(pkgdir, '__init__.py')
718 with open(init_path, 'w') as fobj:
719 fobj.write("foo = 1")
720 current_mode = stat.S_IMODE(os.stat(pkgdir).st_mode)
721 try:
722 os.chmod(pkgdir, current_mode & ~stat.S_IEXEC)
723 with self.restrict_walk_packages(path=[TESTFN]), captured_stdout() as stdout:
724 pydoc.apropos('')
725 self.assertIn('walkpkg', stdout.getvalue())
726 finally:
727 os.chmod(pkgdir, current_mode)
728
Martin Panter9ad0aae2015-11-06 00:27:14 +0000729 def test_url_search_package_error(self):
730 # URL handler search should cope with packages that raise exceptions
731 pkgdir = os.path.join(TESTFN, "test_error_package")
732 os.mkdir(pkgdir)
733 init = os.path.join(pkgdir, "__init__.py")
734 with open(init, "wt", encoding="ascii") as f:
735 f.write("""raise ValueError("ouch")\n""")
736 with self.restrict_walk_packages(path=[TESTFN]):
737 # Package has to be importable for the error to have any effect
738 saved_paths = tuple(sys.path)
739 sys.path.insert(0, TESTFN)
740 try:
741 with self.assertRaisesRegex(ValueError, "ouch"):
742 import test_error_package # Sanity check
743
744 text = self.call_url_handler("search?key=test_error_package",
745 "Pydoc: Search Results")
746 found = ('<a href="test_error_package.html">'
747 'test_error_package</a>')
748 self.assertIn(found, text)
749 finally:
750 sys.path[:] = saved_paths
751
Martin Panter46f50722016-05-26 05:35:26 +0000752 @unittest.skip('causes undesirable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700753 def test_modules(self):
754 # See Helper.listmodules().
755 num_header_lines = 2
756 num_module_lines_min = 5 # Playing it safe.
757 num_footer_lines = 3
758 expected = num_header_lines + num_module_lines_min + num_footer_lines
759
760 output = StringIO()
761 helper = pydoc.Helper(output=output)
762 helper('modules')
763 result = output.getvalue().strip()
764 num_lines = len(result.splitlines())
765
766 self.assertGreaterEqual(num_lines, expected)
767
Martin Panter46f50722016-05-26 05:35:26 +0000768 @unittest.skip('causes undesirable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700769 def test_modules_search(self):
770 # See Helper.listmodules().
771 expected = 'pydoc - '
772
773 output = StringIO()
774 helper = pydoc.Helper(output=output)
775 with captured_stdout() as help_io:
776 helper('modules pydoc')
777 result = help_io.getvalue()
778
779 self.assertIn(expected, result)
780
Eric Snowa46ef702014-02-22 13:57:08 -0700781 @unittest.skip('some buildbots are not cooperating (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700782 def test_modules_search_builtin(self):
Eric Snow5ea97502014-01-04 23:04:27 -0700783 expected = 'gc - '
Eric Snowaed5b222014-01-04 20:38:11 -0700784
785 output = StringIO()
786 helper = pydoc.Helper(output=output)
787 with captured_stdout() as help_io:
Eric Snow5ea97502014-01-04 23:04:27 -0700788 helper('modules garbage')
Eric Snowaed5b222014-01-04 20:38:11 -0700789 result = help_io.getvalue()
790
791 self.assertTrue(result.startswith(expected))
792
793 def test_importfile(self):
794 loaded_pydoc = pydoc.importfile(pydoc.__file__)
795
Eric Snow3a62d142014-01-06 20:42:59 -0700796 self.assertIsNot(loaded_pydoc, pydoc)
Eric Snowaed5b222014-01-04 20:38:11 -0700797 self.assertEqual(loaded_pydoc.__name__, 'pydoc')
798 self.assertEqual(loaded_pydoc.__file__, pydoc.__file__)
Eric Snow3a62d142014-01-06 20:42:59 -0700799 self.assertEqual(loaded_pydoc.__spec__, pydoc.__spec__)
Eric Snowaed5b222014-01-04 20:38:11 -0700800
Ned Deily92a81a12011-10-06 14:19:03 -0700801
Georg Brandlb533e262008-05-25 18:19:30 +0000802class TestDescriptions(unittest.TestCase):
803
804 def test_module(self):
805 # Check that pydocfodder module can be described
806 from test import pydocfodder
807 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000808 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000809
Georg Brandlb533e262008-05-25 18:19:30 +0000810 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000811 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +0000812 c = C()
813
814 self.assertEqual(pydoc.describe(C), 'class C')
815 self.assertEqual(pydoc.describe(c), 'C')
816 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000817 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000818
Guido van Rossum52e50042016-10-22 07:55:18 -0700819 def test_typing_pydoc(self):
820 def foo(data: typing.List[typing.Any],
821 x: int) -> typing.Iterator[typing.Tuple[int, typing.Any]]:
822 ...
823 T = typing.TypeVar('T')
824 class C(typing.Generic[T], typing.Mapping[int, str]): ...
825 self.assertEqual(pydoc.render_doc(foo).splitlines()[-1],
826 'f\x08fo\x08oo\x08o(data:List[Any], x:int)'
827 ' -> Iterator[Tuple[int, Any]]')
828 self.assertEqual(pydoc.render_doc(C).splitlines()[2],
829 'class C\x08C(typing.Mapping)')
830
Éric Araujoe64e51b2011-07-29 17:03:55 +0200831 def test_builtin(self):
832 for name in ('str', 'str.translate', 'builtins.str',
833 'builtins.str.translate'):
834 # test low-level function
835 self.assertIsNotNone(pydoc.locate(name))
836 # test high-level function
837 try:
838 pydoc.render_doc(name)
839 except ImportError:
Terry Jan Reedyfe928de2014-06-20 14:59:11 -0400840 self.fail('finding the doc of {!r} failed'.format(name))
Éric Araujoe64e51b2011-07-29 17:03:55 +0200841
842 for name in ('notbuiltins', 'strrr', 'strr.translate',
843 'str.trrrranslate', 'builtins.strrr',
844 'builtins.str.trrranslate'):
845 self.assertIsNone(pydoc.locate(name))
846 self.assertRaises(ImportError, pydoc.render_doc, name)
847
Larry Hastings24a882b2014-02-20 23:34:46 -0800848 @staticmethod
849 def _get_summary_line(o):
850 text = pydoc.plain(pydoc.render_doc(o))
851 lines = text.split('\n')
852 assert len(lines) >= 2
853 return lines[2]
854
855 # these should include "self"
856 def test_unbound_python_method(self):
857 self.assertEqual(self._get_summary_line(textwrap.TextWrapper.wrap),
858 "wrap(self, text)")
859
Stefan Krah5de32782014-01-18 23:18:39 +0100860 @requires_docstrings
Larry Hastings24a882b2014-02-20 23:34:46 -0800861 def test_unbound_builtin_method(self):
862 self.assertEqual(self._get_summary_line(_pickle.Pickler.dump),
863 "dump(self, obj, /)")
864
865 # these no longer include "self"
866 def test_bound_python_method(self):
867 t = textwrap.TextWrapper()
868 self.assertEqual(self._get_summary_line(t.wrap),
869 "wrap(text) method of textwrap.TextWrapper instance")
870
871 @requires_docstrings
872 def test_bound_builtin_method(self):
873 s = StringIO()
874 p = _pickle.Pickler(s)
875 self.assertEqual(self._get_summary_line(p.dump),
876 "dump(obj, /) method of _pickle.Pickler instance")
877
878 # this should *never* include self!
879 @requires_docstrings
880 def test_module_level_callable(self):
881 self.assertEqual(self._get_summary_line(os.stat),
882 "stat(path, *, dir_fd=None, follow_symlinks=True)")
Larry Hastings1abd7082014-01-16 14:15:03 -0800883
Georg Brandlb533e262008-05-25 18:19:30 +0000884
Victor Stinner62a68f22011-05-20 02:29:13 +0200885@unittest.skipUnless(threading, 'Threading required for this test.')
Georg Brandld2f38572011-01-30 08:37:19 +0000886class PydocServerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000887 """Tests for pydoc._start_server"""
888
889 def test_server(self):
890
891 # Minimal test that starts the server, then stops it.
892 def my_url_handler(url, content_type):
893 text = 'the URL sent was: (%s, %s)' % (url, content_type)
894 return text
895
896 serverthread = pydoc._start_server(my_url_handler, port=0)
Senthil Kumaran2a42a0b2014-09-17 13:17:58 +0800897 self.assertIn('localhost', serverthread.docserver.address)
898
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000899 starttime = time.time()
900 timeout = 1 #seconds
901
902 while serverthread.serving:
903 time.sleep(.01)
904 if serverthread.serving and time.time() - starttime > timeout:
905 serverthread.stop()
906 break
907
908 self.assertEqual(serverthread.error, None)
909
910
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200911class PydocUrlHandlerTest(PydocBaseTest):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000912 """Tests for pydoc._url_handler"""
913
914 def test_content_type_err(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000915 f = pydoc._url_handler
Georg Brandld2f38572011-01-30 08:37:19 +0000916 self.assertRaises(TypeError, f, 'A', '')
917 self.assertRaises(TypeError, f, 'B', 'foobar')
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000918
919 def test_url_requests(self):
920 # Test for the correct title in the html pages returned.
921 # This tests the different parts of the URL handler without
922 # getting too picky about the exact html.
923 requests = [
Georg Brandld2f38572011-01-30 08:37:19 +0000924 ("", "Pydoc: Index of Modules"),
925 ("get?key=", "Pydoc: Index of Modules"),
926 ("index", "Pydoc: Index of Modules"),
927 ("topics", "Pydoc: Topics"),
928 ("keywords", "Pydoc: Keywords"),
929 ("pydoc", "Pydoc: module pydoc"),
930 ("get?key=pydoc", "Pydoc: module pydoc"),
931 ("search?key=pydoc", "Pydoc: Search Results"),
932 ("topic?key=def", "Pydoc: KEYWORD def"),
933 ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
934 ("foobar", "Pydoc: Error - foobar"),
935 ("getfile?key=foobar", "Pydoc: Error - getfile?key=foobar"),
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000936 ]
937
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200938 with self.restrict_walk_packages():
939 for url, title in requests:
Martin Panter9ad0aae2015-11-06 00:27:14 +0000940 self.call_url_handler(url, title)
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200941
942 path = string.__file__
943 title = "Pydoc: getfile " + path
944 url = "getfile?key=" + path
Martin Panter9ad0aae2015-11-06 00:27:14 +0000945 self.call_url_handler(url, title)
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000946
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000947
Ezio Melottib185a042011-04-28 07:42:55 +0300948class TestHelper(unittest.TestCase):
949 def test_keywords(self):
950 self.assertEqual(sorted(pydoc.Helper.keywords),
951 sorted(keyword.kwlist))
952
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700953class PydocWithMetaClasses(unittest.TestCase):
Ethan Furman3f2f1922013-10-22 07:30:24 -0700954 @unittest.skipIf(sys.flags.optimize >= 2,
955 "Docstrings are omitted with -O2 and above")
956 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
957 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700958 def test_DynamicClassAttribute(self):
959 class Meta(type):
960 def __getattr__(self, name):
961 if name == 'ham':
962 return 'spam'
963 return super().__getattr__(name)
964 class DA(metaclass=Meta):
965 @types.DynamicClassAttribute
966 def ham(self):
967 return 'eggs'
Ethan Furman3f2f1922013-10-22 07:30:24 -0700968 expected_text_data_docstrings = tuple('\n | ' + s if s else ''
969 for s in expected_data_docstrings)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700970 output = StringIO()
971 helper = pydoc.Helper(output=output)
972 helper(DA)
Ethan Furman3f2f1922013-10-22 07:30:24 -0700973 expected_text = expected_dynamicattribute_pattern % (
974 (__name__,) + expected_text_data_docstrings[:2])
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700975 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700976 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700977
Ethan Furman3f2f1922013-10-22 07:30:24 -0700978 @unittest.skipIf(sys.flags.optimize >= 2,
979 "Docstrings are omitted with -O2 and above")
980 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
981 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700982 def test_virtualClassAttributeWithOneMeta(self):
983 class Meta(type):
984 def __dir__(cls):
985 return ['__class__', '__module__', '__name__', 'LIFE']
986 def __getattr__(self, name):
987 if name =='LIFE':
988 return 42
989 return super().__getattr(name)
990 class Class(metaclass=Meta):
991 pass
992 output = StringIO()
993 helper = pydoc.Helper(output=output)
994 helper(Class)
995 expected_text = expected_virtualattribute_pattern1 % __name__
996 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700997 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700998
Ethan Furman3f2f1922013-10-22 07:30:24 -0700999 @unittest.skipIf(sys.flags.optimize >= 2,
1000 "Docstrings are omitted with -O2 and above")
1001 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
1002 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001003 def test_virtualClassAttributeWithTwoMeta(self):
1004 class Meta1(type):
1005 def __dir__(cls):
1006 return ['__class__', '__module__', '__name__', 'one']
1007 def __getattr__(self, name):
1008 if name =='one':
1009 return 1
1010 return super().__getattr__(name)
1011 class Meta2(type):
1012 def __dir__(cls):
1013 return ['__class__', '__module__', '__name__', 'two']
1014 def __getattr__(self, name):
1015 if name =='two':
1016 return 2
1017 return super().__getattr__(name)
1018 class Meta3(Meta1, Meta2):
1019 def __dir__(cls):
1020 return list(sorted(set(
1021 ['__class__', '__module__', '__name__', 'three'] +
1022 Meta1.__dir__(cls) + Meta2.__dir__(cls))))
1023 def __getattr__(self, name):
1024 if name =='three':
1025 return 3
1026 return super().__getattr__(name)
1027 class Class1(metaclass=Meta1):
1028 pass
1029 class Class2(Class1, metaclass=Meta3):
1030 pass
1031 fail1 = fail2 = False
1032 output = StringIO()
1033 helper = pydoc.Helper(output=output)
1034 helper(Class1)
1035 expected_text1 = expected_virtualattribute_pattern2 % __name__
1036 result1 = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -07001037 self.assertEqual(expected_text1, result1)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001038 output = StringIO()
1039 helper = pydoc.Helper(output=output)
1040 helper(Class2)
1041 expected_text2 = expected_virtualattribute_pattern3 % __name__
1042 result2 = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -07001043 self.assertEqual(expected_text2, result2)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001044
Ethan Furman3f2f1922013-10-22 07:30:24 -07001045 @unittest.skipIf(sys.flags.optimize >= 2,
1046 "Docstrings are omitted with -O2 and above")
1047 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
1048 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001049 def test_buggy_dir(self):
1050 class M(type):
1051 def __dir__(cls):
1052 return ['__class__', '__name__', 'missing', 'here']
1053 class C(metaclass=M):
1054 here = 'present!'
1055 output = StringIO()
1056 helper = pydoc.Helper(output=output)
1057 helper(C)
1058 expected_text = expected_missingattribute_pattern % __name__
1059 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -07001060 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001061
Serhiy Storchakab6076fb2015-04-21 21:09:48 +03001062 def test_resolve_false(self):
1063 # Issue #23008: pydoc enum.{,Int}Enum failed
1064 # because bool(enum.Enum) is False.
1065 with captured_stdout() as help_io:
1066 pydoc.help('enum.Enum')
1067 helptext = help_io.getvalue()
1068 self.assertIn('class Enum', helptext)
1069
Eric Snowaed5b222014-01-04 20:38:11 -07001070
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001071@reap_threads
Georg Brandlb533e262008-05-25 18:19:30 +00001072def test_main():
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001073 try:
1074 test.support.run_unittest(PydocDocTest,
Ned Deily92a81a12011-10-06 14:19:03 -07001075 PydocImportTest,
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001076 TestDescriptions,
1077 PydocServerTest,
1078 PydocUrlHandlerTest,
1079 TestHelper,
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001080 PydocWithMetaClasses,
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001081 )
1082 finally:
1083 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +00001084
1085if __name__ == "__main__":
1086 test_main()