blob: 59aa7151ee1cf26d8564ca76060667967bfa3f25 [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
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'
Benjamin Petersoned1160b2014-06-07 16:44:00 -070086\x20\x20\x20\x20
87 class C(builtins.object)
88 | Methods defined here:
89 |\x20\x20
90 | get_answer(self)
91 | Return say_no()
92 |\x20\x20
93 | is_it_true(self)
94 | Return self.get_answer()
95 |\x20\x20
96 | say_no(self)
97 |\x20\x20
98 | ----------------------------------------------------------------------
99 | Data descriptors defined here:
100 |\x20\x20
101 | __dict__
102 | dictionary for instance variables (if defined)
103 |\x20\x20
104 | __weakref__
105 | list of weak references to the object (if defined)
Georg Brandlb533e262008-05-25 18:19:30 +0000106
107FUNCTIONS
108 doc_func()
109 This function solves all of the world's problems:
110 hunger
111 lack of Python
112 war
113\x20\x20\x20\x20
114 nodoc_func()
115
116DATA
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000117 __xyz__ = 'X, Y and Z'
Georg Brandlb533e262008-05-25 18:19:30 +0000118
119VERSION
120 1.2.3.4
121
122AUTHOR
123 Benjamin Peterson
124
125CREDITS
126 Nobody
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000127
128FILE
129 %s
Georg Brandlb533e262008-05-25 18:19:30 +0000130""".strip()
131
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200132expected_text_data_docstrings = tuple('\n | ' + s if s else ''
133 for s in expected_data_docstrings)
134
Barry Warsaw28a691b2010-04-17 00:19:56 +0000135expected_html_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +0000136<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
137<tr bgcolor="#7799ee">
138<td valign=bottom>&nbsp;<br>
139<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
140><td align=right valign=bottom
141><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
142 <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
143<p>
144<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
145<tr bgcolor="#ee77aa">
146<td colspan=3 valign=bottom>&nbsp;<br>
147<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
148\x20\x20\x20\x20
149<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
150<td width="100%%"><dl>
151<dt><font face="helvetica, arial"><a href="builtins.html#object">builtins.object</a>
152</font></dt><dd>
153<dl>
154<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
155</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700156</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#C">C</a>
Georg Brandlb533e262008-05-25 18:19:30 +0000157</font></dt></dl>
158</dd>
159</dl>
160 <p>
161<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
162<tr bgcolor="#ffc8d8">
163<td colspan=3 valign=bottom>&nbsp;<br>
164<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>
165\x20\x20\x20\x20
166<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
167<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
168<tr><td>&nbsp;</td>
169<td width="100%%">Methods defined here:<br>
170<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>
171
172<hr>
173Data descriptors defined here:<br>
174<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200175<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000176</dl>
177<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200178<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000179</dl>
180</td></tr></table> <p>
181<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
182<tr bgcolor="#ffc8d8">
183<td colspan=3 valign=bottom>&nbsp;<br>
184<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>
185\x20\x20\x20\x20
186<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
187<td width="100%%">Data descriptors defined here:<br>
188<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200189<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000190</dl>
191<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200192<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000193</dl>
194<hr>
195Data and other attributes defined here:<br>
196<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
197
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700198</td></tr></table> <p>
199<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
200<tr bgcolor="#ffc8d8">
201<td colspan=3 valign=bottom>&nbsp;<br>
202<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>
203\x20\x20\x20\x20
204<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
205<td width="100%%">Methods defined here:<br>
206<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>
207
208<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>
209
210<dl><dt><a name="C-say_no"><strong>say_no</strong></a>(self)</dt></dl>
211
212<hr>
213Data descriptors defined here:<br>
214<dl><dt><strong>__dict__</strong></dt>
215<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
216</dl>
217<dl><dt><strong>__weakref__</strong></dt>
218<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
219</dl>
Georg Brandlb533e262008-05-25 18:19:30 +0000220</td></tr></table></td></tr></table><p>
221<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
222<tr bgcolor="#eeaa77">
223<td colspan=3 valign=bottom>&nbsp;<br>
224<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
225\x20\x20\x20\x20
226<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
227<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>
228hunger<br>
229lack&nbsp;of&nbsp;Python<br>
230war</tt></dd></dl>
231 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
232</td></tr></table><p>
233<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
234<tr bgcolor="#55aa55">
235<td colspan=3 valign=bottom>&nbsp;<br>
236<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
237\x20\x20\x20\x20
238<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000239<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p>
Georg Brandlb533e262008-05-25 18:19:30 +0000240<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
241<tr bgcolor="#7799ee">
242<td colspan=3 valign=bottom>&nbsp;<br>
243<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
244\x20\x20\x20\x20
245<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
246<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
247<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
248<tr bgcolor="#7799ee">
249<td colspan=3 valign=bottom>&nbsp;<br>
250<font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
251\x20\x20\x20\x20
252<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
253<td width="100%%">Nobody</td></tr></table>
Barry Warsaw28a691b2010-04-17 00:19:56 +0000254""".strip() # ' <- emacs turd
Georg Brandlb533e262008-05-25 18:19:30 +0000255
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200256expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;')
257 for s in expected_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000258
259# output pattern for missing module
Serhiy Storchaka1c205512015-03-01 00:42:54 +0200260missing_pattern = '''\
261No Python documentation found for %r.
262Use help() to get the interactive help utility.
263Use help(str) for help on the str class.'''.replace('\n', os.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000264
Benjamin Peterson0289b152009-06-28 17:22:03 +0000265# output pattern for module with bad imports
Brett Cannon679ecb52013-07-04 17:51:50 -0400266badimport_pattern = "problem in %s - ImportError: No module named %r"
Benjamin Peterson0289b152009-06-28 17:22:03 +0000267
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700268expected_dynamicattribute_pattern = """
269Help on class DA in module %s:
270
271class DA(builtins.object)
272 | Data descriptors defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200273 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700274 | __dict__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200275 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700276 | __weakref__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200277 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700278 | ham
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200279 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700280 | ----------------------------------------------------------------------
281 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200282 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700283 | ham = 'spam'
284""".strip()
285
286expected_virtualattribute_pattern1 = """
287Help on class Class in module %s:
288
289class Class(builtins.object)
290 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200291 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700292 | LIFE = 42
293""".strip()
294
295expected_virtualattribute_pattern2 = """
296Help on class Class1 in module %s:
297
298class Class1(builtins.object)
299 | Data and other attributes inherited from Meta1:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200300 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700301 | one = 1
302""".strip()
303
304expected_virtualattribute_pattern3 = """
305Help on class Class2 in module %s:
306
307class Class2(Class1)
308 | Method resolution order:
309 | Class2
310 | Class1
311 | builtins.object
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200312 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700313 | Data and other attributes inherited from Meta1:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200314 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700315 | one = 1
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200316 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700317 | ----------------------------------------------------------------------
318 | Data and other attributes inherited from Meta3:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200319 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700320 | three = 3
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200321 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700322 | ----------------------------------------------------------------------
323 | Data and other attributes inherited from Meta2:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200324 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700325 | two = 2
326""".strip()
327
328expected_missingattribute_pattern = """
329Help on class C in module %s:
330
331class C(builtins.object)
332 | Data and other attributes defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200333 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700334 | here = 'present!'
335""".strip()
336
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200337def run_pydoc(module_name, *args, **env):
Georg Brandlb533e262008-05-25 18:19:30 +0000338 """
339 Runs pydoc on the specified module. Returns the stripped
340 output of pydoc.
341 """
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200342 args = args + (module_name,)
Ned Deily92a81a12011-10-06 14:19:03 -0700343 # do not write bytecode files to avoid caching errors
344 rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200345 return out.strip()
Georg Brandlb533e262008-05-25 18:19:30 +0000346
347def get_pydoc_html(module):
348 "Returns pydoc generated output as html"
349 doc = pydoc.HTMLDoc()
350 output = doc.docmodule(module)
351 loc = doc.getdocloc(pydoc_mod) or ""
352 if loc:
353 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
354 return output.strip(), loc
355
R David Murrayead9bfc2016-06-03 19:28:35 -0400356def get_pydoc_link(module):
357 "Returns a documentation web link of a module"
358 dirname = os.path.dirname
359 basedir = os.path.join(dirname(dirname(__file__)))
360 doc = pydoc.TextDoc()
361 loc = doc.getdocloc(module, basedir=basedir)
362 return loc
363
Georg Brandlb533e262008-05-25 18:19:30 +0000364def get_pydoc_text(module):
365 "Returns pydoc generated output as text"
366 doc = pydoc.TextDoc()
367 loc = doc.getdocloc(pydoc_mod) or ""
368 if loc:
369 loc = "\nMODULE DOCS\n " + loc + "\n"
370
371 output = doc.docmodule(module)
372
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000373 # clean up the extra text formatting that pydoc performs
Georg Brandlb533e262008-05-25 18:19:30 +0000374 patt = re.compile('\b.')
375 output = patt.sub('', output)
376 return output.strip(), loc
377
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000378def get_html_title(text):
Nick Coghlanecace282010-12-03 16:08:46 +0000379 # Bit of hack, but good enough for test purposes
380 header, _, _ = text.partition("</head>")
381 _, _, title = header.partition("<title>")
382 title, _, _ = title.partition("</title>")
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000383 return title
384
Georg Brandlb533e262008-05-25 18:19:30 +0000385
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200386class PydocBaseTest(unittest.TestCase):
387
388 def _restricted_walk_packages(self, walk_packages, path=None):
389 """
390 A version of pkgutil.walk_packages() that will restrict itself to
391 a given path.
392 """
393 default_path = path or [os.path.dirname(__file__)]
394 def wrapper(path=None, prefix='', onerror=None):
395 return walk_packages(path or default_path, prefix, onerror)
396 return wrapper
397
398 @contextlib.contextmanager
399 def restrict_walk_packages(self, path=None):
400 walk_packages = pkgutil.walk_packages
401 pkgutil.walk_packages = self._restricted_walk_packages(walk_packages,
402 path)
403 try:
404 yield
405 finally:
406 pkgutil.walk_packages = walk_packages
407
Martin Panter9ad0aae2015-11-06 00:27:14 +0000408 def call_url_handler(self, url, expected_title):
409 text = pydoc._url_handler(url, "text/html")
410 result = get_html_title(text)
411 # Check the title to ensure an unexpected error page was not returned
412 self.assertEqual(result, expected_title, text)
413 return text
414
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200415
Georg Brandld2f38572011-01-30 08:37:19 +0000416class PydocDocTest(unittest.TestCase):
Georg Brandlb533e262008-05-25 18:19:30 +0000417
R. David Murray378c0cf2010-02-24 01:46:21 +0000418 @unittest.skipIf(sys.flags.optimize >= 2,
419 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000420 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
421 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100422 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000423 def test_html_doc(self):
424 result, doc_loc = get_pydoc_html(pydoc_mod)
425 mod_file = inspect.getabsfile(pydoc_mod)
Zachary Wareeb432142014-07-10 11:18:00 -0500426 mod_url = urllib.parse.quote(mod_file)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200427 expected_html = expected_html_pattern % (
428 (mod_url, mod_file, doc_loc) +
429 expected_html_data_docstrings)
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700430 self.assertEqual(result, expected_html)
Georg Brandlb533e262008-05-25 18:19:30 +0000431
R. David Murray378c0cf2010-02-24 01:46:21 +0000432 @unittest.skipIf(sys.flags.optimize >= 2,
433 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000434 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
435 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100436 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000437 def test_text_doc(self):
438 result, doc_loc = get_pydoc_text(pydoc_mod)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200439 expected_text = expected_text_pattern % (
440 (doc_loc,) +
441 expected_text_data_docstrings +
442 (inspect.getabsfile(pydoc_mod),))
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700443 self.assertEqual(expected_text, result)
Georg Brandlb533e262008-05-25 18:19:30 +0000444
Serhiy Storchaka056eb022014-02-19 23:05:12 +0200445 def test_text_enum_member_with_value_zero(self):
446 # Test issue #20654 to ensure enum member with value 0 can be
447 # displayed. It used to throw KeyError: 'zero'.
448 import enum
449 class BinaryInteger(enum.IntEnum):
450 zero = 0
451 one = 1
452 doc = pydoc.render_doc(BinaryInteger)
453 self.assertIn('<BinaryInteger.zero: 0>', doc)
454
R David Murrayead9bfc2016-06-03 19:28:35 -0400455 def test_mixed_case_module_names_are_lower_cased(self):
456 # issue16484
457 doc_link = get_pydoc_link(xml.etree.ElementTree)
458 self.assertIn('xml.etree.elementtree', doc_link)
459
Brian Curtin49c284c2010-03-31 03:19:28 +0000460 def test_issue8225(self):
461 # Test issue8225 to ensure no doc link appears for xml.etree
462 result, doc_loc = get_pydoc_text(xml.etree)
463 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
464
Benjamin Peterson159824e2014-06-07 20:14:26 -0700465 def test_getpager_with_stdin_none(self):
466 previous_stdin = sys.stdin
467 try:
468 sys.stdin = None
469 pydoc.getpager() # Shouldn't fail.
470 finally:
471 sys.stdin = previous_stdin
472
R David Murrayc43125a2012-04-23 13:23:57 -0400473 def test_non_str_name(self):
474 # issue14638
475 # Treat illegal (non-str) name like no name
476 class A:
477 __name__ = 42
478 class B:
479 pass
480 adoc = pydoc.render_doc(A())
481 bdoc = pydoc.render_doc(B())
482 self.assertEqual(adoc.replace("A", "B"), bdoc)
483
Georg Brandlb533e262008-05-25 18:19:30 +0000484 def test_not_here(self):
485 missing_module = "test.i_am_not_here"
486 result = str(run_pydoc(missing_module), 'ascii')
487 expected = missing_pattern % missing_module
488 self.assertEqual(expected, result,
489 "documentation for missing module found")
490
Serhiy Storchaka4c094e52015-03-01 15:31:36 +0200491 @unittest.skipIf(sys.flags.optimize >= 2,
492 'Docstrings are omitted with -OO and above')
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +0200493 def test_not_ascii(self):
494 result = run_pydoc('test.test_pydoc.nonascii', PYTHONIOENCODING='ascii')
495 encoded = nonascii.__doc__.encode('ascii', 'backslashreplace')
496 self.assertIn(encoded, result)
497
R. David Murray1f1b9d32009-05-27 20:56:59 +0000498 def test_input_strip(self):
499 missing_module = " test.i_am_not_here "
500 result = str(run_pydoc(missing_module), 'ascii')
501 expected = missing_pattern % missing_module.strip()
502 self.assertEqual(expected, result)
503
Ezio Melotti412c95a2010-02-16 23:31:04 +0000504 def test_stripid(self):
505 # test with strings, other implementations might have different repr()
506 stripid = pydoc.stripid
507 # strip the id
508 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
509 '<function stripid>')
510 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
511 '<function stripid>')
512 # nothing to strip, return the same text
513 self.assertEqual(stripid('42'), '42')
514 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
515 "<type 'exceptions.Exception'>")
516
Georg Brandld80d5f42010-12-03 07:47:22 +0000517 @unittest.skipIf(sys.flags.optimize >= 2,
518 'Docstrings are omitted with -O2 and above')
Brett Cannon7a540732011-02-22 03:04:06 +0000519 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
520 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100521 @requires_docstrings
Georg Brandld80d5f42010-12-03 07:47:22 +0000522 def test_help_output_redirect(self):
523 # issue 940286, if output is set in Helper, then all output from
524 # Helper.help should be redirected
525 old_pattern = expected_text_pattern
526 getpager_old = pydoc.getpager
527 getpager_new = lambda: (lambda x: x)
528 self.maxDiff = None
529
530 buf = StringIO()
531 helper = pydoc.Helper(output=buf)
532 unused, doc_loc = get_pydoc_text(pydoc_mod)
533 module = "test.pydoc_mod"
534 help_header = """
535 Help on module test.pydoc_mod in test:
536
537 """.lstrip()
538 help_header = textwrap.dedent(help_header)
539 expected_help_pattern = help_header + expected_text_pattern
540
541 pydoc.getpager = getpager_new
542 try:
543 with captured_output('stdout') as output, \
544 captured_output('stderr') as err:
545 helper.help(module)
546 result = buf.getvalue().strip()
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200547 expected_text = expected_help_pattern % (
548 (doc_loc,) +
549 expected_text_data_docstrings +
550 (inspect.getabsfile(pydoc_mod),))
Georg Brandld80d5f42010-12-03 07:47:22 +0000551 self.assertEqual('', output.getvalue())
552 self.assertEqual('', err.getvalue())
553 self.assertEqual(expected_text, result)
554 finally:
555 pydoc.getpager = getpager_old
556
Raymond Hettinger1103d052011-03-25 14:15:24 -0700557 def test_namedtuple_public_underscore(self):
558 NT = namedtuple('NT', ['abc', 'def'], rename=True)
559 with captured_stdout() as help_io:
Terry Jan Reedy5c811642013-11-04 21:43:26 -0500560 pydoc.help(NT)
Raymond Hettinger1103d052011-03-25 14:15:24 -0700561 helptext = help_io.getvalue()
562 self.assertIn('_1', helptext)
563 self.assertIn('_replace', helptext)
564 self.assertIn('_asdict', helptext)
565
Victor Stinnere6c910e2011-06-30 15:55:43 +0200566 def test_synopsis(self):
567 self.addCleanup(unlink, TESTFN)
568 for encoding in ('ISO-8859-1', 'UTF-8'):
569 with open(TESTFN, 'w', encoding=encoding) as script:
570 if encoding != 'UTF-8':
571 print('#coding: {}'.format(encoding), file=script)
572 print('"""line 1: h\xe9', file=script)
573 print('line 2: hi"""', file=script)
574 synopsis = pydoc.synopsis(TESTFN, {})
575 self.assertEqual(synopsis, 'line 1: h\xe9')
576
Serhiy Storchaka4c094e52015-03-01 15:31:36 +0200577 @unittest.skipIf(sys.flags.optimize >= 2,
578 'Docstrings are omitted with -OO and above')
Eric Snowaed5b222014-01-04 20:38:11 -0700579 def test_synopsis_sourceless(self):
580 expected = os.__doc__.splitlines()[0]
581 filename = os.__cached__
582 synopsis = pydoc.synopsis(filename)
583
584 self.assertEqual(synopsis, expected)
585
Benjamin Peterson54237f92015-02-16 19:45:01 -0500586 def test_synopsis_sourceless_empty_doc(self):
587 with test.support.temp_cwd() as test_dir:
588 init_path = os.path.join(test_dir, 'foomod42.py')
589 cached_path = importlib.util.cache_from_source(init_path)
590 with open(init_path, 'w') as fobj:
591 fobj.write("foo = 1")
592 py_compile.compile(init_path)
593 synopsis = pydoc.synopsis(init_path, {})
594 self.assertIsNone(synopsis)
595 synopsis_cached = pydoc.synopsis(cached_path, {})
596 self.assertIsNone(synopsis_cached)
597
R David Murray455f2962013-03-19 00:00:33 -0400598 def test_splitdoc_with_description(self):
599 example_string = "I Am A Doc\n\n\nHere is my description"
600 self.assertEqual(pydoc.splitdoc(example_string),
601 ('I Am A Doc', '\nHere is my description'))
602
603 def test_is_object_or_method(self):
604 doc = pydoc.Doc()
605 # Bound Method
606 self.assertTrue(pydoc._is_some_method(doc.fail))
607 # Method Descriptor
608 self.assertTrue(pydoc._is_some_method(int.__add__))
609 # String
610 self.assertFalse(pydoc._is_some_method("I am not a method"))
611
612 def test_is_package_when_not_package(self):
613 with test.support.temp_cwd() as test_dir:
614 self.assertFalse(pydoc.ispackage(test_dir))
615
616 def test_is_package_when_is_package(self):
617 with test.support.temp_cwd() as test_dir:
618 init_path = os.path.join(test_dir, '__init__.py')
619 open(init_path, 'w').close()
620 self.assertTrue(pydoc.ispackage(test_dir))
621 os.remove(init_path)
622
R David Murrayac0cea52013-03-19 02:47:44 -0400623 def test_allmethods(self):
624 # issue 17476: allmethods was no longer returning unbound methods.
625 # This test is a bit fragile in the face of changes to object and type,
626 # but I can't think of a better way to do it without duplicating the
627 # logic of the function under test.
628
629 class TestClass(object):
630 def method_returning_true(self):
631 return True
632
633 # What we expect to get back: everything on object...
634 expected = dict(vars(object))
635 # ...plus our unbound method...
636 expected['method_returning_true'] = TestClass.method_returning_true
637 # ...but not the non-methods on object.
638 del expected['__doc__']
639 del expected['__class__']
640 # inspect resolves descriptors on type into methods, but vars doesn't,
641 # so we need to update __subclasshook__.
642 expected['__subclasshook__'] = TestClass.__subclasshook__
643
644 methods = pydoc.allmethods(TestClass)
645 self.assertDictEqual(methods, expected)
646
Georg Brandlb533e262008-05-25 18:19:30 +0000647
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200648class PydocImportTest(PydocBaseTest):
Ned Deily92a81a12011-10-06 14:19:03 -0700649
650 def setUp(self):
651 self.test_dir = os.mkdir(TESTFN)
652 self.addCleanup(rmtree, TESTFN)
Benjamin Peterson54237f92015-02-16 19:45:01 -0500653 importlib.invalidate_caches()
Ned Deily92a81a12011-10-06 14:19:03 -0700654
655 def test_badimport(self):
656 # This tests the fix for issue 5230, where if pydoc found the module
657 # but the module had an internal import error pydoc would report no doc
658 # found.
659 modname = 'testmod_xyzzy'
660 testpairs = (
661 ('i_am_not_here', 'i_am_not_here'),
Brett Cannonfd074152012-04-14 14:10:13 -0400662 ('test.i_am_not_here_either', 'test.i_am_not_here_either'),
663 ('test.i_am_not_here.neither_am_i', 'test.i_am_not_here'),
664 ('i_am_not_here.{}'.format(modname), 'i_am_not_here'),
665 ('test.{}'.format(modname), 'test.{}'.format(modname)),
Ned Deily92a81a12011-10-06 14:19:03 -0700666 )
667
668 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
669 for importstring, expectedinmsg in testpairs:
670 with open(sourcefn, 'w') as f:
671 f.write("import {}\n".format(importstring))
672 result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii")
673 expected = badimport_pattern % (modname, expectedinmsg)
674 self.assertEqual(expected, result)
675
676 def test_apropos_with_bad_package(self):
677 # Issue 7425 - pydoc -k failed when bad package on path
678 pkgdir = os.path.join(TESTFN, "syntaxerr")
679 os.mkdir(pkgdir)
680 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
681 with open(badsyntax, 'w') as f:
682 f.write("invalid python syntax = $1\n")
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200683 with self.restrict_walk_packages(path=[TESTFN]):
684 with captured_stdout() as out:
685 with captured_stderr() as err:
686 pydoc.apropos('xyzzy')
687 # No result, no error
688 self.assertEqual(out.getvalue(), '')
689 self.assertEqual(err.getvalue(), '')
690 # The package name is still matched
691 with captured_stdout() as out:
692 with captured_stderr() as err:
693 pydoc.apropos('syntaxerr')
694 self.assertEqual(out.getvalue().strip(), 'syntaxerr')
695 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700696
697 def test_apropos_with_unreadable_dir(self):
698 # Issue 7367 - pydoc -k failed when unreadable dir on path
699 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
700 os.mkdir(self.unreadable_dir, 0)
701 self.addCleanup(os.rmdir, self.unreadable_dir)
702 # Note, on Windows the directory appears to be still
703 # readable so this is not really testing the issue there
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200704 with self.restrict_walk_packages(path=[TESTFN]):
705 with captured_stdout() as out:
706 with captured_stderr() as err:
707 pydoc.apropos('SOMEKEY')
708 # No result, no error
709 self.assertEqual(out.getvalue(), '')
710 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700711
Benjamin Peterson54237f92015-02-16 19:45:01 -0500712 def test_apropos_empty_doc(self):
713 pkgdir = os.path.join(TESTFN, 'walkpkg')
714 os.mkdir(pkgdir)
715 self.addCleanup(rmtree, pkgdir)
716 init_path = os.path.join(pkgdir, '__init__.py')
717 with open(init_path, 'w') as fobj:
718 fobj.write("foo = 1")
719 current_mode = stat.S_IMODE(os.stat(pkgdir).st_mode)
720 try:
721 os.chmod(pkgdir, current_mode & ~stat.S_IEXEC)
722 with self.restrict_walk_packages(path=[TESTFN]), captured_stdout() as stdout:
723 pydoc.apropos('')
724 self.assertIn('walkpkg', stdout.getvalue())
725 finally:
726 os.chmod(pkgdir, current_mode)
727
Martin Panter9ad0aae2015-11-06 00:27:14 +0000728 def test_url_search_package_error(self):
729 # URL handler search should cope with packages that raise exceptions
730 pkgdir = os.path.join(TESTFN, "test_error_package")
731 os.mkdir(pkgdir)
732 init = os.path.join(pkgdir, "__init__.py")
733 with open(init, "wt", encoding="ascii") as f:
734 f.write("""raise ValueError("ouch")\n""")
735 with self.restrict_walk_packages(path=[TESTFN]):
736 # Package has to be importable for the error to have any effect
737 saved_paths = tuple(sys.path)
738 sys.path.insert(0, TESTFN)
739 try:
740 with self.assertRaisesRegex(ValueError, "ouch"):
741 import test_error_package # Sanity check
742
743 text = self.call_url_handler("search?key=test_error_package",
744 "Pydoc: Search Results")
745 found = ('<a href="test_error_package.html">'
746 'test_error_package</a>')
747 self.assertIn(found, text)
748 finally:
749 sys.path[:] = saved_paths
750
Martin Panter46f50722016-05-26 05:35:26 +0000751 @unittest.skip('causes undesirable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700752 def test_modules(self):
753 # See Helper.listmodules().
754 num_header_lines = 2
755 num_module_lines_min = 5 # Playing it safe.
756 num_footer_lines = 3
757 expected = num_header_lines + num_module_lines_min + num_footer_lines
758
759 output = StringIO()
760 helper = pydoc.Helper(output=output)
761 helper('modules')
762 result = output.getvalue().strip()
763 num_lines = len(result.splitlines())
764
765 self.assertGreaterEqual(num_lines, expected)
766
Martin Panter46f50722016-05-26 05:35:26 +0000767 @unittest.skip('causes undesirable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700768 def test_modules_search(self):
769 # See Helper.listmodules().
770 expected = 'pydoc - '
771
772 output = StringIO()
773 helper = pydoc.Helper(output=output)
774 with captured_stdout() as help_io:
775 helper('modules pydoc')
776 result = help_io.getvalue()
777
778 self.assertIn(expected, result)
779
Eric Snowa46ef702014-02-22 13:57:08 -0700780 @unittest.skip('some buildbots are not cooperating (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700781 def test_modules_search_builtin(self):
Eric Snow5ea97502014-01-04 23:04:27 -0700782 expected = 'gc - '
Eric Snowaed5b222014-01-04 20:38:11 -0700783
784 output = StringIO()
785 helper = pydoc.Helper(output=output)
786 with captured_stdout() as help_io:
Eric Snow5ea97502014-01-04 23:04:27 -0700787 helper('modules garbage')
Eric Snowaed5b222014-01-04 20:38:11 -0700788 result = help_io.getvalue()
789
790 self.assertTrue(result.startswith(expected))
791
792 def test_importfile(self):
793 loaded_pydoc = pydoc.importfile(pydoc.__file__)
794
Eric Snow3a62d142014-01-06 20:42:59 -0700795 self.assertIsNot(loaded_pydoc, pydoc)
Eric Snowaed5b222014-01-04 20:38:11 -0700796 self.assertEqual(loaded_pydoc.__name__, 'pydoc')
797 self.assertEqual(loaded_pydoc.__file__, pydoc.__file__)
Eric Snow3a62d142014-01-06 20:42:59 -0700798 self.assertEqual(loaded_pydoc.__spec__, pydoc.__spec__)
Eric Snowaed5b222014-01-04 20:38:11 -0700799
Ned Deily92a81a12011-10-06 14:19:03 -0700800
Georg Brandlb533e262008-05-25 18:19:30 +0000801class TestDescriptions(unittest.TestCase):
802
803 def test_module(self):
804 # Check that pydocfodder module can be described
805 from test import pydocfodder
806 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000807 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000808
Georg Brandlb533e262008-05-25 18:19:30 +0000809 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000810 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +0000811 c = C()
812
813 self.assertEqual(pydoc.describe(C), 'class C')
814 self.assertEqual(pydoc.describe(c), 'C')
815 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000816 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000817
Éric Araujoe64e51b2011-07-29 17:03:55 +0200818 def test_builtin(self):
819 for name in ('str', 'str.translate', 'builtins.str',
820 'builtins.str.translate'):
821 # test low-level function
822 self.assertIsNotNone(pydoc.locate(name))
823 # test high-level function
824 try:
825 pydoc.render_doc(name)
826 except ImportError:
Terry Jan Reedyfe928de2014-06-20 14:59:11 -0400827 self.fail('finding the doc of {!r} failed'.format(name))
Éric Araujoe64e51b2011-07-29 17:03:55 +0200828
829 for name in ('notbuiltins', 'strrr', 'strr.translate',
830 'str.trrrranslate', 'builtins.strrr',
831 'builtins.str.trrranslate'):
832 self.assertIsNone(pydoc.locate(name))
833 self.assertRaises(ImportError, pydoc.render_doc, name)
834
Larry Hastings24a882b2014-02-20 23:34:46 -0800835 @staticmethod
836 def _get_summary_line(o):
837 text = pydoc.plain(pydoc.render_doc(o))
838 lines = text.split('\n')
839 assert len(lines) >= 2
840 return lines[2]
841
842 # these should include "self"
843 def test_unbound_python_method(self):
844 self.assertEqual(self._get_summary_line(textwrap.TextWrapper.wrap),
845 "wrap(self, text)")
846
Stefan Krah5de32782014-01-18 23:18:39 +0100847 @requires_docstrings
Larry Hastings24a882b2014-02-20 23:34:46 -0800848 def test_unbound_builtin_method(self):
849 self.assertEqual(self._get_summary_line(_pickle.Pickler.dump),
850 "dump(self, obj, /)")
851
852 # these no longer include "self"
853 def test_bound_python_method(self):
854 t = textwrap.TextWrapper()
855 self.assertEqual(self._get_summary_line(t.wrap),
856 "wrap(text) method of textwrap.TextWrapper instance")
857
858 @requires_docstrings
859 def test_bound_builtin_method(self):
860 s = StringIO()
861 p = _pickle.Pickler(s)
862 self.assertEqual(self._get_summary_line(p.dump),
863 "dump(obj, /) method of _pickle.Pickler instance")
864
865 # this should *never* include self!
866 @requires_docstrings
867 def test_module_level_callable(self):
868 self.assertEqual(self._get_summary_line(os.stat),
869 "stat(path, *, dir_fd=None, follow_symlinks=True)")
Larry Hastings1abd7082014-01-16 14:15:03 -0800870
Georg Brandlb533e262008-05-25 18:19:30 +0000871
Victor Stinner62a68f22011-05-20 02:29:13 +0200872@unittest.skipUnless(threading, 'Threading required for this test.')
Georg Brandld2f38572011-01-30 08:37:19 +0000873class PydocServerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000874 """Tests for pydoc._start_server"""
875
876 def test_server(self):
877
878 # Minimal test that starts the server, then stops it.
879 def my_url_handler(url, content_type):
880 text = 'the URL sent was: (%s, %s)' % (url, content_type)
881 return text
882
883 serverthread = pydoc._start_server(my_url_handler, port=0)
Senthil Kumaran2a42a0b2014-09-17 13:17:58 +0800884 self.assertIn('localhost', serverthread.docserver.address)
885
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000886 starttime = time.time()
887 timeout = 1 #seconds
888
889 while serverthread.serving:
890 time.sleep(.01)
891 if serverthread.serving and time.time() - starttime > timeout:
892 serverthread.stop()
893 break
894
895 self.assertEqual(serverthread.error, None)
896
897
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200898class PydocUrlHandlerTest(PydocBaseTest):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000899 """Tests for pydoc._url_handler"""
900
901 def test_content_type_err(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000902 f = pydoc._url_handler
Georg Brandld2f38572011-01-30 08:37:19 +0000903 self.assertRaises(TypeError, f, 'A', '')
904 self.assertRaises(TypeError, f, 'B', 'foobar')
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000905
906 def test_url_requests(self):
907 # Test for the correct title in the html pages returned.
908 # This tests the different parts of the URL handler without
909 # getting too picky about the exact html.
910 requests = [
Georg Brandld2f38572011-01-30 08:37:19 +0000911 ("", "Pydoc: Index of Modules"),
912 ("get?key=", "Pydoc: Index of Modules"),
913 ("index", "Pydoc: Index of Modules"),
914 ("topics", "Pydoc: Topics"),
915 ("keywords", "Pydoc: Keywords"),
916 ("pydoc", "Pydoc: module pydoc"),
917 ("get?key=pydoc", "Pydoc: module pydoc"),
918 ("search?key=pydoc", "Pydoc: Search Results"),
919 ("topic?key=def", "Pydoc: KEYWORD def"),
920 ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
921 ("foobar", "Pydoc: Error - foobar"),
922 ("getfile?key=foobar", "Pydoc: Error - getfile?key=foobar"),
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000923 ]
924
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200925 with self.restrict_walk_packages():
926 for url, title in requests:
Martin Panter9ad0aae2015-11-06 00:27:14 +0000927 self.call_url_handler(url, title)
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200928
929 path = string.__file__
930 title = "Pydoc: getfile " + path
931 url = "getfile?key=" + path
Martin Panter9ad0aae2015-11-06 00:27:14 +0000932 self.call_url_handler(url, title)
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000933
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000934
Ezio Melottib185a042011-04-28 07:42:55 +0300935class TestHelper(unittest.TestCase):
936 def test_keywords(self):
937 self.assertEqual(sorted(pydoc.Helper.keywords),
938 sorted(keyword.kwlist))
939
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700940class PydocWithMetaClasses(unittest.TestCase):
Ethan Furman3f2f1922013-10-22 07:30:24 -0700941 @unittest.skipIf(sys.flags.optimize >= 2,
942 "Docstrings are omitted with -O2 and above")
943 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
944 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700945 def test_DynamicClassAttribute(self):
946 class Meta(type):
947 def __getattr__(self, name):
948 if name == 'ham':
949 return 'spam'
950 return super().__getattr__(name)
951 class DA(metaclass=Meta):
952 @types.DynamicClassAttribute
953 def ham(self):
954 return 'eggs'
Ethan Furman3f2f1922013-10-22 07:30:24 -0700955 expected_text_data_docstrings = tuple('\n | ' + s if s else ''
956 for s in expected_data_docstrings)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700957 output = StringIO()
958 helper = pydoc.Helper(output=output)
959 helper(DA)
Ethan Furman3f2f1922013-10-22 07:30:24 -0700960 expected_text = expected_dynamicattribute_pattern % (
961 (__name__,) + expected_text_data_docstrings[:2])
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700962 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700963 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700964
Ethan Furman3f2f1922013-10-22 07:30:24 -0700965 @unittest.skipIf(sys.flags.optimize >= 2,
966 "Docstrings are omitted with -O2 and above")
967 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
968 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700969 def test_virtualClassAttributeWithOneMeta(self):
970 class Meta(type):
971 def __dir__(cls):
972 return ['__class__', '__module__', '__name__', 'LIFE']
973 def __getattr__(self, name):
974 if name =='LIFE':
975 return 42
976 return super().__getattr(name)
977 class Class(metaclass=Meta):
978 pass
979 output = StringIO()
980 helper = pydoc.Helper(output=output)
981 helper(Class)
982 expected_text = expected_virtualattribute_pattern1 % __name__
983 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700984 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700985
Ethan Furman3f2f1922013-10-22 07:30:24 -0700986 @unittest.skipIf(sys.flags.optimize >= 2,
987 "Docstrings are omitted with -O2 and above")
988 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
989 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700990 def test_virtualClassAttributeWithTwoMeta(self):
991 class Meta1(type):
992 def __dir__(cls):
993 return ['__class__', '__module__', '__name__', 'one']
994 def __getattr__(self, name):
995 if name =='one':
996 return 1
997 return super().__getattr__(name)
998 class Meta2(type):
999 def __dir__(cls):
1000 return ['__class__', '__module__', '__name__', 'two']
1001 def __getattr__(self, name):
1002 if name =='two':
1003 return 2
1004 return super().__getattr__(name)
1005 class Meta3(Meta1, Meta2):
1006 def __dir__(cls):
1007 return list(sorted(set(
1008 ['__class__', '__module__', '__name__', 'three'] +
1009 Meta1.__dir__(cls) + Meta2.__dir__(cls))))
1010 def __getattr__(self, name):
1011 if name =='three':
1012 return 3
1013 return super().__getattr__(name)
1014 class Class1(metaclass=Meta1):
1015 pass
1016 class Class2(Class1, metaclass=Meta3):
1017 pass
1018 fail1 = fail2 = False
1019 output = StringIO()
1020 helper = pydoc.Helper(output=output)
1021 helper(Class1)
1022 expected_text1 = expected_virtualattribute_pattern2 % __name__
1023 result1 = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -07001024 self.assertEqual(expected_text1, result1)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001025 output = StringIO()
1026 helper = pydoc.Helper(output=output)
1027 helper(Class2)
1028 expected_text2 = expected_virtualattribute_pattern3 % __name__
1029 result2 = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -07001030 self.assertEqual(expected_text2, result2)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001031
Ethan Furman3f2f1922013-10-22 07:30:24 -07001032 @unittest.skipIf(sys.flags.optimize >= 2,
1033 "Docstrings are omitted with -O2 and above")
1034 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
1035 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001036 def test_buggy_dir(self):
1037 class M(type):
1038 def __dir__(cls):
1039 return ['__class__', '__name__', 'missing', 'here']
1040 class C(metaclass=M):
1041 here = 'present!'
1042 output = StringIO()
1043 helper = pydoc.Helper(output=output)
1044 helper(C)
1045 expected_text = expected_missingattribute_pattern % __name__
1046 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -07001047 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001048
Serhiy Storchakab6076fb2015-04-21 21:09:48 +03001049 def test_resolve_false(self):
1050 # Issue #23008: pydoc enum.{,Int}Enum failed
1051 # because bool(enum.Enum) is False.
1052 with captured_stdout() as help_io:
1053 pydoc.help('enum.Enum')
1054 helptext = help_io.getvalue()
1055 self.assertIn('class Enum', helptext)
1056
Eric Snowaed5b222014-01-04 20:38:11 -07001057
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001058@reap_threads
Georg Brandlb533e262008-05-25 18:19:30 +00001059def test_main():
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001060 try:
1061 test.support.run_unittest(PydocDocTest,
Ned Deily92a81a12011-10-06 14:19:03 -07001062 PydocImportTest,
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001063 TestDescriptions,
1064 PydocServerTest,
1065 PydocUrlHandlerTest,
1066 TestHelper,
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001067 PydocWithMetaClasses,
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001068 )
1069 finally:
1070 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +00001071
1072if __name__ == "__main__":
1073 test_main()