blob: 60ca12c027cc34af959aaffd12772e6e3d7b729c [file] [log] [blame]
Georg Brandlb533e262008-05-25 18:19:30 +00001import os
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002import sys
Georg Brandlb533e262008-05-25 18:19:30 +00003import difflib
Georg Brandlb533e262008-05-25 18:19:30 +00004import inspect
Nick Coghlan7bb30b72010-12-03 09:29:11 +00005import pydoc
6import re
7import string
8import subprocess
Georg Brandlb533e262008-05-25 18:19:30 +00009import test.support
Nick Coghlan7bb30b72010-12-03 09:29:11 +000010import time
11import unittest
Brian Curtin49c284c2010-03-31 03:19:28 +000012import xml.etree
Georg Brandld80d5f42010-12-03 07:47:22 +000013import textwrap
14from io import StringIO
Benjamin Peterson0289b152009-06-28 17:22:03 +000015from contextlib import contextmanager
Georg Brandld80d5f42010-12-03 07:47:22 +000016from test.support import TESTFN, forget, rmtree, EnvironmentVarGuard, \
17 reap_children, captured_output
Georg Brandlb533e262008-05-25 18:19:30 +000018
19from test import pydoc_mod
20
Florent Xicluna085a6562010-03-06 14:04:16 +000021# Just in case sys.modules["test"] has the optional attribute __loader__.
22if hasattr(pydoc_mod, "__loader__"):
23 del pydoc_mod.__loader__
24
Barry Warsaw28a691b2010-04-17 00:19:56 +000025expected_text_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000026NAME
27 test.pydoc_mod - This is a test module for test_pydoc
Georg Brandlb533e262008-05-25 18:19:30 +000028%s
29CLASSES
30 builtins.object
31 A
32 B
33\x20\x20\x20\x20
34 class A(builtins.object)
35 | Hello and goodbye
36 |\x20\x20
37 | Methods defined here:
38 |\x20\x20
39 | __init__()
40 | Wow, I have no function!
41 |\x20\x20
42 | ----------------------------------------------------------------------
43 | Data descriptors defined here:
44 |\x20\x20
45 | __dict__
46 | dictionary for instance variables (if defined)
47 |\x20\x20
48 | __weakref__
49 | list of weak references to the object (if defined)
50\x20\x20\x20\x20
51 class B(builtins.object)
52 | Data descriptors defined here:
53 |\x20\x20
54 | __dict__
55 | dictionary for instance variables (if defined)
56 |\x20\x20
57 | __weakref__
58 | list of weak references to the object (if defined)
59 |\x20\x20
60 | ----------------------------------------------------------------------
61 | Data and other attributes defined here:
62 |\x20\x20
63 | NO_MEANING = 'eggs'
64
65FUNCTIONS
66 doc_func()
67 This function solves all of the world's problems:
68 hunger
69 lack of Python
70 war
71\x20\x20\x20\x20
72 nodoc_func()
73
74DATA
Alexander Belopolskya47bbf52010-11-18 01:52:54 +000075 __xyz__ = 'X, Y and Z'
Georg Brandlb533e262008-05-25 18:19:30 +000076
77VERSION
78 1.2.3.4
79
80AUTHOR
81 Benjamin Peterson
82
83CREDITS
84 Nobody
Alexander Belopolskya47bbf52010-11-18 01:52:54 +000085
86FILE
87 %s
Georg Brandlb533e262008-05-25 18:19:30 +000088""".strip()
89
Barry Warsaw28a691b2010-04-17 00:19:56 +000090expected_html_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000091<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
92<tr bgcolor="#7799ee">
93<td valign=bottom>&nbsp;<br>
94<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
95><td align=right valign=bottom
96><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
97 <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
98<p>
99<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
100<tr bgcolor="#ee77aa">
101<td colspan=3 valign=bottom>&nbsp;<br>
102<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
103\x20\x20\x20\x20
104<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
105<td width="100%%"><dl>
106<dt><font face="helvetica, arial"><a href="builtins.html#object">builtins.object</a>
107</font></dt><dd>
108<dl>
109<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
110</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
111</font></dt></dl>
112</dd>
113</dl>
114 <p>
115<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
116<tr bgcolor="#ffc8d8">
117<td colspan=3 valign=bottom>&nbsp;<br>
118<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>
119\x20\x20\x20\x20
120<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
121<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
122<tr><td>&nbsp;</td>
123<td width="100%%">Methods defined here:<br>
124<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>
125
126<hr>
127Data descriptors defined here:<br>
128<dl><dt><strong>__dict__</strong></dt>
129<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
130</dl>
131<dl><dt><strong>__weakref__</strong></dt>
132<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
133</dl>
134</td></tr></table> <p>
135<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
136<tr bgcolor="#ffc8d8">
137<td colspan=3 valign=bottom>&nbsp;<br>
138<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>
139\x20\x20\x20\x20
140<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
141<td width="100%%">Data descriptors defined here:<br>
142<dl><dt><strong>__dict__</strong></dt>
143<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
144</dl>
145<dl><dt><strong>__weakref__</strong></dt>
146<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
147</dl>
148<hr>
149Data and other attributes defined here:<br>
150<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
151
152</td></tr></table></td></tr></table><p>
153<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
154<tr bgcolor="#eeaa77">
155<td colspan=3 valign=bottom>&nbsp;<br>
156<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
157\x20\x20\x20\x20
158<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
159<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>
160hunger<br>
161lack&nbsp;of&nbsp;Python<br>
162war</tt></dd></dl>
163 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
164</td></tr></table><p>
165<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
166<tr bgcolor="#55aa55">
167<td colspan=3 valign=bottom>&nbsp;<br>
168<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
169\x20\x20\x20\x20
170<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000171<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p>
Georg Brandlb533e262008-05-25 18:19:30 +0000172<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
173<tr bgcolor="#7799ee">
174<td colspan=3 valign=bottom>&nbsp;<br>
175<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
176\x20\x20\x20\x20
177<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
178<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
179<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
180<tr bgcolor="#7799ee">
181<td colspan=3 valign=bottom>&nbsp;<br>
182<font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
183\x20\x20\x20\x20
184<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
185<td width="100%%">Nobody</td></tr></table>
Barry Warsaw28a691b2010-04-17 00:19:56 +0000186""".strip() # ' <- emacs turd
Georg Brandlb533e262008-05-25 18:19:30 +0000187
188
189# output pattern for missing module
190missing_pattern = "no Python documentation found for '%s'"
191
Benjamin Peterson0289b152009-06-28 17:22:03 +0000192# output pattern for module with bad imports
193badimport_pattern = "problem in %s - ImportError: No module named %s"
194
Georg Brandlb533e262008-05-25 18:19:30 +0000195def run_pydoc(module_name, *args):
196 """
197 Runs pydoc on the specified module. Returns the stripped
198 output of pydoc.
199 """
200 cmd = [sys.executable, pydoc.__file__, " ".join(args), module_name]
Antoine Pitrouaecd3b72009-10-30 21:45:40 +0000201 try:
202 output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
203 return output.strip()
204 finally:
205 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +0000206
207def get_pydoc_html(module):
208 "Returns pydoc generated output as html"
209 doc = pydoc.HTMLDoc()
210 output = doc.docmodule(module)
211 loc = doc.getdocloc(pydoc_mod) or ""
212 if loc:
213 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
214 return output.strip(), loc
215
216def get_pydoc_text(module):
217 "Returns pydoc generated output as text"
218 doc = pydoc.TextDoc()
219 loc = doc.getdocloc(pydoc_mod) or ""
220 if loc:
221 loc = "\nMODULE DOCS\n " + loc + "\n"
222
223 output = doc.docmodule(module)
224
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000225 # clean up the extra text formatting that pydoc performs
Georg Brandlb533e262008-05-25 18:19:30 +0000226 patt = re.compile('\b.')
227 output = patt.sub('', output)
228 return output.strip(), loc
229
230def print_diffs(text1, text2):
231 "Prints unified diffs for two texts"
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000232 # XXX now obsolete, use unittest built-in support
Georg Brandlb533e262008-05-25 18:19:30 +0000233 lines1 = text1.splitlines(True)
234 lines2 = text2.splitlines(True)
235 diffs = difflib.unified_diff(lines1, lines2, n=0, fromfile='expected',
236 tofile='got')
237 print('\n' + ''.join(diffs))
238
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000239def get_html_title(text):
240 _, _, text = text.rpartition("<title>")
241 title, _, _ = text.rpartition("</title>")
242 return title
243
Georg Brandlb533e262008-05-25 18:19:30 +0000244
245class PyDocDocTest(unittest.TestCase):
246
R. David Murray378c0cf2010-02-24 01:46:21 +0000247 @unittest.skipIf(sys.flags.optimize >= 2,
248 "Docstrings are omitted with -O2 and above")
Georg Brandlb533e262008-05-25 18:19:30 +0000249 def test_html_doc(self):
250 result, doc_loc = get_pydoc_html(pydoc_mod)
251 mod_file = inspect.getabsfile(pydoc_mod)
Benjamin Petersonc5e94642008-06-14 23:04:46 +0000252 if sys.platform == 'win32':
253 import nturl2path
254 mod_url = nturl2path.pathname2url(mod_file)
255 else:
256 mod_url = mod_file
257 expected_html = expected_html_pattern % (mod_url, mod_file, doc_loc)
Georg Brandlb533e262008-05-25 18:19:30 +0000258 if result != expected_html:
259 print_diffs(expected_html, result)
260 self.fail("outputs are not equal, see diff above")
261
R. David Murray378c0cf2010-02-24 01:46:21 +0000262 @unittest.skipIf(sys.flags.optimize >= 2,
263 "Docstrings are omitted with -O2 and above")
Georg Brandlb533e262008-05-25 18:19:30 +0000264 def test_text_doc(self):
265 result, doc_loc = get_pydoc_text(pydoc_mod)
266 expected_text = expected_text_pattern % \
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000267 (doc_loc, inspect.getabsfile(pydoc_mod))
Georg Brandlb533e262008-05-25 18:19:30 +0000268 if result != expected_text:
269 print_diffs(expected_text, result)
270 self.fail("outputs are not equal, see diff above")
271
Brian Curtin49c284c2010-03-31 03:19:28 +0000272 def test_issue8225(self):
273 # Test issue8225 to ensure no doc link appears for xml.etree
274 result, doc_loc = get_pydoc_text(xml.etree)
275 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
276
Georg Brandlb533e262008-05-25 18:19:30 +0000277 def test_not_here(self):
278 missing_module = "test.i_am_not_here"
279 result = str(run_pydoc(missing_module), 'ascii')
280 expected = missing_pattern % missing_module
281 self.assertEqual(expected, result,
282 "documentation for missing module found")
283
Benjamin Peterson0289b152009-06-28 17:22:03 +0000284 def test_badimport(self):
285 # This tests the fix for issue 5230, where if pydoc found the module
286 # but the module had an internal import error pydoc would report no doc
287 # found.
288 modname = 'testmod_xyzzy'
289 testpairs = (
290 ('i_am_not_here', 'i_am_not_here'),
291 ('test.i_am_not_here_either', 'i_am_not_here_either'),
292 ('test.i_am_not_here.neither_am_i', 'i_am_not_here.neither_am_i'),
Barry Warsaw28a691b2010-04-17 00:19:56 +0000293 ('i_am_not_here.{}'.format(modname),
294 'i_am_not_here.{}'.format(modname)),
Benjamin Peterson0289b152009-06-28 17:22:03 +0000295 ('test.{}'.format(modname), modname),
296 )
297
298 @contextmanager
299 def newdirinpath(dir):
300 os.mkdir(dir)
301 sys.path.insert(0, dir)
302 yield
303 sys.path.pop(0)
304 rmtree(dir)
305
306 with newdirinpath(TESTFN), EnvironmentVarGuard() as env:
307 env['PYTHONPATH'] = TESTFN
308 fullmodname = os.path.join(TESTFN, modname)
309 sourcefn = fullmodname + os.extsep + "py"
310 for importstring, expectedinmsg in testpairs:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000311 with open(sourcefn, 'w') as f:
312 f.write("import {}\n".format(importstring))
Benjamin Peterson0289b152009-06-28 17:22:03 +0000313 try:
314 result = run_pydoc(modname).decode("ascii")
315 finally:
316 forget(modname)
317 expected = badimport_pattern % (modname, expectedinmsg)
318 self.assertEqual(expected, result)
319
R. David Murray1f1b9d32009-05-27 20:56:59 +0000320 def test_input_strip(self):
321 missing_module = " test.i_am_not_here "
322 result = str(run_pydoc(missing_module), 'ascii')
323 expected = missing_pattern % missing_module.strip()
324 self.assertEqual(expected, result)
325
Ezio Melotti412c95a2010-02-16 23:31:04 +0000326 def test_stripid(self):
327 # test with strings, other implementations might have different repr()
328 stripid = pydoc.stripid
329 # strip the id
330 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
331 '<function stripid>')
332 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
333 '<function stripid>')
334 # nothing to strip, return the same text
335 self.assertEqual(stripid('42'), '42')
336 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
337 "<type 'exceptions.Exception'>")
338
Georg Brandld80d5f42010-12-03 07:47:22 +0000339 @unittest.skipIf(sys.flags.optimize >= 2,
340 'Docstrings are omitted with -O2 and above')
341 def test_help_output_redirect(self):
342 # issue 940286, if output is set in Helper, then all output from
343 # Helper.help should be redirected
344 old_pattern = expected_text_pattern
345 getpager_old = pydoc.getpager
346 getpager_new = lambda: (lambda x: x)
347 self.maxDiff = None
348
349 buf = StringIO()
350 helper = pydoc.Helper(output=buf)
351 unused, doc_loc = get_pydoc_text(pydoc_mod)
352 module = "test.pydoc_mod"
353 help_header = """
354 Help on module test.pydoc_mod in test:
355
356 """.lstrip()
357 help_header = textwrap.dedent(help_header)
358 expected_help_pattern = help_header + expected_text_pattern
359
360 pydoc.getpager = getpager_new
361 try:
362 with captured_output('stdout') as output, \
363 captured_output('stderr') as err:
364 helper.help(module)
365 result = buf.getvalue().strip()
366 expected_text = expected_help_pattern % \
367 (doc_loc, inspect.getabsfile(pydoc_mod))
368 self.assertEqual('', output.getvalue())
369 self.assertEqual('', err.getvalue())
370 self.assertEqual(expected_text, result)
371 finally:
372 pydoc.getpager = getpager_old
373
Georg Brandlb533e262008-05-25 18:19:30 +0000374
375class TestDescriptions(unittest.TestCase):
376
377 def test_module(self):
378 # Check that pydocfodder module can be described
379 from test import pydocfodder
380 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000381 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000382
Georg Brandlb533e262008-05-25 18:19:30 +0000383 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000384 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +0000385 c = C()
386
387 self.assertEqual(pydoc.describe(C), 'class C')
388 self.assertEqual(pydoc.describe(c), 'C')
389 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000390 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000391
392
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000393class PyDocServerTest(unittest.TestCase):
394 """Tests for pydoc._start_server"""
395
396 def test_server(self):
397
398 # Minimal test that starts the server, then stops it.
399 def my_url_handler(url, content_type):
400 text = 'the URL sent was: (%s, %s)' % (url, content_type)
401 return text
402
403 serverthread = pydoc._start_server(my_url_handler, port=0)
404 starttime = time.time()
405 timeout = 1 #seconds
406
407 while serverthread.serving:
408 time.sleep(.01)
409 if serverthread.serving and time.time() - starttime > timeout:
410 serverthread.stop()
411 break
412
413 self.assertEqual(serverthread.error, None)
414
415
416class PyDocUrlHandlerTest(unittest.TestCase):
417 """Tests for pydoc._url_handler"""
418
419 def test_content_type_err(self):
420 err = 'Error: unknown content type '
421 f = pydoc._url_handler
422 result = f("", "")
423 self.assertEqual(result, err + "''")
424 result = f("", "foobar")
425 self.assertEqual(result, err + "'foobar'")
426
427 def test_url_requests(self):
428 # Test for the correct title in the html pages returned.
429 # This tests the different parts of the URL handler without
430 # getting too picky about the exact html.
431 requests = [
432 ("", "Python: Index of Modules"),
433 ("get?key=", "Python: Index of Modules"),
434 ("index", "Python: Index of Modules"),
435 ("topics", "Python: Topics"),
436 ("keywords", "Python: Keywords"),
437 ("pydoc", "Python: module pydoc"),
438 ("get?key=pydoc", "Python: module pydoc"),
439 ("search?key=pydoc", "Python: Search Results"),
440 ("def", "Python: KEYWORD def"),
441 ("STRINGS", "Python: TOPIC STRINGS"),
442 ("foobar", "Python: Error"),
443 ("getfile?key=foobar", "Python: Read Error"),
444 ]
445
446 for url, title in requests:
447 text = pydoc._url_handler(url, "text/html")
448 result = get_html_title(text)
449 self.assertEqual(result, title)
450
451 path = string.__file__
452 title = "Python: getfile /" + path
453 url = "getfile?key=" + path
454 text = pydoc._url_handler(url, "text/html")
455 result = get_html_title(text)
456 self.assertEqual(result, title)
457
458
Georg Brandlb533e262008-05-25 18:19:30 +0000459def test_main():
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000460 test.support.run_unittest(PyDocDocTest,
461 TestDescriptions,
462 PyDocServerTest,
463 PyDocUrlHandlerTest,
464 )
Georg Brandlb533e262008-05-25 18:19:30 +0000465
466if __name__ == "__main__":
467 test_main()