blob: cdcc707d61b3d3ab800c46fba0c9340273ceef4d [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
Antoine Pitrou916fc7b2013-05-19 15:44:54 +02004import contextlib
Georg Brandlb533e262008-05-25 18:19:30 +00005import difflib
Georg Brandlb533e262008-05-25 18:19:30 +00006import inspect
Nick Coghlan7bb30b72010-12-03 09:29:11 +00007import pydoc
Ezio Melottib185a042011-04-28 07:42:55 +03008import keyword
Antoine Pitrou916fc7b2013-05-19 15:44:54 +02009import pkgutil
Nick Coghlan7bb30b72010-12-03 09:29:11 +000010import re
11import string
Georg Brandlb533e262008-05-25 18:19:30 +000012import test.support
Nick Coghlan7bb30b72010-12-03 09:29:11 +000013import time
14import unittest
Brian Curtin49c284c2010-03-31 03:19:28 +000015import xml.etree
Georg Brandld80d5f42010-12-03 07:47:22 +000016import textwrap
17from io import StringIO
Raymond Hettinger1103d052011-03-25 14:15:24 -070018from collections import namedtuple
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 (
Ned Deily92a81a12011-10-06 14:19:03 -070021 TESTFN, rmtree,
Antoine Pitrou916fc7b2013-05-19 15:44:54 +020022 reap_children, reap_threads, captured_output, captured_stdout,
23 captured_stderr, unlink
Antoine Pitroua6e81a22011-07-15 22:32:25 +020024)
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
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020036if test.support.HAVE_DOCSTRINGS:
37 expected_data_docstrings = (
38 'dictionary for instance variables (if defined)',
39 'list of weak references to the object (if defined)',
40 ) * 2
41else:
42 expected_data_docstrings = ('', '', '', '')
43
Barry Warsaw28a691b2010-04-17 00:19:56 +000044expected_text_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000045NAME
46 test.pydoc_mod - This is a test module for test_pydoc
Georg Brandlb533e262008-05-25 18:19:30 +000047%s
48CLASSES
49 builtins.object
50 A
51 B
52\x20\x20\x20\x20
53 class A(builtins.object)
54 | Hello and goodbye
55 |\x20\x20
56 | Methods defined here:
57 |\x20\x20
58 | __init__()
59 | Wow, I have no function!
60 |\x20\x20
61 | ----------------------------------------------------------------------
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\x20\x20
68 class B(builtins.object)
69 | Data descriptors defined here:
70 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020071 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000072 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020073 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000074 |\x20\x20
75 | ----------------------------------------------------------------------
76 | Data and other attributes defined here:
77 |\x20\x20
78 | NO_MEANING = 'eggs'
79
80FUNCTIONS
81 doc_func()
82 This function solves all of the world's problems:
83 hunger
84 lack of Python
85 war
86\x20\x20\x20\x20
87 nodoc_func()
88
89DATA
Alexander Belopolskya47bbf52010-11-18 01:52:54 +000090 __xyz__ = 'X, Y and Z'
Georg Brandlb533e262008-05-25 18:19:30 +000091
92VERSION
93 1.2.3.4
94
95AUTHOR
96 Benjamin Peterson
97
98CREDITS
99 Nobody
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000100
101FILE
102 %s
Georg Brandlb533e262008-05-25 18:19:30 +0000103""".strip()
104
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200105expected_text_data_docstrings = tuple('\n | ' + s if s else ''
106 for s in expected_data_docstrings)
107
Barry Warsaw28a691b2010-04-17 00:19:56 +0000108expected_html_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +0000109<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
110<tr bgcolor="#7799ee">
111<td valign=bottom>&nbsp;<br>
112<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
113><td align=right valign=bottom
114><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
115 <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
116<p>
117<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
118<tr bgcolor="#ee77aa">
119<td colspan=3 valign=bottom>&nbsp;<br>
120<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
121\x20\x20\x20\x20
122<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
123<td width="100%%"><dl>
124<dt><font face="helvetica, arial"><a href="builtins.html#object">builtins.object</a>
125</font></dt><dd>
126<dl>
127<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
128</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
129</font></dt></dl>
130</dd>
131</dl>
132 <p>
133<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
134<tr bgcolor="#ffc8d8">
135<td colspan=3 valign=bottom>&nbsp;<br>
136<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>
137\x20\x20\x20\x20
138<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
139<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
140<tr><td>&nbsp;</td>
141<td width="100%%">Methods defined here:<br>
142<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>
143
144<hr>
145Data descriptors defined here:<br>
146<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200147<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000148</dl>
149<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200150<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000151</dl>
152</td></tr></table> <p>
153<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
154<tr bgcolor="#ffc8d8">
155<td colspan=3 valign=bottom>&nbsp;<br>
156<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>
157\x20\x20\x20\x20
158<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
159<td width="100%%">Data descriptors defined here:<br>
160<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200161<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000162</dl>
163<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200164<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000165</dl>
166<hr>
167Data and other attributes defined here:<br>
168<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
169
170</td></tr></table></td></tr></table><p>
171<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
172<tr bgcolor="#eeaa77">
173<td colspan=3 valign=bottom>&nbsp;<br>
174<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
175\x20\x20\x20\x20
176<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
177<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>
178hunger<br>
179lack&nbsp;of&nbsp;Python<br>
180war</tt></dd></dl>
181 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
182</td></tr></table><p>
183<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
184<tr bgcolor="#55aa55">
185<td colspan=3 valign=bottom>&nbsp;<br>
186<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
187\x20\x20\x20\x20
188<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000189<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p>
Georg Brandlb533e262008-05-25 18:19:30 +0000190<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>Author</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%%">Benjamin&nbsp;Peterson</td></tr></table><p>
197<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
198<tr bgcolor="#7799ee">
199<td colspan=3 valign=bottom>&nbsp;<br>
200<font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
201\x20\x20\x20\x20
202<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
203<td width="100%%">Nobody</td></tr></table>
Barry Warsaw28a691b2010-04-17 00:19:56 +0000204""".strip() # ' <- emacs turd
Georg Brandlb533e262008-05-25 18:19:30 +0000205
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200206expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;')
207 for s in expected_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000208
209# output pattern for missing module
210missing_pattern = "no Python documentation found for '%s'"
211
Benjamin Peterson0289b152009-06-28 17:22:03 +0000212# output pattern for module with bad imports
Victor Stinner98dbba52011-03-14 15:15:47 -0400213badimport_pattern = "problem in %s - ImportError: No module named %r"
Benjamin Peterson0289b152009-06-28 17:22:03 +0000214
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200215def run_pydoc(module_name, *args, **env):
Georg Brandlb533e262008-05-25 18:19:30 +0000216 """
217 Runs pydoc on the specified module. Returns the stripped
218 output of pydoc.
219 """
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200220 args = args + (module_name,)
Ned Deily92a81a12011-10-06 14:19:03 -0700221 # do not write bytecode files to avoid caching errors
222 rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200223 return out.strip()
Georg Brandlb533e262008-05-25 18:19:30 +0000224
225def get_pydoc_html(module):
226 "Returns pydoc generated output as html"
227 doc = pydoc.HTMLDoc()
228 output = doc.docmodule(module)
229 loc = doc.getdocloc(pydoc_mod) or ""
230 if loc:
231 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
232 return output.strip(), loc
233
234def get_pydoc_text(module):
235 "Returns pydoc generated output as text"
236 doc = pydoc.TextDoc()
237 loc = doc.getdocloc(pydoc_mod) or ""
238 if loc:
239 loc = "\nMODULE DOCS\n " + loc + "\n"
240
241 output = doc.docmodule(module)
242
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000243 # clean up the extra text formatting that pydoc performs
Georg Brandlb533e262008-05-25 18:19:30 +0000244 patt = re.compile('\b.')
245 output = patt.sub('', output)
246 return output.strip(), loc
247
248def print_diffs(text1, text2):
249 "Prints unified diffs for two texts"
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000250 # XXX now obsolete, use unittest built-in support
Ezio Melottid8b509b2011-09-28 17:37:55 +0300251 lines1 = text1.splitlines(keepends=True)
252 lines2 = text2.splitlines(keepends=True)
Georg Brandlb533e262008-05-25 18:19:30 +0000253 diffs = difflib.unified_diff(lines1, lines2, n=0, fromfile='expected',
254 tofile='got')
255 print('\n' + ''.join(diffs))
256
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000257def get_html_title(text):
Nick Coghlanecace282010-12-03 16:08:46 +0000258 # Bit of hack, but good enough for test purposes
259 header, _, _ = text.partition("</head>")
260 _, _, title = header.partition("<title>")
261 title, _, _ = title.partition("</title>")
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000262 return title
263
Georg Brandlb533e262008-05-25 18:19:30 +0000264
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200265class PydocBaseTest(unittest.TestCase):
266
267 def _restricted_walk_packages(self, walk_packages, path=None):
268 """
269 A version of pkgutil.walk_packages() that will restrict itself to
270 a given path.
271 """
272 default_path = path or [os.path.dirname(__file__)]
273 def wrapper(path=None, prefix='', onerror=None):
274 return walk_packages(path or default_path, prefix, onerror)
275 return wrapper
276
277 @contextlib.contextmanager
278 def restrict_walk_packages(self, path=None):
279 walk_packages = pkgutil.walk_packages
280 pkgutil.walk_packages = self._restricted_walk_packages(walk_packages,
281 path)
282 try:
283 yield
284 finally:
285 pkgutil.walk_packages = walk_packages
286
287
Georg Brandld2f38572011-01-30 08:37:19 +0000288class PydocDocTest(unittest.TestCase):
Georg Brandlb533e262008-05-25 18:19:30 +0000289
R. David Murray378c0cf2010-02-24 01:46:21 +0000290 @unittest.skipIf(sys.flags.optimize >= 2,
291 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000292 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
293 'trace function introduces __locals__ unexpectedly')
Georg Brandlb533e262008-05-25 18:19:30 +0000294 def test_html_doc(self):
295 result, doc_loc = get_pydoc_html(pydoc_mod)
296 mod_file = inspect.getabsfile(pydoc_mod)
Benjamin Petersonc5e94642008-06-14 23:04:46 +0000297 if sys.platform == 'win32':
298 import nturl2path
299 mod_url = nturl2path.pathname2url(mod_file)
300 else:
301 mod_url = mod_file
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200302 expected_html = expected_html_pattern % (
303 (mod_url, mod_file, doc_loc) +
304 expected_html_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000305 if result != expected_html:
306 print_diffs(expected_html, result)
307 self.fail("outputs are not equal, see diff above")
308
R. David Murray378c0cf2010-02-24 01:46:21 +0000309 @unittest.skipIf(sys.flags.optimize >= 2,
310 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000311 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
312 'trace function introduces __locals__ unexpectedly')
Georg Brandlb533e262008-05-25 18:19:30 +0000313 def test_text_doc(self):
314 result, doc_loc = get_pydoc_text(pydoc_mod)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200315 expected_text = expected_text_pattern % (
316 (doc_loc,) +
317 expected_text_data_docstrings +
318 (inspect.getabsfile(pydoc_mod),))
Georg Brandlb533e262008-05-25 18:19:30 +0000319 if result != expected_text:
320 print_diffs(expected_text, result)
321 self.fail("outputs are not equal, see diff above")
322
Brian Curtin49c284c2010-03-31 03:19:28 +0000323 def test_issue8225(self):
324 # Test issue8225 to ensure no doc link appears for xml.etree
325 result, doc_loc = get_pydoc_text(xml.etree)
326 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
327
R David Murrayc43125a2012-04-23 13:23:57 -0400328 def test_non_str_name(self):
329 # issue14638
330 # Treat illegal (non-str) name like no name
331 class A:
332 __name__ = 42
333 class B:
334 pass
335 adoc = pydoc.render_doc(A())
336 bdoc = pydoc.render_doc(B())
337 self.assertEqual(adoc.replace("A", "B"), bdoc)
338
Georg Brandlb533e262008-05-25 18:19:30 +0000339 def test_not_here(self):
340 missing_module = "test.i_am_not_here"
341 result = str(run_pydoc(missing_module), 'ascii')
342 expected = missing_pattern % missing_module
343 self.assertEqual(expected, result,
344 "documentation for missing module found")
345
R. David Murray1f1b9d32009-05-27 20:56:59 +0000346 def test_input_strip(self):
347 missing_module = " test.i_am_not_here "
348 result = str(run_pydoc(missing_module), 'ascii')
349 expected = missing_pattern % missing_module.strip()
350 self.assertEqual(expected, result)
351
Ezio Melotti412c95a2010-02-16 23:31:04 +0000352 def test_stripid(self):
353 # test with strings, other implementations might have different repr()
354 stripid = pydoc.stripid
355 # strip the id
356 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
357 '<function stripid>')
358 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
359 '<function stripid>')
360 # nothing to strip, return the same text
361 self.assertEqual(stripid('42'), '42')
362 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
363 "<type 'exceptions.Exception'>")
364
Georg Brandld80d5f42010-12-03 07:47:22 +0000365 @unittest.skipIf(sys.flags.optimize >= 2,
366 'Docstrings are omitted with -O2 and above')
Brett Cannon7a540732011-02-22 03:04:06 +0000367 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
368 'trace function introduces __locals__ unexpectedly')
Georg Brandld80d5f42010-12-03 07:47:22 +0000369 def test_help_output_redirect(self):
370 # issue 940286, if output is set in Helper, then all output from
371 # Helper.help should be redirected
372 old_pattern = expected_text_pattern
373 getpager_old = pydoc.getpager
374 getpager_new = lambda: (lambda x: x)
375 self.maxDiff = None
376
377 buf = StringIO()
378 helper = pydoc.Helper(output=buf)
379 unused, doc_loc = get_pydoc_text(pydoc_mod)
380 module = "test.pydoc_mod"
381 help_header = """
382 Help on module test.pydoc_mod in test:
383
384 """.lstrip()
385 help_header = textwrap.dedent(help_header)
386 expected_help_pattern = help_header + expected_text_pattern
387
388 pydoc.getpager = getpager_new
389 try:
390 with captured_output('stdout') as output, \
391 captured_output('stderr') as err:
392 helper.help(module)
393 result = buf.getvalue().strip()
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200394 expected_text = expected_help_pattern % (
395 (doc_loc,) +
396 expected_text_data_docstrings +
397 (inspect.getabsfile(pydoc_mod),))
Georg Brandld80d5f42010-12-03 07:47:22 +0000398 self.assertEqual('', output.getvalue())
399 self.assertEqual('', err.getvalue())
400 self.assertEqual(expected_text, result)
401 finally:
402 pydoc.getpager = getpager_old
403
Raymond Hettinger1103d052011-03-25 14:15:24 -0700404 def test_namedtuple_public_underscore(self):
405 NT = namedtuple('NT', ['abc', 'def'], rename=True)
406 with captured_stdout() as help_io:
407 help(NT)
408 helptext = help_io.getvalue()
409 self.assertIn('_1', helptext)
410 self.assertIn('_replace', helptext)
411 self.assertIn('_asdict', helptext)
412
Victor Stinnere6c910e2011-06-30 15:55:43 +0200413 def test_synopsis(self):
414 self.addCleanup(unlink, TESTFN)
415 for encoding in ('ISO-8859-1', 'UTF-8'):
416 with open(TESTFN, 'w', encoding=encoding) as script:
417 if encoding != 'UTF-8':
418 print('#coding: {}'.format(encoding), file=script)
419 print('"""line 1: h\xe9', file=script)
420 print('line 2: hi"""', file=script)
421 synopsis = pydoc.synopsis(TESTFN, {})
422 self.assertEqual(synopsis, 'line 1: h\xe9')
423
R David Murray9929bc52013-03-19 02:31:06 -0400424 def test_allmethods(self):
425 # issue 17476: allmethods was no longer returning unbound methods.
426 # This test is a bit fragile in the face of changes to object and type,
427 # but I can't think of a better way to do it without duplicating the
428 # logic of the function under test.
429
430 class TestClass(object):
431 def method_returning_true(self):
432 return True
433
434 # What we expect to get back: everything on object...
435 expected = dict(vars(object))
436 # ...plus our unbound method...
437 expected['method_returning_true'] = TestClass.method_returning_true
438 # ...but not the non-methods on object.
439 del expected['__doc__']
440 del expected['__class__']
441 # inspect resolves descriptors on type into methods, but vars doesn't,
442 # so we need to update __subclasshook__.
443 expected['__subclasshook__'] = TestClass.__subclasshook__
444
445 methods = pydoc.allmethods(TestClass)
446 self.assertDictEqual(methods, expected)
447
Georg Brandlb533e262008-05-25 18:19:30 +0000448
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200449class PydocImportTest(PydocBaseTest):
Ned Deily92a81a12011-10-06 14:19:03 -0700450
451 def setUp(self):
452 self.test_dir = os.mkdir(TESTFN)
453 self.addCleanup(rmtree, TESTFN)
454
455 def test_badimport(self):
456 # This tests the fix for issue 5230, where if pydoc found the module
457 # but the module had an internal import error pydoc would report no doc
458 # found.
459 modname = 'testmod_xyzzy'
460 testpairs = (
461 ('i_am_not_here', 'i_am_not_here'),
Brett Cannonfd074152012-04-14 14:10:13 -0400462 ('test.i_am_not_here_either', 'test.i_am_not_here_either'),
463 ('test.i_am_not_here.neither_am_i', 'test.i_am_not_here'),
464 ('i_am_not_here.{}'.format(modname), 'i_am_not_here'),
465 ('test.{}'.format(modname), 'test.{}'.format(modname)),
Ned Deily92a81a12011-10-06 14:19:03 -0700466 )
467
468 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
469 for importstring, expectedinmsg in testpairs:
470 with open(sourcefn, 'w') as f:
471 f.write("import {}\n".format(importstring))
472 result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii")
473 expected = badimport_pattern % (modname, expectedinmsg)
474 self.assertEqual(expected, result)
475
476 def test_apropos_with_bad_package(self):
477 # Issue 7425 - pydoc -k failed when bad package on path
478 pkgdir = os.path.join(TESTFN, "syntaxerr")
479 os.mkdir(pkgdir)
480 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
481 with open(badsyntax, 'w') as f:
482 f.write("invalid python syntax = $1\n")
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200483 with self.restrict_walk_packages(path=[TESTFN]):
484 with captured_stdout() as out:
485 with captured_stderr() as err:
486 pydoc.apropos('xyzzy')
487 # No result, no error
488 self.assertEqual(out.getvalue(), '')
489 self.assertEqual(err.getvalue(), '')
490 # The package name is still matched
491 with captured_stdout() as out:
492 with captured_stderr() as err:
493 pydoc.apropos('syntaxerr')
494 self.assertEqual(out.getvalue().strip(), 'syntaxerr')
495 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700496
497 def test_apropos_with_unreadable_dir(self):
498 # Issue 7367 - pydoc -k failed when unreadable dir on path
499 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
500 os.mkdir(self.unreadable_dir, 0)
501 self.addCleanup(os.rmdir, self.unreadable_dir)
502 # Note, on Windows the directory appears to be still
503 # readable so this is not really testing the issue there
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200504 with self.restrict_walk_packages(path=[TESTFN]):
505 with captured_stdout() as out:
506 with captured_stderr() as err:
507 pydoc.apropos('SOMEKEY')
508 # No result, no error
509 self.assertEqual(out.getvalue(), '')
510 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700511
512
Georg Brandlb533e262008-05-25 18:19:30 +0000513class TestDescriptions(unittest.TestCase):
514
515 def test_module(self):
516 # Check that pydocfodder module can be described
517 from test import pydocfodder
518 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000519 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000520
Georg Brandlb533e262008-05-25 18:19:30 +0000521 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000522 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +0000523 c = C()
524
525 self.assertEqual(pydoc.describe(C), 'class C')
526 self.assertEqual(pydoc.describe(c), 'C')
527 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000528 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000529
Éric Araujoe64e51b2011-07-29 17:03:55 +0200530 def test_builtin(self):
531 for name in ('str', 'str.translate', 'builtins.str',
532 'builtins.str.translate'):
533 # test low-level function
534 self.assertIsNotNone(pydoc.locate(name))
535 # test high-level function
536 try:
537 pydoc.render_doc(name)
538 except ImportError:
539 self.fail('finding the doc of {!r} failed'.format(o))
540
541 for name in ('notbuiltins', 'strrr', 'strr.translate',
542 'str.trrrranslate', 'builtins.strrr',
543 'builtins.str.trrranslate'):
544 self.assertIsNone(pydoc.locate(name))
545 self.assertRaises(ImportError, pydoc.render_doc, name)
546
Georg Brandlb533e262008-05-25 18:19:30 +0000547
Victor Stinner62a68f22011-05-20 02:29:13 +0200548@unittest.skipUnless(threading, 'Threading required for this test.')
Georg Brandld2f38572011-01-30 08:37:19 +0000549class PydocServerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000550 """Tests for pydoc._start_server"""
551
552 def test_server(self):
553
554 # Minimal test that starts the server, then stops it.
555 def my_url_handler(url, content_type):
556 text = 'the URL sent was: (%s, %s)' % (url, content_type)
557 return text
558
559 serverthread = pydoc._start_server(my_url_handler, port=0)
560 starttime = time.time()
561 timeout = 1 #seconds
562
563 while serverthread.serving:
564 time.sleep(.01)
565 if serverthread.serving and time.time() - starttime > timeout:
566 serverthread.stop()
567 break
568
569 self.assertEqual(serverthread.error, None)
570
571
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200572class PydocUrlHandlerTest(PydocBaseTest):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000573 """Tests for pydoc._url_handler"""
574
575 def test_content_type_err(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000576 f = pydoc._url_handler
Georg Brandld2f38572011-01-30 08:37:19 +0000577 self.assertRaises(TypeError, f, 'A', '')
578 self.assertRaises(TypeError, f, 'B', 'foobar')
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000579
580 def test_url_requests(self):
581 # Test for the correct title in the html pages returned.
582 # This tests the different parts of the URL handler without
583 # getting too picky about the exact html.
584 requests = [
Georg Brandld2f38572011-01-30 08:37:19 +0000585 ("", "Pydoc: Index of Modules"),
586 ("get?key=", "Pydoc: Index of Modules"),
587 ("index", "Pydoc: Index of Modules"),
588 ("topics", "Pydoc: Topics"),
589 ("keywords", "Pydoc: Keywords"),
590 ("pydoc", "Pydoc: module pydoc"),
591 ("get?key=pydoc", "Pydoc: module pydoc"),
592 ("search?key=pydoc", "Pydoc: Search Results"),
593 ("topic?key=def", "Pydoc: KEYWORD def"),
594 ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
595 ("foobar", "Pydoc: Error - foobar"),
596 ("getfile?key=foobar", "Pydoc: Error - getfile?key=foobar"),
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000597 ]
598
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200599 with self.restrict_walk_packages():
600 for url, title in requests:
601 text = pydoc._url_handler(url, "text/html")
602 result = get_html_title(text)
603 self.assertEqual(result, title, text)
604
605 path = string.__file__
606 title = "Pydoc: getfile " + path
607 url = "getfile?key=" + path
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000608 text = pydoc._url_handler(url, "text/html")
609 result = get_html_title(text)
610 self.assertEqual(result, title)
611
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000612
Ezio Melottib185a042011-04-28 07:42:55 +0300613class TestHelper(unittest.TestCase):
614 def test_keywords(self):
615 self.assertEqual(sorted(pydoc.Helper.keywords),
616 sorted(keyword.kwlist))
617
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200618@reap_threads
Georg Brandlb533e262008-05-25 18:19:30 +0000619def test_main():
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200620 try:
621 test.support.run_unittest(PydocDocTest,
Ned Deily92a81a12011-10-06 14:19:03 -0700622 PydocImportTest,
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200623 TestDescriptions,
624 PydocServerTest,
625 PydocUrlHandlerTest,
626 TestHelper,
627 )
628 finally:
629 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +0000630
631if __name__ == "__main__":
632 test_main()