blob: f0d7ffd562c9d964508be2afaa5b70215183d2c4 [file] [log] [blame]
Georg Brandlb533e262008-05-25 18:19:30 +00001import os
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002import sys
Antoine Pitrou916fc7b2013-05-19 15:44:54 +02003import contextlib
Benjamin Peterson54237f92015-02-16 19:45:01 -05004import importlib.util
Georg Brandlb533e262008-05-25 18:19:30 +00005import inspect
Nick Coghlan7bb30b72010-12-03 09:29:11 +00006import pydoc
Benjamin Peterson54237f92015-02-16 19:45:01 -05007import py_compile
Ezio Melottib185a042011-04-28 07:42:55 +03008import keyword
Larry Hastings24a882b2014-02-20 23:34:46 -08009import _pickle
Antoine Pitrou916fc7b2013-05-19 15:44:54 +020010import pkgutil
Nick Coghlan7bb30b72010-12-03 09:29:11 +000011import re
Benjamin Peterson54237f92015-02-16 19:45:01 -050012import stat
Nick Coghlan7bb30b72010-12-03 09:29:11 +000013import string
Nick Coghlan82a94812018-04-15 21:52:57 +100014import tempfile
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
Hai Shie80697d2020-05-28 06:10:27 +080027from test.support import threading_helper
Antoine Pitroua6e81a22011-07-15 22:32:25 +020028from test.support import (
Ned Deily92a81a12011-10-06 14:19:03 -070029 TESTFN, rmtree,
Hai Shie80697d2020-05-28 06:10:27 +080030 reap_children, captured_output, captured_stdout,
Stefan Krah5de32782014-01-18 23:18:39 +010031 captured_stderr, unlink, requires_docstrings
Antoine Pitroua6e81a22011-07-15 22:32:25 +020032)
Georg Brandlb533e262008-05-25 18:19:30 +000033from test import pydoc_mod
34
Victor Stinner62a68f22011-05-20 02:29:13 +020035
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +020036class nonascii:
37 'Це не латиниця'
38 pass
39
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020040if test.support.HAVE_DOCSTRINGS:
41 expected_data_docstrings = (
42 'dictionary for instance variables (if defined)',
43 'list of weak references to the object (if defined)',
44 ) * 2
45else:
46 expected_data_docstrings = ('', '', '', '')
47
Barry Warsaw28a691b2010-04-17 00:19:56 +000048expected_text_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000049NAME
50 test.pydoc_mod - This is a test module for test_pydoc
Georg Brandlb533e262008-05-25 18:19:30 +000051%s
52CLASSES
53 builtins.object
54 A
55 B
Benjamin Petersoned1160b2014-06-07 16:44:00 -070056 C
Georg Brandlb533e262008-05-25 18:19:30 +000057\x20\x20\x20\x20
58 class A(builtins.object)
59 | Hello and goodbye
60 |\x20\x20
61 | Methods defined here:
62 |\x20\x20
63 | __init__()
64 | Wow, I have no function!
65 |\x20\x20
66 | ----------------------------------------------------------------------
67 | Data descriptors defined here:
68 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020069 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000070 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020071 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000072\x20\x20\x20\x20
73 class B(builtins.object)
74 | Data descriptors defined here:
75 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020076 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000077 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020078 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000079 |\x20\x20
80 | ----------------------------------------------------------------------
81 | Data and other attributes defined here:
82 |\x20\x20
83 | NO_MEANING = 'eggs'
Yury Selivanovf8cb8a12016-09-08 20:50:03 -070084 |\x20\x20
85 | __annotations__ = {'NO_MEANING': <class 'str'>}
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
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700198<dl><dt><strong>__annotations__</strong> = {'NO_MEANING': &lt;class 'str'&gt;}</dl>
199
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700200</td></tr></table> <p>
201<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
202<tr bgcolor="#ffc8d8">
203<td colspan=3 valign=bottom>&nbsp;<br>
204<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>
205\x20\x20\x20\x20
206<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
207<td width="100%%">Methods defined here:<br>
208<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>
209
210<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>
211
212<dl><dt><a name="C-say_no"><strong>say_no</strong></a>(self)</dt></dl>
213
214<hr>
215Data descriptors defined here:<br>
216<dl><dt><strong>__dict__</strong></dt>
217<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
218</dl>
219<dl><dt><strong>__weakref__</strong></dt>
220<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
221</dl>
Georg Brandlb533e262008-05-25 18:19:30 +0000222</td></tr></table></td></tr></table><p>
223<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
224<tr bgcolor="#eeaa77">
225<td colspan=3 valign=bottom>&nbsp;<br>
226<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
227\x20\x20\x20\x20
228<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
229<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>
230hunger<br>
231lack&nbsp;of&nbsp;Python<br>
232war</tt></dd></dl>
233 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
234</td></tr></table><p>
235<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
236<tr bgcolor="#55aa55">
237<td colspan=3 valign=bottom>&nbsp;<br>
238<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
239\x20\x20\x20\x20
240<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000241<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p>
Georg Brandlb533e262008-05-25 18:19:30 +0000242<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
243<tr bgcolor="#7799ee">
244<td colspan=3 valign=bottom>&nbsp;<br>
245<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
246\x20\x20\x20\x20
247<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
248<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
249<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
250<tr bgcolor="#7799ee">
251<td colspan=3 valign=bottom>&nbsp;<br>
252<font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
253\x20\x20\x20\x20
254<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
255<td width="100%%">Nobody</td></tr></table>
Barry Warsaw28a691b2010-04-17 00:19:56 +0000256""".strip() # ' <- emacs turd
Georg Brandlb533e262008-05-25 18:19:30 +0000257
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200258expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;')
259 for s in expected_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000260
261# output pattern for missing module
Serhiy Storchaka1c205512015-03-01 00:42:54 +0200262missing_pattern = '''\
263No Python documentation found for %r.
264Use help() to get the interactive help utility.
265Use help(str) for help on the str class.'''.replace('\n', os.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000266
Benjamin Peterson0289b152009-06-28 17:22:03 +0000267# output pattern for module with bad imports
Eric Snow46f97b82016-09-07 16:56:15 -0700268badimport_pattern = "problem in %s - ModuleNotFoundError: No module named %r"
Benjamin Peterson0289b152009-06-28 17:22:03 +0000269
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700270expected_dynamicattribute_pattern = """
271Help on class DA in module %s:
272
273class DA(builtins.object)
274 | Data descriptors defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200275 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700276 | __dict__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200277 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700278 | __weakref__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200279 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700280 | ham
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200281 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700282 | ----------------------------------------------------------------------
283 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200284 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700285 | ham = 'spam'
286""".strip()
287
288expected_virtualattribute_pattern1 = """
289Help on class Class in module %s:
290
291class Class(builtins.object)
292 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200293 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700294 | LIFE = 42
295""".strip()
296
297expected_virtualattribute_pattern2 = """
298Help on class Class1 in module %s:
299
300class Class1(builtins.object)
301 | Data and other attributes inherited from Meta1:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200302 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700303 | one = 1
304""".strip()
305
306expected_virtualattribute_pattern3 = """
307Help on class Class2 in module %s:
308
309class Class2(Class1)
310 | Method resolution order:
311 | Class2
312 | Class1
313 | builtins.object
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200314 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700315 | Data and other attributes inherited from Meta1:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200316 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700317 | one = 1
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200318 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700319 | ----------------------------------------------------------------------
320 | Data and other attributes inherited from Meta3:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200321 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700322 | three = 3
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200323 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700324 | ----------------------------------------------------------------------
325 | Data and other attributes inherited from Meta2:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200326 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700327 | two = 2
328""".strip()
329
330expected_missingattribute_pattern = """
331Help on class C in module %s:
332
333class C(builtins.object)
334 | Data and other attributes defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200335 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700336 | here = 'present!'
337""".strip()
338
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200339def run_pydoc(module_name, *args, **env):
Georg Brandlb533e262008-05-25 18:19:30 +0000340 """
341 Runs pydoc on the specified module. Returns the stripped
342 output of pydoc.
343 """
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200344 args = args + (module_name,)
Ned Deily92a81a12011-10-06 14:19:03 -0700345 # do not write bytecode files to avoid caching errors
346 rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200347 return out.strip()
Georg Brandlb533e262008-05-25 18:19:30 +0000348
349def get_pydoc_html(module):
350 "Returns pydoc generated output as html"
351 doc = pydoc.HTMLDoc()
352 output = doc.docmodule(module)
353 loc = doc.getdocloc(pydoc_mod) or ""
354 if loc:
355 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
356 return output.strip(), loc
357
R David Murrayead9bfc2016-06-03 19:28:35 -0400358def get_pydoc_link(module):
359 "Returns a documentation web link of a module"
Bo Bayles4e11c462018-07-29 14:15:14 -0500360 abspath = os.path.abspath
R David Murrayead9bfc2016-06-03 19:28:35 -0400361 dirname = os.path.dirname
Bo Bayles4e11c462018-07-29 14:15:14 -0500362 basedir = dirname(dirname(abspath(__file__)))
R David Murrayead9bfc2016-06-03 19:28:35 -0400363 doc = pydoc.TextDoc()
364 loc = doc.getdocloc(module, basedir=basedir)
365 return loc
366
Georg Brandlb533e262008-05-25 18:19:30 +0000367def get_pydoc_text(module):
368 "Returns pydoc generated output as text"
369 doc = pydoc.TextDoc()
370 loc = doc.getdocloc(pydoc_mod) or ""
371 if loc:
372 loc = "\nMODULE DOCS\n " + loc + "\n"
373
374 output = doc.docmodule(module)
375
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000376 # clean up the extra text formatting that pydoc performs
Georg Brandlb533e262008-05-25 18:19:30 +0000377 patt = re.compile('\b.')
378 output = patt.sub('', output)
379 return output.strip(), loc
380
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000381def get_html_title(text):
Nick Coghlanecace282010-12-03 16:08:46 +0000382 # Bit of hack, but good enough for test purposes
383 header, _, _ = text.partition("</head>")
384 _, _, title = header.partition("<title>")
385 title, _, _ = title.partition("</title>")
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000386 return title
387
Georg Brandlb533e262008-05-25 18:19:30 +0000388
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200389class PydocBaseTest(unittest.TestCase):
390
391 def _restricted_walk_packages(self, walk_packages, path=None):
392 """
393 A version of pkgutil.walk_packages() that will restrict itself to
394 a given path.
395 """
396 default_path = path or [os.path.dirname(__file__)]
397 def wrapper(path=None, prefix='', onerror=None):
398 return walk_packages(path or default_path, prefix, onerror)
399 return wrapper
400
401 @contextlib.contextmanager
402 def restrict_walk_packages(self, path=None):
403 walk_packages = pkgutil.walk_packages
404 pkgutil.walk_packages = self._restricted_walk_packages(walk_packages,
405 path)
406 try:
407 yield
408 finally:
409 pkgutil.walk_packages = walk_packages
410
Martin Panter9ad0aae2015-11-06 00:27:14 +0000411 def call_url_handler(self, url, expected_title):
412 text = pydoc._url_handler(url, "text/html")
413 result = get_html_title(text)
414 # Check the title to ensure an unexpected error page was not returned
415 self.assertEqual(result, expected_title, text)
416 return text
417
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200418
Georg Brandld2f38572011-01-30 08:37:19 +0000419class PydocDocTest(unittest.TestCase):
Serhiy Storchakaa44d34e2018-11-08 08:48:11 +0200420 maxDiff = None
Georg Brandlb533e262008-05-25 18:19:30 +0000421
R. David Murray378c0cf2010-02-24 01:46:21 +0000422 @unittest.skipIf(sys.flags.optimize >= 2,
423 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000424 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
425 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100426 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000427 def test_html_doc(self):
428 result, doc_loc = get_pydoc_html(pydoc_mod)
429 mod_file = inspect.getabsfile(pydoc_mod)
Zachary Wareeb432142014-07-10 11:18:00 -0500430 mod_url = urllib.parse.quote(mod_file)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200431 expected_html = expected_html_pattern % (
432 (mod_url, mod_file, doc_loc) +
433 expected_html_data_docstrings)
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700434 self.assertEqual(result, expected_html)
Georg Brandlb533e262008-05-25 18:19:30 +0000435
R. David Murray378c0cf2010-02-24 01:46:21 +0000436 @unittest.skipIf(sys.flags.optimize >= 2,
437 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000438 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
439 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100440 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000441 def test_text_doc(self):
442 result, doc_loc = get_pydoc_text(pydoc_mod)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200443 expected_text = expected_text_pattern % (
444 (doc_loc,) +
445 expected_text_data_docstrings +
446 (inspect.getabsfile(pydoc_mod),))
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700447 self.assertEqual(expected_text, result)
Georg Brandlb533e262008-05-25 18:19:30 +0000448
Serhiy Storchaka056eb022014-02-19 23:05:12 +0200449 def test_text_enum_member_with_value_zero(self):
450 # Test issue #20654 to ensure enum member with value 0 can be
451 # displayed. It used to throw KeyError: 'zero'.
452 import enum
453 class BinaryInteger(enum.IntEnum):
454 zero = 0
455 one = 1
456 doc = pydoc.render_doc(BinaryInteger)
457 self.assertIn('<BinaryInteger.zero: 0>', doc)
458
R David Murrayead9bfc2016-06-03 19:28:35 -0400459 def test_mixed_case_module_names_are_lower_cased(self):
460 # issue16484
461 doc_link = get_pydoc_link(xml.etree.ElementTree)
462 self.assertIn('xml.etree.elementtree', doc_link)
463
Brian Curtin49c284c2010-03-31 03:19:28 +0000464 def test_issue8225(self):
465 # Test issue8225 to ensure no doc link appears for xml.etree
466 result, doc_loc = get_pydoc_text(xml.etree)
467 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
468
Benjamin Peterson159824e2014-06-07 20:14:26 -0700469 def test_getpager_with_stdin_none(self):
470 previous_stdin = sys.stdin
471 try:
472 sys.stdin = None
473 pydoc.getpager() # Shouldn't fail.
474 finally:
475 sys.stdin = previous_stdin
476
R David Murrayc43125a2012-04-23 13:23:57 -0400477 def test_non_str_name(self):
478 # issue14638
479 # Treat illegal (non-str) name like no name
Karthikeyan Singaravelan696136b2020-04-18 21:49:32 +0530480
R David Murrayc43125a2012-04-23 13:23:57 -0400481 class A:
482 __name__ = 42
483 class B:
484 pass
485 adoc = pydoc.render_doc(A())
486 bdoc = pydoc.render_doc(B())
Eric Snow4f29e752016-09-08 15:11:11 -0700487 self.assertEqual(adoc.replace("A", "B"), bdoc)
R David Murrayc43125a2012-04-23 13:23:57 -0400488
Georg Brandlb533e262008-05-25 18:19:30 +0000489 def test_not_here(self):
490 missing_module = "test.i_am_not_here"
491 result = str(run_pydoc(missing_module), 'ascii')
492 expected = missing_pattern % missing_module
493 self.assertEqual(expected, result,
494 "documentation for missing module found")
495
Serhiy Storchaka4c094e52015-03-01 15:31:36 +0200496 @unittest.skipIf(sys.flags.optimize >= 2,
497 'Docstrings are omitted with -OO and above')
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +0200498 def test_not_ascii(self):
499 result = run_pydoc('test.test_pydoc.nonascii', PYTHONIOENCODING='ascii')
500 encoded = nonascii.__doc__.encode('ascii', 'backslashreplace')
501 self.assertIn(encoded, result)
502
R. David Murray1f1b9d32009-05-27 20:56:59 +0000503 def test_input_strip(self):
504 missing_module = " test.i_am_not_here "
505 result = str(run_pydoc(missing_module), 'ascii')
506 expected = missing_pattern % missing_module.strip()
507 self.assertEqual(expected, result)
508
Ezio Melotti412c95a2010-02-16 23:31:04 +0000509 def test_stripid(self):
510 # test with strings, other implementations might have different repr()
511 stripid = pydoc.stripid
512 # strip the id
513 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
514 '<function stripid>')
515 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
516 '<function stripid>')
517 # nothing to strip, return the same text
518 self.assertEqual(stripid('42'), '42')
519 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
520 "<type 'exceptions.Exception'>")
521
Sanyam Khuranaa323cdc2018-10-21 00:22:02 -0700522 def test_builtin_with_more_than_four_children(self):
523 """Tests help on builtin object which have more than four child classes.
524
525 When running help() on a builtin class which has child classes, it
526 should contain a "Built-in subclasses" section and only 4 classes
527 should be displayed with a hint on how many more subclasses are present.
528 For example:
529
530 >>> help(object)
531 Help on class object in module builtins:
532
533 class object
534 | The most base type
535 |
536 | Built-in subclasses:
537 | async_generator
538 | BaseException
539 | builtin_function_or_method
540 | bytearray
541 | ... and 82 other subclasses
542 """
543 doc = pydoc.TextDoc()
544 text = doc.docclass(object)
545 snip = (" | Built-in subclasses:\n"
546 " | async_generator\n"
547 " | BaseException\n"
548 " | builtin_function_or_method\n"
549 " | bytearray\n"
550 " | ... and \\d+ other subclasses")
551 self.assertRegex(text, snip)
552
553 def test_builtin_with_child(self):
554 """Tests help on builtin object which have only child classes.
555
556 When running help() on a builtin class which has child classes, it
557 should contain a "Built-in subclasses" section. For example:
558
559 >>> help(ArithmeticError)
560 Help on class ArithmeticError in module builtins:
561
562 class ArithmeticError(Exception)
563 | Base class for arithmetic errors.
564 |
565 ...
566 |
567 | Built-in subclasses:
568 | FloatingPointError
569 | OverflowError
570 | ZeroDivisionError
571 """
572 doc = pydoc.TextDoc()
573 text = doc.docclass(ArithmeticError)
574 snip = (" | Built-in subclasses:\n"
575 " | FloatingPointError\n"
576 " | OverflowError\n"
577 " | ZeroDivisionError")
578 self.assertIn(snip, text)
579
580 def test_builtin_with_grandchild(self):
581 """Tests help on builtin classes which have grandchild classes.
582
583 When running help() on a builtin class which has child classes, it
584 should contain a "Built-in subclasses" section. However, if it also has
585 grandchildren, these should not show up on the subclasses section.
586 For example:
587
588 >>> help(Exception)
589 Help on class Exception in module builtins:
590
591 class Exception(BaseException)
592 | Common base class for all non-exit exceptions.
593 |
594 ...
595 |
596 | Built-in subclasses:
597 | ArithmeticError
598 | AssertionError
599 | AttributeError
600 ...
601 """
602 doc = pydoc.TextDoc()
603 text = doc.docclass(Exception)
604 snip = (" | Built-in subclasses:\n"
605 " | ArithmeticError\n"
606 " | AssertionError\n"
607 " | AttributeError")
608 self.assertIn(snip, text)
609 # Testing that the grandchild ZeroDivisionError does not show up
610 self.assertNotIn('ZeroDivisionError', text)
611
612 def test_builtin_no_child(self):
613 """Tests help on builtin object which have no child classes.
614
615 When running help() on a builtin class which has no child classes, it
616 should not contain any "Built-in subclasses" section. For example:
617
618 >>> help(ZeroDivisionError)
619
620 Help on class ZeroDivisionError in module builtins:
621
622 class ZeroDivisionError(ArithmeticError)
623 | Second argument to a division or modulo operation was zero.
624 |
625 | Method resolution order:
626 | ZeroDivisionError
627 | ArithmeticError
628 | Exception
629 | BaseException
630 | object
631 |
632 | Methods defined here:
633 ...
634 """
635 doc = pydoc.TextDoc()
636 text = doc.docclass(ZeroDivisionError)
637 # Testing that the subclasses section does not appear
638 self.assertNotIn('Built-in subclasses', text)
639
Sanyam Khuranab539cef2018-12-31 10:44:47 +0530640 def test_builtin_on_metaclasses(self):
641 """Tests help on metaclasses.
642
643 When running help() on a metaclasses such as type, it
644 should not contain any "Built-in subclasses" section.
645 """
646 doc = pydoc.TextDoc()
647 text = doc.docclass(type)
648 # Testing that the subclasses section does not appear
649 self.assertNotIn('Built-in subclasses', text)
650
Georg Brandld80d5f42010-12-03 07:47:22 +0000651 @unittest.skipIf(sys.flags.optimize >= 2,
652 'Docstrings are omitted with -O2 and above')
Brett Cannon7a540732011-02-22 03:04:06 +0000653 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
654 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100655 @requires_docstrings
Georg Brandld80d5f42010-12-03 07:47:22 +0000656 def test_help_output_redirect(self):
657 # issue 940286, if output is set in Helper, then all output from
658 # Helper.help should be redirected
659 old_pattern = expected_text_pattern
660 getpager_old = pydoc.getpager
661 getpager_new = lambda: (lambda x: x)
662 self.maxDiff = None
663
664 buf = StringIO()
665 helper = pydoc.Helper(output=buf)
666 unused, doc_loc = get_pydoc_text(pydoc_mod)
667 module = "test.pydoc_mod"
668 help_header = """
669 Help on module test.pydoc_mod in test:
670
671 """.lstrip()
672 help_header = textwrap.dedent(help_header)
673 expected_help_pattern = help_header + expected_text_pattern
674
675 pydoc.getpager = getpager_new
676 try:
677 with captured_output('stdout') as output, \
678 captured_output('stderr') as err:
679 helper.help(module)
680 result = buf.getvalue().strip()
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200681 expected_text = expected_help_pattern % (
682 (doc_loc,) +
683 expected_text_data_docstrings +
684 (inspect.getabsfile(pydoc_mod),))
Georg Brandld80d5f42010-12-03 07:47:22 +0000685 self.assertEqual('', output.getvalue())
686 self.assertEqual('', err.getvalue())
687 self.assertEqual(expected_text, result)
688 finally:
689 pydoc.getpager = getpager_old
690
Serhiy Storchaka052b2df2018-12-31 14:15:16 +0200691 def test_namedtuple_fields(self):
692 Person = namedtuple('Person', ['nickname', 'firstname'])
693 with captured_stdout() as help_io:
694 pydoc.help(Person)
695 helptext = help_io.getvalue()
696 self.assertIn("nickname", helptext)
697 self.assertIn("firstname", helptext)
698 self.assertIn("Alias for field number 0", helptext)
699 self.assertIn("Alias for field number 1", helptext)
700
Raymond Hettinger1103d052011-03-25 14:15:24 -0700701 def test_namedtuple_public_underscore(self):
702 NT = namedtuple('NT', ['abc', 'def'], rename=True)
703 with captured_stdout() as help_io:
Terry Jan Reedy5c811642013-11-04 21:43:26 -0500704 pydoc.help(NT)
Raymond Hettinger1103d052011-03-25 14:15:24 -0700705 helptext = help_io.getvalue()
706 self.assertIn('_1', helptext)
707 self.assertIn('_replace', helptext)
708 self.assertIn('_asdict', helptext)
709
Victor Stinnere6c910e2011-06-30 15:55:43 +0200710 def test_synopsis(self):
711 self.addCleanup(unlink, TESTFN)
712 for encoding in ('ISO-8859-1', 'UTF-8'):
713 with open(TESTFN, 'w', encoding=encoding) as script:
714 if encoding != 'UTF-8':
715 print('#coding: {}'.format(encoding), file=script)
716 print('"""line 1: h\xe9', file=script)
717 print('line 2: hi"""', file=script)
718 synopsis = pydoc.synopsis(TESTFN, {})
719 self.assertEqual(synopsis, 'line 1: h\xe9')
720
Serhiy Storchaka4c094e52015-03-01 15:31:36 +0200721 @unittest.skipIf(sys.flags.optimize >= 2,
722 'Docstrings are omitted with -OO and above')
Eric Snowaed5b222014-01-04 20:38:11 -0700723 def test_synopsis_sourceless(self):
724 expected = os.__doc__.splitlines()[0]
725 filename = os.__cached__
726 synopsis = pydoc.synopsis(filename)
727
728 self.assertEqual(synopsis, expected)
729
Benjamin Peterson54237f92015-02-16 19:45:01 -0500730 def test_synopsis_sourceless_empty_doc(self):
731 with test.support.temp_cwd() as test_dir:
732 init_path = os.path.join(test_dir, 'foomod42.py')
733 cached_path = importlib.util.cache_from_source(init_path)
734 with open(init_path, 'w') as fobj:
735 fobj.write("foo = 1")
736 py_compile.compile(init_path)
737 synopsis = pydoc.synopsis(init_path, {})
738 self.assertIsNone(synopsis)
739 synopsis_cached = pydoc.synopsis(cached_path, {})
740 self.assertIsNone(synopsis_cached)
741
R David Murray455f2962013-03-19 00:00:33 -0400742 def test_splitdoc_with_description(self):
743 example_string = "I Am A Doc\n\n\nHere is my description"
744 self.assertEqual(pydoc.splitdoc(example_string),
745 ('I Am A Doc', '\nHere is my description'))
746
R David Murray455f2962013-03-19 00:00:33 -0400747 def test_is_package_when_not_package(self):
748 with test.support.temp_cwd() as test_dir:
749 self.assertFalse(pydoc.ispackage(test_dir))
750
751 def test_is_package_when_is_package(self):
752 with test.support.temp_cwd() as test_dir:
753 init_path = os.path.join(test_dir, '__init__.py')
754 open(init_path, 'w').close()
755 self.assertTrue(pydoc.ispackage(test_dir))
756 os.remove(init_path)
757
R David Murrayac0cea52013-03-19 02:47:44 -0400758 def test_allmethods(self):
759 # issue 17476: allmethods was no longer returning unbound methods.
760 # This test is a bit fragile in the face of changes to object and type,
761 # but I can't think of a better way to do it without duplicating the
762 # logic of the function under test.
763
764 class TestClass(object):
765 def method_returning_true(self):
766 return True
767
768 # What we expect to get back: everything on object...
769 expected = dict(vars(object))
770 # ...plus our unbound method...
771 expected['method_returning_true'] = TestClass.method_returning_true
772 # ...but not the non-methods on object.
773 del expected['__doc__']
774 del expected['__class__']
775 # inspect resolves descriptors on type into methods, but vars doesn't,
Nick Coghland78448e2016-07-30 16:26:03 +1000776 # so we need to update __subclasshook__ and __init_subclass__.
R David Murrayac0cea52013-03-19 02:47:44 -0400777 expected['__subclasshook__'] = TestClass.__subclasshook__
Nick Coghland78448e2016-07-30 16:26:03 +1000778 expected['__init_subclass__'] = TestClass.__init_subclass__
R David Murrayac0cea52013-03-19 02:47:44 -0400779
780 methods = pydoc.allmethods(TestClass)
781 self.assertDictEqual(methods, expected)
782
Serhiy Storchakaa44d34e2018-11-08 08:48:11 +0200783 def test_method_aliases(self):
784 class A:
785 def tkraise(self, aboveThis=None):
786 """Raise this widget in the stacking order."""
787 lift = tkraise
788 def a_size(self):
789 """Return size"""
790 class B(A):
791 def itemconfigure(self, tagOrId, cnf=None, **kw):
792 """Configure resources of an item TAGORID."""
793 itemconfig = itemconfigure
794 b_size = A.a_size
795
796 doc = pydoc.render_doc(B)
797 # clean up the extra text formatting that pydoc performs
798 doc = re.sub('\b.', '', doc)
799 self.assertEqual(doc, '''\
800Python Library Documentation: class B in module %s
801
802class B(A)
803 | Method resolution order:
804 | B
805 | A
806 | builtins.object
807 |\x20\x20
808 | Methods defined here:
809 |\x20\x20
810 | b_size = a_size(self)
811 |\x20\x20
812 | itemconfig = itemconfigure(self, tagOrId, cnf=None, **kw)
813 |\x20\x20
814 | itemconfigure(self, tagOrId, cnf=None, **kw)
815 | Configure resources of an item TAGORID.
816 |\x20\x20
817 | ----------------------------------------------------------------------
818 | Methods inherited from A:
819 |\x20\x20
820 | a_size(self)
821 | Return size
822 |\x20\x20
823 | lift = tkraise(self, aboveThis=None)
824 |\x20\x20
825 | tkraise(self, aboveThis=None)
826 | Raise this widget in the stacking order.
827 |\x20\x20
828 | ----------------------------------------------------------------------
829 | Data descriptors inherited from A:
830 |\x20\x20
831 | __dict__
832 | dictionary for instance variables (if defined)
833 |\x20\x20
834 | __weakref__
835 | list of weak references to the object (if defined)
836''' % __name__)
837
838 doc = pydoc.render_doc(B, renderer=pydoc.HTMLDoc())
839 self.assertEqual(doc, '''\
840Python Library Documentation: class B in module %s
841
842<p>
843<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
844<tr bgcolor="#ffc8d8">
845<td colspan=3 valign=bottom>&nbsp;<br>
846<font color="#000000" face="helvetica, arial"><a name="B">class <strong>B</strong></a>(A)</font></td></tr>
847\x20\x20\x20\x20
848<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
849<td width="100%%"><dl><dt>Method resolution order:</dt>
850<dd>B</dd>
851<dd>A</dd>
852<dd><a href="builtins.html#object">builtins.object</a></dd>
853</dl>
854<hr>
855Methods defined here:<br>
856<dl><dt><a name="B-b_size"><strong>b_size</strong></a> = <a href="#B-a_size">a_size</a>(self)</dt></dl>
857
858<dl><dt><a name="B-itemconfig"><strong>itemconfig</strong></a> = <a href="#B-itemconfigure">itemconfigure</a>(self, tagOrId, cnf=None, **kw)</dt></dl>
859
860<dl><dt><a name="B-itemconfigure"><strong>itemconfigure</strong></a>(self, tagOrId, cnf=None, **kw)</dt><dd><tt>Configure&nbsp;resources&nbsp;of&nbsp;an&nbsp;item&nbsp;TAGORID.</tt></dd></dl>
861
862<hr>
863Methods inherited from A:<br>
864<dl><dt><a name="B-a_size"><strong>a_size</strong></a>(self)</dt><dd><tt>Return&nbsp;size</tt></dd></dl>
865
866<dl><dt><a name="B-lift"><strong>lift</strong></a> = <a href="#B-tkraise">tkraise</a>(self, aboveThis=None)</dt></dl>
867
868<dl><dt><a name="B-tkraise"><strong>tkraise</strong></a>(self, aboveThis=None)</dt><dd><tt>Raise&nbsp;this&nbsp;widget&nbsp;in&nbsp;the&nbsp;stacking&nbsp;order.</tt></dd></dl>
869
870<hr>
871Data descriptors inherited from A:<br>
872<dl><dt><strong>__dict__</strong></dt>
873<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
874</dl>
875<dl><dt><strong>__weakref__</strong></dt>
876<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
877</dl>
878</td></tr></table>\
879''' % __name__)
880
Georg Brandlb533e262008-05-25 18:19:30 +0000881
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200882class PydocImportTest(PydocBaseTest):
Ned Deily92a81a12011-10-06 14:19:03 -0700883
884 def setUp(self):
885 self.test_dir = os.mkdir(TESTFN)
886 self.addCleanup(rmtree, TESTFN)
Benjamin Peterson54237f92015-02-16 19:45:01 -0500887 importlib.invalidate_caches()
Ned Deily92a81a12011-10-06 14:19:03 -0700888
889 def test_badimport(self):
890 # This tests the fix for issue 5230, where if pydoc found the module
891 # but the module had an internal import error pydoc would report no doc
892 # found.
893 modname = 'testmod_xyzzy'
894 testpairs = (
895 ('i_am_not_here', 'i_am_not_here'),
Brett Cannonfd074152012-04-14 14:10:13 -0400896 ('test.i_am_not_here_either', 'test.i_am_not_here_either'),
897 ('test.i_am_not_here.neither_am_i', 'test.i_am_not_here'),
898 ('i_am_not_here.{}'.format(modname), 'i_am_not_here'),
899 ('test.{}'.format(modname), 'test.{}'.format(modname)),
Ned Deily92a81a12011-10-06 14:19:03 -0700900 )
901
902 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
903 for importstring, expectedinmsg in testpairs:
904 with open(sourcefn, 'w') as f:
905 f.write("import {}\n".format(importstring))
906 result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii")
907 expected = badimport_pattern % (modname, expectedinmsg)
908 self.assertEqual(expected, result)
909
910 def test_apropos_with_bad_package(self):
911 # Issue 7425 - pydoc -k failed when bad package on path
912 pkgdir = os.path.join(TESTFN, "syntaxerr")
913 os.mkdir(pkgdir)
914 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
915 with open(badsyntax, 'w') as f:
916 f.write("invalid python syntax = $1\n")
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200917 with self.restrict_walk_packages(path=[TESTFN]):
918 with captured_stdout() as out:
919 with captured_stderr() as err:
920 pydoc.apropos('xyzzy')
921 # No result, no error
922 self.assertEqual(out.getvalue(), '')
923 self.assertEqual(err.getvalue(), '')
924 # The package name is still matched
925 with captured_stdout() as out:
926 with captured_stderr() as err:
927 pydoc.apropos('syntaxerr')
928 self.assertEqual(out.getvalue().strip(), 'syntaxerr')
929 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700930
931 def test_apropos_with_unreadable_dir(self):
932 # Issue 7367 - pydoc -k failed when unreadable dir on path
933 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
934 os.mkdir(self.unreadable_dir, 0)
935 self.addCleanup(os.rmdir, self.unreadable_dir)
936 # Note, on Windows the directory appears to be still
937 # readable so this is not really testing the issue there
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200938 with self.restrict_walk_packages(path=[TESTFN]):
939 with captured_stdout() as out:
940 with captured_stderr() as err:
941 pydoc.apropos('SOMEKEY')
942 # No result, no error
943 self.assertEqual(out.getvalue(), '')
944 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700945
Benjamin Peterson54237f92015-02-16 19:45:01 -0500946 def test_apropos_empty_doc(self):
947 pkgdir = os.path.join(TESTFN, 'walkpkg')
948 os.mkdir(pkgdir)
949 self.addCleanup(rmtree, pkgdir)
950 init_path = os.path.join(pkgdir, '__init__.py')
951 with open(init_path, 'w') as fobj:
952 fobj.write("foo = 1")
953 current_mode = stat.S_IMODE(os.stat(pkgdir).st_mode)
954 try:
955 os.chmod(pkgdir, current_mode & ~stat.S_IEXEC)
956 with self.restrict_walk_packages(path=[TESTFN]), captured_stdout() as stdout:
957 pydoc.apropos('')
958 self.assertIn('walkpkg', stdout.getvalue())
959 finally:
960 os.chmod(pkgdir, current_mode)
961
Martin Panter9ad0aae2015-11-06 00:27:14 +0000962 def test_url_search_package_error(self):
963 # URL handler search should cope with packages that raise exceptions
964 pkgdir = os.path.join(TESTFN, "test_error_package")
965 os.mkdir(pkgdir)
966 init = os.path.join(pkgdir, "__init__.py")
967 with open(init, "wt", encoding="ascii") as f:
968 f.write("""raise ValueError("ouch")\n""")
969 with self.restrict_walk_packages(path=[TESTFN]):
970 # Package has to be importable for the error to have any effect
971 saved_paths = tuple(sys.path)
972 sys.path.insert(0, TESTFN)
973 try:
974 with self.assertRaisesRegex(ValueError, "ouch"):
975 import test_error_package # Sanity check
976
977 text = self.call_url_handler("search?key=test_error_package",
978 "Pydoc: Search Results")
979 found = ('<a href="test_error_package.html">'
980 'test_error_package</a>')
981 self.assertIn(found, text)
982 finally:
983 sys.path[:] = saved_paths
984
Martin Panter46f50722016-05-26 05:35:26 +0000985 @unittest.skip('causes undesirable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700986 def test_modules(self):
987 # See Helper.listmodules().
988 num_header_lines = 2
989 num_module_lines_min = 5 # Playing it safe.
990 num_footer_lines = 3
991 expected = num_header_lines + num_module_lines_min + num_footer_lines
992
993 output = StringIO()
994 helper = pydoc.Helper(output=output)
995 helper('modules')
996 result = output.getvalue().strip()
997 num_lines = len(result.splitlines())
998
999 self.assertGreaterEqual(num_lines, expected)
1000
Martin Panter46f50722016-05-26 05:35:26 +00001001 @unittest.skip('causes undesirable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -07001002 def test_modules_search(self):
1003 # See Helper.listmodules().
1004 expected = 'pydoc - '
1005
1006 output = StringIO()
1007 helper = pydoc.Helper(output=output)
1008 with captured_stdout() as help_io:
1009 helper('modules pydoc')
1010 result = help_io.getvalue()
1011
1012 self.assertIn(expected, result)
1013
Eric Snowa46ef702014-02-22 13:57:08 -07001014 @unittest.skip('some buildbots are not cooperating (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -07001015 def test_modules_search_builtin(self):
Eric Snow5ea97502014-01-04 23:04:27 -07001016 expected = 'gc - '
Eric Snowaed5b222014-01-04 20:38:11 -07001017
1018 output = StringIO()
1019 helper = pydoc.Helper(output=output)
1020 with captured_stdout() as help_io:
Eric Snow5ea97502014-01-04 23:04:27 -07001021 helper('modules garbage')
Eric Snowaed5b222014-01-04 20:38:11 -07001022 result = help_io.getvalue()
1023
1024 self.assertTrue(result.startswith(expected))
1025
1026 def test_importfile(self):
1027 loaded_pydoc = pydoc.importfile(pydoc.__file__)
1028
Eric Snow3a62d142014-01-06 20:42:59 -07001029 self.assertIsNot(loaded_pydoc, pydoc)
Eric Snowaed5b222014-01-04 20:38:11 -07001030 self.assertEqual(loaded_pydoc.__name__, 'pydoc')
1031 self.assertEqual(loaded_pydoc.__file__, pydoc.__file__)
Eric Snow3a62d142014-01-06 20:42:59 -07001032 self.assertEqual(loaded_pydoc.__spec__, pydoc.__spec__)
Eric Snowaed5b222014-01-04 20:38:11 -07001033
Ned Deily92a81a12011-10-06 14:19:03 -07001034
Georg Brandlb533e262008-05-25 18:19:30 +00001035class TestDescriptions(unittest.TestCase):
1036
1037 def test_module(self):
1038 # Check that pydocfodder module can be described
1039 from test import pydocfodder
1040 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001041 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +00001042
Georg Brandlb533e262008-05-25 18:19:30 +00001043 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +00001044 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +00001045 c = C()
1046
1047 self.assertEqual(pydoc.describe(C), 'class C')
1048 self.assertEqual(pydoc.describe(c), 'C')
1049 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +00001050 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +00001051
Guido van Rossum52e50042016-10-22 07:55:18 -07001052 def test_typing_pydoc(self):
1053 def foo(data: typing.List[typing.Any],
1054 x: int) -> typing.Iterator[typing.Tuple[int, typing.Any]]:
1055 ...
1056 T = typing.TypeVar('T')
1057 class C(typing.Generic[T], typing.Mapping[int, str]): ...
1058 self.assertEqual(pydoc.render_doc(foo).splitlines()[-1],
Dong-hee Na762b9572017-11-16 03:30:59 +09001059 'f\x08fo\x08oo\x08o(data: List[Any], x: int)'
Guido van Rossum52e50042016-10-22 07:55:18 -07001060 ' -> Iterator[Tuple[int, Any]]')
1061 self.assertEqual(pydoc.render_doc(C).splitlines()[2],
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001062 'class C\x08C(collections.abc.Mapping, typing.Generic)')
Guido van Rossum52e50042016-10-22 07:55:18 -07001063
Éric Araujoe64e51b2011-07-29 17:03:55 +02001064 def test_builtin(self):
1065 for name in ('str', 'str.translate', 'builtins.str',
1066 'builtins.str.translate'):
1067 # test low-level function
1068 self.assertIsNotNone(pydoc.locate(name))
1069 # test high-level function
1070 try:
1071 pydoc.render_doc(name)
1072 except ImportError:
Terry Jan Reedyfe928de2014-06-20 14:59:11 -04001073 self.fail('finding the doc of {!r} failed'.format(name))
Éric Araujoe64e51b2011-07-29 17:03:55 +02001074
1075 for name in ('notbuiltins', 'strrr', 'strr.translate',
1076 'str.trrrranslate', 'builtins.strrr',
1077 'builtins.str.trrranslate'):
1078 self.assertIsNone(pydoc.locate(name))
1079 self.assertRaises(ImportError, pydoc.render_doc, name)
1080
Larry Hastings24a882b2014-02-20 23:34:46 -08001081 @staticmethod
1082 def _get_summary_line(o):
1083 text = pydoc.plain(pydoc.render_doc(o))
1084 lines = text.split('\n')
1085 assert len(lines) >= 2
1086 return lines[2]
1087
Serhiy Storchakaefcf82f2019-01-15 10:53:18 +02001088 @staticmethod
1089 def _get_summary_lines(o):
1090 text = pydoc.plain(pydoc.render_doc(o))
1091 lines = text.split('\n')
1092 return '\n'.join(lines[2:])
1093
Larry Hastings24a882b2014-02-20 23:34:46 -08001094 # these should include "self"
1095 def test_unbound_python_method(self):
1096 self.assertEqual(self._get_summary_line(textwrap.TextWrapper.wrap),
1097 "wrap(self, text)")
1098
Stefan Krah5de32782014-01-18 23:18:39 +01001099 @requires_docstrings
Larry Hastings24a882b2014-02-20 23:34:46 -08001100 def test_unbound_builtin_method(self):
1101 self.assertEqual(self._get_summary_line(_pickle.Pickler.dump),
1102 "dump(self, obj, /)")
1103
1104 # these no longer include "self"
1105 def test_bound_python_method(self):
1106 t = textwrap.TextWrapper()
1107 self.assertEqual(self._get_summary_line(t.wrap),
1108 "wrap(text) method of textwrap.TextWrapper instance")
Raymond Hettinger95801bb2015-08-18 22:25:16 -07001109 def test_field_order_for_named_tuples(self):
1110 Person = namedtuple('Person', ['nickname', 'firstname', 'agegroup'])
1111 s = pydoc.render_doc(Person)
1112 self.assertLess(s.index('nickname'), s.index('firstname'))
1113 self.assertLess(s.index('firstname'), s.index('agegroup'))
1114
1115 class NonIterableFields:
1116 _fields = None
1117
1118 class NonHashableFields:
1119 _fields = [[]]
1120
1121 # Make sure these doesn't fail
1122 pydoc.render_doc(NonIterableFields)
1123 pydoc.render_doc(NonHashableFields)
1124
Larry Hastings24a882b2014-02-20 23:34:46 -08001125 @requires_docstrings
1126 def test_bound_builtin_method(self):
1127 s = StringIO()
1128 p = _pickle.Pickler(s)
1129 self.assertEqual(self._get_summary_line(p.dump),
1130 "dump(obj, /) method of _pickle.Pickler instance")
1131
1132 # this should *never* include self!
1133 @requires_docstrings
1134 def test_module_level_callable(self):
1135 self.assertEqual(self._get_summary_line(os.stat),
1136 "stat(path, *, dir_fd=None, follow_symlinks=True)")
Larry Hastings1abd7082014-01-16 14:15:03 -08001137
Serhiy Storchakaefcf82f2019-01-15 10:53:18 +02001138 @requires_docstrings
1139 def test_staticmethod(self):
1140 class X:
1141 @staticmethod
1142 def sm(x, y):
1143 '''A static method'''
1144 ...
1145 self.assertEqual(self._get_summary_lines(X.__dict__['sm']),
1146 "<staticmethod object>")
1147 self.assertEqual(self._get_summary_lines(X.sm), """\
1148sm(x, y)
1149 A static method
1150""")
1151 self.assertIn("""
1152 | Static methods defined here:
1153 |\x20\x20
1154 | sm(x, y)
1155 | A static method
1156""", pydoc.plain(pydoc.render_doc(X)))
1157
1158 @requires_docstrings
1159 def test_classmethod(self):
1160 class X:
1161 @classmethod
1162 def cm(cls, x):
1163 '''A class method'''
1164 ...
1165 self.assertEqual(self._get_summary_lines(X.__dict__['cm']),
1166 "<classmethod object>")
1167 self.assertEqual(self._get_summary_lines(X.cm), """\
1168cm(x) method of builtins.type instance
1169 A class method
1170""")
1171 self.assertIn("""
1172 | Class methods defined here:
1173 |\x20\x20
1174 | cm(x) from builtins.type
1175 | A class method
1176""", pydoc.plain(pydoc.render_doc(X)))
1177
1178 @requires_docstrings
1179 def test_getset_descriptor(self):
1180 # Currently these attributes are implemented as getset descriptors
1181 # in CPython.
1182 self.assertEqual(self._get_summary_line(int.numerator), "numerator")
1183 self.assertEqual(self._get_summary_line(float.real), "real")
1184 self.assertEqual(self._get_summary_line(Exception.args), "args")
1185 self.assertEqual(self._get_summary_line(memoryview.obj), "obj")
1186
1187 @requires_docstrings
1188 def test_member_descriptor(self):
1189 # Currently these attributes are implemented as member descriptors
1190 # in CPython.
1191 self.assertEqual(self._get_summary_line(complex.real), "real")
1192 self.assertEqual(self._get_summary_line(range.start), "start")
1193 self.assertEqual(self._get_summary_line(slice.start), "start")
1194 self.assertEqual(self._get_summary_line(property.fget), "fget")
1195 self.assertEqual(self._get_summary_line(StopIteration.value), "value")
1196
1197 @requires_docstrings
1198 def test_slot_descriptor(self):
1199 class Point:
1200 __slots__ = 'x', 'y'
1201 self.assertEqual(self._get_summary_line(Point.x), "x")
1202
1203 @requires_docstrings
1204 def test_dict_attr_descriptor(self):
1205 class NS:
1206 pass
1207 self.assertEqual(self._get_summary_line(NS.__dict__['__dict__']),
1208 "__dict__")
1209
1210 @requires_docstrings
1211 def test_structseq_member_descriptor(self):
1212 self.assertEqual(self._get_summary_line(type(sys.hash_info).width),
1213 "width")
1214 self.assertEqual(self._get_summary_line(type(sys.flags).debug),
1215 "debug")
1216 self.assertEqual(self._get_summary_line(type(sys.version_info).major),
1217 "major")
1218 self.assertEqual(self._get_summary_line(type(sys.float_info).max),
1219 "max")
1220
1221 @requires_docstrings
1222 def test_namedtuple_field_descriptor(self):
1223 Box = namedtuple('Box', ('width', 'height'))
1224 self.assertEqual(self._get_summary_lines(Box.width), """\
1225 Alias for field number 0
1226""")
1227
1228 @requires_docstrings
1229 def test_property(self):
1230 class Rect:
1231 @property
1232 def area(self):
1233 '''Area of the rect'''
1234 return self.w * self.h
1235
1236 self.assertEqual(self._get_summary_lines(Rect.area), """\
1237 Area of the rect
1238""")
1239 self.assertIn("""
1240 | area
1241 | Area of the rect
1242""", pydoc.plain(pydoc.render_doc(Rect)))
1243
1244 @requires_docstrings
1245 def test_custom_non_data_descriptor(self):
1246 class Descr:
1247 def __get__(self, obj, cls):
1248 if obj is None:
1249 return self
1250 return 42
1251 class X:
1252 attr = Descr()
1253
Serhiy Storchakaefcf82f2019-01-15 10:53:18 +02001254 self.assertEqual(self._get_summary_lines(X.attr), """\
1255<test.test_pydoc.TestDescriptions.test_custom_non_data_descriptor.<locals>.Descr object>""")
1256
1257 X.attr.__doc__ = 'Custom descriptor'
1258 self.assertEqual(self._get_summary_lines(X.attr), """\
Serhiy Storchakafbf27862020-04-15 23:00:20 +03001259<test.test_pydoc.TestDescriptions.test_custom_non_data_descriptor.<locals>.Descr object>
Serhiy Storchaka7e644142020-04-18 17:13:21 +03001260 Custom descriptor
1261""")
Serhiy Storchakaefcf82f2019-01-15 10:53:18 +02001262
1263 X.attr.__name__ = 'foo'
1264 self.assertEqual(self._get_summary_lines(X.attr), """\
1265foo(...)
1266 Custom descriptor
1267""")
1268
1269 @requires_docstrings
1270 def test_custom_data_descriptor(self):
1271 class Descr:
1272 def __get__(self, obj, cls):
1273 if obj is None:
1274 return self
1275 return 42
1276 def __set__(self, obj, cls):
1277 1/0
1278 class X:
1279 attr = Descr()
1280
Serhiy Storchakaefcf82f2019-01-15 10:53:18 +02001281 self.assertEqual(self._get_summary_lines(X.attr), "")
1282
1283 X.attr.__doc__ = 'Custom descriptor'
Serhiy Storchakaefcf82f2019-01-15 10:53:18 +02001284 self.assertEqual(self._get_summary_lines(X.attr), """\
1285 Custom descriptor
1286""")
1287
1288 X.attr.__name__ = 'foo'
Serhiy Storchakaefcf82f2019-01-15 10:53:18 +02001289 self.assertEqual(self._get_summary_lines(X.attr), """\
1290foo
1291 Custom descriptor
1292""")
1293
Dan Rose2a37f8f2019-05-24 06:38:01 -05001294 def test_async_annotation(self):
1295 async def coro_function(ign) -> int:
1296 return 1
1297
1298 text = pydoc.plain(pydoc.plaintext.document(coro_function))
1299 self.assertIn('async coro_function', text)
1300
1301 html = pydoc.HTMLDoc().document(coro_function)
1302 self.assertIn(
1303 'async <a name="-coro_function"><strong>coro_function',
1304 html)
1305
1306 def test_async_generator_annotation(self):
1307 async def an_async_generator():
1308 yield 1
1309
1310 text = pydoc.plain(pydoc.plaintext.document(an_async_generator))
1311 self.assertIn('async an_async_generator', text)
1312
1313 html = pydoc.HTMLDoc().document(an_async_generator)
1314 self.assertIn(
1315 'async <a name="-an_async_generator"><strong>an_async_generator',
1316 html)
Georg Brandlb533e262008-05-25 18:19:30 +00001317
Kirill61289d42019-11-13 19:13:53 +03001318 def test_html_for_https_links(self):
1319 def a_fn_with_https_link():
1320 """a link https://localhost/"""
1321 pass
1322
1323 html = pydoc.HTMLDoc().document(a_fn_with_https_link)
1324 self.assertIn(
1325 '<a href="https://localhost/">https://localhost/</a>',
1326 html
1327 )
1328
Georg Brandld2f38572011-01-30 08:37:19 +00001329class PydocServerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +00001330 """Tests for pydoc._start_server"""
1331
1332 def test_server(self):
1333
1334 # Minimal test that starts the server, then stops it.
1335 def my_url_handler(url, content_type):
1336 text = 'the URL sent was: (%s, %s)' % (url, content_type)
1337 return text
1338
Feanil Patel6a396c92017-09-14 17:54:09 -04001339 serverthread = pydoc._start_server(my_url_handler, hostname='0.0.0.0', port=0)
1340 self.assertIn('0.0.0.0', serverthread.docserver.address)
Senthil Kumaran2a42a0b2014-09-17 13:17:58 +08001341
Victor Stinner2cf4c202018-12-17 09:36:36 +01001342 starttime = time.monotonic()
Victor Stinner0d63bac2019-12-11 11:30:03 +01001343 timeout = test.support.SHORT_TIMEOUT
Nick Coghlan7bb30b72010-12-03 09:29:11 +00001344
1345 while serverthread.serving:
1346 time.sleep(.01)
Victor Stinner2cf4c202018-12-17 09:36:36 +01001347 if serverthread.serving and time.monotonic() - starttime > timeout:
Nick Coghlan7bb30b72010-12-03 09:29:11 +00001348 serverthread.stop()
1349 break
1350
1351 self.assertEqual(serverthread.error, None)
1352
1353
Antoine Pitrou916fc7b2013-05-19 15:44:54 +02001354class PydocUrlHandlerTest(PydocBaseTest):
Nick Coghlan7bb30b72010-12-03 09:29:11 +00001355 """Tests for pydoc._url_handler"""
1356
1357 def test_content_type_err(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +00001358 f = pydoc._url_handler
Georg Brandld2f38572011-01-30 08:37:19 +00001359 self.assertRaises(TypeError, f, 'A', '')
1360 self.assertRaises(TypeError, f, 'B', 'foobar')
Nick Coghlan7bb30b72010-12-03 09:29:11 +00001361
1362 def test_url_requests(self):
1363 # Test for the correct title in the html pages returned.
1364 # This tests the different parts of the URL handler without
1365 # getting too picky about the exact html.
1366 requests = [
Georg Brandld2f38572011-01-30 08:37:19 +00001367 ("", "Pydoc: Index of Modules"),
1368 ("get?key=", "Pydoc: Index of Modules"),
1369 ("index", "Pydoc: Index of Modules"),
1370 ("topics", "Pydoc: Topics"),
1371 ("keywords", "Pydoc: Keywords"),
1372 ("pydoc", "Pydoc: module pydoc"),
1373 ("get?key=pydoc", "Pydoc: module pydoc"),
1374 ("search?key=pydoc", "Pydoc: Search Results"),
1375 ("topic?key=def", "Pydoc: KEYWORD def"),
1376 ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
1377 ("foobar", "Pydoc: Error - foobar"),
1378 ("getfile?key=foobar", "Pydoc: Error - getfile?key=foobar"),
Nick Coghlan7bb30b72010-12-03 09:29:11 +00001379 ]
1380
Antoine Pitrou916fc7b2013-05-19 15:44:54 +02001381 with self.restrict_walk_packages():
1382 for url, title in requests:
Martin Panter9ad0aae2015-11-06 00:27:14 +00001383 self.call_url_handler(url, title)
Antoine Pitrou916fc7b2013-05-19 15:44:54 +02001384
1385 path = string.__file__
1386 title = "Pydoc: getfile " + path
1387 url = "getfile?key=" + path
Martin Panter9ad0aae2015-11-06 00:27:14 +00001388 self.call_url_handler(url, title)
Nick Coghlan7bb30b72010-12-03 09:29:11 +00001389
Nick Coghlan7bb30b72010-12-03 09:29:11 +00001390
Ezio Melottib185a042011-04-28 07:42:55 +03001391class TestHelper(unittest.TestCase):
1392 def test_keywords(self):
1393 self.assertEqual(sorted(pydoc.Helper.keywords),
1394 sorted(keyword.kwlist))
1395
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001396class PydocWithMetaClasses(unittest.TestCase):
Ethan Furman3f2f1922013-10-22 07:30:24 -07001397 @unittest.skipIf(sys.flags.optimize >= 2,
1398 "Docstrings are omitted with -O2 and above")
1399 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
1400 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001401 def test_DynamicClassAttribute(self):
1402 class Meta(type):
1403 def __getattr__(self, name):
1404 if name == 'ham':
1405 return 'spam'
1406 return super().__getattr__(name)
1407 class DA(metaclass=Meta):
1408 @types.DynamicClassAttribute
1409 def ham(self):
1410 return 'eggs'
Ethan Furman3f2f1922013-10-22 07:30:24 -07001411 expected_text_data_docstrings = tuple('\n | ' + s if s else ''
1412 for s in expected_data_docstrings)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001413 output = StringIO()
1414 helper = pydoc.Helper(output=output)
1415 helper(DA)
Ethan Furman3f2f1922013-10-22 07:30:24 -07001416 expected_text = expected_dynamicattribute_pattern % (
1417 (__name__,) + expected_text_data_docstrings[:2])
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001418 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -07001419 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001420
Ethan Furman3f2f1922013-10-22 07:30:24 -07001421 @unittest.skipIf(sys.flags.optimize >= 2,
1422 "Docstrings are omitted with -O2 and above")
1423 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
1424 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001425 def test_virtualClassAttributeWithOneMeta(self):
1426 class Meta(type):
1427 def __dir__(cls):
1428 return ['__class__', '__module__', '__name__', 'LIFE']
1429 def __getattr__(self, name):
1430 if name =='LIFE':
1431 return 42
1432 return super().__getattr(name)
1433 class Class(metaclass=Meta):
1434 pass
1435 output = StringIO()
1436 helper = pydoc.Helper(output=output)
1437 helper(Class)
1438 expected_text = expected_virtualattribute_pattern1 % __name__
1439 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -07001440 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001441
Ethan Furman3f2f1922013-10-22 07:30:24 -07001442 @unittest.skipIf(sys.flags.optimize >= 2,
1443 "Docstrings are omitted with -O2 and above")
1444 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
1445 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001446 def test_virtualClassAttributeWithTwoMeta(self):
1447 class Meta1(type):
1448 def __dir__(cls):
1449 return ['__class__', '__module__', '__name__', 'one']
1450 def __getattr__(self, name):
1451 if name =='one':
1452 return 1
1453 return super().__getattr__(name)
1454 class Meta2(type):
1455 def __dir__(cls):
1456 return ['__class__', '__module__', '__name__', 'two']
1457 def __getattr__(self, name):
1458 if name =='two':
1459 return 2
1460 return super().__getattr__(name)
1461 class Meta3(Meta1, Meta2):
1462 def __dir__(cls):
1463 return list(sorted(set(
1464 ['__class__', '__module__', '__name__', 'three'] +
1465 Meta1.__dir__(cls) + Meta2.__dir__(cls))))
1466 def __getattr__(self, name):
1467 if name =='three':
1468 return 3
1469 return super().__getattr__(name)
1470 class Class1(metaclass=Meta1):
1471 pass
1472 class Class2(Class1, metaclass=Meta3):
1473 pass
1474 fail1 = fail2 = False
1475 output = StringIO()
1476 helper = pydoc.Helper(output=output)
1477 helper(Class1)
1478 expected_text1 = expected_virtualattribute_pattern2 % __name__
1479 result1 = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -07001480 self.assertEqual(expected_text1, result1)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001481 output = StringIO()
1482 helper = pydoc.Helper(output=output)
1483 helper(Class2)
1484 expected_text2 = expected_virtualattribute_pattern3 % __name__
1485 result2 = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -07001486 self.assertEqual(expected_text2, result2)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001487
Ethan Furman3f2f1922013-10-22 07:30:24 -07001488 @unittest.skipIf(sys.flags.optimize >= 2,
1489 "Docstrings are omitted with -O2 and above")
1490 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
1491 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001492 def test_buggy_dir(self):
1493 class M(type):
1494 def __dir__(cls):
1495 return ['__class__', '__name__', 'missing', 'here']
1496 class C(metaclass=M):
1497 here = 'present!'
1498 output = StringIO()
1499 helper = pydoc.Helper(output=output)
1500 helper(C)
1501 expected_text = expected_missingattribute_pattern % __name__
1502 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -07001503 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001504
Serhiy Storchakab6076fb2015-04-21 21:09:48 +03001505 def test_resolve_false(self):
1506 # Issue #23008: pydoc enum.{,Int}Enum failed
1507 # because bool(enum.Enum) is False.
1508 with captured_stdout() as help_io:
1509 pydoc.help('enum.Enum')
1510 helptext = help_io.getvalue()
1511 self.assertIn('class Enum', helptext)
1512
Eric Snowaed5b222014-01-04 20:38:11 -07001513
Nick Coghlan82a94812018-04-15 21:52:57 +10001514class TestInternalUtilities(unittest.TestCase):
1515
1516 def setUp(self):
1517 tmpdir = tempfile.TemporaryDirectory()
1518 self.argv0dir = tmpdir.name
1519 self.argv0 = os.path.join(tmpdir.name, "nonexistent")
1520 self.addCleanup(tmpdir.cleanup)
1521 self.abs_curdir = abs_curdir = os.getcwd()
1522 self.curdir_spellings = ["", os.curdir, abs_curdir]
1523
1524 def _get_revised_path(self, given_path, argv0=None):
1525 # Checking that pydoc.cli() actually calls pydoc._get_revised_path()
1526 # is handled via code review (at least for now).
1527 if argv0 is None:
1528 argv0 = self.argv0
1529 return pydoc._get_revised_path(given_path, argv0)
1530
1531 def _get_starting_path(self):
Nick Coghlan1a5c4bd2018-04-15 23:32:05 +10001532 # Get a copy of sys.path without the current directory.
Nick Coghlan82a94812018-04-15 21:52:57 +10001533 clean_path = sys.path.copy()
1534 for spelling in self.curdir_spellings:
1535 for __ in range(clean_path.count(spelling)):
1536 clean_path.remove(spelling)
1537 return clean_path
1538
1539 def test_sys_path_adjustment_adds_missing_curdir(self):
1540 clean_path = self._get_starting_path()
1541 expected_path = [self.abs_curdir] + clean_path
1542 self.assertEqual(self._get_revised_path(clean_path), expected_path)
1543
1544 def test_sys_path_adjustment_removes_argv0_dir(self):
1545 clean_path = self._get_starting_path()
1546 expected_path = [self.abs_curdir] + clean_path
1547 leading_argv0dir = [self.argv0dir] + clean_path
1548 self.assertEqual(self._get_revised_path(leading_argv0dir), expected_path)
1549 trailing_argv0dir = clean_path + [self.argv0dir]
1550 self.assertEqual(self._get_revised_path(trailing_argv0dir), expected_path)
1551
1552
1553 def test_sys_path_adjustment_protects_pydoc_dir(self):
1554 def _get_revised_path(given_path):
1555 return self._get_revised_path(given_path, argv0=pydoc.__file__)
1556 clean_path = self._get_starting_path()
1557 leading_argv0dir = [self.argv0dir] + clean_path
1558 expected_path = [self.abs_curdir] + leading_argv0dir
1559 self.assertEqual(_get_revised_path(leading_argv0dir), expected_path)
1560 trailing_argv0dir = clean_path + [self.argv0dir]
1561 expected_path = [self.abs_curdir] + trailing_argv0dir
1562 self.assertEqual(_get_revised_path(trailing_argv0dir), expected_path)
1563
1564 def test_sys_path_adjustment_when_curdir_already_included(self):
1565 clean_path = self._get_starting_path()
1566 for spelling in self.curdir_spellings:
1567 with self.subTest(curdir_spelling=spelling):
1568 # If curdir is already present, no alterations are made at all
1569 leading_curdir = [spelling] + clean_path
1570 self.assertIsNone(self._get_revised_path(leading_curdir))
1571 trailing_curdir = clean_path + [spelling]
1572 self.assertIsNone(self._get_revised_path(trailing_curdir))
1573 leading_argv0dir = [self.argv0dir] + leading_curdir
1574 self.assertIsNone(self._get_revised_path(leading_argv0dir))
1575 trailing_argv0dir = trailing_curdir + [self.argv0dir]
1576 self.assertIsNone(self._get_revised_path(trailing_argv0dir))
1577
1578
Hai Shie80697d2020-05-28 06:10:27 +08001579@threading_helper.reap_threads
Georg Brandlb533e262008-05-25 18:19:30 +00001580def test_main():
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001581 try:
1582 test.support.run_unittest(PydocDocTest,
Ned Deily92a81a12011-10-06 14:19:03 -07001583 PydocImportTest,
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001584 TestDescriptions,
1585 PydocServerTest,
1586 PydocUrlHandlerTest,
1587 TestHelper,
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001588 PydocWithMetaClasses,
Nick Coghlan82a94812018-04-15 21:52:57 +10001589 TestInternalUtilities,
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001590 )
1591 finally:
1592 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +00001593
1594if __name__ == "__main__":
1595 test_main()