blob: 72f5882cf5e5346d84d567a97edc8af6a5b5bb49 [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
Antoine Pitrouf7f54752011-07-15 22:42:12 +020019
20from 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
204badimport_pattern = "problem in %s - ImportError: No module named %s"
205
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
Georg Brandlb533e262008-05-25 18:19:30 +0000241 lines1 = text1.splitlines(True)
242 lines2 = text2.splitlines(True)
243 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")
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")
Georg Brandlb533e262008-05-25 18:19:30 +0000274 def test_text_doc(self):
275 result, doc_loc = get_pydoc_text(pydoc_mod)
276 expected_text = expected_text_pattern % \
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000277 (doc_loc, inspect.getabsfile(pydoc_mod))
Georg Brandlb533e262008-05-25 18:19:30 +0000278 if result != expected_text:
279 print_diffs(expected_text, result)
280 self.fail("outputs are not equal, see diff above")
281
Brian Curtin49c284c2010-03-31 03:19:28 +0000282 def test_issue8225(self):
283 # Test issue8225 to ensure no doc link appears for xml.etree
284 result, doc_loc = get_pydoc_text(xml.etree)
285 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
286
Georg Brandlb533e262008-05-25 18:19:30 +0000287 def test_not_here(self):
288 missing_module = "test.i_am_not_here"
289 result = str(run_pydoc(missing_module), 'ascii')
290 expected = missing_pattern % missing_module
291 self.assertEqual(expected, result,
292 "documentation for missing module found")
293
Benjamin Peterson0289b152009-06-28 17:22:03 +0000294 def test_badimport(self):
295 # This tests the fix for issue 5230, where if pydoc found the module
296 # but the module had an internal import error pydoc would report no doc
297 # found.
298 modname = 'testmod_xyzzy'
299 testpairs = (
300 ('i_am_not_here', 'i_am_not_here'),
301 ('test.i_am_not_here_either', 'i_am_not_here_either'),
302 ('test.i_am_not_here.neither_am_i', 'i_am_not_here.neither_am_i'),
Barry Warsaw28a691b2010-04-17 00:19:56 +0000303 ('i_am_not_here.{}'.format(modname),
304 'i_am_not_here.{}'.format(modname)),
Benjamin Peterson0289b152009-06-28 17:22:03 +0000305 ('test.{}'.format(modname), modname),
306 )
307
308 @contextmanager
309 def newdirinpath(dir):
310 os.mkdir(dir)
311 sys.path.insert(0, dir)
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200312 try:
313 yield
314 finally:
315 sys.path.pop(0)
316 rmtree(dir)
Benjamin Peterson0289b152009-06-28 17:22:03 +0000317
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200318 with newdirinpath(TESTFN):
Benjamin Peterson0289b152009-06-28 17:22:03 +0000319 fullmodname = os.path.join(TESTFN, modname)
320 sourcefn = fullmodname + os.extsep + "py"
321 for importstring, expectedinmsg in testpairs:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000322 with open(sourcefn, 'w') as f:
323 f.write("import {}\n".format(importstring))
Benjamin Peterson0289b152009-06-28 17:22:03 +0000324 try:
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200325 result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii")
Benjamin Peterson0289b152009-06-28 17:22:03 +0000326 finally:
327 forget(modname)
328 expected = badimport_pattern % (modname, expectedinmsg)
329 self.assertEqual(expected, result)
330
R. David Murray1f1b9d32009-05-27 20:56:59 +0000331 def test_input_strip(self):
332 missing_module = " test.i_am_not_here "
333 result = str(run_pydoc(missing_module), 'ascii')
334 expected = missing_pattern % missing_module.strip()
335 self.assertEqual(expected, result)
336
Ezio Melotti412c95a2010-02-16 23:31:04 +0000337 def test_stripid(self):
338 # test with strings, other implementations might have different repr()
339 stripid = pydoc.stripid
340 # strip the id
341 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
342 '<function stripid>')
343 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
344 '<function stripid>')
345 # nothing to strip, return the same text
346 self.assertEqual(stripid('42'), '42')
347 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
348 "<type 'exceptions.Exception'>")
349
Georg Brandld80d5f42010-12-03 07:47:22 +0000350 @unittest.skipIf(sys.flags.optimize >= 2,
351 'Docstrings are omitted with -O2 and above')
352 def test_help_output_redirect(self):
353 # issue 940286, if output is set in Helper, then all output from
354 # Helper.help should be redirected
355 old_pattern = expected_text_pattern
356 getpager_old = pydoc.getpager
357 getpager_new = lambda: (lambda x: x)
358 self.maxDiff = None
359
360 buf = StringIO()
361 helper = pydoc.Helper(output=buf)
362 unused, doc_loc = get_pydoc_text(pydoc_mod)
363 module = "test.pydoc_mod"
364 help_header = """
365 Help on module test.pydoc_mod in test:
366
367 """.lstrip()
368 help_header = textwrap.dedent(help_header)
369 expected_help_pattern = help_header + expected_text_pattern
370
371 pydoc.getpager = getpager_new
372 try:
373 with captured_output('stdout') as output, \
374 captured_output('stderr') as err:
375 helper.help(module)
376 result = buf.getvalue().strip()
377 expected_text = expected_help_pattern % \
378 (doc_loc, inspect.getabsfile(pydoc_mod))
379 self.assertEqual('', output.getvalue())
380 self.assertEqual('', err.getvalue())
381 self.assertEqual(expected_text, result)
382 finally:
383 pydoc.getpager = getpager_old
384
Raymond Hettinger1103d052011-03-25 14:15:24 -0700385 def test_namedtuple_public_underscore(self):
386 NT = namedtuple('NT', ['abc', 'def'], rename=True)
387 with captured_stdout() as help_io:
388 help(NT)
389 helptext = help_io.getvalue()
390 self.assertIn('_1', helptext)
391 self.assertIn('_replace', helptext)
392 self.assertIn('_asdict', helptext)
393
Victor Stinnere6c910e2011-06-30 15:55:43 +0200394 def test_synopsis(self):
395 self.addCleanup(unlink, TESTFN)
396 for encoding in ('ISO-8859-1', 'UTF-8'):
397 with open(TESTFN, 'w', encoding=encoding) as script:
398 if encoding != 'UTF-8':
399 print('#coding: {}'.format(encoding), file=script)
400 print('"""line 1: h\xe9', file=script)
401 print('line 2: hi"""', file=script)
402 synopsis = pydoc.synopsis(TESTFN, {})
403 self.assertEqual(synopsis, 'line 1: h\xe9')
404
Georg Brandlb533e262008-05-25 18:19:30 +0000405
406class TestDescriptions(unittest.TestCase):
407
408 def test_module(self):
409 # Check that pydocfodder module can be described
410 from test import pydocfodder
411 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000412 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000413
Georg Brandlb533e262008-05-25 18:19:30 +0000414 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000415 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +0000416 c = C()
417
418 self.assertEqual(pydoc.describe(C), 'class C')
419 self.assertEqual(pydoc.describe(c), 'C')
420 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000421 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000422
Éric Araujoe64e51b2011-07-29 17:03:55 +0200423 def test_builtin(self):
424 for name in ('str', 'str.translate', 'builtins.str',
425 'builtins.str.translate'):
426 # test low-level function
427 self.assertIsNotNone(pydoc.locate(name))
428 # test high-level function
429 try:
430 pydoc.render_doc(name)
431 except ImportError:
432 self.fail('finding the doc of {!r} failed'.format(o))
433
434 for name in ('notbuiltins', 'strrr', 'strr.translate',
435 'str.trrrranslate', 'builtins.strrr',
436 'builtins.str.trrranslate'):
437 self.assertIsNone(pydoc.locate(name))
438 self.assertRaises(ImportError, pydoc.render_doc, name)
439
Georg Brandlb533e262008-05-25 18:19:30 +0000440
Victor Stinner62a68f22011-05-20 02:29:13 +0200441@unittest.skipUnless(threading, 'Threading required for this test.')
Georg Brandld2f38572011-01-30 08:37:19 +0000442class PydocServerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000443 """Tests for pydoc._start_server"""
444
445 def test_server(self):
446
447 # Minimal test that starts the server, then stops it.
448 def my_url_handler(url, content_type):
449 text = 'the URL sent was: (%s, %s)' % (url, content_type)
450 return text
451
452 serverthread = pydoc._start_server(my_url_handler, port=0)
453 starttime = time.time()
454 timeout = 1 #seconds
455
456 while serverthread.serving:
457 time.sleep(.01)
458 if serverthread.serving and time.time() - starttime > timeout:
459 serverthread.stop()
460 break
461
462 self.assertEqual(serverthread.error, None)
463
464
Georg Brandld2f38572011-01-30 08:37:19 +0000465class PydocUrlHandlerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000466 """Tests for pydoc._url_handler"""
467
468 def test_content_type_err(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000469 f = pydoc._url_handler
Georg Brandld2f38572011-01-30 08:37:19 +0000470 self.assertRaises(TypeError, f, 'A', '')
471 self.assertRaises(TypeError, f, 'B', 'foobar')
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000472
473 def test_url_requests(self):
474 # Test for the correct title in the html pages returned.
475 # This tests the different parts of the URL handler without
476 # getting too picky about the exact html.
477 requests = [
Georg Brandld2f38572011-01-30 08:37:19 +0000478 ("", "Pydoc: Index of Modules"),
479 ("get?key=", "Pydoc: Index of Modules"),
480 ("index", "Pydoc: Index of Modules"),
481 ("topics", "Pydoc: Topics"),
482 ("keywords", "Pydoc: Keywords"),
483 ("pydoc", "Pydoc: module pydoc"),
484 ("get?key=pydoc", "Pydoc: module pydoc"),
485 ("search?key=pydoc", "Pydoc: Search Results"),
486 ("topic?key=def", "Pydoc: KEYWORD def"),
487 ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
488 ("foobar", "Pydoc: Error - foobar"),
489 ("getfile?key=foobar", "Pydoc: Error - getfile?key=foobar"),
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000490 ]
491
492 for url, title in requests:
493 text = pydoc._url_handler(url, "text/html")
494 result = get_html_title(text)
495 self.assertEqual(result, title)
496
497 path = string.__file__
Georg Brandld2f38572011-01-30 08:37:19 +0000498 title = "Pydoc: getfile " + path
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000499 url = "getfile?key=" + path
500 text = pydoc._url_handler(url, "text/html")
501 result = get_html_title(text)
502 self.assertEqual(result, title)
503
504
Ezio Melottib185a042011-04-28 07:42:55 +0300505class TestHelper(unittest.TestCase):
506 def test_keywords(self):
507 self.assertEqual(sorted(pydoc.Helper.keywords),
508 sorted(keyword.kwlist))
509
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200510@reap_threads
Georg Brandlb533e262008-05-25 18:19:30 +0000511def test_main():
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200512 try:
513 test.support.run_unittest(PydocDocTest,
514 TestDescriptions,
515 PydocServerTest,
516 PydocUrlHandlerTest,
517 TestHelper,
518 )
519 finally:
520 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +0000521
522if __name__ == "__main__":
523 test_main()