blob: 95ef115a4e3ee64210d4c6d03f296d5481fde94e [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
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020032if test.support.HAVE_DOCSTRINGS:
33 expected_data_docstrings = (
34 'dictionary for instance variables (if defined)',
35 'list of weak references to the object (if defined)',
36 ) * 2
37else:
38 expected_data_docstrings = ('', '', '', '')
39
Barry Warsaw28a691b2010-04-17 00:19:56 +000040expected_text_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000041NAME
42 test.pydoc_mod - This is a test module for test_pydoc
Georg Brandlb533e262008-05-25 18:19:30 +000043%s
44CLASSES
45 builtins.object
46 A
47 B
48\x20\x20\x20\x20
49 class A(builtins.object)
50 | Hello and goodbye
51 |\x20\x20
52 | Methods defined here:
53 |\x20\x20
54 | __init__()
55 | Wow, I have no function!
56 |\x20\x20
57 | ----------------------------------------------------------------------
58 | Data descriptors defined here:
59 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020060 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000061 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020062 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000063\x20\x20\x20\x20
64 class B(builtins.object)
65 | Data descriptors defined here:
66 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020067 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000068 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020069 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000070 |\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
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200101expected_text_data_docstrings = tuple('\n | ' + s if s else ''
102 for s in expected_data_docstrings)
103
Barry Warsaw28a691b2010-04-17 00:19:56 +0000104expected_html_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +0000105<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
106<tr bgcolor="#7799ee">
107<td valign=bottom>&nbsp;<br>
108<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
109><td align=right valign=bottom
110><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
111 <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
112<p>
113<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
114<tr bgcolor="#ee77aa">
115<td colspan=3 valign=bottom>&nbsp;<br>
116<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
117\x20\x20\x20\x20
118<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
119<td width="100%%"><dl>
120<dt><font face="helvetica, arial"><a href="builtins.html#object">builtins.object</a>
121</font></dt><dd>
122<dl>
123<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
124</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
125</font></dt></dl>
126</dd>
127</dl>
128 <p>
129<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
130<tr bgcolor="#ffc8d8">
131<td colspan=3 valign=bottom>&nbsp;<br>
132<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>
133\x20\x20\x20\x20
134<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
135<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
136<tr><td>&nbsp;</td>
137<td width="100%%">Methods defined here:<br>
138<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>
139
140<hr>
141Data descriptors defined here:<br>
142<dl><dt><strong>__dict__</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<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200146<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000147</dl>
148</td></tr></table> <p>
149<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
150<tr bgcolor="#ffc8d8">
151<td colspan=3 valign=bottom>&nbsp;<br>
152<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>
153\x20\x20\x20\x20
154<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
155<td width="100%%">Data descriptors defined here:<br>
156<dl><dt><strong>__dict__</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<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200160<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000161</dl>
162<hr>
163Data and other attributes defined here:<br>
164<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
165
166</td></tr></table></td></tr></table><p>
167<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
168<tr bgcolor="#eeaa77">
169<td colspan=3 valign=bottom>&nbsp;<br>
170<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
171\x20\x20\x20\x20
172<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
173<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>
174hunger<br>
175lack&nbsp;of&nbsp;Python<br>
176war</tt></dd></dl>
177 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
178</td></tr></table><p>
179<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
180<tr bgcolor="#55aa55">
181<td colspan=3 valign=bottom>&nbsp;<br>
182<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
183\x20\x20\x20\x20
184<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000185<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p>
Georg Brandlb533e262008-05-25 18:19:30 +0000186<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
187<tr bgcolor="#7799ee">
188<td colspan=3 valign=bottom>&nbsp;<br>
189<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
190\x20\x20\x20\x20
191<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
192<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
193<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
194<tr bgcolor="#7799ee">
195<td colspan=3 valign=bottom>&nbsp;<br>
196<font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
197\x20\x20\x20\x20
198<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
199<td width="100%%">Nobody</td></tr></table>
Barry Warsaw28a691b2010-04-17 00:19:56 +0000200""".strip() # ' <- emacs turd
Georg Brandlb533e262008-05-25 18:19:30 +0000201
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200202expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;')
203 for s in expected_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000204
205# output pattern for missing module
206missing_pattern = "no Python documentation found for '%s'"
207
Benjamin Peterson0289b152009-06-28 17:22:03 +0000208# output pattern for module with bad imports
Brett Cannonb1611e22013-06-12 16:59:46 -0400209badimport_pattern = "problem in %s - ModuleNotFoundError: No module named %r"
Benjamin Peterson0289b152009-06-28 17:22:03 +0000210
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200211def run_pydoc(module_name, *args, **env):
Georg Brandlb533e262008-05-25 18:19:30 +0000212 """
213 Runs pydoc on the specified module. Returns the stripped
214 output of pydoc.
215 """
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200216 args = args + (module_name,)
Ned Deily92a81a12011-10-06 14:19:03 -0700217 # do not write bytecode files to avoid caching errors
218 rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200219 return out.strip()
Georg Brandlb533e262008-05-25 18:19:30 +0000220
221def get_pydoc_html(module):
222 "Returns pydoc generated output as html"
223 doc = pydoc.HTMLDoc()
224 output = doc.docmodule(module)
225 loc = doc.getdocloc(pydoc_mod) or ""
226 if loc:
227 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
228 return output.strip(), loc
229
230def get_pydoc_text(module):
231 "Returns pydoc generated output as text"
232 doc = pydoc.TextDoc()
233 loc = doc.getdocloc(pydoc_mod) or ""
234 if loc:
235 loc = "\nMODULE DOCS\n " + loc + "\n"
236
237 output = doc.docmodule(module)
238
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000239 # clean up the extra text formatting that pydoc performs
Georg Brandlb533e262008-05-25 18:19:30 +0000240 patt = re.compile('\b.')
241 output = patt.sub('', output)
242 return output.strip(), loc
243
244def print_diffs(text1, text2):
245 "Prints unified diffs for two texts"
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000246 # XXX now obsolete, use unittest built-in support
Ezio Melottid8b509b2011-09-28 17:37:55 +0300247 lines1 = text1.splitlines(keepends=True)
248 lines2 = text2.splitlines(keepends=True)
Georg Brandlb533e262008-05-25 18:19:30 +0000249 diffs = difflib.unified_diff(lines1, lines2, n=0, fromfile='expected',
250 tofile='got')
251 print('\n' + ''.join(diffs))
252
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000253def get_html_title(text):
Nick Coghlanecace282010-12-03 16:08:46 +0000254 # Bit of hack, but good enough for test purposes
255 header, _, _ = text.partition("</head>")
256 _, _, title = header.partition("<title>")
257 title, _, _ = title.partition("</title>")
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000258 return title
259
Georg Brandlb533e262008-05-25 18:19:30 +0000260
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200261class PydocBaseTest(unittest.TestCase):
262
263 def _restricted_walk_packages(self, walk_packages, path=None):
264 """
265 A version of pkgutil.walk_packages() that will restrict itself to
266 a given path.
267 """
268 default_path = path or [os.path.dirname(__file__)]
269 def wrapper(path=None, prefix='', onerror=None):
270 return walk_packages(path or default_path, prefix, onerror)
271 return wrapper
272
273 @contextlib.contextmanager
274 def restrict_walk_packages(self, path=None):
275 walk_packages = pkgutil.walk_packages
276 pkgutil.walk_packages = self._restricted_walk_packages(walk_packages,
277 path)
278 try:
279 yield
280 finally:
281 pkgutil.walk_packages = walk_packages
282
283
Georg Brandld2f38572011-01-30 08:37:19 +0000284class PydocDocTest(unittest.TestCase):
Georg Brandlb533e262008-05-25 18:19:30 +0000285
R. David Murray378c0cf2010-02-24 01:46:21 +0000286 @unittest.skipIf(sys.flags.optimize >= 2,
287 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000288 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
289 'trace function introduces __locals__ unexpectedly')
Georg Brandlb533e262008-05-25 18:19:30 +0000290 def test_html_doc(self):
291 result, doc_loc = get_pydoc_html(pydoc_mod)
292 mod_file = inspect.getabsfile(pydoc_mod)
Benjamin Petersonc5e94642008-06-14 23:04:46 +0000293 if sys.platform == 'win32':
294 import nturl2path
295 mod_url = nturl2path.pathname2url(mod_file)
296 else:
297 mod_url = mod_file
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200298 expected_html = expected_html_pattern % (
299 (mod_url, mod_file, doc_loc) +
300 expected_html_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000301 if result != expected_html:
302 print_diffs(expected_html, result)
303 self.fail("outputs are not equal, see diff above")
304
R. David Murray378c0cf2010-02-24 01:46:21 +0000305 @unittest.skipIf(sys.flags.optimize >= 2,
306 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000307 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
308 'trace function introduces __locals__ unexpectedly')
Georg Brandlb533e262008-05-25 18:19:30 +0000309 def test_text_doc(self):
310 result, doc_loc = get_pydoc_text(pydoc_mod)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200311 expected_text = expected_text_pattern % (
312 (doc_loc,) +
313 expected_text_data_docstrings +
314 (inspect.getabsfile(pydoc_mod),))
Georg Brandlb533e262008-05-25 18:19:30 +0000315 if result != expected_text:
316 print_diffs(expected_text, result)
317 self.fail("outputs are not equal, see diff above")
318
Brian Curtin49c284c2010-03-31 03:19:28 +0000319 def test_issue8225(self):
320 # Test issue8225 to ensure no doc link appears for xml.etree
321 result, doc_loc = get_pydoc_text(xml.etree)
322 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
323
R David Murrayc43125a2012-04-23 13:23:57 -0400324 def test_non_str_name(self):
325 # issue14638
326 # Treat illegal (non-str) name like no name
327 class A:
328 __name__ = 42
329 class B:
330 pass
331 adoc = pydoc.render_doc(A())
332 bdoc = pydoc.render_doc(B())
333 self.assertEqual(adoc.replace("A", "B"), bdoc)
334
Georg Brandlb533e262008-05-25 18:19:30 +0000335 def test_not_here(self):
336 missing_module = "test.i_am_not_here"
337 result = str(run_pydoc(missing_module), 'ascii')
338 expected = missing_pattern % missing_module
339 self.assertEqual(expected, result,
340 "documentation for missing module found")
341
R. David Murray1f1b9d32009-05-27 20:56:59 +0000342 def test_input_strip(self):
343 missing_module = " test.i_am_not_here "
344 result = str(run_pydoc(missing_module), 'ascii')
345 expected = missing_pattern % missing_module.strip()
346 self.assertEqual(expected, result)
347
Ezio Melotti412c95a2010-02-16 23:31:04 +0000348 def test_stripid(self):
349 # test with strings, other implementations might have different repr()
350 stripid = pydoc.stripid
351 # strip the id
352 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
353 '<function stripid>')
354 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
355 '<function stripid>')
356 # nothing to strip, return the same text
357 self.assertEqual(stripid('42'), '42')
358 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
359 "<type 'exceptions.Exception'>")
360
Georg Brandld80d5f42010-12-03 07:47:22 +0000361 @unittest.skipIf(sys.flags.optimize >= 2,
362 'Docstrings are omitted with -O2 and above')
Brett Cannon7a540732011-02-22 03:04:06 +0000363 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
364 'trace function introduces __locals__ unexpectedly')
Georg Brandld80d5f42010-12-03 07:47:22 +0000365 def test_help_output_redirect(self):
366 # issue 940286, if output is set in Helper, then all output from
367 # Helper.help should be redirected
368 old_pattern = expected_text_pattern
369 getpager_old = pydoc.getpager
370 getpager_new = lambda: (lambda x: x)
371 self.maxDiff = None
372
373 buf = StringIO()
374 helper = pydoc.Helper(output=buf)
375 unused, doc_loc = get_pydoc_text(pydoc_mod)
376 module = "test.pydoc_mod"
377 help_header = """
378 Help on module test.pydoc_mod in test:
379
380 """.lstrip()
381 help_header = textwrap.dedent(help_header)
382 expected_help_pattern = help_header + expected_text_pattern
383
384 pydoc.getpager = getpager_new
385 try:
386 with captured_output('stdout') as output, \
387 captured_output('stderr') as err:
388 helper.help(module)
389 result = buf.getvalue().strip()
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200390 expected_text = expected_help_pattern % (
391 (doc_loc,) +
392 expected_text_data_docstrings +
393 (inspect.getabsfile(pydoc_mod),))
Georg Brandld80d5f42010-12-03 07:47:22 +0000394 self.assertEqual('', output.getvalue())
395 self.assertEqual('', err.getvalue())
396 self.assertEqual(expected_text, result)
397 finally:
398 pydoc.getpager = getpager_old
399
Raymond Hettinger1103d052011-03-25 14:15:24 -0700400 def test_namedtuple_public_underscore(self):
401 NT = namedtuple('NT', ['abc', 'def'], rename=True)
402 with captured_stdout() as help_io:
403 help(NT)
404 helptext = help_io.getvalue()
405 self.assertIn('_1', helptext)
406 self.assertIn('_replace', helptext)
407 self.assertIn('_asdict', helptext)
408
Victor Stinnere6c910e2011-06-30 15:55:43 +0200409 def test_synopsis(self):
410 self.addCleanup(unlink, TESTFN)
411 for encoding in ('ISO-8859-1', 'UTF-8'):
412 with open(TESTFN, 'w', encoding=encoding) as script:
413 if encoding != 'UTF-8':
414 print('#coding: {}'.format(encoding), file=script)
415 print('"""line 1: h\xe9', file=script)
416 print('line 2: hi"""', file=script)
417 synopsis = pydoc.synopsis(TESTFN, {})
418 self.assertEqual(synopsis, 'line 1: h\xe9')
419
R David Murray455f2962013-03-19 00:00:33 -0400420 def test_splitdoc_with_description(self):
421 example_string = "I Am A Doc\n\n\nHere is my description"
422 self.assertEqual(pydoc.splitdoc(example_string),
423 ('I Am A Doc', '\nHere is my description'))
424
425 def test_is_object_or_method(self):
426 doc = pydoc.Doc()
427 # Bound Method
428 self.assertTrue(pydoc._is_some_method(doc.fail))
429 # Method Descriptor
430 self.assertTrue(pydoc._is_some_method(int.__add__))
431 # String
432 self.assertFalse(pydoc._is_some_method("I am not a method"))
433
434 def test_is_package_when_not_package(self):
435 with test.support.temp_cwd() as test_dir:
436 self.assertFalse(pydoc.ispackage(test_dir))
437
438 def test_is_package_when_is_package(self):
439 with test.support.temp_cwd() as test_dir:
440 init_path = os.path.join(test_dir, '__init__.py')
441 open(init_path, 'w').close()
442 self.assertTrue(pydoc.ispackage(test_dir))
443 os.remove(init_path)
444
R David Murrayac0cea52013-03-19 02:47:44 -0400445 def test_allmethods(self):
446 # issue 17476: allmethods was no longer returning unbound methods.
447 # This test is a bit fragile in the face of changes to object and type,
448 # but I can't think of a better way to do it without duplicating the
449 # logic of the function under test.
450
451 class TestClass(object):
452 def method_returning_true(self):
453 return True
454
455 # What we expect to get back: everything on object...
456 expected = dict(vars(object))
457 # ...plus our unbound method...
458 expected['method_returning_true'] = TestClass.method_returning_true
459 # ...but not the non-methods on object.
460 del expected['__doc__']
461 del expected['__class__']
462 # inspect resolves descriptors on type into methods, but vars doesn't,
463 # so we need to update __subclasshook__.
464 expected['__subclasshook__'] = TestClass.__subclasshook__
465
466 methods = pydoc.allmethods(TestClass)
467 self.assertDictEqual(methods, expected)
468
Georg Brandlb533e262008-05-25 18:19:30 +0000469
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200470class PydocImportTest(PydocBaseTest):
Ned Deily92a81a12011-10-06 14:19:03 -0700471
472 def setUp(self):
473 self.test_dir = os.mkdir(TESTFN)
474 self.addCleanup(rmtree, TESTFN)
475
476 def test_badimport(self):
477 # This tests the fix for issue 5230, where if pydoc found the module
478 # but the module had an internal import error pydoc would report no doc
479 # found.
480 modname = 'testmod_xyzzy'
481 testpairs = (
482 ('i_am_not_here', 'i_am_not_here'),
Brett Cannonfd074152012-04-14 14:10:13 -0400483 ('test.i_am_not_here_either', 'test.i_am_not_here_either'),
484 ('test.i_am_not_here.neither_am_i', 'test.i_am_not_here'),
485 ('i_am_not_here.{}'.format(modname), 'i_am_not_here'),
486 ('test.{}'.format(modname), 'test.{}'.format(modname)),
Ned Deily92a81a12011-10-06 14:19:03 -0700487 )
488
489 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
490 for importstring, expectedinmsg in testpairs:
491 with open(sourcefn, 'w') as f:
492 f.write("import {}\n".format(importstring))
493 result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii")
494 expected = badimport_pattern % (modname, expectedinmsg)
495 self.assertEqual(expected, result)
496
497 def test_apropos_with_bad_package(self):
498 # Issue 7425 - pydoc -k failed when bad package on path
499 pkgdir = os.path.join(TESTFN, "syntaxerr")
500 os.mkdir(pkgdir)
501 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
502 with open(badsyntax, 'w') as f:
503 f.write("invalid python syntax = $1\n")
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('xyzzy')
508 # No result, no error
509 self.assertEqual(out.getvalue(), '')
510 self.assertEqual(err.getvalue(), '')
511 # The package name is still matched
512 with captured_stdout() as out:
513 with captured_stderr() as err:
514 pydoc.apropos('syntaxerr')
515 self.assertEqual(out.getvalue().strip(), 'syntaxerr')
516 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700517
518 def test_apropos_with_unreadable_dir(self):
519 # Issue 7367 - pydoc -k failed when unreadable dir on path
520 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
521 os.mkdir(self.unreadable_dir, 0)
522 self.addCleanup(os.rmdir, self.unreadable_dir)
523 # Note, on Windows the directory appears to be still
524 # readable so this is not really testing the issue there
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200525 with self.restrict_walk_packages(path=[TESTFN]):
526 with captured_stdout() as out:
527 with captured_stderr() as err:
528 pydoc.apropos('SOMEKEY')
529 # No result, no error
530 self.assertEqual(out.getvalue(), '')
531 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700532
533
Georg Brandlb533e262008-05-25 18:19:30 +0000534class TestDescriptions(unittest.TestCase):
535
536 def test_module(self):
537 # Check that pydocfodder module can be described
538 from test import pydocfodder
539 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000540 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000541
Georg Brandlb533e262008-05-25 18:19:30 +0000542 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000543 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +0000544 c = C()
545
546 self.assertEqual(pydoc.describe(C), 'class C')
547 self.assertEqual(pydoc.describe(c), 'C')
548 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000549 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000550
Éric Araujoe64e51b2011-07-29 17:03:55 +0200551 def test_builtin(self):
552 for name in ('str', 'str.translate', 'builtins.str',
553 'builtins.str.translate'):
554 # test low-level function
555 self.assertIsNotNone(pydoc.locate(name))
556 # test high-level function
557 try:
558 pydoc.render_doc(name)
559 except ImportError:
560 self.fail('finding the doc of {!r} failed'.format(o))
561
562 for name in ('notbuiltins', 'strrr', 'strr.translate',
563 'str.trrrranslate', 'builtins.strrr',
564 'builtins.str.trrranslate'):
565 self.assertIsNone(pydoc.locate(name))
566 self.assertRaises(ImportError, pydoc.render_doc, name)
567
Georg Brandlb533e262008-05-25 18:19:30 +0000568
Victor Stinner62a68f22011-05-20 02:29:13 +0200569@unittest.skipUnless(threading, 'Threading required for this test.')
Georg Brandld2f38572011-01-30 08:37:19 +0000570class PydocServerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000571 """Tests for pydoc._start_server"""
572
573 def test_server(self):
574
575 # Minimal test that starts the server, then stops it.
576 def my_url_handler(url, content_type):
577 text = 'the URL sent was: (%s, %s)' % (url, content_type)
578 return text
579
580 serverthread = pydoc._start_server(my_url_handler, port=0)
581 starttime = time.time()
582 timeout = 1 #seconds
583
584 while serverthread.serving:
585 time.sleep(.01)
586 if serverthread.serving and time.time() - starttime > timeout:
587 serverthread.stop()
588 break
589
590 self.assertEqual(serverthread.error, None)
591
592
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200593class PydocUrlHandlerTest(PydocBaseTest):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000594 """Tests for pydoc._url_handler"""
595
596 def test_content_type_err(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000597 f = pydoc._url_handler
Georg Brandld2f38572011-01-30 08:37:19 +0000598 self.assertRaises(TypeError, f, 'A', '')
599 self.assertRaises(TypeError, f, 'B', 'foobar')
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000600
601 def test_url_requests(self):
602 # Test for the correct title in the html pages returned.
603 # This tests the different parts of the URL handler without
604 # getting too picky about the exact html.
605 requests = [
Georg Brandld2f38572011-01-30 08:37:19 +0000606 ("", "Pydoc: Index of Modules"),
607 ("get?key=", "Pydoc: Index of Modules"),
608 ("index", "Pydoc: Index of Modules"),
609 ("topics", "Pydoc: Topics"),
610 ("keywords", "Pydoc: Keywords"),
611 ("pydoc", "Pydoc: module pydoc"),
612 ("get?key=pydoc", "Pydoc: module pydoc"),
613 ("search?key=pydoc", "Pydoc: Search Results"),
614 ("topic?key=def", "Pydoc: KEYWORD def"),
615 ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
616 ("foobar", "Pydoc: Error - foobar"),
617 ("getfile?key=foobar", "Pydoc: Error - getfile?key=foobar"),
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000618 ]
619
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200620 with self.restrict_walk_packages():
621 for url, title in requests:
622 text = pydoc._url_handler(url, "text/html")
623 result = get_html_title(text)
624 self.assertEqual(result, title, text)
625
626 path = string.__file__
627 title = "Pydoc: getfile " + path
628 url = "getfile?key=" + path
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000629 text = pydoc._url_handler(url, "text/html")
630 result = get_html_title(text)
631 self.assertEqual(result, title)
632
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000633
Ezio Melottib185a042011-04-28 07:42:55 +0300634class TestHelper(unittest.TestCase):
635 def test_keywords(self):
636 self.assertEqual(sorted(pydoc.Helper.keywords),
637 sorted(keyword.kwlist))
638
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200639@reap_threads
Georg Brandlb533e262008-05-25 18:19:30 +0000640def test_main():
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200641 try:
642 test.support.run_unittest(PydocDocTest,
Ned Deily92a81a12011-10-06 14:19:03 -0700643 PydocImportTest,
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200644 TestDescriptions,
645 PydocServerTest,
646 PydocUrlHandlerTest,
647 TestHelper,
648 )
649 finally:
650 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +0000651
652if __name__ == "__main__":
653 test_main()