blob: 8ad5706a840d0e29bf2873ded13854f573d95f4f [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
Georg Brandld80d5f42010-12-03 07:47:22 +000021import textwrap
22from io import StringIO
Raymond Hettinger1103d052011-03-25 14:15:24 -070023from collections import namedtuple
Berker Peksagce643912015-05-06 06:33:17 +030024from test.support.script_helper import assert_python_ok
Antoine Pitroua6e81a22011-07-15 22:32:25 +020025from test.support import (
Ned Deily92a81a12011-10-06 14:19:03 -070026 TESTFN, rmtree,
Antoine Pitrou916fc7b2013-05-19 15:44:54 +020027 reap_children, reap_threads, captured_output, captured_stdout,
Stefan Krah5de32782014-01-18 23:18:39 +010028 captured_stderr, unlink, requires_docstrings
Antoine Pitroua6e81a22011-07-15 22:32:25 +020029)
Georg Brandlb533e262008-05-25 18:19:30 +000030from test import pydoc_mod
31
Victor Stinner62a68f22011-05-20 02:29:13 +020032try:
33 import threading
34except ImportError:
35 threading = None
36
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +020037class nonascii:
38 'Це не латиниця'
39 pass
40
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020041if test.support.HAVE_DOCSTRINGS:
42 expected_data_docstrings = (
43 'dictionary for instance variables (if defined)',
44 'list of weak references to the object (if defined)',
45 ) * 2
46else:
47 expected_data_docstrings = ('', '', '', '')
48
Barry Warsaw28a691b2010-04-17 00:19:56 +000049expected_text_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000050NAME
51 test.pydoc_mod - This is a test module for test_pydoc
Georg Brandlb533e262008-05-25 18:19:30 +000052%s
53CLASSES
54 builtins.object
55 A
56 B
Benjamin Petersoned1160b2014-06-07 16:44:00 -070057 C
Georg Brandlb533e262008-05-25 18:19:30 +000058\x20\x20\x20\x20
59 class A(builtins.object)
60 | Hello and goodbye
61 |\x20\x20
62 | Methods defined here:
63 |\x20\x20
64 | __init__()
65 | Wow, I have no function!
66 |\x20\x20
67 | ----------------------------------------------------------------------
68 | Data descriptors defined here:
69 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020070 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000071 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020072 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000073\x20\x20\x20\x20
74 class B(builtins.object)
75 | Data descriptors defined here:
76 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020077 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000078 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020079 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000080 |\x20\x20
81 | ----------------------------------------------------------------------
82 | Data and other attributes defined here:
83 |\x20\x20
84 | NO_MEANING = 'eggs'
Benjamin Petersoned1160b2014-06-07 16:44:00 -070085\x20\x20\x20\x20
86 class C(builtins.object)
87 | Methods defined here:
88 |\x20\x20
89 | get_answer(self)
90 | Return say_no()
91 |\x20\x20
92 | is_it_true(self)
93 | Return self.get_answer()
94 |\x20\x20
95 | say_no(self)
96 |\x20\x20
97 | ----------------------------------------------------------------------
98 | Data descriptors defined here:
99 |\x20\x20
100 | __dict__
101 | dictionary for instance variables (if defined)
102 |\x20\x20
103 | __weakref__
104 | list of weak references to the object (if defined)
Georg Brandlb533e262008-05-25 18:19:30 +0000105
106FUNCTIONS
107 doc_func()
108 This function solves all of the world's problems:
109 hunger
110 lack of Python
111 war
112\x20\x20\x20\x20
113 nodoc_func()
114
115DATA
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000116 __xyz__ = 'X, Y and Z'
Georg Brandlb533e262008-05-25 18:19:30 +0000117
118VERSION
119 1.2.3.4
120
121AUTHOR
122 Benjamin Peterson
123
124CREDITS
125 Nobody
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000126
127FILE
128 %s
Georg Brandlb533e262008-05-25 18:19:30 +0000129""".strip()
130
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200131expected_text_data_docstrings = tuple('\n | ' + s if s else ''
132 for s in expected_data_docstrings)
133
Barry Warsaw28a691b2010-04-17 00:19:56 +0000134expected_html_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +0000135<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
136<tr bgcolor="#7799ee">
137<td valign=bottom>&nbsp;<br>
138<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
139><td align=right valign=bottom
140><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
141 <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
142<p>
143<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
144<tr bgcolor="#ee77aa">
145<td colspan=3 valign=bottom>&nbsp;<br>
146<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
147\x20\x20\x20\x20
148<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
149<td width="100%%"><dl>
150<dt><font face="helvetica, arial"><a href="builtins.html#object">builtins.object</a>
151</font></dt><dd>
152<dl>
153<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
154</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700155</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#C">C</a>
Georg Brandlb533e262008-05-25 18:19:30 +0000156</font></dt></dl>
157</dd>
158</dl>
159 <p>
160<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
161<tr bgcolor="#ffc8d8">
162<td colspan=3 valign=bottom>&nbsp;<br>
163<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>
164\x20\x20\x20\x20
165<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
166<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
167<tr><td>&nbsp;</td>
168<td width="100%%">Methods defined here:<br>
169<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>
170
171<hr>
172Data descriptors defined here:<br>
173<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200174<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000175</dl>
176<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200177<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000178</dl>
179</td></tr></table> <p>
180<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
181<tr bgcolor="#ffc8d8">
182<td colspan=3 valign=bottom>&nbsp;<br>
183<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>
184\x20\x20\x20\x20
185<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
186<td width="100%%">Data descriptors defined here:<br>
187<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200188<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000189</dl>
190<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200191<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000192</dl>
193<hr>
194Data and other attributes defined here:<br>
195<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
196
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700197</td></tr></table> <p>
198<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
199<tr bgcolor="#ffc8d8">
200<td colspan=3 valign=bottom>&nbsp;<br>
201<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>
202\x20\x20\x20\x20
203<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
204<td width="100%%">Methods defined here:<br>
205<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>
206
207<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>
208
209<dl><dt><a name="C-say_no"><strong>say_no</strong></a>(self)</dt></dl>
210
211<hr>
212Data descriptors defined here:<br>
213<dl><dt><strong>__dict__</strong></dt>
214<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
215</dl>
216<dl><dt><strong>__weakref__</strong></dt>
217<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
218</dl>
Georg Brandlb533e262008-05-25 18:19:30 +0000219</td></tr></table></td></tr></table><p>
220<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
221<tr bgcolor="#eeaa77">
222<td colspan=3 valign=bottom>&nbsp;<br>
223<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
224\x20\x20\x20\x20
225<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
226<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>
227hunger<br>
228lack&nbsp;of&nbsp;Python<br>
229war</tt></dd></dl>
230 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
231</td></tr></table><p>
232<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
233<tr bgcolor="#55aa55">
234<td colspan=3 valign=bottom>&nbsp;<br>
235<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
236\x20\x20\x20\x20
237<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000238<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p>
Georg Brandlb533e262008-05-25 18:19:30 +0000239<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
240<tr bgcolor="#7799ee">
241<td colspan=3 valign=bottom>&nbsp;<br>
242<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
243\x20\x20\x20\x20
244<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
245<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
246<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
247<tr bgcolor="#7799ee">
248<td colspan=3 valign=bottom>&nbsp;<br>
249<font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
250\x20\x20\x20\x20
251<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
252<td width="100%%">Nobody</td></tr></table>
Barry Warsaw28a691b2010-04-17 00:19:56 +0000253""".strip() # ' <- emacs turd
Georg Brandlb533e262008-05-25 18:19:30 +0000254
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200255expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;')
256 for s in expected_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000257
258# output pattern for missing module
Serhiy Storchaka1c205512015-03-01 00:42:54 +0200259missing_pattern = '''\
260No Python documentation found for %r.
261Use help() to get the interactive help utility.
262Use help(str) for help on the str class.'''.replace('\n', os.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000263
Benjamin Peterson0289b152009-06-28 17:22:03 +0000264# output pattern for module with bad imports
Brett Cannon679ecb52013-07-04 17:51:50 -0400265badimport_pattern = "problem in %s - ImportError: No module named %r"
Benjamin Peterson0289b152009-06-28 17:22:03 +0000266
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700267expected_dynamicattribute_pattern = """
268Help on class DA in module %s:
269
270class DA(builtins.object)
271 | Data descriptors defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200272 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700273 | __dict__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200274 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700275 | __weakref__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200276 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700277 | ham
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200278 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700279 | ----------------------------------------------------------------------
280 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200281 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700282 | ham = 'spam'
283""".strip()
284
285expected_virtualattribute_pattern1 = """
286Help on class Class in module %s:
287
288class Class(builtins.object)
289 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200290 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700291 | LIFE = 42
292""".strip()
293
294expected_virtualattribute_pattern2 = """
295Help on class Class1 in module %s:
296
297class Class1(builtins.object)
298 | Data and other attributes inherited from Meta1:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200299 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700300 | one = 1
301""".strip()
302
303expected_virtualattribute_pattern3 = """
304Help on class Class2 in module %s:
305
306class Class2(Class1)
307 | Method resolution order:
308 | Class2
309 | Class1
310 | builtins.object
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200311 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700312 | Data and other attributes inherited from Meta1:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200313 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700314 | one = 1
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200315 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700316 | ----------------------------------------------------------------------
317 | Data and other attributes inherited from Meta3:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200318 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700319 | three = 3
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200320 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700321 | ----------------------------------------------------------------------
322 | Data and other attributes inherited from Meta2:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200323 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700324 | two = 2
325""".strip()
326
327expected_missingattribute_pattern = """
328Help on class C in module %s:
329
330class C(builtins.object)
331 | Data and other attributes defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200332 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700333 | here = 'present!'
334""".strip()
335
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200336def run_pydoc(module_name, *args, **env):
Georg Brandlb533e262008-05-25 18:19:30 +0000337 """
338 Runs pydoc on the specified module. Returns the stripped
339 output of pydoc.
340 """
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200341 args = args + (module_name,)
Ned Deily92a81a12011-10-06 14:19:03 -0700342 # do not write bytecode files to avoid caching errors
343 rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200344 return out.strip()
Georg Brandlb533e262008-05-25 18:19:30 +0000345
346def get_pydoc_html(module):
347 "Returns pydoc generated output as html"
348 doc = pydoc.HTMLDoc()
349 output = doc.docmodule(module)
350 loc = doc.getdocloc(pydoc_mod) or ""
351 if loc:
352 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
353 return output.strip(), loc
354
355def get_pydoc_text(module):
356 "Returns pydoc generated output as text"
357 doc = pydoc.TextDoc()
358 loc = doc.getdocloc(pydoc_mod) or ""
359 if loc:
360 loc = "\nMODULE DOCS\n " + loc + "\n"
361
362 output = doc.docmodule(module)
363
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000364 # clean up the extra text formatting that pydoc performs
Georg Brandlb533e262008-05-25 18:19:30 +0000365 patt = re.compile('\b.')
366 output = patt.sub('', output)
367 return output.strip(), loc
368
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000369def get_html_title(text):
Nick Coghlanecace282010-12-03 16:08:46 +0000370 # Bit of hack, but good enough for test purposes
371 header, _, _ = text.partition("</head>")
372 _, _, title = header.partition("<title>")
373 title, _, _ = title.partition("</title>")
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000374 return title
375
Georg Brandlb533e262008-05-25 18:19:30 +0000376
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200377class PydocBaseTest(unittest.TestCase):
378
379 def _restricted_walk_packages(self, walk_packages, path=None):
380 """
381 A version of pkgutil.walk_packages() that will restrict itself to
382 a given path.
383 """
384 default_path = path or [os.path.dirname(__file__)]
385 def wrapper(path=None, prefix='', onerror=None):
386 return walk_packages(path or default_path, prefix, onerror)
387 return wrapper
388
389 @contextlib.contextmanager
390 def restrict_walk_packages(self, path=None):
391 walk_packages = pkgutil.walk_packages
392 pkgutil.walk_packages = self._restricted_walk_packages(walk_packages,
393 path)
394 try:
395 yield
396 finally:
397 pkgutil.walk_packages = walk_packages
398
Martin Panter9ad0aae2015-11-06 00:27:14 +0000399 def call_url_handler(self, url, expected_title):
400 text = pydoc._url_handler(url, "text/html")
401 result = get_html_title(text)
402 # Check the title to ensure an unexpected error page was not returned
403 self.assertEqual(result, expected_title, text)
404 return text
405
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200406
Georg Brandld2f38572011-01-30 08:37:19 +0000407class PydocDocTest(unittest.TestCase):
Georg Brandlb533e262008-05-25 18:19:30 +0000408
R. David Murray378c0cf2010-02-24 01:46:21 +0000409 @unittest.skipIf(sys.flags.optimize >= 2,
410 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000411 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
412 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100413 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000414 def test_html_doc(self):
415 result, doc_loc = get_pydoc_html(pydoc_mod)
416 mod_file = inspect.getabsfile(pydoc_mod)
Zachary Wareeb432142014-07-10 11:18:00 -0500417 mod_url = urllib.parse.quote(mod_file)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200418 expected_html = expected_html_pattern % (
419 (mod_url, mod_file, doc_loc) +
420 expected_html_data_docstrings)
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700421 self.assertEqual(result, expected_html)
Georg Brandlb533e262008-05-25 18:19:30 +0000422
R. David Murray378c0cf2010-02-24 01:46:21 +0000423 @unittest.skipIf(sys.flags.optimize >= 2,
424 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000425 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
426 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100427 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000428 def test_text_doc(self):
429 result, doc_loc = get_pydoc_text(pydoc_mod)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200430 expected_text = expected_text_pattern % (
431 (doc_loc,) +
432 expected_text_data_docstrings +
433 (inspect.getabsfile(pydoc_mod),))
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700434 self.assertEqual(expected_text, result)
Georg Brandlb533e262008-05-25 18:19:30 +0000435
Serhiy Storchaka056eb022014-02-19 23:05:12 +0200436 def test_text_enum_member_with_value_zero(self):
437 # Test issue #20654 to ensure enum member with value 0 can be
438 # displayed. It used to throw KeyError: 'zero'.
439 import enum
440 class BinaryInteger(enum.IntEnum):
441 zero = 0
442 one = 1
443 doc = pydoc.render_doc(BinaryInteger)
444 self.assertIn('<BinaryInteger.zero: 0>', doc)
445
Brian Curtin49c284c2010-03-31 03:19:28 +0000446 def test_issue8225(self):
447 # Test issue8225 to ensure no doc link appears for xml.etree
448 result, doc_loc = get_pydoc_text(xml.etree)
449 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
450
Benjamin Peterson159824e2014-06-07 20:14:26 -0700451 def test_getpager_with_stdin_none(self):
452 previous_stdin = sys.stdin
453 try:
454 sys.stdin = None
455 pydoc.getpager() # Shouldn't fail.
456 finally:
457 sys.stdin = previous_stdin
458
R David Murrayc43125a2012-04-23 13:23:57 -0400459 def test_non_str_name(self):
460 # issue14638
461 # Treat illegal (non-str) name like no name
462 class A:
463 __name__ = 42
464 class B:
465 pass
466 adoc = pydoc.render_doc(A())
467 bdoc = pydoc.render_doc(B())
468 self.assertEqual(adoc.replace("A", "B"), bdoc)
469
Georg Brandlb533e262008-05-25 18:19:30 +0000470 def test_not_here(self):
471 missing_module = "test.i_am_not_here"
472 result = str(run_pydoc(missing_module), 'ascii')
473 expected = missing_pattern % missing_module
474 self.assertEqual(expected, result,
475 "documentation for missing module found")
476
Serhiy Storchaka4c094e52015-03-01 15:31:36 +0200477 @unittest.skipIf(sys.flags.optimize >= 2,
478 'Docstrings are omitted with -OO and above')
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +0200479 def test_not_ascii(self):
480 result = run_pydoc('test.test_pydoc.nonascii', PYTHONIOENCODING='ascii')
481 encoded = nonascii.__doc__.encode('ascii', 'backslashreplace')
482 self.assertIn(encoded, result)
483
R. David Murray1f1b9d32009-05-27 20:56:59 +0000484 def test_input_strip(self):
485 missing_module = " test.i_am_not_here "
486 result = str(run_pydoc(missing_module), 'ascii')
487 expected = missing_pattern % missing_module.strip()
488 self.assertEqual(expected, result)
489
Ezio Melotti412c95a2010-02-16 23:31:04 +0000490 def test_stripid(self):
491 # test with strings, other implementations might have different repr()
492 stripid = pydoc.stripid
493 # strip the id
494 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
495 '<function stripid>')
496 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
497 '<function stripid>')
498 # nothing to strip, return the same text
499 self.assertEqual(stripid('42'), '42')
500 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
501 "<type 'exceptions.Exception'>")
502
Georg Brandld80d5f42010-12-03 07:47:22 +0000503 @unittest.skipIf(sys.flags.optimize >= 2,
504 'Docstrings are omitted with -O2 and above')
Brett Cannon7a540732011-02-22 03:04:06 +0000505 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
506 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100507 @requires_docstrings
Georg Brandld80d5f42010-12-03 07:47:22 +0000508 def test_help_output_redirect(self):
509 # issue 940286, if output is set in Helper, then all output from
510 # Helper.help should be redirected
511 old_pattern = expected_text_pattern
512 getpager_old = pydoc.getpager
513 getpager_new = lambda: (lambda x: x)
514 self.maxDiff = None
515
516 buf = StringIO()
517 helper = pydoc.Helper(output=buf)
518 unused, doc_loc = get_pydoc_text(pydoc_mod)
519 module = "test.pydoc_mod"
520 help_header = """
521 Help on module test.pydoc_mod in test:
522
523 """.lstrip()
524 help_header = textwrap.dedent(help_header)
525 expected_help_pattern = help_header + expected_text_pattern
526
527 pydoc.getpager = getpager_new
528 try:
529 with captured_output('stdout') as output, \
530 captured_output('stderr') as err:
531 helper.help(module)
532 result = buf.getvalue().strip()
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200533 expected_text = expected_help_pattern % (
534 (doc_loc,) +
535 expected_text_data_docstrings +
536 (inspect.getabsfile(pydoc_mod),))
Georg Brandld80d5f42010-12-03 07:47:22 +0000537 self.assertEqual('', output.getvalue())
538 self.assertEqual('', err.getvalue())
539 self.assertEqual(expected_text, result)
540 finally:
541 pydoc.getpager = getpager_old
542
Raymond Hettinger1103d052011-03-25 14:15:24 -0700543 def test_namedtuple_public_underscore(self):
544 NT = namedtuple('NT', ['abc', 'def'], rename=True)
545 with captured_stdout() as help_io:
Terry Jan Reedy5c811642013-11-04 21:43:26 -0500546 pydoc.help(NT)
Raymond Hettinger1103d052011-03-25 14:15:24 -0700547 helptext = help_io.getvalue()
548 self.assertIn('_1', helptext)
549 self.assertIn('_replace', helptext)
550 self.assertIn('_asdict', helptext)
551
Victor Stinnere6c910e2011-06-30 15:55:43 +0200552 def test_synopsis(self):
553 self.addCleanup(unlink, TESTFN)
554 for encoding in ('ISO-8859-1', 'UTF-8'):
555 with open(TESTFN, 'w', encoding=encoding) as script:
556 if encoding != 'UTF-8':
557 print('#coding: {}'.format(encoding), file=script)
558 print('"""line 1: h\xe9', file=script)
559 print('line 2: hi"""', file=script)
560 synopsis = pydoc.synopsis(TESTFN, {})
561 self.assertEqual(synopsis, 'line 1: h\xe9')
562
Serhiy Storchaka4c094e52015-03-01 15:31:36 +0200563 @unittest.skipIf(sys.flags.optimize >= 2,
564 'Docstrings are omitted with -OO and above')
Eric Snowaed5b222014-01-04 20:38:11 -0700565 def test_synopsis_sourceless(self):
566 expected = os.__doc__.splitlines()[0]
567 filename = os.__cached__
568 synopsis = pydoc.synopsis(filename)
569
570 self.assertEqual(synopsis, expected)
571
Benjamin Peterson54237f92015-02-16 19:45:01 -0500572 def test_synopsis_sourceless_empty_doc(self):
573 with test.support.temp_cwd() as test_dir:
574 init_path = os.path.join(test_dir, 'foomod42.py')
575 cached_path = importlib.util.cache_from_source(init_path)
576 with open(init_path, 'w') as fobj:
577 fobj.write("foo = 1")
578 py_compile.compile(init_path)
579 synopsis = pydoc.synopsis(init_path, {})
580 self.assertIsNone(synopsis)
581 synopsis_cached = pydoc.synopsis(cached_path, {})
582 self.assertIsNone(synopsis_cached)
583
R David Murray455f2962013-03-19 00:00:33 -0400584 def test_splitdoc_with_description(self):
585 example_string = "I Am A Doc\n\n\nHere is my description"
586 self.assertEqual(pydoc.splitdoc(example_string),
587 ('I Am A Doc', '\nHere is my description'))
588
589 def test_is_object_or_method(self):
590 doc = pydoc.Doc()
591 # Bound Method
592 self.assertTrue(pydoc._is_some_method(doc.fail))
593 # Method Descriptor
594 self.assertTrue(pydoc._is_some_method(int.__add__))
595 # String
596 self.assertFalse(pydoc._is_some_method("I am not a method"))
597
598 def test_is_package_when_not_package(self):
599 with test.support.temp_cwd() as test_dir:
600 self.assertFalse(pydoc.ispackage(test_dir))
601
602 def test_is_package_when_is_package(self):
603 with test.support.temp_cwd() as test_dir:
604 init_path = os.path.join(test_dir, '__init__.py')
605 open(init_path, 'w').close()
606 self.assertTrue(pydoc.ispackage(test_dir))
607 os.remove(init_path)
608
R David Murrayac0cea52013-03-19 02:47:44 -0400609 def test_allmethods(self):
610 # issue 17476: allmethods was no longer returning unbound methods.
611 # This test is a bit fragile in the face of changes to object and type,
612 # but I can't think of a better way to do it without duplicating the
613 # logic of the function under test.
614
615 class TestClass(object):
616 def method_returning_true(self):
617 return True
618
619 # What we expect to get back: everything on object...
620 expected = dict(vars(object))
621 # ...plus our unbound method...
622 expected['method_returning_true'] = TestClass.method_returning_true
623 # ...but not the non-methods on object.
624 del expected['__doc__']
625 del expected['__class__']
626 # inspect resolves descriptors on type into methods, but vars doesn't,
627 # so we need to update __subclasshook__.
628 expected['__subclasshook__'] = TestClass.__subclasshook__
629
630 methods = pydoc.allmethods(TestClass)
631 self.assertDictEqual(methods, expected)
632
Georg Brandlb533e262008-05-25 18:19:30 +0000633
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200634class PydocImportTest(PydocBaseTest):
Ned Deily92a81a12011-10-06 14:19:03 -0700635
636 def setUp(self):
637 self.test_dir = os.mkdir(TESTFN)
638 self.addCleanup(rmtree, TESTFN)
Benjamin Peterson54237f92015-02-16 19:45:01 -0500639 importlib.invalidate_caches()
Ned Deily92a81a12011-10-06 14:19:03 -0700640
641 def test_badimport(self):
642 # This tests the fix for issue 5230, where if pydoc found the module
643 # but the module had an internal import error pydoc would report no doc
644 # found.
645 modname = 'testmod_xyzzy'
646 testpairs = (
647 ('i_am_not_here', 'i_am_not_here'),
Brett Cannonfd074152012-04-14 14:10:13 -0400648 ('test.i_am_not_here_either', 'test.i_am_not_here_either'),
649 ('test.i_am_not_here.neither_am_i', 'test.i_am_not_here'),
650 ('i_am_not_here.{}'.format(modname), 'i_am_not_here'),
651 ('test.{}'.format(modname), 'test.{}'.format(modname)),
Ned Deily92a81a12011-10-06 14:19:03 -0700652 )
653
654 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
655 for importstring, expectedinmsg in testpairs:
656 with open(sourcefn, 'w') as f:
657 f.write("import {}\n".format(importstring))
658 result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii")
659 expected = badimport_pattern % (modname, expectedinmsg)
660 self.assertEqual(expected, result)
661
662 def test_apropos_with_bad_package(self):
663 # Issue 7425 - pydoc -k failed when bad package on path
664 pkgdir = os.path.join(TESTFN, "syntaxerr")
665 os.mkdir(pkgdir)
666 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
667 with open(badsyntax, 'w') as f:
668 f.write("invalid python syntax = $1\n")
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200669 with self.restrict_walk_packages(path=[TESTFN]):
670 with captured_stdout() as out:
671 with captured_stderr() as err:
672 pydoc.apropos('xyzzy')
673 # No result, no error
674 self.assertEqual(out.getvalue(), '')
675 self.assertEqual(err.getvalue(), '')
676 # The package name is still matched
677 with captured_stdout() as out:
678 with captured_stderr() as err:
679 pydoc.apropos('syntaxerr')
680 self.assertEqual(out.getvalue().strip(), 'syntaxerr')
681 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700682
683 def test_apropos_with_unreadable_dir(self):
684 # Issue 7367 - pydoc -k failed when unreadable dir on path
685 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
686 os.mkdir(self.unreadable_dir, 0)
687 self.addCleanup(os.rmdir, self.unreadable_dir)
688 # Note, on Windows the directory appears to be still
689 # readable so this is not really testing the issue there
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200690 with self.restrict_walk_packages(path=[TESTFN]):
691 with captured_stdout() as out:
692 with captured_stderr() as err:
693 pydoc.apropos('SOMEKEY')
694 # No result, no error
695 self.assertEqual(out.getvalue(), '')
696 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700697
Benjamin Peterson54237f92015-02-16 19:45:01 -0500698 def test_apropos_empty_doc(self):
699 pkgdir = os.path.join(TESTFN, 'walkpkg')
700 os.mkdir(pkgdir)
701 self.addCleanup(rmtree, pkgdir)
702 init_path = os.path.join(pkgdir, '__init__.py')
703 with open(init_path, 'w') as fobj:
704 fobj.write("foo = 1")
705 current_mode = stat.S_IMODE(os.stat(pkgdir).st_mode)
706 try:
707 os.chmod(pkgdir, current_mode & ~stat.S_IEXEC)
708 with self.restrict_walk_packages(path=[TESTFN]), captured_stdout() as stdout:
709 pydoc.apropos('')
710 self.assertIn('walkpkg', stdout.getvalue())
711 finally:
712 os.chmod(pkgdir, current_mode)
713
Martin Panter9ad0aae2015-11-06 00:27:14 +0000714 def test_url_search_package_error(self):
715 # URL handler search should cope with packages that raise exceptions
716 pkgdir = os.path.join(TESTFN, "test_error_package")
717 os.mkdir(pkgdir)
718 init = os.path.join(pkgdir, "__init__.py")
719 with open(init, "wt", encoding="ascii") as f:
720 f.write("""raise ValueError("ouch")\n""")
721 with self.restrict_walk_packages(path=[TESTFN]):
722 # Package has to be importable for the error to have any effect
723 saved_paths = tuple(sys.path)
724 sys.path.insert(0, TESTFN)
725 try:
726 with self.assertRaisesRegex(ValueError, "ouch"):
727 import test_error_package # Sanity check
728
729 text = self.call_url_handler("search?key=test_error_package",
730 "Pydoc: Search Results")
731 found = ('<a href="test_error_package.html">'
732 'test_error_package</a>')
733 self.assertIn(found, text)
734 finally:
735 sys.path[:] = saved_paths
736
Eric Snowa46ef702014-02-22 13:57:08 -0700737 @unittest.skip('causes undesireable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700738 def test_modules(self):
739 # See Helper.listmodules().
740 num_header_lines = 2
741 num_module_lines_min = 5 # Playing it safe.
742 num_footer_lines = 3
743 expected = num_header_lines + num_module_lines_min + num_footer_lines
744
745 output = StringIO()
746 helper = pydoc.Helper(output=output)
747 helper('modules')
748 result = output.getvalue().strip()
749 num_lines = len(result.splitlines())
750
751 self.assertGreaterEqual(num_lines, expected)
752
Eric Snowa46ef702014-02-22 13:57:08 -0700753 @unittest.skip('causes undesireable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700754 def test_modules_search(self):
755 # See Helper.listmodules().
756 expected = 'pydoc - '
757
758 output = StringIO()
759 helper = pydoc.Helper(output=output)
760 with captured_stdout() as help_io:
761 helper('modules pydoc')
762 result = help_io.getvalue()
763
764 self.assertIn(expected, result)
765
Eric Snowa46ef702014-02-22 13:57:08 -0700766 @unittest.skip('some buildbots are not cooperating (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700767 def test_modules_search_builtin(self):
Eric Snow5ea97502014-01-04 23:04:27 -0700768 expected = 'gc - '
Eric Snowaed5b222014-01-04 20:38:11 -0700769
770 output = StringIO()
771 helper = pydoc.Helper(output=output)
772 with captured_stdout() as help_io:
Eric Snow5ea97502014-01-04 23:04:27 -0700773 helper('modules garbage')
Eric Snowaed5b222014-01-04 20:38:11 -0700774 result = help_io.getvalue()
775
776 self.assertTrue(result.startswith(expected))
777
778 def test_importfile(self):
779 loaded_pydoc = pydoc.importfile(pydoc.__file__)
780
Eric Snow3a62d142014-01-06 20:42:59 -0700781 self.assertIsNot(loaded_pydoc, pydoc)
Eric Snowaed5b222014-01-04 20:38:11 -0700782 self.assertEqual(loaded_pydoc.__name__, 'pydoc')
783 self.assertEqual(loaded_pydoc.__file__, pydoc.__file__)
Eric Snow3a62d142014-01-06 20:42:59 -0700784 self.assertEqual(loaded_pydoc.__spec__, pydoc.__spec__)
Eric Snowaed5b222014-01-04 20:38:11 -0700785
Ned Deily92a81a12011-10-06 14:19:03 -0700786
Georg Brandlb533e262008-05-25 18:19:30 +0000787class TestDescriptions(unittest.TestCase):
788
789 def test_module(self):
790 # Check that pydocfodder module can be described
791 from test import pydocfodder
792 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000793 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000794
Georg Brandlb533e262008-05-25 18:19:30 +0000795 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000796 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +0000797 c = C()
798
799 self.assertEqual(pydoc.describe(C), 'class C')
800 self.assertEqual(pydoc.describe(c), 'C')
801 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000802 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000803
Éric Araujoe64e51b2011-07-29 17:03:55 +0200804 def test_builtin(self):
805 for name in ('str', 'str.translate', 'builtins.str',
806 'builtins.str.translate'):
807 # test low-level function
808 self.assertIsNotNone(pydoc.locate(name))
809 # test high-level function
810 try:
811 pydoc.render_doc(name)
812 except ImportError:
Terry Jan Reedyfe928de2014-06-20 14:59:11 -0400813 self.fail('finding the doc of {!r} failed'.format(name))
Éric Araujoe64e51b2011-07-29 17:03:55 +0200814
815 for name in ('notbuiltins', 'strrr', 'strr.translate',
816 'str.trrrranslate', 'builtins.strrr',
817 'builtins.str.trrranslate'):
818 self.assertIsNone(pydoc.locate(name))
819 self.assertRaises(ImportError, pydoc.render_doc, name)
820
Larry Hastings24a882b2014-02-20 23:34:46 -0800821 @staticmethod
822 def _get_summary_line(o):
823 text = pydoc.plain(pydoc.render_doc(o))
824 lines = text.split('\n')
825 assert len(lines) >= 2
826 return lines[2]
827
828 # these should include "self"
829 def test_unbound_python_method(self):
830 self.assertEqual(self._get_summary_line(textwrap.TextWrapper.wrap),
831 "wrap(self, text)")
832
Stefan Krah5de32782014-01-18 23:18:39 +0100833 @requires_docstrings
Larry Hastings24a882b2014-02-20 23:34:46 -0800834 def test_unbound_builtin_method(self):
835 self.assertEqual(self._get_summary_line(_pickle.Pickler.dump),
836 "dump(self, obj, /)")
837
838 # these no longer include "self"
839 def test_bound_python_method(self):
840 t = textwrap.TextWrapper()
841 self.assertEqual(self._get_summary_line(t.wrap),
842 "wrap(text) method of textwrap.TextWrapper instance")
843
844 @requires_docstrings
845 def test_bound_builtin_method(self):
846 s = StringIO()
847 p = _pickle.Pickler(s)
848 self.assertEqual(self._get_summary_line(p.dump),
849 "dump(obj, /) method of _pickle.Pickler instance")
850
851 # this should *never* include self!
852 @requires_docstrings
853 def test_module_level_callable(self):
854 self.assertEqual(self._get_summary_line(os.stat),
855 "stat(path, *, dir_fd=None, follow_symlinks=True)")
Larry Hastings1abd7082014-01-16 14:15:03 -0800856
Georg Brandlb533e262008-05-25 18:19:30 +0000857
Victor Stinner62a68f22011-05-20 02:29:13 +0200858@unittest.skipUnless(threading, 'Threading required for this test.')
Georg Brandld2f38572011-01-30 08:37:19 +0000859class PydocServerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000860 """Tests for pydoc._start_server"""
861
862 def test_server(self):
863
864 # Minimal test that starts the server, then stops it.
865 def my_url_handler(url, content_type):
866 text = 'the URL sent was: (%s, %s)' % (url, content_type)
867 return text
868
869 serverthread = pydoc._start_server(my_url_handler, port=0)
Senthil Kumaran2a42a0b2014-09-17 13:17:58 +0800870 self.assertIn('localhost', serverthread.docserver.address)
871
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000872 starttime = time.time()
873 timeout = 1 #seconds
874
875 while serverthread.serving:
876 time.sleep(.01)
877 if serverthread.serving and time.time() - starttime > timeout:
878 serverthread.stop()
879 break
880
881 self.assertEqual(serverthread.error, None)
882
883
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200884class PydocUrlHandlerTest(PydocBaseTest):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000885 """Tests for pydoc._url_handler"""
886
887 def test_content_type_err(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000888 f = pydoc._url_handler
Georg Brandld2f38572011-01-30 08:37:19 +0000889 self.assertRaises(TypeError, f, 'A', '')
890 self.assertRaises(TypeError, f, 'B', 'foobar')
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000891
892 def test_url_requests(self):
893 # Test for the correct title in the html pages returned.
894 # This tests the different parts of the URL handler without
895 # getting too picky about the exact html.
896 requests = [
Georg Brandld2f38572011-01-30 08:37:19 +0000897 ("", "Pydoc: Index of Modules"),
898 ("get?key=", "Pydoc: Index of Modules"),
899 ("index", "Pydoc: Index of Modules"),
900 ("topics", "Pydoc: Topics"),
901 ("keywords", "Pydoc: Keywords"),
902 ("pydoc", "Pydoc: module pydoc"),
903 ("get?key=pydoc", "Pydoc: module pydoc"),
904 ("search?key=pydoc", "Pydoc: Search Results"),
905 ("topic?key=def", "Pydoc: KEYWORD def"),
906 ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
907 ("foobar", "Pydoc: Error - foobar"),
908 ("getfile?key=foobar", "Pydoc: Error - getfile?key=foobar"),
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000909 ]
910
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200911 with self.restrict_walk_packages():
912 for url, title in requests:
Martin Panter9ad0aae2015-11-06 00:27:14 +0000913 self.call_url_handler(url, title)
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200914
915 path = string.__file__
916 title = "Pydoc: getfile " + path
917 url = "getfile?key=" + path
Martin Panter9ad0aae2015-11-06 00:27:14 +0000918 self.call_url_handler(url, title)
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000919
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000920
Ezio Melottib185a042011-04-28 07:42:55 +0300921class TestHelper(unittest.TestCase):
922 def test_keywords(self):
923 self.assertEqual(sorted(pydoc.Helper.keywords),
924 sorted(keyword.kwlist))
925
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700926class PydocWithMetaClasses(unittest.TestCase):
Ethan Furman3f2f1922013-10-22 07:30:24 -0700927 @unittest.skipIf(sys.flags.optimize >= 2,
928 "Docstrings are omitted with -O2 and above")
929 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
930 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700931 def test_DynamicClassAttribute(self):
932 class Meta(type):
933 def __getattr__(self, name):
934 if name == 'ham':
935 return 'spam'
936 return super().__getattr__(name)
937 class DA(metaclass=Meta):
938 @types.DynamicClassAttribute
939 def ham(self):
940 return 'eggs'
Ethan Furman3f2f1922013-10-22 07:30:24 -0700941 expected_text_data_docstrings = tuple('\n | ' + s if s else ''
942 for s in expected_data_docstrings)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700943 output = StringIO()
944 helper = pydoc.Helper(output=output)
945 helper(DA)
Ethan Furman3f2f1922013-10-22 07:30:24 -0700946 expected_text = expected_dynamicattribute_pattern % (
947 (__name__,) + expected_text_data_docstrings[:2])
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700948 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700949 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700950
Ethan Furman3f2f1922013-10-22 07:30:24 -0700951 @unittest.skipIf(sys.flags.optimize >= 2,
952 "Docstrings are omitted with -O2 and above")
953 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
954 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700955 def test_virtualClassAttributeWithOneMeta(self):
956 class Meta(type):
957 def __dir__(cls):
958 return ['__class__', '__module__', '__name__', 'LIFE']
959 def __getattr__(self, name):
960 if name =='LIFE':
961 return 42
962 return super().__getattr(name)
963 class Class(metaclass=Meta):
964 pass
965 output = StringIO()
966 helper = pydoc.Helper(output=output)
967 helper(Class)
968 expected_text = expected_virtualattribute_pattern1 % __name__
969 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700970 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700971
Ethan Furman3f2f1922013-10-22 07:30:24 -0700972 @unittest.skipIf(sys.flags.optimize >= 2,
973 "Docstrings are omitted with -O2 and above")
974 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
975 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700976 def test_virtualClassAttributeWithTwoMeta(self):
977 class Meta1(type):
978 def __dir__(cls):
979 return ['__class__', '__module__', '__name__', 'one']
980 def __getattr__(self, name):
981 if name =='one':
982 return 1
983 return super().__getattr__(name)
984 class Meta2(type):
985 def __dir__(cls):
986 return ['__class__', '__module__', '__name__', 'two']
987 def __getattr__(self, name):
988 if name =='two':
989 return 2
990 return super().__getattr__(name)
991 class Meta3(Meta1, Meta2):
992 def __dir__(cls):
993 return list(sorted(set(
994 ['__class__', '__module__', '__name__', 'three'] +
995 Meta1.__dir__(cls) + Meta2.__dir__(cls))))
996 def __getattr__(self, name):
997 if name =='three':
998 return 3
999 return super().__getattr__(name)
1000 class Class1(metaclass=Meta1):
1001 pass
1002 class Class2(Class1, metaclass=Meta3):
1003 pass
1004 fail1 = fail2 = False
1005 output = StringIO()
1006 helper = pydoc.Helper(output=output)
1007 helper(Class1)
1008 expected_text1 = expected_virtualattribute_pattern2 % __name__
1009 result1 = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -07001010 self.assertEqual(expected_text1, result1)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001011 output = StringIO()
1012 helper = pydoc.Helper(output=output)
1013 helper(Class2)
1014 expected_text2 = expected_virtualattribute_pattern3 % __name__
1015 result2 = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -07001016 self.assertEqual(expected_text2, result2)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001017
Ethan Furman3f2f1922013-10-22 07:30:24 -07001018 @unittest.skipIf(sys.flags.optimize >= 2,
1019 "Docstrings are omitted with -O2 and above")
1020 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
1021 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001022 def test_buggy_dir(self):
1023 class M(type):
1024 def __dir__(cls):
1025 return ['__class__', '__name__', 'missing', 'here']
1026 class C(metaclass=M):
1027 here = 'present!'
1028 output = StringIO()
1029 helper = pydoc.Helper(output=output)
1030 helper(C)
1031 expected_text = expected_missingattribute_pattern % __name__
1032 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -07001033 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001034
Serhiy Storchakab6076fb2015-04-21 21:09:48 +03001035 def test_resolve_false(self):
1036 # Issue #23008: pydoc enum.{,Int}Enum failed
1037 # because bool(enum.Enum) is False.
1038 with captured_stdout() as help_io:
1039 pydoc.help('enum.Enum')
1040 helptext = help_io.getvalue()
1041 self.assertIn('class Enum', helptext)
1042
Eric Snowaed5b222014-01-04 20:38:11 -07001043
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001044@reap_threads
Georg Brandlb533e262008-05-25 18:19:30 +00001045def test_main():
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001046 try:
1047 test.support.run_unittest(PydocDocTest,
Ned Deily92a81a12011-10-06 14:19:03 -07001048 PydocImportTest,
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001049 TestDescriptions,
1050 PydocServerTest,
1051 PydocUrlHandlerTest,
1052 TestHelper,
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001053 PydocWithMetaClasses,
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001054 )
1055 finally:
1056 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +00001057
1058if __name__ == "__main__":
1059 test_main()