blob: 7591303d2dd5818cc7fd174ff7e1955b9b7aff06 [file] [log] [blame]
Georg Brandlb533e262008-05-25 18:19:30 +00001import os
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002import sys
Georg Brandlb533e262008-05-25 18:19:30 +00003import difflib
Georg Brandlb533e262008-05-25 18:19:30 +00004import inspect
Nick Coghlan7bb30b72010-12-03 09:29:11 +00005import pydoc
Ezio Melottib185a042011-04-28 07:42:55 +03006import keyword
Nick Coghlan7bb30b72010-12-03 09:29:11 +00007import re
8import string
9import subprocess
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
Benjamin Peterson0289b152009-06-28 17:22:03 +000017from contextlib import contextmanager
Georg Brandlb533e262008-05-25 18:19:30 +000018
Antoine Pitrouf7f54752011-07-15 22:42:12 +020019from test.script_helper import assert_python_ok
Antoine Pitroua6e81a22011-07-15 22:32:25 +020020from test.support import (
21 TESTFN, forget, rmtree, EnvironmentVarGuard,
22 reap_children, reap_threads, captured_output, captured_stdout, unlink
23)
Georg Brandlb533e262008-05-25 18:19:30 +000024from test import pydoc_mod
25
Victor Stinner62a68f22011-05-20 02:29:13 +020026try:
27 import threading
28except ImportError:
29 threading = None
30
Florent Xicluna085a6562010-03-06 14:04:16 +000031# Just in case sys.modules["test"] has the optional attribute __loader__.
32if hasattr(pydoc_mod, "__loader__"):
33 del pydoc_mod.__loader__
34
Barry Warsaw28a691b2010-04-17 00:19:56 +000035expected_text_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000036NAME
37 test.pydoc_mod - This is a test module for test_pydoc
Georg Brandlb533e262008-05-25 18:19:30 +000038%s
39CLASSES
40 builtins.object
41 A
42 B
43\x20\x20\x20\x20
44 class A(builtins.object)
45 | Hello and goodbye
46 |\x20\x20
47 | Methods defined here:
48 |\x20\x20
49 | __init__()
50 | Wow, I have no function!
51 |\x20\x20
52 | ----------------------------------------------------------------------
53 | Data descriptors defined here:
54 |\x20\x20
55 | __dict__
56 | dictionary for instance variables (if defined)
57 |\x20\x20
58 | __weakref__
59 | list of weak references to the object (if defined)
60\x20\x20\x20\x20
61 class B(builtins.object)
62 | Data descriptors defined here:
63 |\x20\x20
64 | __dict__
65 | dictionary for instance variables (if defined)
66 |\x20\x20
67 | __weakref__
68 | list of weak references to the object (if defined)
69 |\x20\x20
70 | ----------------------------------------------------------------------
71 | Data and other attributes defined here:
72 |\x20\x20
73 | NO_MEANING = 'eggs'
74
75FUNCTIONS
76 doc_func()
77 This function solves all of the world's problems:
78 hunger
79 lack of Python
80 war
81\x20\x20\x20\x20
82 nodoc_func()
83
84DATA
Alexander Belopolskya47bbf52010-11-18 01:52:54 +000085 __xyz__ = 'X, Y and Z'
Georg Brandlb533e262008-05-25 18:19:30 +000086
87VERSION
88 1.2.3.4
89
90AUTHOR
91 Benjamin Peterson
92
93CREDITS
94 Nobody
Alexander Belopolskya47bbf52010-11-18 01:52:54 +000095
96FILE
97 %s
Georg Brandlb533e262008-05-25 18:19:30 +000098""".strip()
99
Barry Warsaw28a691b2010-04-17 00:19:56 +0000100expected_html_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +0000101<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
102<tr bgcolor="#7799ee">
103<td valign=bottom>&nbsp;<br>
104<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
105><td align=right valign=bottom
106><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
107 <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
108<p>
109<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
110<tr bgcolor="#ee77aa">
111<td colspan=3 valign=bottom>&nbsp;<br>
112<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
113\x20\x20\x20\x20
114<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
115<td width="100%%"><dl>
116<dt><font face="helvetica, arial"><a href="builtins.html#object">builtins.object</a>
117</font></dt><dd>
118<dl>
119<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
120</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
121</font></dt></dl>
122</dd>
123</dl>
124 <p>
125<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
126<tr bgcolor="#ffc8d8">
127<td colspan=3 valign=bottom>&nbsp;<br>
128<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>
129\x20\x20\x20\x20
130<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
131<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
132<tr><td>&nbsp;</td>
133<td width="100%%">Methods defined here:<br>
134<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>
135
136<hr>
137Data descriptors defined here:<br>
138<dl><dt><strong>__dict__</strong></dt>
139<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
140</dl>
141<dl><dt><strong>__weakref__</strong></dt>
142<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
143</dl>
144</td></tr></table> <p>
145<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
146<tr bgcolor="#ffc8d8">
147<td colspan=3 valign=bottom>&nbsp;<br>
148<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>
149\x20\x20\x20\x20
150<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
151<td width="100%%">Data descriptors defined here:<br>
152<dl><dt><strong>__dict__</strong></dt>
153<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
154</dl>
155<dl><dt><strong>__weakref__</strong></dt>
156<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
157</dl>
158<hr>
159Data and other attributes defined here:<br>
160<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
161
162</td></tr></table></td></tr></table><p>
163<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
164<tr bgcolor="#eeaa77">
165<td colspan=3 valign=bottom>&nbsp;<br>
166<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
167\x20\x20\x20\x20
168<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
169<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>
170hunger<br>
171lack&nbsp;of&nbsp;Python<br>
172war</tt></dd></dl>
173 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
174</td></tr></table><p>
175<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
176<tr bgcolor="#55aa55">
177<td colspan=3 valign=bottom>&nbsp;<br>
178<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
179\x20\x20\x20\x20
180<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000181<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p>
Georg Brandlb533e262008-05-25 18:19:30 +0000182<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
183<tr bgcolor="#7799ee">
184<td colspan=3 valign=bottom>&nbsp;<br>
185<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
186\x20\x20\x20\x20
187<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
188<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
189<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
190<tr bgcolor="#7799ee">
191<td colspan=3 valign=bottom>&nbsp;<br>
192<font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
193\x20\x20\x20\x20
194<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
195<td width="100%%">Nobody</td></tr></table>
Barry Warsaw28a691b2010-04-17 00:19:56 +0000196""".strip() # ' <- emacs turd
Georg Brandlb533e262008-05-25 18:19:30 +0000197
198
199# output pattern for missing module
200missing_pattern = "no Python documentation found for '%s'"
201
Benjamin Peterson0289b152009-06-28 17:22:03 +0000202# output pattern for module with bad imports
Victor Stinner98dbba52011-03-14 15:15:47 -0400203badimport_pattern = "problem in %s - ImportError: No module named %r"
Benjamin Peterson0289b152009-06-28 17:22:03 +0000204
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200205def run_pydoc(module_name, *args, **env):
Georg Brandlb533e262008-05-25 18:19:30 +0000206 """
207 Runs pydoc on the specified module. Returns the stripped
208 output of pydoc.
209 """
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200210 args = args + (module_name,)
211 rc, out, err = assert_python_ok(pydoc.__file__, *args, **env)
212 return out.strip()
Georg Brandlb533e262008-05-25 18:19:30 +0000213
214def get_pydoc_html(module):
215 "Returns pydoc generated output as html"
216 doc = pydoc.HTMLDoc()
217 output = doc.docmodule(module)
218 loc = doc.getdocloc(pydoc_mod) or ""
219 if loc:
220 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
221 return output.strip(), loc
222
223def get_pydoc_text(module):
224 "Returns pydoc generated output as text"
225 doc = pydoc.TextDoc()
226 loc = doc.getdocloc(pydoc_mod) or ""
227 if loc:
228 loc = "\nMODULE DOCS\n " + loc + "\n"
229
230 output = doc.docmodule(module)
231
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000232 # clean up the extra text formatting that pydoc performs
Georg Brandlb533e262008-05-25 18:19:30 +0000233 patt = re.compile('\b.')
234 output = patt.sub('', output)
235 return output.strip(), loc
236
237def print_diffs(text1, text2):
238 "Prints unified diffs for two texts"
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000239 # XXX now obsolete, use unittest built-in support
Georg Brandlb533e262008-05-25 18:19:30 +0000240 lines1 = text1.splitlines(True)
241 lines2 = text2.splitlines(True)
242 diffs = difflib.unified_diff(lines1, lines2, n=0, fromfile='expected',
243 tofile='got')
244 print('\n' + ''.join(diffs))
245
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000246def get_html_title(text):
Nick Coghlanecace282010-12-03 16:08:46 +0000247 # Bit of hack, but good enough for test purposes
248 header, _, _ = text.partition("</head>")
249 _, _, title = header.partition("<title>")
250 title, _, _ = title.partition("</title>")
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000251 return title
252
Georg Brandlb533e262008-05-25 18:19:30 +0000253
Georg Brandld2f38572011-01-30 08:37:19 +0000254class PydocDocTest(unittest.TestCase):
Georg Brandlb533e262008-05-25 18:19:30 +0000255
R. David Murray378c0cf2010-02-24 01:46:21 +0000256 @unittest.skipIf(sys.flags.optimize >= 2,
257 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000258 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
259 'trace function introduces __locals__ unexpectedly')
Georg Brandlb533e262008-05-25 18:19:30 +0000260 def test_html_doc(self):
261 result, doc_loc = get_pydoc_html(pydoc_mod)
262 mod_file = inspect.getabsfile(pydoc_mod)
Benjamin Petersonc5e94642008-06-14 23:04:46 +0000263 if sys.platform == 'win32':
264 import nturl2path
265 mod_url = nturl2path.pathname2url(mod_file)
266 else:
267 mod_url = mod_file
268 expected_html = expected_html_pattern % (mod_url, mod_file, doc_loc)
Georg Brandlb533e262008-05-25 18:19:30 +0000269 if result != expected_html:
270 print_diffs(expected_html, result)
271 self.fail("outputs are not equal, see diff above")
272
R. David Murray378c0cf2010-02-24 01:46:21 +0000273 @unittest.skipIf(sys.flags.optimize >= 2,
274 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000275 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
276 'trace function introduces __locals__ unexpectedly')
Georg Brandlb533e262008-05-25 18:19:30 +0000277 def test_text_doc(self):
278 result, doc_loc = get_pydoc_text(pydoc_mod)
279 expected_text = expected_text_pattern % \
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000280 (doc_loc, inspect.getabsfile(pydoc_mod))
Georg Brandlb533e262008-05-25 18:19:30 +0000281 if result != expected_text:
282 print_diffs(expected_text, result)
283 self.fail("outputs are not equal, see diff above")
284
Brian Curtin49c284c2010-03-31 03:19:28 +0000285 def test_issue8225(self):
286 # Test issue8225 to ensure no doc link appears for xml.etree
287 result, doc_loc = get_pydoc_text(xml.etree)
288 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
289
Georg Brandlb533e262008-05-25 18:19:30 +0000290 def test_not_here(self):
291 missing_module = "test.i_am_not_here"
292 result = str(run_pydoc(missing_module), 'ascii')
293 expected = missing_pattern % missing_module
294 self.assertEqual(expected, result,
295 "documentation for missing module found")
296
Benjamin Peterson0289b152009-06-28 17:22:03 +0000297 def test_badimport(self):
298 # This tests the fix for issue 5230, where if pydoc found the module
299 # but the module had an internal import error pydoc would report no doc
300 # found.
301 modname = 'testmod_xyzzy'
302 testpairs = (
303 ('i_am_not_here', 'i_am_not_here'),
304 ('test.i_am_not_here_either', 'i_am_not_here_either'),
305 ('test.i_am_not_here.neither_am_i', 'i_am_not_here.neither_am_i'),
Barry Warsaw28a691b2010-04-17 00:19:56 +0000306 ('i_am_not_here.{}'.format(modname),
307 'i_am_not_here.{}'.format(modname)),
Benjamin Peterson0289b152009-06-28 17:22:03 +0000308 ('test.{}'.format(modname), modname),
309 )
310
311 @contextmanager
312 def newdirinpath(dir):
313 os.mkdir(dir)
314 sys.path.insert(0, dir)
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200315 try:
316 yield
317 finally:
318 sys.path.pop(0)
319 rmtree(dir)
Benjamin Peterson0289b152009-06-28 17:22:03 +0000320
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200321 with newdirinpath(TESTFN):
Benjamin Peterson0289b152009-06-28 17:22:03 +0000322 fullmodname = os.path.join(TESTFN, modname)
323 sourcefn = fullmodname + os.extsep + "py"
324 for importstring, expectedinmsg in testpairs:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000325 with open(sourcefn, 'w') as f:
326 f.write("import {}\n".format(importstring))
Benjamin Peterson0289b152009-06-28 17:22:03 +0000327 try:
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200328 result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii")
Benjamin Peterson0289b152009-06-28 17:22:03 +0000329 finally:
330 forget(modname)
331 expected = badimport_pattern % (modname, expectedinmsg)
332 self.assertEqual(expected, result)
333
R. David Murray1f1b9d32009-05-27 20:56:59 +0000334 def test_input_strip(self):
335 missing_module = " test.i_am_not_here "
336 result = str(run_pydoc(missing_module), 'ascii')
337 expected = missing_pattern % missing_module.strip()
338 self.assertEqual(expected, result)
339
Ezio Melotti412c95a2010-02-16 23:31:04 +0000340 def test_stripid(self):
341 # test with strings, other implementations might have different repr()
342 stripid = pydoc.stripid
343 # strip the id
344 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
345 '<function stripid>')
346 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
347 '<function stripid>')
348 # nothing to strip, return the same text
349 self.assertEqual(stripid('42'), '42')
350 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
351 "<type 'exceptions.Exception'>")
352
Georg Brandld80d5f42010-12-03 07:47:22 +0000353 @unittest.skipIf(sys.flags.optimize >= 2,
354 'Docstrings are omitted with -O2 and above')
Brett Cannon7a540732011-02-22 03:04:06 +0000355 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
356 'trace function introduces __locals__ unexpectedly')
Georg Brandld80d5f42010-12-03 07:47:22 +0000357 def test_help_output_redirect(self):
358 # issue 940286, if output is set in Helper, then all output from
359 # Helper.help should be redirected
360 old_pattern = expected_text_pattern
361 getpager_old = pydoc.getpager
362 getpager_new = lambda: (lambda x: x)
363 self.maxDiff = None
364
365 buf = StringIO()
366 helper = pydoc.Helper(output=buf)
367 unused, doc_loc = get_pydoc_text(pydoc_mod)
368 module = "test.pydoc_mod"
369 help_header = """
370 Help on module test.pydoc_mod in test:
371
372 """.lstrip()
373 help_header = textwrap.dedent(help_header)
374 expected_help_pattern = help_header + expected_text_pattern
375
376 pydoc.getpager = getpager_new
377 try:
378 with captured_output('stdout') as output, \
379 captured_output('stderr') as err:
380 helper.help(module)
381 result = buf.getvalue().strip()
382 expected_text = expected_help_pattern % \
383 (doc_loc, inspect.getabsfile(pydoc_mod))
384 self.assertEqual('', output.getvalue())
385 self.assertEqual('', err.getvalue())
386 self.assertEqual(expected_text, result)
387 finally:
388 pydoc.getpager = getpager_old
389
Raymond Hettinger1103d052011-03-25 14:15:24 -0700390 def test_namedtuple_public_underscore(self):
391 NT = namedtuple('NT', ['abc', 'def'], rename=True)
392 with captured_stdout() as help_io:
393 help(NT)
394 helptext = help_io.getvalue()
395 self.assertIn('_1', helptext)
396 self.assertIn('_replace', helptext)
397 self.assertIn('_asdict', helptext)
398
Victor Stinnere6c910e2011-06-30 15:55:43 +0200399 def test_synopsis(self):
400 self.addCleanup(unlink, TESTFN)
401 for encoding in ('ISO-8859-1', 'UTF-8'):
402 with open(TESTFN, 'w', encoding=encoding) as script:
403 if encoding != 'UTF-8':
404 print('#coding: {}'.format(encoding), file=script)
405 print('"""line 1: h\xe9', file=script)
406 print('line 2: hi"""', file=script)
407 synopsis = pydoc.synopsis(TESTFN, {})
408 self.assertEqual(synopsis, 'line 1: h\xe9')
409
Georg Brandlb533e262008-05-25 18:19:30 +0000410
411class TestDescriptions(unittest.TestCase):
412
413 def test_module(self):
414 # Check that pydocfodder module can be described
415 from test import pydocfodder
416 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000417 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000418
Georg Brandlb533e262008-05-25 18:19:30 +0000419 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000420 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +0000421 c = C()
422
423 self.assertEqual(pydoc.describe(C), 'class C')
424 self.assertEqual(pydoc.describe(c), 'C')
425 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000426 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000427
428
Victor Stinner62a68f22011-05-20 02:29:13 +0200429@unittest.skipUnless(threading, 'Threading required for this test.')
Georg Brandld2f38572011-01-30 08:37:19 +0000430class PydocServerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000431 """Tests for pydoc._start_server"""
432
433 def test_server(self):
434
435 # Minimal test that starts the server, then stops it.
436 def my_url_handler(url, content_type):
437 text = 'the URL sent was: (%s, %s)' % (url, content_type)
438 return text
439
440 serverthread = pydoc._start_server(my_url_handler, port=0)
441 starttime = time.time()
442 timeout = 1 #seconds
443
444 while serverthread.serving:
445 time.sleep(.01)
446 if serverthread.serving and time.time() - starttime > timeout:
447 serverthread.stop()
448 break
449
450 self.assertEqual(serverthread.error, None)
451
452
Georg Brandld2f38572011-01-30 08:37:19 +0000453class PydocUrlHandlerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000454 """Tests for pydoc._url_handler"""
455
456 def test_content_type_err(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000457 f = pydoc._url_handler
Georg Brandld2f38572011-01-30 08:37:19 +0000458 self.assertRaises(TypeError, f, 'A', '')
459 self.assertRaises(TypeError, f, 'B', 'foobar')
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000460
461 def test_url_requests(self):
462 # Test for the correct title in the html pages returned.
463 # This tests the different parts of the URL handler without
464 # getting too picky about the exact html.
465 requests = [
Georg Brandld2f38572011-01-30 08:37:19 +0000466 ("", "Pydoc: Index of Modules"),
467 ("get?key=", "Pydoc: Index of Modules"),
468 ("index", "Pydoc: Index of Modules"),
469 ("topics", "Pydoc: Topics"),
470 ("keywords", "Pydoc: Keywords"),
471 ("pydoc", "Pydoc: module pydoc"),
472 ("get?key=pydoc", "Pydoc: module pydoc"),
473 ("search?key=pydoc", "Pydoc: Search Results"),
474 ("topic?key=def", "Pydoc: KEYWORD def"),
475 ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
476 ("foobar", "Pydoc: Error - foobar"),
477 ("getfile?key=foobar", "Pydoc: Error - getfile?key=foobar"),
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000478 ]
479
480 for url, title in requests:
481 text = pydoc._url_handler(url, "text/html")
482 result = get_html_title(text)
483 self.assertEqual(result, title)
484
485 path = string.__file__
Georg Brandld2f38572011-01-30 08:37:19 +0000486 title = "Pydoc: getfile " + path
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000487 url = "getfile?key=" + path
488 text = pydoc._url_handler(url, "text/html")
489 result = get_html_title(text)
490 self.assertEqual(result, title)
491
492
Ezio Melottib185a042011-04-28 07:42:55 +0300493class TestHelper(unittest.TestCase):
494 def test_keywords(self):
495 self.assertEqual(sorted(pydoc.Helper.keywords),
496 sorted(keyword.kwlist))
497
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200498@reap_threads
Georg Brandlb533e262008-05-25 18:19:30 +0000499def test_main():
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200500 try:
501 test.support.run_unittest(PydocDocTest,
502 TestDescriptions,
503 PydocServerTest,
504 PydocUrlHandlerTest,
505 TestHelper,
506 )
507 finally:
508 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +0000509
510if __name__ == "__main__":
511 test_main()