blob: ab8d79ffbcd382a6c52d012a8b4fd0439b6b507c [file] [log] [blame]
Georg Brandlb533e262008-05-25 18:19:30 +00001import sys
2import os
Benjamin Peterson0289b152009-06-28 17:22:03 +00003import os.path
Georg Brandlb533e262008-05-25 18:19:30 +00004import difflib
5import subprocess
6import re
7import pydoc
8import inspect
9import unittest
10import test.support
Brian Curtin49c284c2010-03-31 03:19:28 +000011import xml.etree
Georg Brandld80d5f42010-12-03 07:47:22 +000012import textwrap
13from io import StringIO
Benjamin Peterson0289b152009-06-28 17:22:03 +000014from contextlib import contextmanager
Georg Brandld80d5f42010-12-03 07:47:22 +000015from test.support import TESTFN, forget, rmtree, EnvironmentVarGuard, \
16 reap_children, captured_output
Georg Brandlb533e262008-05-25 18:19:30 +000017
18from test import pydoc_mod
19
Florent Xicluna085a6562010-03-06 14:04:16 +000020# Just in case sys.modules["test"] has the optional attribute __loader__.
21if hasattr(pydoc_mod, "__loader__"):
22 del pydoc_mod.__loader__
23
Barry Warsaw28a691b2010-04-17 00:19:56 +000024expected_text_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000025NAME
26 test.pydoc_mod - This is a test module for test_pydoc
Georg Brandlb533e262008-05-25 18:19:30 +000027%s
28CLASSES
29 builtins.object
30 A
31 B
32\x20\x20\x20\x20
33 class A(builtins.object)
34 | Hello and goodbye
35 |\x20\x20
36 | Methods defined here:
37 |\x20\x20
38 | __init__()
39 | Wow, I have no function!
40 |\x20\x20
41 | ----------------------------------------------------------------------
42 | Data descriptors defined here:
43 |\x20\x20
44 | __dict__
45 | dictionary for instance variables (if defined)
46 |\x20\x20
47 | __weakref__
48 | list of weak references to the object (if defined)
49\x20\x20\x20\x20
50 class B(builtins.object)
51 | Data descriptors defined here:
52 |\x20\x20
53 | __dict__
54 | dictionary for instance variables (if defined)
55 |\x20\x20
56 | __weakref__
57 | list of weak references to the object (if defined)
58 |\x20\x20
59 | ----------------------------------------------------------------------
60 | Data and other attributes defined here:
61 |\x20\x20
62 | NO_MEANING = 'eggs'
63
64FUNCTIONS
65 doc_func()
66 This function solves all of the world's problems:
67 hunger
68 lack of Python
69 war
70\x20\x20\x20\x20
71 nodoc_func()
72
73DATA
Alexander Belopolskya47bbf52010-11-18 01:52:54 +000074 __xyz__ = 'X, Y and Z'
Georg Brandlb533e262008-05-25 18:19:30 +000075
76VERSION
77 1.2.3.4
78
79AUTHOR
80 Benjamin Peterson
81
82CREDITS
83 Nobody
Alexander Belopolskya47bbf52010-11-18 01:52:54 +000084
85FILE
86 %s
Georg Brandlb533e262008-05-25 18:19:30 +000087""".strip()
88
Barry Warsaw28a691b2010-04-17 00:19:56 +000089expected_html_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000090<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
91<tr bgcolor="#7799ee">
92<td valign=bottom>&nbsp;<br>
93<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
94><td align=right valign=bottom
95><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
96 <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
97<p>
98<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
99<tr bgcolor="#ee77aa">
100<td colspan=3 valign=bottom>&nbsp;<br>
101<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
102\x20\x20\x20\x20
103<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
104<td width="100%%"><dl>
105<dt><font face="helvetica, arial"><a href="builtins.html#object">builtins.object</a>
106</font></dt><dd>
107<dl>
108<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
109</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
110</font></dt></dl>
111</dd>
112</dl>
113 <p>
114<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
115<tr bgcolor="#ffc8d8">
116<td colspan=3 valign=bottom>&nbsp;<br>
117<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>
118\x20\x20\x20\x20
119<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
120<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
121<tr><td>&nbsp;</td>
122<td width="100%%">Methods defined here:<br>
123<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>
124
125<hr>
126Data descriptors defined here:<br>
127<dl><dt><strong>__dict__</strong></dt>
128<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
129</dl>
130<dl><dt><strong>__weakref__</strong></dt>
131<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
132</dl>
133</td></tr></table> <p>
134<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
135<tr bgcolor="#ffc8d8">
136<td colspan=3 valign=bottom>&nbsp;<br>
137<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>
138\x20\x20\x20\x20
139<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
140<td width="100%%">Data descriptors defined here:<br>
141<dl><dt><strong>__dict__</strong></dt>
142<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
143</dl>
144<dl><dt><strong>__weakref__</strong></dt>
145<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
146</dl>
147<hr>
148Data and other attributes defined here:<br>
149<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
150
151</td></tr></table></td></tr></table><p>
152<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
153<tr bgcolor="#eeaa77">
154<td colspan=3 valign=bottom>&nbsp;<br>
155<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
156\x20\x20\x20\x20
157<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
158<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>
159hunger<br>
160lack&nbsp;of&nbsp;Python<br>
161war</tt></dd></dl>
162 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
163</td></tr></table><p>
164<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
165<tr bgcolor="#55aa55">
166<td colspan=3 valign=bottom>&nbsp;<br>
167<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
168\x20\x20\x20\x20
169<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000170<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p>
Georg Brandlb533e262008-05-25 18:19:30 +0000171<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
172<tr bgcolor="#7799ee">
173<td colspan=3 valign=bottom>&nbsp;<br>
174<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
175\x20\x20\x20\x20
176<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
177<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
178<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
179<tr bgcolor="#7799ee">
180<td colspan=3 valign=bottom>&nbsp;<br>
181<font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
182\x20\x20\x20\x20
183<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
184<td width="100%%">Nobody</td></tr></table>
Barry Warsaw28a691b2010-04-17 00:19:56 +0000185""".strip() # ' <- emacs turd
Georg Brandlb533e262008-05-25 18:19:30 +0000186
187
188# output pattern for missing module
189missing_pattern = "no Python documentation found for '%s'"
190
Benjamin Peterson0289b152009-06-28 17:22:03 +0000191# output pattern for module with bad imports
192badimport_pattern = "problem in %s - ImportError: No module named %s"
193
Georg Brandlb533e262008-05-25 18:19:30 +0000194def run_pydoc(module_name, *args):
195 """
196 Runs pydoc on the specified module. Returns the stripped
197 output of pydoc.
198 """
199 cmd = [sys.executable, pydoc.__file__, " ".join(args), module_name]
Antoine Pitrouaecd3b72009-10-30 21:45:40 +0000200 try:
201 output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
202 return output.strip()
203 finally:
204 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +0000205
206def get_pydoc_html(module):
207 "Returns pydoc generated output as html"
208 doc = pydoc.HTMLDoc()
209 output = doc.docmodule(module)
210 loc = doc.getdocloc(pydoc_mod) or ""
211 if loc:
212 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
213 return output.strip(), loc
214
215def get_pydoc_text(module):
216 "Returns pydoc generated output as text"
217 doc = pydoc.TextDoc()
218 loc = doc.getdocloc(pydoc_mod) or ""
219 if loc:
220 loc = "\nMODULE DOCS\n " + loc + "\n"
221
222 output = doc.docmodule(module)
223
224 # cleanup the extra text formatting that pydoc preforms
225 patt = re.compile('\b.')
226 output = patt.sub('', output)
227 return output.strip(), loc
228
229def print_diffs(text1, text2):
230 "Prints unified diffs for two texts"
231 lines1 = text1.splitlines(True)
232 lines2 = text2.splitlines(True)
233 diffs = difflib.unified_diff(lines1, lines2, n=0, fromfile='expected',
234 tofile='got')
235 print('\n' + ''.join(diffs))
236
237
238class PyDocDocTest(unittest.TestCase):
239
R. David Murray378c0cf2010-02-24 01:46:21 +0000240 @unittest.skipIf(sys.flags.optimize >= 2,
241 "Docstrings are omitted with -O2 and above")
Georg Brandlb533e262008-05-25 18:19:30 +0000242 def test_html_doc(self):
243 result, doc_loc = get_pydoc_html(pydoc_mod)
244 mod_file = inspect.getabsfile(pydoc_mod)
Benjamin Petersonc5e94642008-06-14 23:04:46 +0000245 if sys.platform == 'win32':
246 import nturl2path
247 mod_url = nturl2path.pathname2url(mod_file)
248 else:
249 mod_url = mod_file
250 expected_html = expected_html_pattern % (mod_url, mod_file, doc_loc)
Georg Brandlb533e262008-05-25 18:19:30 +0000251 if result != expected_html:
252 print_diffs(expected_html, result)
253 self.fail("outputs are not equal, see diff above")
254
R. David Murray378c0cf2010-02-24 01:46:21 +0000255 @unittest.skipIf(sys.flags.optimize >= 2,
256 "Docstrings are omitted with -O2 and above")
Georg Brandlb533e262008-05-25 18:19:30 +0000257 def test_text_doc(self):
258 result, doc_loc = get_pydoc_text(pydoc_mod)
259 expected_text = expected_text_pattern % \
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000260 (doc_loc, inspect.getabsfile(pydoc_mod))
Georg Brandlb533e262008-05-25 18:19:30 +0000261 if result != expected_text:
262 print_diffs(expected_text, result)
263 self.fail("outputs are not equal, see diff above")
264
Brian Curtin49c284c2010-03-31 03:19:28 +0000265 def test_issue8225(self):
266 # Test issue8225 to ensure no doc link appears for xml.etree
267 result, doc_loc = get_pydoc_text(xml.etree)
268 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
269
Georg Brandlb533e262008-05-25 18:19:30 +0000270 def test_not_here(self):
271 missing_module = "test.i_am_not_here"
272 result = str(run_pydoc(missing_module), 'ascii')
273 expected = missing_pattern % missing_module
274 self.assertEqual(expected, result,
275 "documentation for missing module found")
276
Benjamin Peterson0289b152009-06-28 17:22:03 +0000277 def test_badimport(self):
278 # This tests the fix for issue 5230, where if pydoc found the module
279 # but the module had an internal import error pydoc would report no doc
280 # found.
281 modname = 'testmod_xyzzy'
282 testpairs = (
283 ('i_am_not_here', 'i_am_not_here'),
284 ('test.i_am_not_here_either', 'i_am_not_here_either'),
285 ('test.i_am_not_here.neither_am_i', 'i_am_not_here.neither_am_i'),
Barry Warsaw28a691b2010-04-17 00:19:56 +0000286 ('i_am_not_here.{}'.format(modname),
287 'i_am_not_here.{}'.format(modname)),
Benjamin Peterson0289b152009-06-28 17:22:03 +0000288 ('test.{}'.format(modname), modname),
289 )
290
291 @contextmanager
292 def newdirinpath(dir):
293 os.mkdir(dir)
294 sys.path.insert(0, dir)
295 yield
296 sys.path.pop(0)
297 rmtree(dir)
298
299 with newdirinpath(TESTFN), EnvironmentVarGuard() as env:
300 env['PYTHONPATH'] = TESTFN
301 fullmodname = os.path.join(TESTFN, modname)
302 sourcefn = fullmodname + os.extsep + "py"
303 for importstring, expectedinmsg in testpairs:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000304 with open(sourcefn, 'w') as f:
305 f.write("import {}\n".format(importstring))
Benjamin Peterson0289b152009-06-28 17:22:03 +0000306 try:
307 result = run_pydoc(modname).decode("ascii")
308 finally:
309 forget(modname)
310 expected = badimport_pattern % (modname, expectedinmsg)
311 self.assertEqual(expected, result)
312
R. David Murray1f1b9d32009-05-27 20:56:59 +0000313 def test_input_strip(self):
314 missing_module = " test.i_am_not_here "
315 result = str(run_pydoc(missing_module), 'ascii')
316 expected = missing_pattern % missing_module.strip()
317 self.assertEqual(expected, result)
318
Ezio Melotti412c95a2010-02-16 23:31:04 +0000319 def test_stripid(self):
320 # test with strings, other implementations might have different repr()
321 stripid = pydoc.stripid
322 # strip the id
323 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
324 '<function stripid>')
325 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
326 '<function stripid>')
327 # nothing to strip, return the same text
328 self.assertEqual(stripid('42'), '42')
329 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
330 "<type 'exceptions.Exception'>")
331
Georg Brandld80d5f42010-12-03 07:47:22 +0000332 @unittest.skipIf(sys.flags.optimize >= 2,
333 'Docstrings are omitted with -O2 and above')
334 def test_help_output_redirect(self):
335 # issue 940286, if output is set in Helper, then all output from
336 # Helper.help should be redirected
337 old_pattern = expected_text_pattern
338 getpager_old = pydoc.getpager
339 getpager_new = lambda: (lambda x: x)
340 self.maxDiff = None
341
342 buf = StringIO()
343 helper = pydoc.Helper(output=buf)
344 unused, doc_loc = get_pydoc_text(pydoc_mod)
345 module = "test.pydoc_mod"
346 help_header = """
347 Help on module test.pydoc_mod in test:
348
349 """.lstrip()
350 help_header = textwrap.dedent(help_header)
351 expected_help_pattern = help_header + expected_text_pattern
352
353 pydoc.getpager = getpager_new
354 try:
355 with captured_output('stdout') as output, \
356 captured_output('stderr') as err:
357 helper.help(module)
358 result = buf.getvalue().strip()
359 expected_text = expected_help_pattern % \
360 (doc_loc, inspect.getabsfile(pydoc_mod))
361 self.assertEqual('', output.getvalue())
362 self.assertEqual('', err.getvalue())
363 self.assertEqual(expected_text, result)
364 finally:
365 pydoc.getpager = getpager_old
366
Georg Brandlb533e262008-05-25 18:19:30 +0000367
368class TestDescriptions(unittest.TestCase):
369
370 def test_module(self):
371 # Check that pydocfodder module can be described
372 from test import pydocfodder
373 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000374 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000375
376 def test_classic_class(self):
377 class C: "Classic class"
378 c = C()
379 self.assertEqual(pydoc.describe(C), 'class C')
380 self.assertEqual(pydoc.describe(c), 'C')
381 expected = 'C in module %s' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000382 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000383
384 def test_class(self):
385 class C(object): "New-style class"
386 c = C()
387
388 self.assertEqual(pydoc.describe(C), 'class C')
389 self.assertEqual(pydoc.describe(c), 'C')
390 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000391 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000392
393
394def test_main():
395 test.support.run_unittest(PyDocDocTest, TestDescriptions)
396
397if __name__ == "__main__":
398 test_main()