blob: 6d3923f28ee3795c47acdddee78ed52778b6371b [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
10import subprocess
Georg Brandlb533e262008-05-25 18:19:30 +000011import test.support
Nick Coghlan7bb30b72010-12-03 09:29:11 +000012import time
13import unittest
Brian Curtin49c284c2010-03-31 03:19:28 +000014import xml.etree
Georg Brandld80d5f42010-12-03 07:47:22 +000015import textwrap
16from io import StringIO
Raymond Hettinger1103d052011-03-25 14:15:24 -070017from collections import namedtuple
Benjamin Peterson0289b152009-06-28 17:22:03 +000018from contextlib import contextmanager
Georg Brandlb533e262008-05-25 18:19:30 +000019
Antoine Pitrouf7f54752011-07-15 22:42:12 +020020from test.script_helper import assert_python_ok
Antoine Pitroua6e81a22011-07-15 22:32:25 +020021from test.support import (
22 TESTFN, forget, rmtree, EnvironmentVarGuard,
23 reap_children, reap_threads, captured_output, captured_stdout, unlink
24)
Georg Brandlb533e262008-05-25 18:19:30 +000025from test import pydoc_mod
26
Victor Stinner62a68f22011-05-20 02:29:13 +020027try:
28 import threading
29except ImportError:
30 threading = None
31
Florent Xicluna085a6562010-03-06 14:04:16 +000032# Just in case sys.modules["test"] has the optional attribute __loader__.
33if hasattr(pydoc_mod, "__loader__"):
34 del pydoc_mod.__loader__
35
Barry Warsaw28a691b2010-04-17 00:19:56 +000036expected_text_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000037NAME
38 test.pydoc_mod - This is a test module for test_pydoc
Georg Brandlb533e262008-05-25 18:19:30 +000039%s
40CLASSES
41 builtins.object
42 A
43 B
44\x20\x20\x20\x20
45 class A(builtins.object)
46 | Hello and goodbye
47 |\x20\x20
48 | Methods defined here:
49 |\x20\x20
50 | __init__()
51 | Wow, I have no function!
52 |\x20\x20
53 | ----------------------------------------------------------------------
54 | Data descriptors defined here:
55 |\x20\x20
56 | __dict__
57 | dictionary for instance variables (if defined)
58 |\x20\x20
59 | __weakref__
60 | list of weak references to the object (if defined)
61\x20\x20\x20\x20
62 class B(builtins.object)
63 | Data descriptors defined here:
64 |\x20\x20
65 | __dict__
66 | dictionary for instance variables (if defined)
67 |\x20\x20
68 | __weakref__
69 | list of weak references to the object (if defined)
70 |\x20\x20
71 | ----------------------------------------------------------------------
72 | Data and other attributes defined here:
73 |\x20\x20
74 | NO_MEANING = 'eggs'
75
76FUNCTIONS
77 doc_func()
78 This function solves all of the world's problems:
79 hunger
80 lack of Python
81 war
82\x20\x20\x20\x20
83 nodoc_func()
84
85DATA
Alexander Belopolskya47bbf52010-11-18 01:52:54 +000086 __xyz__ = 'X, Y and Z'
Georg Brandlb533e262008-05-25 18:19:30 +000087
88VERSION
89 1.2.3.4
90
91AUTHOR
92 Benjamin Peterson
93
94CREDITS
95 Nobody
Alexander Belopolskya47bbf52010-11-18 01:52:54 +000096
97FILE
98 %s
Georg Brandlb533e262008-05-25 18:19:30 +000099""".strip()
100
Barry Warsaw28a691b2010-04-17 00:19:56 +0000101expected_html_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +0000102<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
103<tr bgcolor="#7799ee">
104<td valign=bottom>&nbsp;<br>
105<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
106><td align=right valign=bottom
107><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
108 <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
109<p>
110<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
111<tr bgcolor="#ee77aa">
112<td colspan=3 valign=bottom>&nbsp;<br>
113<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
114\x20\x20\x20\x20
115<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
116<td width="100%%"><dl>
117<dt><font face="helvetica, arial"><a href="builtins.html#object">builtins.object</a>
118</font></dt><dd>
119<dl>
120<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
121</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
122</font></dt></dl>
123</dd>
124</dl>
125 <p>
126<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
127<tr bgcolor="#ffc8d8">
128<td colspan=3 valign=bottom>&nbsp;<br>
129<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>
130\x20\x20\x20\x20
131<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
132<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
133<tr><td>&nbsp;</td>
134<td width="100%%">Methods defined here:<br>
135<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>
136
137<hr>
138Data descriptors defined here:<br>
139<dl><dt><strong>__dict__</strong></dt>
140<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
141</dl>
142<dl><dt><strong>__weakref__</strong></dt>
143<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
144</dl>
145</td></tr></table> <p>
146<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
147<tr bgcolor="#ffc8d8">
148<td colspan=3 valign=bottom>&nbsp;<br>
149<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>
150\x20\x20\x20\x20
151<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
152<td width="100%%">Data descriptors defined here:<br>
153<dl><dt><strong>__dict__</strong></dt>
154<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
155</dl>
156<dl><dt><strong>__weakref__</strong></dt>
157<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
158</dl>
159<hr>
160Data and other attributes defined here:<br>
161<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
162
163</td></tr></table></td></tr></table><p>
164<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
165<tr bgcolor="#eeaa77">
166<td colspan=3 valign=bottom>&nbsp;<br>
167<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
168\x20\x20\x20\x20
169<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
170<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>
171hunger<br>
172lack&nbsp;of&nbsp;Python<br>
173war</tt></dd></dl>
174 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
175</td></tr></table><p>
176<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
177<tr bgcolor="#55aa55">
178<td colspan=3 valign=bottom>&nbsp;<br>
179<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
180\x20\x20\x20\x20
181<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000182<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p>
Georg Brandlb533e262008-05-25 18:19:30 +0000183<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
184<tr bgcolor="#7799ee">
185<td colspan=3 valign=bottom>&nbsp;<br>
186<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
187\x20\x20\x20\x20
188<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
189<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
190<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
191<tr bgcolor="#7799ee">
192<td colspan=3 valign=bottom>&nbsp;<br>
193<font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
194\x20\x20\x20\x20
195<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
196<td width="100%%">Nobody</td></tr></table>
Barry Warsaw28a691b2010-04-17 00:19:56 +0000197""".strip() # ' <- emacs turd
Georg Brandlb533e262008-05-25 18:19:30 +0000198
199
200# output pattern for missing module
201missing_pattern = "no Python documentation found for '%s'"
202
Benjamin Peterson0289b152009-06-28 17:22:03 +0000203# output pattern for module with bad imports
Victor Stinner98dbba52011-03-14 15:15:47 -0400204badimport_pattern = "problem in %s - ImportError: No module named %r"
Benjamin Peterson0289b152009-06-28 17:22:03 +0000205
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200206def run_pydoc(module_name, *args, **env):
Georg Brandlb533e262008-05-25 18:19:30 +0000207 """
208 Runs pydoc on the specified module. Returns the stripped
209 output of pydoc.
210 """
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200211 args = args + (module_name,)
212 rc, out, err = assert_python_ok(pydoc.__file__, *args, **env)
213 return out.strip()
Georg Brandlb533e262008-05-25 18:19:30 +0000214
215def get_pydoc_html(module):
216 "Returns pydoc generated output as html"
217 doc = pydoc.HTMLDoc()
218 output = doc.docmodule(module)
219 loc = doc.getdocloc(pydoc_mod) or ""
220 if loc:
221 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
222 return output.strip(), loc
223
224def get_pydoc_text(module):
225 "Returns pydoc generated output as text"
226 doc = pydoc.TextDoc()
227 loc = doc.getdocloc(pydoc_mod) or ""
228 if loc:
229 loc = "\nMODULE DOCS\n " + loc + "\n"
230
231 output = doc.docmodule(module)
232
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000233 # clean up the extra text formatting that pydoc performs
Georg Brandlb533e262008-05-25 18:19:30 +0000234 patt = re.compile('\b.')
235 output = patt.sub('', output)
236 return output.strip(), loc
237
238def print_diffs(text1, text2):
239 "Prints unified diffs for two texts"
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000240 # XXX now obsolete, use unittest built-in support
Ezio Melottid8b509b2011-09-28 17:37:55 +0300241 lines1 = text1.splitlines(keepends=True)
242 lines2 = text2.splitlines(keepends=True)
Georg Brandlb533e262008-05-25 18:19:30 +0000243 diffs = difflib.unified_diff(lines1, lines2, n=0, fromfile='expected',
244 tofile='got')
245 print('\n' + ''.join(diffs))
246
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000247def get_html_title(text):
Nick Coghlanecace282010-12-03 16:08:46 +0000248 # Bit of hack, but good enough for test purposes
249 header, _, _ = text.partition("</head>")
250 _, _, title = header.partition("<title>")
251 title, _, _ = title.partition("</title>")
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000252 return title
253
Georg Brandlb533e262008-05-25 18:19:30 +0000254
Georg Brandld2f38572011-01-30 08:37:19 +0000255class PydocDocTest(unittest.TestCase):
Georg Brandlb533e262008-05-25 18:19:30 +0000256
R. David Murray378c0cf2010-02-24 01:46:21 +0000257 @unittest.skipIf(sys.flags.optimize >= 2,
258 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000259 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
260 'trace function introduces __locals__ unexpectedly')
Georg Brandlb533e262008-05-25 18:19:30 +0000261 def test_html_doc(self):
262 result, doc_loc = get_pydoc_html(pydoc_mod)
263 mod_file = inspect.getabsfile(pydoc_mod)
Benjamin Petersonc5e94642008-06-14 23:04:46 +0000264 if sys.platform == 'win32':
265 import nturl2path
266 mod_url = nturl2path.pathname2url(mod_file)
267 else:
268 mod_url = mod_file
269 expected_html = expected_html_pattern % (mod_url, mod_file, doc_loc)
Georg Brandlb533e262008-05-25 18:19:30 +0000270 if result != expected_html:
271 print_diffs(expected_html, result)
272 self.fail("outputs are not equal, see diff above")
273
R. David Murray378c0cf2010-02-24 01:46:21 +0000274 @unittest.skipIf(sys.flags.optimize >= 2,
275 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000276 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
277 'trace function introduces __locals__ unexpectedly')
Georg Brandlb533e262008-05-25 18:19:30 +0000278 def test_text_doc(self):
279 result, doc_loc = get_pydoc_text(pydoc_mod)
280 expected_text = expected_text_pattern % \
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000281 (doc_loc, inspect.getabsfile(pydoc_mod))
Georg Brandlb533e262008-05-25 18:19:30 +0000282 if result != expected_text:
283 print_diffs(expected_text, result)
284 self.fail("outputs are not equal, see diff above")
285
Brian Curtin49c284c2010-03-31 03:19:28 +0000286 def test_issue8225(self):
287 # Test issue8225 to ensure no doc link appears for xml.etree
288 result, doc_loc = get_pydoc_text(xml.etree)
289 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
290
Georg Brandlb533e262008-05-25 18:19:30 +0000291 def test_not_here(self):
292 missing_module = "test.i_am_not_here"
293 result = str(run_pydoc(missing_module), 'ascii')
294 expected = missing_pattern % missing_module
295 self.assertEqual(expected, result,
296 "documentation for missing module found")
297
Benjamin Peterson0289b152009-06-28 17:22:03 +0000298 def test_badimport(self):
299 # This tests the fix for issue 5230, where if pydoc found the module
300 # but the module had an internal import error pydoc would report no doc
301 # found.
302 modname = 'testmod_xyzzy'
303 testpairs = (
304 ('i_am_not_here', 'i_am_not_here'),
305 ('test.i_am_not_here_either', 'i_am_not_here_either'),
306 ('test.i_am_not_here.neither_am_i', 'i_am_not_here.neither_am_i'),
Barry Warsaw28a691b2010-04-17 00:19:56 +0000307 ('i_am_not_here.{}'.format(modname),
308 'i_am_not_here.{}'.format(modname)),
Benjamin Peterson0289b152009-06-28 17:22:03 +0000309 ('test.{}'.format(modname), modname),
310 )
311
312 @contextmanager
313 def newdirinpath(dir):
314 os.mkdir(dir)
315 sys.path.insert(0, dir)
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200316 try:
317 yield
318 finally:
319 sys.path.pop(0)
320 rmtree(dir)
Benjamin Peterson0289b152009-06-28 17:22:03 +0000321
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200322 with newdirinpath(TESTFN):
Benjamin Peterson0289b152009-06-28 17:22:03 +0000323 fullmodname = os.path.join(TESTFN, modname)
324 sourcefn = fullmodname + os.extsep + "py"
325 for importstring, expectedinmsg in testpairs:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000326 with open(sourcefn, 'w') as f:
327 f.write("import {}\n".format(importstring))
Benjamin Peterson0289b152009-06-28 17:22:03 +0000328 try:
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200329 result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii")
Benjamin Peterson0289b152009-06-28 17:22:03 +0000330 finally:
331 forget(modname)
332 expected = badimport_pattern % (modname, expectedinmsg)
333 self.assertEqual(expected, result)
334
R. David Murray1f1b9d32009-05-27 20:56:59 +0000335 def test_input_strip(self):
336 missing_module = " test.i_am_not_here "
337 result = str(run_pydoc(missing_module), 'ascii')
338 expected = missing_pattern % missing_module.strip()
339 self.assertEqual(expected, result)
340
Ezio Melotti412c95a2010-02-16 23:31:04 +0000341 def test_stripid(self):
342 # test with strings, other implementations might have different repr()
343 stripid = pydoc.stripid
344 # strip the id
345 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
346 '<function stripid>')
347 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
348 '<function stripid>')
349 # nothing to strip, return the same text
350 self.assertEqual(stripid('42'), '42')
351 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
352 "<type 'exceptions.Exception'>")
353
Georg Brandld80d5f42010-12-03 07:47:22 +0000354 @unittest.skipIf(sys.flags.optimize >= 2,
355 'Docstrings are omitted with -O2 and above')
Brett Cannon7a540732011-02-22 03:04:06 +0000356 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
357 'trace function introduces __locals__ unexpectedly')
Georg Brandld80d5f42010-12-03 07:47:22 +0000358 def test_help_output_redirect(self):
359 # issue 940286, if output is set in Helper, then all output from
360 # Helper.help should be redirected
361 old_pattern = expected_text_pattern
362 getpager_old = pydoc.getpager
363 getpager_new = lambda: (lambda x: x)
364 self.maxDiff = None
365
366 buf = StringIO()
367 helper = pydoc.Helper(output=buf)
368 unused, doc_loc = get_pydoc_text(pydoc_mod)
369 module = "test.pydoc_mod"
370 help_header = """
371 Help on module test.pydoc_mod in test:
372
373 """.lstrip()
374 help_header = textwrap.dedent(help_header)
375 expected_help_pattern = help_header + expected_text_pattern
376
377 pydoc.getpager = getpager_new
378 try:
379 with captured_output('stdout') as output, \
380 captured_output('stderr') as err:
381 helper.help(module)
382 result = buf.getvalue().strip()
383 expected_text = expected_help_pattern % \
384 (doc_loc, inspect.getabsfile(pydoc_mod))
385 self.assertEqual('', output.getvalue())
386 self.assertEqual('', err.getvalue())
387 self.assertEqual(expected_text, result)
388 finally:
389 pydoc.getpager = getpager_old
390
Raymond Hettinger1103d052011-03-25 14:15:24 -0700391 def test_namedtuple_public_underscore(self):
392 NT = namedtuple('NT', ['abc', 'def'], rename=True)
393 with captured_stdout() as help_io:
394 help(NT)
395 helptext = help_io.getvalue()
396 self.assertIn('_1', helptext)
397 self.assertIn('_replace', helptext)
398 self.assertIn('_asdict', helptext)
399
Victor Stinnere6c910e2011-06-30 15:55:43 +0200400 def test_synopsis(self):
401 self.addCleanup(unlink, TESTFN)
402 for encoding in ('ISO-8859-1', 'UTF-8'):
403 with open(TESTFN, 'w', encoding=encoding) as script:
404 if encoding != 'UTF-8':
405 print('#coding: {}'.format(encoding), file=script)
406 print('"""line 1: h\xe9', file=script)
407 print('line 2: hi"""', file=script)
408 synopsis = pydoc.synopsis(TESTFN, {})
409 self.assertEqual(synopsis, 'line 1: h\xe9')
410
Georg Brandlb533e262008-05-25 18:19:30 +0000411
412class TestDescriptions(unittest.TestCase):
413
414 def test_module(self):
415 # Check that pydocfodder module can be described
416 from test import pydocfodder
417 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000418 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000419
Georg Brandlb533e262008-05-25 18:19:30 +0000420 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000421 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +0000422 c = C()
423
424 self.assertEqual(pydoc.describe(C), 'class C')
425 self.assertEqual(pydoc.describe(c), 'C')
426 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000427 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000428
Éric Araujoe64e51b2011-07-29 17:03:55 +0200429 def test_builtin(self):
430 for name in ('str', 'str.translate', 'builtins.str',
431 'builtins.str.translate'):
432 # test low-level function
433 self.assertIsNotNone(pydoc.locate(name))
434 # test high-level function
435 try:
436 pydoc.render_doc(name)
437 except ImportError:
438 self.fail('finding the doc of {!r} failed'.format(o))
439
440 for name in ('notbuiltins', 'strrr', 'strr.translate',
441 'str.trrrranslate', 'builtins.strrr',
442 'builtins.str.trrranslate'):
443 self.assertIsNone(pydoc.locate(name))
444 self.assertRaises(ImportError, pydoc.render_doc, name)
445
Georg Brandlb533e262008-05-25 18:19:30 +0000446
Victor Stinner62a68f22011-05-20 02:29:13 +0200447@unittest.skipUnless(threading, 'Threading required for this test.')
Georg Brandld2f38572011-01-30 08:37:19 +0000448class PydocServerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000449 """Tests for pydoc._start_server"""
450
451 def test_server(self):
452
453 # Minimal test that starts the server, then stops it.
454 def my_url_handler(url, content_type):
455 text = 'the URL sent was: (%s, %s)' % (url, content_type)
456 return text
457
458 serverthread = pydoc._start_server(my_url_handler, port=0)
459 starttime = time.time()
460 timeout = 1 #seconds
461
462 while serverthread.serving:
463 time.sleep(.01)
464 if serverthread.serving and time.time() - starttime > timeout:
465 serverthread.stop()
466 break
467
468 self.assertEqual(serverthread.error, None)
469
470
Georg Brandld2f38572011-01-30 08:37:19 +0000471class PydocUrlHandlerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000472 """Tests for pydoc._url_handler"""
473
474 def test_content_type_err(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000475 f = pydoc._url_handler
Georg Brandld2f38572011-01-30 08:37:19 +0000476 self.assertRaises(TypeError, f, 'A', '')
477 self.assertRaises(TypeError, f, 'B', 'foobar')
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000478
479 def test_url_requests(self):
480 # Test for the correct title in the html pages returned.
481 # This tests the different parts of the URL handler without
482 # getting too picky about the exact html.
483 requests = [
Georg Brandld2f38572011-01-30 08:37:19 +0000484 ("", "Pydoc: Index of Modules"),
485 ("get?key=", "Pydoc: Index of Modules"),
486 ("index", "Pydoc: Index of Modules"),
487 ("topics", "Pydoc: Topics"),
488 ("keywords", "Pydoc: Keywords"),
489 ("pydoc", "Pydoc: module pydoc"),
490 ("get?key=pydoc", "Pydoc: module pydoc"),
491 ("search?key=pydoc", "Pydoc: Search Results"),
492 ("topic?key=def", "Pydoc: KEYWORD def"),
493 ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
494 ("foobar", "Pydoc: Error - foobar"),
495 ("getfile?key=foobar", "Pydoc: Error - getfile?key=foobar"),
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000496 ]
497
498 for url, title in requests:
499 text = pydoc._url_handler(url, "text/html")
500 result = get_html_title(text)
501 self.assertEqual(result, title)
502
503 path = string.__file__
Georg Brandld2f38572011-01-30 08:37:19 +0000504 title = "Pydoc: getfile " + path
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000505 url = "getfile?key=" + path
506 text = pydoc._url_handler(url, "text/html")
507 result = get_html_title(text)
508 self.assertEqual(result, title)
509
510
Ezio Melottib185a042011-04-28 07:42:55 +0300511class TestHelper(unittest.TestCase):
512 def test_keywords(self):
513 self.assertEqual(sorted(pydoc.Helper.keywords),
514 sorted(keyword.kwlist))
515
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200516@reap_threads
Georg Brandlb533e262008-05-25 18:19:30 +0000517def test_main():
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200518 try:
519 test.support.run_unittest(PydocDocTest,
520 TestDescriptions,
521 PydocServerTest,
522 PydocUrlHandlerTest,
523 TestHelper,
524 )
525 finally:
526 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +0000527
528if __name__ == "__main__":
529 test_main()