blob: 8e2001ba5f77df22a4e697672984abcc18a67282 [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
Barry Warsaw28a691b2010-04-17 00:19:56 +000033expected_text_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000034NAME
35 test.pydoc_mod - This is a test module for test_pydoc
Georg Brandlb533e262008-05-25 18:19:30 +000036%s
37CLASSES
38 builtins.object
39 A
40 B
41\x20\x20\x20\x20
42 class A(builtins.object)
43 | Hello and goodbye
44 |\x20\x20
45 | Methods defined here:
46 |\x20\x20
47 | __init__()
48 | Wow, I have no function!
49 |\x20\x20
50 | ----------------------------------------------------------------------
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\x20\x20
59 class B(builtins.object)
60 | Data descriptors defined here:
61 |\x20\x20
62 | __dict__
63 | dictionary for instance variables (if defined)
64 |\x20\x20
65 | __weakref__
66 | list of weak references to the object (if defined)
67 |\x20\x20
68 | ----------------------------------------------------------------------
69 | Data and other attributes defined here:
70 |\x20\x20
71 | NO_MEANING = 'eggs'
72
73FUNCTIONS
74 doc_func()
75 This function solves all of the world's problems:
76 hunger
77 lack of Python
78 war
79\x20\x20\x20\x20
80 nodoc_func()
81
82DATA
Alexander Belopolskya47bbf52010-11-18 01:52:54 +000083 __xyz__ = 'X, Y and Z'
Georg Brandlb533e262008-05-25 18:19:30 +000084
85VERSION
86 1.2.3.4
87
88AUTHOR
89 Benjamin Peterson
90
91CREDITS
92 Nobody
Alexander Belopolskya47bbf52010-11-18 01:52:54 +000093
94FILE
95 %s
Georg Brandlb533e262008-05-25 18:19:30 +000096""".strip()
97
Barry Warsaw28a691b2010-04-17 00:19:56 +000098expected_html_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000099<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
100<tr bgcolor="#7799ee">
101<td valign=bottom>&nbsp;<br>
102<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
103><td align=right valign=bottom
104><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
105 <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
106<p>
107<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
108<tr bgcolor="#ee77aa">
109<td colspan=3 valign=bottom>&nbsp;<br>
110<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
111\x20\x20\x20\x20
112<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
113<td width="100%%"><dl>
114<dt><font face="helvetica, arial"><a href="builtins.html#object">builtins.object</a>
115</font></dt><dd>
116<dl>
117<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
118</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
119</font></dt></dl>
120</dd>
121</dl>
122 <p>
123<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
124<tr bgcolor="#ffc8d8">
125<td colspan=3 valign=bottom>&nbsp;<br>
126<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>
127\x20\x20\x20\x20
128<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
129<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
130<tr><td>&nbsp;</td>
131<td width="100%%">Methods defined here:<br>
132<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>
133
134<hr>
135Data descriptors defined here:<br>
136<dl><dt><strong>__dict__</strong></dt>
137<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
138</dl>
139<dl><dt><strong>__weakref__</strong></dt>
140<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
141</dl>
142</td></tr></table> <p>
143<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
144<tr bgcolor="#ffc8d8">
145<td colspan=3 valign=bottom>&nbsp;<br>
146<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>
147\x20\x20\x20\x20
148<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
149<td width="100%%">Data descriptors defined here:<br>
150<dl><dt><strong>__dict__</strong></dt>
151<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
152</dl>
153<dl><dt><strong>__weakref__</strong></dt>
154<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
155</dl>
156<hr>
157Data and other attributes defined here:<br>
158<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
159
160</td></tr></table></td></tr></table><p>
161<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
162<tr bgcolor="#eeaa77">
163<td colspan=3 valign=bottom>&nbsp;<br>
164<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
165\x20\x20\x20\x20
166<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
167<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>
168hunger<br>
169lack&nbsp;of&nbsp;Python<br>
170war</tt></dd></dl>
171 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
172</td></tr></table><p>
173<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
174<tr bgcolor="#55aa55">
175<td colspan=3 valign=bottom>&nbsp;<br>
176<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
177\x20\x20\x20\x20
178<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000179<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p>
Georg Brandlb533e262008-05-25 18:19:30 +0000180<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
181<tr bgcolor="#7799ee">
182<td colspan=3 valign=bottom>&nbsp;<br>
183<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
184\x20\x20\x20\x20
185<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
186<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
187<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>Credits</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%%">Nobody</td></tr></table>
Barry Warsaw28a691b2010-04-17 00:19:56 +0000194""".strip() # ' <- emacs turd
Georg Brandlb533e262008-05-25 18:19:30 +0000195
196
197# output pattern for missing module
198missing_pattern = "no Python documentation found for '%s'"
199
Benjamin Peterson0289b152009-06-28 17:22:03 +0000200# output pattern for module with bad imports
Victor Stinner98dbba52011-03-14 15:15:47 -0400201badimport_pattern = "problem in %s - ImportError: No module named %r"
Benjamin Peterson0289b152009-06-28 17:22:03 +0000202
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200203def run_pydoc(module_name, *args, **env):
Georg Brandlb533e262008-05-25 18:19:30 +0000204 """
205 Runs pydoc on the specified module. Returns the stripped
206 output of pydoc.
207 """
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200208 args = args + (module_name,)
Ned Deily92a81a12011-10-06 14:19:03 -0700209 # do not write bytecode files to avoid caching errors
210 rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200211 return out.strip()
Georg Brandlb533e262008-05-25 18:19:30 +0000212
213def get_pydoc_html(module):
214 "Returns pydoc generated output as html"
215 doc = pydoc.HTMLDoc()
216 output = doc.docmodule(module)
217 loc = doc.getdocloc(pydoc_mod) or ""
218 if loc:
219 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
220 return output.strip(), loc
221
222def get_pydoc_text(module):
223 "Returns pydoc generated output as text"
224 doc = pydoc.TextDoc()
225 loc = doc.getdocloc(pydoc_mod) or ""
226 if loc:
227 loc = "\nMODULE DOCS\n " + loc + "\n"
228
229 output = doc.docmodule(module)
230
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000231 # clean up the extra text formatting that pydoc performs
Georg Brandlb533e262008-05-25 18:19:30 +0000232 patt = re.compile('\b.')
233 output = patt.sub('', output)
234 return output.strip(), loc
235
236def print_diffs(text1, text2):
237 "Prints unified diffs for two texts"
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000238 # XXX now obsolete, use unittest built-in support
Ezio Melottid8b509b2011-09-28 17:37:55 +0300239 lines1 = text1.splitlines(keepends=True)
240 lines2 = text2.splitlines(keepends=True)
Georg Brandlb533e262008-05-25 18:19:30 +0000241 diffs = difflib.unified_diff(lines1, lines2, n=0, fromfile='expected',
242 tofile='got')
243 print('\n' + ''.join(diffs))
244
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000245def get_html_title(text):
Nick Coghlanecace282010-12-03 16:08:46 +0000246 # Bit of hack, but good enough for test purposes
247 header, _, _ = text.partition("</head>")
248 _, _, title = header.partition("<title>")
249 title, _, _ = title.partition("</title>")
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000250 return title
251
Georg Brandlb533e262008-05-25 18:19:30 +0000252
Georg Brandld2f38572011-01-30 08:37:19 +0000253class PydocDocTest(unittest.TestCase):
Georg Brandlb533e262008-05-25 18:19:30 +0000254
R. David Murray378c0cf2010-02-24 01:46:21 +0000255 @unittest.skipIf(sys.flags.optimize >= 2,
256 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000257 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
258 'trace function introduces __locals__ unexpectedly')
Georg Brandlb533e262008-05-25 18:19:30 +0000259 def test_html_doc(self):
260 result, doc_loc = get_pydoc_html(pydoc_mod)
261 mod_file = inspect.getabsfile(pydoc_mod)
Benjamin Petersonc5e94642008-06-14 23:04:46 +0000262 if sys.platform == 'win32':
263 import nturl2path
264 mod_url = nturl2path.pathname2url(mod_file)
265 else:
266 mod_url = mod_file
267 expected_html = expected_html_pattern % (mod_url, mod_file, doc_loc)
Georg Brandlb533e262008-05-25 18:19:30 +0000268 if result != expected_html:
269 print_diffs(expected_html, result)
270 self.fail("outputs are not equal, see diff above")
271
R. David Murray378c0cf2010-02-24 01:46:21 +0000272 @unittest.skipIf(sys.flags.optimize >= 2,
273 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000274 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
275 'trace function introduces __locals__ unexpectedly')
Georg Brandlb533e262008-05-25 18:19:30 +0000276 def test_text_doc(self):
277 result, doc_loc = get_pydoc_text(pydoc_mod)
278 expected_text = expected_text_pattern % \
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000279 (doc_loc, inspect.getabsfile(pydoc_mod))
Georg Brandlb533e262008-05-25 18:19:30 +0000280 if result != expected_text:
281 print_diffs(expected_text, result)
282 self.fail("outputs are not equal, see diff above")
283
Brian Curtin49c284c2010-03-31 03:19:28 +0000284 def test_issue8225(self):
285 # Test issue8225 to ensure no doc link appears for xml.etree
286 result, doc_loc = get_pydoc_text(xml.etree)
287 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
288
R David Murrayc43125a2012-04-23 13:23:57 -0400289 def test_non_str_name(self):
290 # issue14638
291 # Treat illegal (non-str) name like no name
292 class A:
293 __name__ = 42
294 class B:
295 pass
296 adoc = pydoc.render_doc(A())
297 bdoc = pydoc.render_doc(B())
298 self.assertEqual(adoc.replace("A", "B"), bdoc)
299
Georg Brandlb533e262008-05-25 18:19:30 +0000300 def test_not_here(self):
301 missing_module = "test.i_am_not_here"
302 result = str(run_pydoc(missing_module), 'ascii')
303 expected = missing_pattern % missing_module
304 self.assertEqual(expected, result,
305 "documentation for missing module found")
306
R. David Murray1f1b9d32009-05-27 20:56:59 +0000307 def test_input_strip(self):
308 missing_module = " test.i_am_not_here "
309 result = str(run_pydoc(missing_module), 'ascii')
310 expected = missing_pattern % missing_module.strip()
311 self.assertEqual(expected, result)
312
Ezio Melotti412c95a2010-02-16 23:31:04 +0000313 def test_stripid(self):
314 # test with strings, other implementations might have different repr()
315 stripid = pydoc.stripid
316 # strip the id
317 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
318 '<function stripid>')
319 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
320 '<function stripid>')
321 # nothing to strip, return the same text
322 self.assertEqual(stripid('42'), '42')
323 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
324 "<type 'exceptions.Exception'>")
325
Georg Brandld80d5f42010-12-03 07:47:22 +0000326 @unittest.skipIf(sys.flags.optimize >= 2,
327 'Docstrings are omitted with -O2 and above')
Brett Cannon7a540732011-02-22 03:04:06 +0000328 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
329 'trace function introduces __locals__ unexpectedly')
Georg Brandld80d5f42010-12-03 07:47:22 +0000330 def test_help_output_redirect(self):
331 # issue 940286, if output is set in Helper, then all output from
332 # Helper.help should be redirected
333 old_pattern = expected_text_pattern
334 getpager_old = pydoc.getpager
335 getpager_new = lambda: (lambda x: x)
336 self.maxDiff = None
337
338 buf = StringIO()
339 helper = pydoc.Helper(output=buf)
340 unused, doc_loc = get_pydoc_text(pydoc_mod)
341 module = "test.pydoc_mod"
342 help_header = """
343 Help on module test.pydoc_mod in test:
344
345 """.lstrip()
346 help_header = textwrap.dedent(help_header)
347 expected_help_pattern = help_header + expected_text_pattern
348
349 pydoc.getpager = getpager_new
350 try:
351 with captured_output('stdout') as output, \
352 captured_output('stderr') as err:
353 helper.help(module)
354 result = buf.getvalue().strip()
355 expected_text = expected_help_pattern % \
356 (doc_loc, inspect.getabsfile(pydoc_mod))
357 self.assertEqual('', output.getvalue())
358 self.assertEqual('', err.getvalue())
359 self.assertEqual(expected_text, result)
360 finally:
361 pydoc.getpager = getpager_old
362
Raymond Hettinger1103d052011-03-25 14:15:24 -0700363 def test_namedtuple_public_underscore(self):
364 NT = namedtuple('NT', ['abc', 'def'], rename=True)
365 with captured_stdout() as help_io:
366 help(NT)
367 helptext = help_io.getvalue()
368 self.assertIn('_1', helptext)
369 self.assertIn('_replace', helptext)
370 self.assertIn('_asdict', helptext)
371
Victor Stinnere6c910e2011-06-30 15:55:43 +0200372 def test_synopsis(self):
373 self.addCleanup(unlink, TESTFN)
374 for encoding in ('ISO-8859-1', 'UTF-8'):
375 with open(TESTFN, 'w', encoding=encoding) as script:
376 if encoding != 'UTF-8':
377 print('#coding: {}'.format(encoding), file=script)
378 print('"""line 1: h\xe9', file=script)
379 print('line 2: hi"""', file=script)
380 synopsis = pydoc.synopsis(TESTFN, {})
381 self.assertEqual(synopsis, 'line 1: h\xe9')
382
Georg Brandlb533e262008-05-25 18:19:30 +0000383
Ned Deily92a81a12011-10-06 14:19:03 -0700384class PydocImportTest(unittest.TestCase):
385
386 def setUp(self):
387 self.test_dir = os.mkdir(TESTFN)
388 self.addCleanup(rmtree, TESTFN)
389
390 def test_badimport(self):
391 # This tests the fix for issue 5230, where if pydoc found the module
392 # but the module had an internal import error pydoc would report no doc
393 # found.
394 modname = 'testmod_xyzzy'
395 testpairs = (
396 ('i_am_not_here', 'i_am_not_here'),
Brett Cannonfd074152012-04-14 14:10:13 -0400397 ('test.i_am_not_here_either', 'test.i_am_not_here_either'),
398 ('test.i_am_not_here.neither_am_i', 'test.i_am_not_here'),
399 ('i_am_not_here.{}'.format(modname), 'i_am_not_here'),
400 ('test.{}'.format(modname), 'test.{}'.format(modname)),
Ned Deily92a81a12011-10-06 14:19:03 -0700401 )
402
403 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
404 for importstring, expectedinmsg in testpairs:
405 with open(sourcefn, 'w') as f:
406 f.write("import {}\n".format(importstring))
407 result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii")
408 expected = badimport_pattern % (modname, expectedinmsg)
409 self.assertEqual(expected, result)
410
411 def test_apropos_with_bad_package(self):
412 # Issue 7425 - pydoc -k failed when bad package on path
413 pkgdir = os.path.join(TESTFN, "syntaxerr")
414 os.mkdir(pkgdir)
415 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
416 with open(badsyntax, 'w') as f:
417 f.write("invalid python syntax = $1\n")
Ned Deily34294912012-02-03 23:14:37 +0100418 result = run_pydoc('zqwykjv', '-k', PYTHONPATH=TESTFN)
Ned Deily92a81a12011-10-06 14:19:03 -0700419 self.assertEqual(b'', result)
420
421 def test_apropos_with_unreadable_dir(self):
422 # Issue 7367 - pydoc -k failed when unreadable dir on path
423 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
424 os.mkdir(self.unreadable_dir, 0)
425 self.addCleanup(os.rmdir, self.unreadable_dir)
426 # Note, on Windows the directory appears to be still
427 # readable so this is not really testing the issue there
Ned Deily34294912012-02-03 23:14:37 +0100428 result = run_pydoc('zqwykjv', '-k', PYTHONPATH=TESTFN)
Ned Deily92a81a12011-10-06 14:19:03 -0700429 self.assertEqual(b'', result)
430
431
Georg Brandlb533e262008-05-25 18:19:30 +0000432class TestDescriptions(unittest.TestCase):
433
434 def test_module(self):
435 # Check that pydocfodder module can be described
436 from test import pydocfodder
437 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000438 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000439
Georg Brandlb533e262008-05-25 18:19:30 +0000440 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000441 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +0000442 c = C()
443
444 self.assertEqual(pydoc.describe(C), 'class C')
445 self.assertEqual(pydoc.describe(c), 'C')
446 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000447 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000448
Éric Araujoe64e51b2011-07-29 17:03:55 +0200449 def test_builtin(self):
450 for name in ('str', 'str.translate', 'builtins.str',
451 'builtins.str.translate'):
452 # test low-level function
453 self.assertIsNotNone(pydoc.locate(name))
454 # test high-level function
455 try:
456 pydoc.render_doc(name)
457 except ImportError:
458 self.fail('finding the doc of {!r} failed'.format(o))
459
460 for name in ('notbuiltins', 'strrr', 'strr.translate',
461 'str.trrrranslate', 'builtins.strrr',
462 'builtins.str.trrranslate'):
463 self.assertIsNone(pydoc.locate(name))
464 self.assertRaises(ImportError, pydoc.render_doc, name)
465
Georg Brandlb533e262008-05-25 18:19:30 +0000466
Victor Stinner62a68f22011-05-20 02:29:13 +0200467@unittest.skipUnless(threading, 'Threading required for this test.')
Georg Brandld2f38572011-01-30 08:37:19 +0000468class PydocServerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000469 """Tests for pydoc._start_server"""
470
471 def test_server(self):
472
473 # Minimal test that starts the server, then stops it.
474 def my_url_handler(url, content_type):
475 text = 'the URL sent was: (%s, %s)' % (url, content_type)
476 return text
477
478 serverthread = pydoc._start_server(my_url_handler, port=0)
479 starttime = time.time()
480 timeout = 1 #seconds
481
482 while serverthread.serving:
483 time.sleep(.01)
484 if serverthread.serving and time.time() - starttime > timeout:
485 serverthread.stop()
486 break
487
488 self.assertEqual(serverthread.error, None)
489
490
Georg Brandld2f38572011-01-30 08:37:19 +0000491class PydocUrlHandlerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000492 """Tests for pydoc._url_handler"""
493
494 def test_content_type_err(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000495 f = pydoc._url_handler
Georg Brandld2f38572011-01-30 08:37:19 +0000496 self.assertRaises(TypeError, f, 'A', '')
497 self.assertRaises(TypeError, f, 'B', 'foobar')
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000498
499 def test_url_requests(self):
500 # Test for the correct title in the html pages returned.
501 # This tests the different parts of the URL handler without
502 # getting too picky about the exact html.
503 requests = [
Georg Brandld2f38572011-01-30 08:37:19 +0000504 ("", "Pydoc: Index of Modules"),
505 ("get?key=", "Pydoc: Index of Modules"),
506 ("index", "Pydoc: Index of Modules"),
507 ("topics", "Pydoc: Topics"),
508 ("keywords", "Pydoc: Keywords"),
509 ("pydoc", "Pydoc: module pydoc"),
510 ("get?key=pydoc", "Pydoc: module pydoc"),
511 ("search?key=pydoc", "Pydoc: Search Results"),
512 ("topic?key=def", "Pydoc: KEYWORD def"),
513 ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
514 ("foobar", "Pydoc: Error - foobar"),
515 ("getfile?key=foobar", "Pydoc: Error - getfile?key=foobar"),
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000516 ]
517
518 for url, title in requests:
519 text = pydoc._url_handler(url, "text/html")
520 result = get_html_title(text)
521 self.assertEqual(result, title)
522
523 path = string.__file__
Georg Brandld2f38572011-01-30 08:37:19 +0000524 title = "Pydoc: getfile " + path
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000525 url = "getfile?key=" + path
526 text = pydoc._url_handler(url, "text/html")
527 result = get_html_title(text)
528 self.assertEqual(result, title)
529
530
Ezio Melottib185a042011-04-28 07:42:55 +0300531class TestHelper(unittest.TestCase):
532 def test_keywords(self):
533 self.assertEqual(sorted(pydoc.Helper.keywords),
534 sorted(keyword.kwlist))
535
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200536@reap_threads
Georg Brandlb533e262008-05-25 18:19:30 +0000537def test_main():
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200538 try:
539 test.support.run_unittest(PydocDocTest,
Ned Deily92a81a12011-10-06 14:19:03 -0700540 PydocImportTest,
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200541 TestDescriptions,
542 PydocServerTest,
543 PydocUrlHandlerTest,
544 TestHelper,
545 )
546 finally:
547 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +0000548
549if __name__ == "__main__":
550 test_main()