blob: 8524e5aa61c0919a7fb85e8b72d94929045b7c9e [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
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020029if test.support.HAVE_DOCSTRINGS:
30 expected_data_docstrings = (
31 'dictionary for instance variables (if defined)',
32 'list of weak references to the object (if defined)',
33 ) * 2
34else:
35 expected_data_docstrings = ('', '', '', '')
36
Barry Warsaw28a691b2010-04-17 00:19:56 +000037expected_text_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000038NAME
39 test.pydoc_mod - This is a test module for test_pydoc
Georg Brandlb533e262008-05-25 18:19:30 +000040%s
41CLASSES
42 builtins.object
43 A
44 B
45\x20\x20\x20\x20
46 class A(builtins.object)
47 | Hello and goodbye
48 |\x20\x20
49 | Methods defined here:
50 |\x20\x20
51 | __init__()
52 | Wow, I have no function!
53 |\x20\x20
54 | ----------------------------------------------------------------------
55 | Data descriptors defined here:
56 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020057 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000058 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020059 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000060\x20\x20\x20\x20
61 class B(builtins.object)
62 | Data descriptors defined here:
63 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020064 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000065 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020066 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000067 |\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
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020098expected_text_data_docstrings = tuple('\n | ' + s if s else ''
99 for s in expected_data_docstrings)
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>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200140<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000141</dl>
142<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200143<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000144</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>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200154<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000155</dl>
156<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200157<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000158</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
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200199expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;')
200 for s in expected_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000201
202# output pattern for missing module
203missing_pattern = "no Python documentation found for '%s'"
204
Benjamin Peterson0289b152009-06-28 17:22:03 +0000205# output pattern for module with bad imports
Victor Stinner98dbba52011-03-14 15:15:47 -0400206badimport_pattern = "problem in %s - ImportError: No module named %r"
Benjamin Peterson0289b152009-06-28 17:22:03 +0000207
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200208def run_pydoc(module_name, *args, **env):
Georg Brandlb533e262008-05-25 18:19:30 +0000209 """
210 Runs pydoc on the specified module. Returns the stripped
211 output of pydoc.
212 """
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200213 args = args + (module_name,)
Ned Deily92a81a12011-10-06 14:19:03 -0700214 # do not write bytecode files to avoid caching errors
215 rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200216 return out.strip()
Georg Brandlb533e262008-05-25 18:19:30 +0000217
218def get_pydoc_html(module):
219 "Returns pydoc generated output as html"
220 doc = pydoc.HTMLDoc()
221 output = doc.docmodule(module)
222 loc = doc.getdocloc(pydoc_mod) or ""
223 if loc:
224 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
225 return output.strip(), loc
226
227def get_pydoc_text(module):
228 "Returns pydoc generated output as text"
229 doc = pydoc.TextDoc()
230 loc = doc.getdocloc(pydoc_mod) or ""
231 if loc:
232 loc = "\nMODULE DOCS\n " + loc + "\n"
233
234 output = doc.docmodule(module)
235
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000236 # clean up the extra text formatting that pydoc performs
Georg Brandlb533e262008-05-25 18:19:30 +0000237 patt = re.compile('\b.')
238 output = patt.sub('', output)
239 return output.strip(), loc
240
241def print_diffs(text1, text2):
242 "Prints unified diffs for two texts"
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000243 # XXX now obsolete, use unittest built-in support
Ezio Melottid8b509b2011-09-28 17:37:55 +0300244 lines1 = text1.splitlines(keepends=True)
245 lines2 = text2.splitlines(keepends=True)
Georg Brandlb533e262008-05-25 18:19:30 +0000246 diffs = difflib.unified_diff(lines1, lines2, n=0, fromfile='expected',
247 tofile='got')
248 print('\n' + ''.join(diffs))
249
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000250def get_html_title(text):
Nick Coghlanecace282010-12-03 16:08:46 +0000251 # Bit of hack, but good enough for test purposes
252 header, _, _ = text.partition("</head>")
253 _, _, title = header.partition("<title>")
254 title, _, _ = title.partition("</title>")
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000255 return title
256
Georg Brandlb533e262008-05-25 18:19:30 +0000257
Georg Brandld2f38572011-01-30 08:37:19 +0000258class PydocDocTest(unittest.TestCase):
Georg Brandlb533e262008-05-25 18:19:30 +0000259
R. David Murray378c0cf2010-02-24 01:46:21 +0000260 @unittest.skipIf(sys.flags.optimize >= 2,
261 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000262 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
263 'trace function introduces __locals__ unexpectedly')
Georg Brandlb533e262008-05-25 18:19:30 +0000264 def test_html_doc(self):
265 result, doc_loc = get_pydoc_html(pydoc_mod)
266 mod_file = inspect.getabsfile(pydoc_mod)
Benjamin Petersonc5e94642008-06-14 23:04:46 +0000267 if sys.platform == 'win32':
268 import nturl2path
269 mod_url = nturl2path.pathname2url(mod_file)
270 else:
271 mod_url = mod_file
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200272 expected_html = expected_html_pattern % (
273 (mod_url, mod_file, doc_loc) +
274 expected_html_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000275 if result != expected_html:
276 print_diffs(expected_html, result)
277 self.fail("outputs are not equal, see diff above")
278
R. David Murray378c0cf2010-02-24 01:46:21 +0000279 @unittest.skipIf(sys.flags.optimize >= 2,
280 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000281 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
282 'trace function introduces __locals__ unexpectedly')
Georg Brandlb533e262008-05-25 18:19:30 +0000283 def test_text_doc(self):
284 result, doc_loc = get_pydoc_text(pydoc_mod)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200285 expected_text = expected_text_pattern % (
286 (doc_loc,) +
287 expected_text_data_docstrings +
288 (inspect.getabsfile(pydoc_mod),))
Georg Brandlb533e262008-05-25 18:19:30 +0000289 if result != expected_text:
290 print_diffs(expected_text, result)
291 self.fail("outputs are not equal, see diff above")
292
Brian Curtin49c284c2010-03-31 03:19:28 +0000293 def test_issue8225(self):
294 # Test issue8225 to ensure no doc link appears for xml.etree
295 result, doc_loc = get_pydoc_text(xml.etree)
296 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
297
R David Murrayc43125a2012-04-23 13:23:57 -0400298 def test_non_str_name(self):
299 # issue14638
300 # Treat illegal (non-str) name like no name
301 class A:
302 __name__ = 42
303 class B:
304 pass
305 adoc = pydoc.render_doc(A())
306 bdoc = pydoc.render_doc(B())
307 self.assertEqual(adoc.replace("A", "B"), bdoc)
308
Georg Brandlb533e262008-05-25 18:19:30 +0000309 def test_not_here(self):
310 missing_module = "test.i_am_not_here"
311 result = str(run_pydoc(missing_module), 'ascii')
312 expected = missing_pattern % missing_module
313 self.assertEqual(expected, result,
314 "documentation for missing module found")
315
R. David Murray1f1b9d32009-05-27 20:56:59 +0000316 def test_input_strip(self):
317 missing_module = " test.i_am_not_here "
318 result = str(run_pydoc(missing_module), 'ascii')
319 expected = missing_pattern % missing_module.strip()
320 self.assertEqual(expected, result)
321
Ezio Melotti412c95a2010-02-16 23:31:04 +0000322 def test_stripid(self):
323 # test with strings, other implementations might have different repr()
324 stripid = pydoc.stripid
325 # strip the id
326 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
327 '<function stripid>')
328 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
329 '<function stripid>')
330 # nothing to strip, return the same text
331 self.assertEqual(stripid('42'), '42')
332 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
333 "<type 'exceptions.Exception'>")
334
Georg Brandld80d5f42010-12-03 07:47:22 +0000335 @unittest.skipIf(sys.flags.optimize >= 2,
336 'Docstrings are omitted with -O2 and above')
Brett Cannon7a540732011-02-22 03:04:06 +0000337 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
338 'trace function introduces __locals__ unexpectedly')
Georg Brandld80d5f42010-12-03 07:47:22 +0000339 def test_help_output_redirect(self):
340 # issue 940286, if output is set in Helper, then all output from
341 # Helper.help should be redirected
342 old_pattern = expected_text_pattern
343 getpager_old = pydoc.getpager
344 getpager_new = lambda: (lambda x: x)
345 self.maxDiff = None
346
347 buf = StringIO()
348 helper = pydoc.Helper(output=buf)
349 unused, doc_loc = get_pydoc_text(pydoc_mod)
350 module = "test.pydoc_mod"
351 help_header = """
352 Help on module test.pydoc_mod in test:
353
354 """.lstrip()
355 help_header = textwrap.dedent(help_header)
356 expected_help_pattern = help_header + expected_text_pattern
357
358 pydoc.getpager = getpager_new
359 try:
360 with captured_output('stdout') as output, \
361 captured_output('stderr') as err:
362 helper.help(module)
363 result = buf.getvalue().strip()
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200364 expected_text = expected_help_pattern % (
365 (doc_loc,) +
366 expected_text_data_docstrings +
367 (inspect.getabsfile(pydoc_mod),))
Georg Brandld80d5f42010-12-03 07:47:22 +0000368 self.assertEqual('', output.getvalue())
369 self.assertEqual('', err.getvalue())
370 self.assertEqual(expected_text, result)
371 finally:
372 pydoc.getpager = getpager_old
373
Raymond Hettinger1103d052011-03-25 14:15:24 -0700374 def test_namedtuple_public_underscore(self):
375 NT = namedtuple('NT', ['abc', 'def'], rename=True)
376 with captured_stdout() as help_io:
377 help(NT)
378 helptext = help_io.getvalue()
379 self.assertIn('_1', helptext)
380 self.assertIn('_replace', helptext)
381 self.assertIn('_asdict', helptext)
382
Victor Stinnere6c910e2011-06-30 15:55:43 +0200383 def test_synopsis(self):
384 self.addCleanup(unlink, TESTFN)
385 for encoding in ('ISO-8859-1', 'UTF-8'):
386 with open(TESTFN, 'w', encoding=encoding) as script:
387 if encoding != 'UTF-8':
388 print('#coding: {}'.format(encoding), file=script)
389 print('"""line 1: h\xe9', file=script)
390 print('line 2: hi"""', file=script)
391 synopsis = pydoc.synopsis(TESTFN, {})
392 self.assertEqual(synopsis, 'line 1: h\xe9')
393
R David Murray455f2962013-03-19 00:00:33 -0400394 def test_splitdoc_with_description(self):
395 example_string = "I Am A Doc\n\n\nHere is my description"
396 self.assertEqual(pydoc.splitdoc(example_string),
397 ('I Am A Doc', '\nHere is my description'))
398
399 def test_is_object_or_method(self):
400 doc = pydoc.Doc()
401 # Bound Method
402 self.assertTrue(pydoc._is_some_method(doc.fail))
403 # Method Descriptor
404 self.assertTrue(pydoc._is_some_method(int.__add__))
405 # String
406 self.assertFalse(pydoc._is_some_method("I am not a method"))
407
408 def test_is_package_when_not_package(self):
409 with test.support.temp_cwd() as test_dir:
410 self.assertFalse(pydoc.ispackage(test_dir))
411
412 def test_is_package_when_is_package(self):
413 with test.support.temp_cwd() as test_dir:
414 init_path = os.path.join(test_dir, '__init__.py')
415 open(init_path, 'w').close()
416 self.assertTrue(pydoc.ispackage(test_dir))
417 os.remove(init_path)
418
R David Murrayac0cea52013-03-19 02:47:44 -0400419 def test_allmethods(self):
420 # issue 17476: allmethods was no longer returning unbound methods.
421 # This test is a bit fragile in the face of changes to object and type,
422 # but I can't think of a better way to do it without duplicating the
423 # logic of the function under test.
424
425 class TestClass(object):
426 def method_returning_true(self):
427 return True
428
429 # What we expect to get back: everything on object...
430 expected = dict(vars(object))
431 # ...plus our unbound method...
432 expected['method_returning_true'] = TestClass.method_returning_true
433 # ...but not the non-methods on object.
434 del expected['__doc__']
435 del expected['__class__']
436 # inspect resolves descriptors on type into methods, but vars doesn't,
437 # so we need to update __subclasshook__.
438 expected['__subclasshook__'] = TestClass.__subclasshook__
439
440 methods = pydoc.allmethods(TestClass)
441 self.assertDictEqual(methods, expected)
442
Georg Brandlb533e262008-05-25 18:19:30 +0000443
Ned Deily92a81a12011-10-06 14:19:03 -0700444class PydocImportTest(unittest.TestCase):
445
446 def setUp(self):
447 self.test_dir = os.mkdir(TESTFN)
448 self.addCleanup(rmtree, TESTFN)
449
450 def test_badimport(self):
451 # This tests the fix for issue 5230, where if pydoc found the module
452 # but the module had an internal import error pydoc would report no doc
453 # found.
454 modname = 'testmod_xyzzy'
455 testpairs = (
456 ('i_am_not_here', 'i_am_not_here'),
Brett Cannonfd074152012-04-14 14:10:13 -0400457 ('test.i_am_not_here_either', 'test.i_am_not_here_either'),
458 ('test.i_am_not_here.neither_am_i', 'test.i_am_not_here'),
459 ('i_am_not_here.{}'.format(modname), 'i_am_not_here'),
460 ('test.{}'.format(modname), 'test.{}'.format(modname)),
Ned Deily92a81a12011-10-06 14:19:03 -0700461 )
462
463 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
464 for importstring, expectedinmsg in testpairs:
465 with open(sourcefn, 'w') as f:
466 f.write("import {}\n".format(importstring))
467 result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii")
468 expected = badimport_pattern % (modname, expectedinmsg)
469 self.assertEqual(expected, result)
470
471 def test_apropos_with_bad_package(self):
472 # Issue 7425 - pydoc -k failed when bad package on path
473 pkgdir = os.path.join(TESTFN, "syntaxerr")
474 os.mkdir(pkgdir)
475 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
476 with open(badsyntax, 'w') as f:
477 f.write("invalid python syntax = $1\n")
Ned Deily34294912012-02-03 23:14:37 +0100478 result = run_pydoc('zqwykjv', '-k', PYTHONPATH=TESTFN)
Ned Deily92a81a12011-10-06 14:19:03 -0700479 self.assertEqual(b'', result)
480
481 def test_apropos_with_unreadable_dir(self):
482 # Issue 7367 - pydoc -k failed when unreadable dir on path
483 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
484 os.mkdir(self.unreadable_dir, 0)
485 self.addCleanup(os.rmdir, self.unreadable_dir)
486 # Note, on Windows the directory appears to be still
487 # readable so this is not really testing the issue there
Ned Deily34294912012-02-03 23:14:37 +0100488 result = run_pydoc('zqwykjv', '-k', PYTHONPATH=TESTFN)
Ned Deily92a81a12011-10-06 14:19:03 -0700489 self.assertEqual(b'', result)
490
491
Georg Brandlb533e262008-05-25 18:19:30 +0000492class TestDescriptions(unittest.TestCase):
493
494 def test_module(self):
495 # Check that pydocfodder module can be described
496 from test import pydocfodder
497 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000498 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000499
Georg Brandlb533e262008-05-25 18:19:30 +0000500 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000501 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +0000502 c = C()
503
504 self.assertEqual(pydoc.describe(C), 'class C')
505 self.assertEqual(pydoc.describe(c), 'C')
506 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000507 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000508
Éric Araujoe64e51b2011-07-29 17:03:55 +0200509 def test_builtin(self):
510 for name in ('str', 'str.translate', 'builtins.str',
511 'builtins.str.translate'):
512 # test low-level function
513 self.assertIsNotNone(pydoc.locate(name))
514 # test high-level function
515 try:
516 pydoc.render_doc(name)
517 except ImportError:
518 self.fail('finding the doc of {!r} failed'.format(o))
519
520 for name in ('notbuiltins', 'strrr', 'strr.translate',
521 'str.trrrranslate', 'builtins.strrr',
522 'builtins.str.trrranslate'):
523 self.assertIsNone(pydoc.locate(name))
524 self.assertRaises(ImportError, pydoc.render_doc, name)
525
Georg Brandlb533e262008-05-25 18:19:30 +0000526
Victor Stinner62a68f22011-05-20 02:29:13 +0200527@unittest.skipUnless(threading, 'Threading required for this test.')
Georg Brandld2f38572011-01-30 08:37:19 +0000528class PydocServerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000529 """Tests for pydoc._start_server"""
530
531 def test_server(self):
532
533 # Minimal test that starts the server, then stops it.
534 def my_url_handler(url, content_type):
535 text = 'the URL sent was: (%s, %s)' % (url, content_type)
536 return text
537
538 serverthread = pydoc._start_server(my_url_handler, port=0)
539 starttime = time.time()
540 timeout = 1 #seconds
541
542 while serverthread.serving:
543 time.sleep(.01)
544 if serverthread.serving and time.time() - starttime > timeout:
545 serverthread.stop()
546 break
547
548 self.assertEqual(serverthread.error, None)
549
550
Georg Brandld2f38572011-01-30 08:37:19 +0000551class PydocUrlHandlerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000552 """Tests for pydoc._url_handler"""
553
554 def test_content_type_err(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000555 f = pydoc._url_handler
Georg Brandld2f38572011-01-30 08:37:19 +0000556 self.assertRaises(TypeError, f, 'A', '')
557 self.assertRaises(TypeError, f, 'B', 'foobar')
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000558
559 def test_url_requests(self):
560 # Test for the correct title in the html pages returned.
561 # This tests the different parts of the URL handler without
562 # getting too picky about the exact html.
563 requests = [
Georg Brandld2f38572011-01-30 08:37:19 +0000564 ("", "Pydoc: Index of Modules"),
565 ("get?key=", "Pydoc: Index of Modules"),
566 ("index", "Pydoc: Index of Modules"),
567 ("topics", "Pydoc: Topics"),
568 ("keywords", "Pydoc: Keywords"),
569 ("pydoc", "Pydoc: module pydoc"),
570 ("get?key=pydoc", "Pydoc: module pydoc"),
571 ("search?key=pydoc", "Pydoc: Search Results"),
572 ("topic?key=def", "Pydoc: KEYWORD def"),
573 ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
574 ("foobar", "Pydoc: Error - foobar"),
575 ("getfile?key=foobar", "Pydoc: Error - getfile?key=foobar"),
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000576 ]
577
578 for url, title in requests:
579 text = pydoc._url_handler(url, "text/html")
580 result = get_html_title(text)
581 self.assertEqual(result, title)
582
583 path = string.__file__
Georg Brandld2f38572011-01-30 08:37:19 +0000584 title = "Pydoc: getfile " + path
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000585 url = "getfile?key=" + path
586 text = pydoc._url_handler(url, "text/html")
587 result = get_html_title(text)
588 self.assertEqual(result, title)
589
590
Ezio Melottib185a042011-04-28 07:42:55 +0300591class TestHelper(unittest.TestCase):
592 def test_keywords(self):
593 self.assertEqual(sorted(pydoc.Helper.keywords),
594 sorted(keyword.kwlist))
595
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200596@reap_threads
Georg Brandlb533e262008-05-25 18:19:30 +0000597def test_main():
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200598 try:
599 test.support.run_unittest(PydocDocTest,
Ned Deily92a81a12011-10-06 14:19:03 -0700600 PydocImportTest,
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200601 TestDescriptions,
602 PydocServerTest,
603 PydocUrlHandlerTest,
604 TestHelper,
605 )
606 finally:
607 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +0000608
609if __name__ == "__main__":
610 test_main()