blob: 7f927f600c5a8e1ccc05f2028c75a89e47ac7066 [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):
Nick Coghlanecace282010-12-03 16:08:46 +0000240 # Bit of hack, but good enough for test purposes
241 header, _, _ = text.partition("</head>")
242 _, _, title = header.partition("<title>")
243 title, _, _ = title.partition("</title>")
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000244 return title
245
Georg Brandlb533e262008-05-25 18:19:30 +0000246
247class PyDocDocTest(unittest.TestCase):
248
R. David Murray378c0cf2010-02-24 01:46:21 +0000249 @unittest.skipIf(sys.flags.optimize >= 2,
250 "Docstrings are omitted with -O2 and above")
Georg Brandlb533e262008-05-25 18:19:30 +0000251 def test_html_doc(self):
252 result, doc_loc = get_pydoc_html(pydoc_mod)
253 mod_file = inspect.getabsfile(pydoc_mod)
Benjamin Petersonc5e94642008-06-14 23:04:46 +0000254 if sys.platform == 'win32':
255 import nturl2path
256 mod_url = nturl2path.pathname2url(mod_file)
257 else:
258 mod_url = mod_file
259 expected_html = expected_html_pattern % (mod_url, mod_file, doc_loc)
Georg Brandlb533e262008-05-25 18:19:30 +0000260 if result != expected_html:
261 print_diffs(expected_html, result)
262 self.fail("outputs are not equal, see diff above")
263
R. David Murray378c0cf2010-02-24 01:46:21 +0000264 @unittest.skipIf(sys.flags.optimize >= 2,
265 "Docstrings are omitted with -O2 and above")
Georg Brandlb533e262008-05-25 18:19:30 +0000266 def test_text_doc(self):
267 result, doc_loc = get_pydoc_text(pydoc_mod)
268 expected_text = expected_text_pattern % \
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000269 (doc_loc, inspect.getabsfile(pydoc_mod))
Georg Brandlb533e262008-05-25 18:19:30 +0000270 if result != expected_text:
271 print_diffs(expected_text, result)
272 self.fail("outputs are not equal, see diff above")
273
Brian Curtin49c284c2010-03-31 03:19:28 +0000274 def test_issue8225(self):
275 # Test issue8225 to ensure no doc link appears for xml.etree
276 result, doc_loc = get_pydoc_text(xml.etree)
277 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
278
Georg Brandlb533e262008-05-25 18:19:30 +0000279 def test_not_here(self):
280 missing_module = "test.i_am_not_here"
281 result = str(run_pydoc(missing_module), 'ascii')
282 expected = missing_pattern % missing_module
283 self.assertEqual(expected, result,
284 "documentation for missing module found")
285
Benjamin Peterson0289b152009-06-28 17:22:03 +0000286 def test_badimport(self):
287 # This tests the fix for issue 5230, where if pydoc found the module
288 # but the module had an internal import error pydoc would report no doc
289 # found.
290 modname = 'testmod_xyzzy'
291 testpairs = (
292 ('i_am_not_here', 'i_am_not_here'),
293 ('test.i_am_not_here_either', 'i_am_not_here_either'),
294 ('test.i_am_not_here.neither_am_i', 'i_am_not_here.neither_am_i'),
Barry Warsaw28a691b2010-04-17 00:19:56 +0000295 ('i_am_not_here.{}'.format(modname),
296 'i_am_not_here.{}'.format(modname)),
Benjamin Peterson0289b152009-06-28 17:22:03 +0000297 ('test.{}'.format(modname), modname),
298 )
299
300 @contextmanager
301 def newdirinpath(dir):
302 os.mkdir(dir)
303 sys.path.insert(0, dir)
304 yield
305 sys.path.pop(0)
306 rmtree(dir)
307
308 with newdirinpath(TESTFN), EnvironmentVarGuard() as env:
309 env['PYTHONPATH'] = TESTFN
310 fullmodname = os.path.join(TESTFN, modname)
311 sourcefn = fullmodname + os.extsep + "py"
312 for importstring, expectedinmsg in testpairs:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000313 with open(sourcefn, 'w') as f:
314 f.write("import {}\n".format(importstring))
Benjamin Peterson0289b152009-06-28 17:22:03 +0000315 try:
316 result = run_pydoc(modname).decode("ascii")
317 finally:
318 forget(modname)
319 expected = badimport_pattern % (modname, expectedinmsg)
320 self.assertEqual(expected, result)
321
R. David Murray1f1b9d32009-05-27 20:56:59 +0000322 def test_input_strip(self):
323 missing_module = " test.i_am_not_here "
324 result = str(run_pydoc(missing_module), 'ascii')
325 expected = missing_pattern % missing_module.strip()
326 self.assertEqual(expected, result)
327
Ezio Melotti412c95a2010-02-16 23:31:04 +0000328 def test_stripid(self):
329 # test with strings, other implementations might have different repr()
330 stripid = pydoc.stripid
331 # strip the id
332 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
333 '<function stripid>')
334 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
335 '<function stripid>')
336 # nothing to strip, return the same text
337 self.assertEqual(stripid('42'), '42')
338 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
339 "<type 'exceptions.Exception'>")
340
Georg Brandld80d5f42010-12-03 07:47:22 +0000341 @unittest.skipIf(sys.flags.optimize >= 2,
342 'Docstrings are omitted with -O2 and above')
343 def test_help_output_redirect(self):
344 # issue 940286, if output is set in Helper, then all output from
345 # Helper.help should be redirected
346 old_pattern = expected_text_pattern
347 getpager_old = pydoc.getpager
348 getpager_new = lambda: (lambda x: x)
349 self.maxDiff = None
350
351 buf = StringIO()
352 helper = pydoc.Helper(output=buf)
353 unused, doc_loc = get_pydoc_text(pydoc_mod)
354 module = "test.pydoc_mod"
355 help_header = """
356 Help on module test.pydoc_mod in test:
357
358 """.lstrip()
359 help_header = textwrap.dedent(help_header)
360 expected_help_pattern = help_header + expected_text_pattern
361
362 pydoc.getpager = getpager_new
363 try:
364 with captured_output('stdout') as output, \
365 captured_output('stderr') as err:
366 helper.help(module)
367 result = buf.getvalue().strip()
368 expected_text = expected_help_pattern % \
369 (doc_loc, inspect.getabsfile(pydoc_mod))
370 self.assertEqual('', output.getvalue())
371 self.assertEqual('', err.getvalue())
372 self.assertEqual(expected_text, result)
373 finally:
374 pydoc.getpager = getpager_old
375
Georg Brandlb533e262008-05-25 18:19:30 +0000376
377class TestDescriptions(unittest.TestCase):
378
379 def test_module(self):
380 # Check that pydocfodder module can be described
381 from test import pydocfodder
382 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000383 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000384
Georg Brandlb533e262008-05-25 18:19:30 +0000385 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000386 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +0000387 c = C()
388
389 self.assertEqual(pydoc.describe(C), 'class C')
390 self.assertEqual(pydoc.describe(c), 'C')
391 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000392 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000393
394
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000395class PyDocServerTest(unittest.TestCase):
396 """Tests for pydoc._start_server"""
397
398 def test_server(self):
399
400 # Minimal test that starts the server, then stops it.
401 def my_url_handler(url, content_type):
402 text = 'the URL sent was: (%s, %s)' % (url, content_type)
403 return text
404
405 serverthread = pydoc._start_server(my_url_handler, port=0)
406 starttime = time.time()
407 timeout = 1 #seconds
408
409 while serverthread.serving:
410 time.sleep(.01)
411 if serverthread.serving and time.time() - starttime > timeout:
412 serverthread.stop()
413 break
414
415 self.assertEqual(serverthread.error, None)
416
417
418class PyDocUrlHandlerTest(unittest.TestCase):
419 """Tests for pydoc._url_handler"""
420
421 def test_content_type_err(self):
422 err = 'Error: unknown content type '
423 f = pydoc._url_handler
424 result = f("", "")
425 self.assertEqual(result, err + "''")
426 result = f("", "foobar")
427 self.assertEqual(result, err + "'foobar'")
428
429 def test_url_requests(self):
430 # Test for the correct title in the html pages returned.
431 # This tests the different parts of the URL handler without
432 # getting too picky about the exact html.
433 requests = [
434 ("", "Python: Index of Modules"),
435 ("get?key=", "Python: Index of Modules"),
436 ("index", "Python: Index of Modules"),
437 ("topics", "Python: Topics"),
438 ("keywords", "Python: Keywords"),
439 ("pydoc", "Python: module pydoc"),
440 ("get?key=pydoc", "Python: module pydoc"),
441 ("search?key=pydoc", "Python: Search Results"),
442 ("def", "Python: KEYWORD def"),
443 ("STRINGS", "Python: TOPIC STRINGS"),
444 ("foobar", "Python: Error"),
445 ("getfile?key=foobar", "Python: Read Error"),
446 ]
447
448 for url, title in requests:
449 text = pydoc._url_handler(url, "text/html")
450 result = get_html_title(text)
451 self.assertEqual(result, title)
452
453 path = string.__file__
Nick Coghlanecace282010-12-03 16:08:46 +0000454 title = "Python: getfile " + path
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000455 url = "getfile?key=" + path
456 text = pydoc._url_handler(url, "text/html")
457 result = get_html_title(text)
458 self.assertEqual(result, title)
459
460
Georg Brandlb533e262008-05-25 18:19:30 +0000461def test_main():
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000462 test.support.run_unittest(PyDocDocTest,
463 TestDescriptions,
464 PyDocServerTest,
465 PyDocUrlHandlerTest,
466 )
Georg Brandlb533e262008-05-25 18:19:30 +0000467
468if __name__ == "__main__":
469 test_main()