blob: 42a4089940c8ce0129fd95bc2dde0c67727b52d3 [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
Georg Brandlb533e262008-05-25 18:19:30 +00004import difflib
Georg Brandlb533e262008-05-25 18:19:30 +00005import inspect
Nick Coghlan7bb30b72010-12-03 09:29:11 +00006import pydoc
Ezio Melottib185a042011-04-28 07:42:55 +03007import keyword
Nick Coghlan7bb30b72010-12-03 09:29:11 +00008import re
9import string
Georg Brandlb533e262008-05-25 18:19:30 +000010import test.support
Nick Coghlan7bb30b72010-12-03 09:29:11 +000011import time
12import unittest
Brian Curtin49c284c2010-03-31 03:19:28 +000013import xml.etree
Georg Brandld80d5f42010-12-03 07:47:22 +000014import textwrap
15from io import StringIO
Raymond Hettinger1103d052011-03-25 14:15:24 -070016from collections import namedtuple
Antoine Pitrouf7f54752011-07-15 22:42:12 +020017from test.script_helper import assert_python_ok
Antoine Pitroua6e81a22011-07-15 22:32:25 +020018from test.support import (
Ned Deily92a81a12011-10-06 14:19:03 -070019 TESTFN, rmtree,
Antoine Pitroua6e81a22011-07-15 22:32:25 +020020 reap_children, reap_threads, captured_output, captured_stdout, unlink
21)
Georg Brandlb533e262008-05-25 18:19:30 +000022from test import pydoc_mod
23
Victor Stinner62a68f22011-05-20 02:29:13 +020024try:
25 import threading
26except ImportError:
27 threading = None
28
Florent Xicluna085a6562010-03-06 14:04:16 +000029# Just in case sys.modules["test"] has the optional attribute __loader__.
30if hasattr(pydoc_mod, "__loader__"):
31 del pydoc_mod.__loader__
32
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020033if test.support.HAVE_DOCSTRINGS:
34 expected_data_docstrings = (
35 'dictionary for instance variables (if defined)',
36 'list of weak references to the object (if defined)',
37 ) * 2
38else:
39 expected_data_docstrings = ('', '', '', '')
40
Barry Warsaw28a691b2010-04-17 00:19:56 +000041expected_text_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000042NAME
43 test.pydoc_mod - This is a test module for test_pydoc
Georg Brandlb533e262008-05-25 18:19:30 +000044%s
45CLASSES
46 builtins.object
47 A
48 B
49\x20\x20\x20\x20
50 class A(builtins.object)
51 | Hello and goodbye
52 |\x20\x20
53 | Methods defined here:
54 |\x20\x20
55 | __init__()
56 | Wow, I have no function!
57 |\x20\x20
58 | ----------------------------------------------------------------------
59 | Data descriptors defined here:
60 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020061 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000062 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020063 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000064\x20\x20\x20\x20
65 class B(builtins.object)
66 | Data descriptors defined here:
67 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020068 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000069 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020070 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000071 |\x20\x20
72 | ----------------------------------------------------------------------
73 | Data and other attributes defined here:
74 |\x20\x20
75 | NO_MEANING = 'eggs'
76
77FUNCTIONS
78 doc_func()
79 This function solves all of the world's problems:
80 hunger
81 lack of Python
82 war
83\x20\x20\x20\x20
84 nodoc_func()
85
86DATA
Alexander Belopolskya47bbf52010-11-18 01:52:54 +000087 __xyz__ = 'X, Y and Z'
Georg Brandlb533e262008-05-25 18:19:30 +000088
89VERSION
90 1.2.3.4
91
92AUTHOR
93 Benjamin Peterson
94
95CREDITS
96 Nobody
Alexander Belopolskya47bbf52010-11-18 01:52:54 +000097
98FILE
99 %s
Georg Brandlb533e262008-05-25 18:19:30 +0000100""".strip()
101
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200102expected_text_data_docstrings = tuple('\n | ' + s if s else ''
103 for s in expected_data_docstrings)
104
Barry Warsaw28a691b2010-04-17 00:19:56 +0000105expected_html_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +0000106<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
107<tr bgcolor="#7799ee">
108<td valign=bottom>&nbsp;<br>
109<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
110><td align=right valign=bottom
111><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
112 <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
113<p>
114<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
115<tr bgcolor="#ee77aa">
116<td colspan=3 valign=bottom>&nbsp;<br>
117<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
118\x20\x20\x20\x20
119<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
120<td width="100%%"><dl>
121<dt><font face="helvetica, arial"><a href="builtins.html#object">builtins.object</a>
122</font></dt><dd>
123<dl>
124<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
125</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
126</font></dt></dl>
127</dd>
128</dl>
129 <p>
130<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
131<tr bgcolor="#ffc8d8">
132<td colspan=3 valign=bottom>&nbsp;<br>
133<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>
134\x20\x20\x20\x20
135<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
136<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
137<tr><td>&nbsp;</td>
138<td width="100%%">Methods defined here:<br>
139<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>
140
141<hr>
142Data descriptors defined here:<br>
143<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200144<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000145</dl>
146<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200147<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000148</dl>
149</td></tr></table> <p>
150<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
151<tr bgcolor="#ffc8d8">
152<td colspan=3 valign=bottom>&nbsp;<br>
153<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>
154\x20\x20\x20\x20
155<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
156<td width="100%%">Data descriptors defined here:<br>
157<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200158<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000159</dl>
160<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200161<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000162</dl>
163<hr>
164Data and other attributes defined here:<br>
165<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
166
167</td></tr></table></td></tr></table><p>
168<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
169<tr bgcolor="#eeaa77">
170<td colspan=3 valign=bottom>&nbsp;<br>
171<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
172\x20\x20\x20\x20
173<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
174<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>
175hunger<br>
176lack&nbsp;of&nbsp;Python<br>
177war</tt></dd></dl>
178 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
179</td></tr></table><p>
180<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
181<tr bgcolor="#55aa55">
182<td colspan=3 valign=bottom>&nbsp;<br>
183<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
184\x20\x20\x20\x20
185<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000186<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p>
Georg Brandlb533e262008-05-25 18:19:30 +0000187<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
188<tr bgcolor="#7799ee">
189<td colspan=3 valign=bottom>&nbsp;<br>
190<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
191\x20\x20\x20\x20
192<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
193<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
194<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
195<tr bgcolor="#7799ee">
196<td colspan=3 valign=bottom>&nbsp;<br>
197<font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
198\x20\x20\x20\x20
199<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
200<td width="100%%">Nobody</td></tr></table>
Barry Warsaw28a691b2010-04-17 00:19:56 +0000201""".strip() # ' <- emacs turd
Georg Brandlb533e262008-05-25 18:19:30 +0000202
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200203expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;')
204 for s in expected_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000205
206# output pattern for missing module
207missing_pattern = "no Python documentation found for '%s'"
208
Benjamin Peterson0289b152009-06-28 17:22:03 +0000209# output pattern for module with bad imports
210badimport_pattern = "problem in %s - ImportError: No module named %s"
211
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200212def run_pydoc(module_name, *args, **env):
Georg Brandlb533e262008-05-25 18:19:30 +0000213 """
214 Runs pydoc on the specified module. Returns the stripped
215 output of pydoc.
216 """
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200217 args = args + (module_name,)
Ned Deily92a81a12011-10-06 14:19:03 -0700218 # do not write bytecode files to avoid caching errors
219 rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200220 return out.strip()
Georg Brandlb533e262008-05-25 18:19:30 +0000221
222def get_pydoc_html(module):
223 "Returns pydoc generated output as html"
224 doc = pydoc.HTMLDoc()
225 output = doc.docmodule(module)
226 loc = doc.getdocloc(pydoc_mod) or ""
227 if loc:
228 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
229 return output.strip(), loc
230
231def get_pydoc_text(module):
232 "Returns pydoc generated output as text"
233 doc = pydoc.TextDoc()
234 loc = doc.getdocloc(pydoc_mod) or ""
235 if loc:
236 loc = "\nMODULE DOCS\n " + loc + "\n"
237
238 output = doc.docmodule(module)
239
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000240 # clean up the extra text formatting that pydoc performs
Georg Brandlb533e262008-05-25 18:19:30 +0000241 patt = re.compile('\b.')
242 output = patt.sub('', output)
243 return output.strip(), loc
244
245def print_diffs(text1, text2):
246 "Prints unified diffs for two texts"
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000247 # XXX now obsolete, use unittest built-in support
Georg Brandlb533e262008-05-25 18:19:30 +0000248 lines1 = text1.splitlines(True)
249 lines2 = text2.splitlines(True)
250 diffs = difflib.unified_diff(lines1, lines2, n=0, fromfile='expected',
251 tofile='got')
252 print('\n' + ''.join(diffs))
253
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000254def get_html_title(text):
Nick Coghlanecace282010-12-03 16:08:46 +0000255 # Bit of hack, but good enough for test purposes
256 header, _, _ = text.partition("</head>")
257 _, _, title = header.partition("<title>")
258 title, _, _ = title.partition("</title>")
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000259 return title
260
Georg Brandlb533e262008-05-25 18:19:30 +0000261
Georg Brandld2f38572011-01-30 08:37:19 +0000262class PydocDocTest(unittest.TestCase):
Georg Brandlb533e262008-05-25 18:19:30 +0000263
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_html_doc(self):
267 result, doc_loc = get_pydoc_html(pydoc_mod)
268 mod_file = inspect.getabsfile(pydoc_mod)
Benjamin Petersonc5e94642008-06-14 23:04:46 +0000269 if sys.platform == 'win32':
270 import nturl2path
271 mod_url = nturl2path.pathname2url(mod_file)
272 else:
273 mod_url = mod_file
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200274 expected_html = expected_html_pattern % (
275 (mod_url, mod_file, doc_loc) +
276 expected_html_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000277 if result != expected_html:
278 print_diffs(expected_html, result)
279 self.fail("outputs are not equal, see diff above")
280
R. David Murray378c0cf2010-02-24 01:46:21 +0000281 @unittest.skipIf(sys.flags.optimize >= 2,
282 "Docstrings are omitted with -O2 and above")
Georg Brandlb533e262008-05-25 18:19:30 +0000283 def test_text_doc(self):
284 result, doc_loc = get_pydoc_text(pydoc_mod)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200285 expected_text = expected_text_pattern % (
286 (doc_loc,) +
287 expected_text_data_docstrings +
288 (inspect.getabsfile(pydoc_mod),))
Georg Brandlb533e262008-05-25 18:19:30 +0000289 if result != expected_text:
290 print_diffs(expected_text, result)
291 self.fail("outputs are not equal, see diff above")
292
Brian Curtin49c284c2010-03-31 03:19:28 +0000293 def test_issue8225(self):
294 # Test issue8225 to ensure no doc link appears for xml.etree
295 result, doc_loc = get_pydoc_text(xml.etree)
296 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
297
R David Murrayc43125a2012-04-23 13:23:57 -0400298 def test_non_str_name(self):
299 # issue14638
300 # Treat illegal (non-str) name like no name
301 class A:
302 __name__ = 42
303 class B:
304 pass
305 adoc = pydoc.render_doc(A())
306 bdoc = pydoc.render_doc(B())
307 self.assertEqual(adoc.replace("A", "B"), bdoc)
308
Georg Brandlb533e262008-05-25 18:19:30 +0000309 def test_not_here(self):
310 missing_module = "test.i_am_not_here"
311 result = str(run_pydoc(missing_module), 'ascii')
312 expected = missing_pattern % missing_module
313 self.assertEqual(expected, result,
314 "documentation for missing module found")
315
R. David Murray1f1b9d32009-05-27 20:56:59 +0000316 def test_input_strip(self):
317 missing_module = " test.i_am_not_here "
318 result = str(run_pydoc(missing_module), 'ascii')
319 expected = missing_pattern % missing_module.strip()
320 self.assertEqual(expected, result)
321
Ezio Melotti412c95a2010-02-16 23:31:04 +0000322 def test_stripid(self):
323 # test with strings, other implementations might have different repr()
324 stripid = pydoc.stripid
325 # strip the id
326 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
327 '<function stripid>')
328 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
329 '<function stripid>')
330 # nothing to strip, return the same text
331 self.assertEqual(stripid('42'), '42')
332 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
333 "<type 'exceptions.Exception'>")
334
Georg Brandld80d5f42010-12-03 07:47:22 +0000335 @unittest.skipIf(sys.flags.optimize >= 2,
336 'Docstrings are omitted with -O2 and above')
337 def test_help_output_redirect(self):
338 # issue 940286, if output is set in Helper, then all output from
339 # Helper.help should be redirected
340 old_pattern = expected_text_pattern
341 getpager_old = pydoc.getpager
342 getpager_new = lambda: (lambda x: x)
343 self.maxDiff = None
344
345 buf = StringIO()
346 helper = pydoc.Helper(output=buf)
347 unused, doc_loc = get_pydoc_text(pydoc_mod)
348 module = "test.pydoc_mod"
349 help_header = """
350 Help on module test.pydoc_mod in test:
351
352 """.lstrip()
353 help_header = textwrap.dedent(help_header)
354 expected_help_pattern = help_header + expected_text_pattern
355
356 pydoc.getpager = getpager_new
357 try:
358 with captured_output('stdout') as output, \
359 captured_output('stderr') as err:
360 helper.help(module)
361 result = buf.getvalue().strip()
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200362 expected_text = expected_help_pattern % (
363 (doc_loc,) +
364 expected_text_data_docstrings +
365 (inspect.getabsfile(pydoc_mod),))
Georg Brandld80d5f42010-12-03 07:47:22 +0000366 self.assertEqual('', output.getvalue())
367 self.assertEqual('', err.getvalue())
368 self.assertEqual(expected_text, result)
369 finally:
370 pydoc.getpager = getpager_old
371
Raymond Hettinger1103d052011-03-25 14:15:24 -0700372 def test_namedtuple_public_underscore(self):
373 NT = namedtuple('NT', ['abc', 'def'], rename=True)
374 with captured_stdout() as help_io:
375 help(NT)
376 helptext = help_io.getvalue()
377 self.assertIn('_1', helptext)
378 self.assertIn('_replace', helptext)
379 self.assertIn('_asdict', helptext)
380
Victor Stinnere6c910e2011-06-30 15:55:43 +0200381 def test_synopsis(self):
382 self.addCleanup(unlink, TESTFN)
383 for encoding in ('ISO-8859-1', 'UTF-8'):
384 with open(TESTFN, 'w', encoding=encoding) as script:
385 if encoding != 'UTF-8':
386 print('#coding: {}'.format(encoding), file=script)
387 print('"""line 1: h\xe9', file=script)
388 print('line 2: hi"""', file=script)
389 synopsis = pydoc.synopsis(TESTFN, {})
390 self.assertEqual(synopsis, 'line 1: h\xe9')
391
R David Murray9929bc52013-03-19 02:31:06 -0400392 def test_allmethods(self):
393 # issue 17476: allmethods was no longer returning unbound methods.
394 # This test is a bit fragile in the face of changes to object and type,
395 # but I can't think of a better way to do it without duplicating the
396 # logic of the function under test.
397
398 class TestClass(object):
399 def method_returning_true(self):
400 return True
401
402 # What we expect to get back: everything on object...
403 expected = dict(vars(object))
404 # ...plus our unbound method...
405 expected['method_returning_true'] = TestClass.method_returning_true
406 # ...but not the non-methods on object.
407 del expected['__doc__']
408 del expected['__class__']
409 # inspect resolves descriptors on type into methods, but vars doesn't,
410 # so we need to update __subclasshook__.
411 expected['__subclasshook__'] = TestClass.__subclasshook__
412
413 methods = pydoc.allmethods(TestClass)
414 self.assertDictEqual(methods, expected)
415
Georg Brandlb533e262008-05-25 18:19:30 +0000416
Ned Deily92a81a12011-10-06 14:19:03 -0700417class PydocImportTest(unittest.TestCase):
418
419 def setUp(self):
420 self.test_dir = os.mkdir(TESTFN)
421 self.addCleanup(rmtree, TESTFN)
422
423 def test_badimport(self):
424 # This tests the fix for issue 5230, where if pydoc found the module
425 # but the module had an internal import error pydoc would report no doc
426 # found.
427 modname = 'testmod_xyzzy'
428 testpairs = (
429 ('i_am_not_here', 'i_am_not_here'),
430 ('test.i_am_not_here_either', 'i_am_not_here_either'),
431 ('test.i_am_not_here.neither_am_i', 'i_am_not_here.neither_am_i'),
432 ('i_am_not_here.{}'.format(modname),
433 'i_am_not_here.{}'.format(modname)),
434 ('test.{}'.format(modname), modname),
435 )
436
437 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
438 for importstring, expectedinmsg in testpairs:
439 with open(sourcefn, 'w') as f:
440 f.write("import {}\n".format(importstring))
441 result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii")
442 expected = badimport_pattern % (modname, expectedinmsg)
443 self.assertEqual(expected, result)
444
445 def test_apropos_with_bad_package(self):
446 # Issue 7425 - pydoc -k failed when bad package on path
447 pkgdir = os.path.join(TESTFN, "syntaxerr")
448 os.mkdir(pkgdir)
449 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
450 with open(badsyntax, 'w') as f:
451 f.write("invalid python syntax = $1\n")
Ned Deily34294912012-02-03 23:14:37 +0100452 result = run_pydoc('zqwykjv', '-k', PYTHONPATH=TESTFN)
Ned Deily92a81a12011-10-06 14:19:03 -0700453 self.assertEqual(b'', result)
454
455 def test_apropos_with_unreadable_dir(self):
456 # Issue 7367 - pydoc -k failed when unreadable dir on path
457 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
458 os.mkdir(self.unreadable_dir, 0)
459 self.addCleanup(os.rmdir, self.unreadable_dir)
460 # Note, on Windows the directory appears to be still
461 # readable so this is not really testing the issue there
Ned Deily34294912012-02-03 23:14:37 +0100462 result = run_pydoc('zqwykjv', '-k', PYTHONPATH=TESTFN)
Ned Deily92a81a12011-10-06 14:19:03 -0700463 self.assertEqual(b'', result)
464
465
Georg Brandlb533e262008-05-25 18:19:30 +0000466class TestDescriptions(unittest.TestCase):
467
468 def test_module(self):
469 # Check that pydocfodder module can be described
470 from test import pydocfodder
471 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000472 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000473
Georg Brandlb533e262008-05-25 18:19:30 +0000474 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000475 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +0000476 c = C()
477
478 self.assertEqual(pydoc.describe(C), 'class C')
479 self.assertEqual(pydoc.describe(c), 'C')
480 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000481 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000482
Éric Araujoe64e51b2011-07-29 17:03:55 +0200483 def test_builtin(self):
484 for name in ('str', 'str.translate', 'builtins.str',
485 'builtins.str.translate'):
486 # test low-level function
487 self.assertIsNotNone(pydoc.locate(name))
488 # test high-level function
489 try:
490 pydoc.render_doc(name)
491 except ImportError:
492 self.fail('finding the doc of {!r} failed'.format(o))
493
494 for name in ('notbuiltins', 'strrr', 'strr.translate',
495 'str.trrrranslate', 'builtins.strrr',
496 'builtins.str.trrranslate'):
497 self.assertIsNone(pydoc.locate(name))
498 self.assertRaises(ImportError, pydoc.render_doc, name)
499
Georg Brandlb533e262008-05-25 18:19:30 +0000500
Victor Stinner62a68f22011-05-20 02:29:13 +0200501@unittest.skipUnless(threading, 'Threading required for this test.')
Georg Brandld2f38572011-01-30 08:37:19 +0000502class PydocServerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000503 """Tests for pydoc._start_server"""
504
505 def test_server(self):
506
507 # Minimal test that starts the server, then stops it.
508 def my_url_handler(url, content_type):
509 text = 'the URL sent was: (%s, %s)' % (url, content_type)
510 return text
511
512 serverthread = pydoc._start_server(my_url_handler, port=0)
513 starttime = time.time()
514 timeout = 1 #seconds
515
516 while serverthread.serving:
517 time.sleep(.01)
518 if serverthread.serving and time.time() - starttime > timeout:
519 serverthread.stop()
520 break
521
522 self.assertEqual(serverthread.error, None)
523
524
Georg Brandld2f38572011-01-30 08:37:19 +0000525class PydocUrlHandlerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000526 """Tests for pydoc._url_handler"""
527
528 def test_content_type_err(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000529 f = pydoc._url_handler
Georg Brandld2f38572011-01-30 08:37:19 +0000530 self.assertRaises(TypeError, f, 'A', '')
531 self.assertRaises(TypeError, f, 'B', 'foobar')
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000532
533 def test_url_requests(self):
534 # Test for the correct title in the html pages returned.
535 # This tests the different parts of the URL handler without
536 # getting too picky about the exact html.
537 requests = [
Georg Brandld2f38572011-01-30 08:37:19 +0000538 ("", "Pydoc: Index of Modules"),
539 ("get?key=", "Pydoc: Index of Modules"),
540 ("index", "Pydoc: Index of Modules"),
541 ("topics", "Pydoc: Topics"),
542 ("keywords", "Pydoc: Keywords"),
543 ("pydoc", "Pydoc: module pydoc"),
544 ("get?key=pydoc", "Pydoc: module pydoc"),
545 ("search?key=pydoc", "Pydoc: Search Results"),
546 ("topic?key=def", "Pydoc: KEYWORD def"),
547 ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
548 ("foobar", "Pydoc: Error - foobar"),
549 ("getfile?key=foobar", "Pydoc: Error - getfile?key=foobar"),
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000550 ]
551
552 for url, title in requests:
553 text = pydoc._url_handler(url, "text/html")
554 result = get_html_title(text)
555 self.assertEqual(result, title)
556
557 path = string.__file__
Georg Brandld2f38572011-01-30 08:37:19 +0000558 title = "Pydoc: getfile " + path
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000559 url = "getfile?key=" + path
560 text = pydoc._url_handler(url, "text/html")
561 result = get_html_title(text)
562 self.assertEqual(result, title)
563
564
Ezio Melottib185a042011-04-28 07:42:55 +0300565class TestHelper(unittest.TestCase):
566 def test_keywords(self):
567 self.assertEqual(sorted(pydoc.Helper.keywords),
568 sorted(keyword.kwlist))
569
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200570@reap_threads
Georg Brandlb533e262008-05-25 18:19:30 +0000571def test_main():
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200572 try:
573 test.support.run_unittest(PydocDocTest,
Ned Deily92a81a12011-10-06 14:19:03 -0700574 PydocImportTest,
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200575 TestDescriptions,
576 PydocServerTest,
577 PydocUrlHandlerTest,
578 TestHelper,
579 )
580 finally:
581 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +0000582
583if __name__ == "__main__":
584 test_main()