blob: 6d27a3021d0b6bb4343cb0c594f8a57421a01dda [file] [log] [blame]
Benjamin Peterson3a7305e2008-05-22 23:09:26 +00001import os
Éric Araujo9a528302011-07-29 17:34:35 +02002import sys
Georg Brandl8632cc22008-05-18 16:32:48 +00003import difflib
Éric Araujo9a528302011-07-29 17:34:35 +02004import __builtin__
Georg Brandl8632cc22008-05-18 16:32:48 +00005import re
6import pydoc
Antoine Pitrouf41ffed2013-05-19 15:44:54 +02007import contextlib
Georg Brandlb7e419e2008-05-20 08:10:03 +00008import inspect
Ezio Melottibdfa2e62011-04-28 07:59:33 +03009import keyword
Antoine Pitrouf41ffed2013-05-19 15:44:54 +020010import pkgutil
Georg Brandl8632cc22008-05-18 16:32:48 +000011import unittest
Brian Curtinaeb2e822010-03-31 03:10:21 +000012import xml.etree
R David Murray984f6302014-01-05 12:35:59 -050013import types
Georg Brandl8632cc22008-05-18 16:32:48 +000014import test.test_support
Raymond Hettinger9aa5a342011-03-25 16:00:13 -070015from collections import namedtuple
Ned Deily1a96f8d2011-10-06 14:17:34 -070016from test.script_helper import assert_python_ok
Antoine Pitrou161df942009-10-30 21:41:22 +000017from test.test_support import (
Antoine Pitrouf41ffed2013-05-19 15:44:54 +020018 TESTFN, rmtree, reap_children, captured_stdout, captured_stderr)
Benjamin Petersonf5c38da2008-05-18 20:48:07 +000019
Georg Brandl8632cc22008-05-18 16:32:48 +000020from test import pydoc_mod
21
Serhiy Storchaka72121c62013-01-27 19:45:49 +020022if test.test_support.HAVE_DOCSTRINGS:
23 expected_data_docstrings = (
24 'dictionary for instance variables (if defined)',
25 'list of weak references to the object (if defined)',
26 )
27else:
28 expected_data_docstrings = ('', '')
29
Georg Brandl8632cc22008-05-18 16:32:48 +000030expected_text_pattern = \
31"""
32NAME
33 test.pydoc_mod - This is a test module for test_pydoc
34
35FILE
36 %s
Benjamin Peterson3a7305e2008-05-22 23:09:26 +000037%s
Georg Brandl8632cc22008-05-18 16:32:48 +000038CLASSES
39 __builtin__.object
40 B
Benjamin Petersonc3e1e902014-06-07 16:44:00 -070041 C
Georg Brandl8632cc22008-05-18 16:32:48 +000042 A
43\x20\x20\x20\x20
44 class A
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\x20\x20
52 class B(__builtin__.object)
53 | Data descriptors defined here:
54 |\x20\x20
Serhiy Storchaka72121c62013-01-27 19:45:49 +020055 | __dict__%s
Georg Brandl8632cc22008-05-18 16:32:48 +000056 |\x20\x20
Serhiy Storchaka72121c62013-01-27 19:45:49 +020057 | __weakref__%s
Georg Brandl8632cc22008-05-18 16:32:48 +000058 |\x20\x20
59 | ----------------------------------------------------------------------
60 | Data and other attributes defined here:
61 |\x20\x20
62 | NO_MEANING = 'eggs'
Benjamin Petersonc3e1e902014-06-07 16:44:00 -070063\x20\x20\x20\x20
64 class C(__builtin__.object)
65 | Methods defined here:
66 |\x20\x20
67 | get_answer(self)
68 | Return say_no()
69 |\x20\x20
70 | is_it_true(self)
71 | Return self.get_answer()
72 |\x20\x20
73 | say_no(self)
74 |\x20\x20
75 | ----------------------------------------------------------------------
76 | Data descriptors defined here:
77 |\x20\x20
78 | __dict__
79 | dictionary for instance variables (if defined)
80 |\x20\x20
81 | __weakref__
82 | list of weak references to the object (if defined)
Georg Brandl8632cc22008-05-18 16:32:48 +000083
84FUNCTIONS
85 doc_func()
86 This function solves all of the world's problems:
87 hunger
88 lack of Python
89 war
90\x20\x20\x20\x20
91 nodoc_func()
92
93DATA
94 __author__ = 'Benjamin Peterson'
95 __credits__ = 'Nobody'
Georg Brandl8632cc22008-05-18 16:32:48 +000096 __version__ = '1.2.3.4'
97
98VERSION
99 1.2.3.4
100
101AUTHOR
102 Benjamin Peterson
103
104CREDITS
105 Nobody
106""".strip()
107
Serhiy Storchaka72121c62013-01-27 19:45:49 +0200108expected_text_data_docstrings = tuple('\n | ' + s if s else ''
109 for s in expected_data_docstrings)
110
Georg Brandl8632cc22008-05-18 16:32:48 +0000111expected_html_pattern = \
112"""
113<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
114<tr bgcolor="#7799ee">
115<td valign=bottom>&nbsp;<br>
116<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
117><td align=right valign=bottom
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000118><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
Georg Brandl8632cc22008-05-18 16:32:48 +0000119 <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
120<p>
121<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
122<tr bgcolor="#ee77aa">
123<td colspan=3 valign=bottom>&nbsp;<br>
124<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
125\x20\x20\x20\x20
126<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
127<td width="100%%"><dl>
128<dt><font face="helvetica, arial"><a href="__builtin__.html#object">__builtin__.object</a>
129</font></dt><dd>
130<dl>
131<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
Benjamin Petersonc3e1e902014-06-07 16:44:00 -0700132</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#C">C</a>
Georg Brandl8632cc22008-05-18 16:32:48 +0000133</font></dt></dl>
134</dd>
135<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
136</font></dt></dl>
137 <p>
138<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
139<tr bgcolor="#ffc8d8">
140<td colspan=3 valign=bottom>&nbsp;<br>
141<font color="#000000" face="helvetica, arial"><a name="A">class <strong>A</strong></a></font></td></tr>
142\x20\x20\x20\x20
143<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
144<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
145<tr><td>&nbsp;</td>
146<td width="100%%">Methods defined here:<br>
147<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>
148
149</td></tr></table> <p>
150<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
151<tr bgcolor="#ffc8d8">
152<td colspan=3 valign=bottom>&nbsp;<br>
153<font color="#000000" face="helvetica, arial"><a name="B">class <strong>B</strong></a>(<a href="__builtin__.html#object">__builtin__.object</a>)</font></td></tr>
154\x20\x20\x20\x20
155<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
156<td width="100%%">Data descriptors defined here:<br>
157<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka72121c62013-01-27 19:45:49 +0200158<dd><tt>%s</tt></dd>
Georg Brandl8632cc22008-05-18 16:32:48 +0000159</dl>
160<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka72121c62013-01-27 19:45:49 +0200161<dd><tt>%s</tt></dd>
Georg Brandl8632cc22008-05-18 16:32:48 +0000162</dl>
163<hr>
164Data and other attributes defined here:<br>
165<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
166
Benjamin Petersonc3e1e902014-06-07 16:44:00 -0700167</td></tr></table> <p>
168<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
169<tr bgcolor="#ffc8d8">
170<td colspan=3 valign=bottom>&nbsp;<br>
171<font color="#000000" face="helvetica, arial"><a name="C">class <strong>C</strong></a>(<a href="__builtin__.html#object">__builtin__.object</a>)</font></td></tr>
172\x20\x20\x20\x20
173<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
174<td width="100%%">Methods defined here:<br>
175<dl><dt><a name="C-get_answer"><strong>get_answer</strong></a>(self)</dt><dd><tt>Return&nbsp;<a href="#C-say_no">say_no</a>()</tt></dd></dl>
176
177<dl><dt><a name="C-is_it_true"><strong>is_it_true</strong></a>(self)</dt><dd><tt>Return&nbsp;self.<a href="#C-get_answer">get_answer</a>()</tt></dd></dl>
178
179<dl><dt><a name="C-say_no"><strong>say_no</strong></a>(self)</dt></dl>
180
181<hr>
182Data descriptors defined here:<br>
183<dl><dt><strong>__dict__</strong></dt>
184<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
185</dl>
186<dl><dt><strong>__weakref__</strong></dt>
187<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
188</dl>
Georg Brandl8632cc22008-05-18 16:32:48 +0000189</td></tr></table></td></tr></table><p>
190<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
191<tr bgcolor="#eeaa77">
192<td colspan=3 valign=bottom>&nbsp;<br>
193<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
194\x20\x20\x20\x20
195<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
196<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>
197hunger<br>
198lack&nbsp;of&nbsp;Python<br>
199war</tt></dd></dl>
200 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
201</td></tr></table><p>
202<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
203<tr bgcolor="#55aa55">
204<td colspan=3 valign=bottom>&nbsp;<br>
205<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
206\x20\x20\x20\x20
207<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
208<td width="100%%"><strong>__author__</strong> = 'Benjamin Peterson'<br>
209<strong>__credits__</strong> = 'Nobody'<br>
Georg Brandl8632cc22008-05-18 16:32:48 +0000210<strong>__version__</strong> = '1.2.3.4'</td></tr></table><p>
211<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
212<tr bgcolor="#7799ee">
213<td colspan=3 valign=bottom>&nbsp;<br>
214<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
215\x20\x20\x20\x20
216<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
217<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
218<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
219<tr bgcolor="#7799ee">
220<td colspan=3 valign=bottom>&nbsp;<br>
221<font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
222\x20\x20\x20\x20
223<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
224<td width="100%%">Nobody</td></tr></table>
225""".strip()
226
Serhiy Storchaka72121c62013-01-27 19:45:49 +0200227expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;')
228 for s in expected_data_docstrings)
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000229
Georg Brandl8632cc22008-05-18 16:32:48 +0000230# output pattern for missing module
231missing_pattern = "no Python documentation found for '%s'"
232
R. David Murrayef087da2009-06-23 18:02:46 +0000233# output pattern for module with bad imports
234badimport_pattern = "problem in %s - <type 'exceptions.ImportError'>: No module named %s"
235
Ned Deily1a96f8d2011-10-06 14:17:34 -0700236def run_pydoc(module_name, *args, **env):
Georg Brandl8632cc22008-05-18 16:32:48 +0000237 """
238 Runs pydoc on the specified module. Returns the stripped
239 output of pydoc.
240 """
Ned Deily1a96f8d2011-10-06 14:17:34 -0700241 args = args + (module_name,)
242 # do not write bytecode files to avoid caching errors
243 rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
244 return out.strip()
Georg Brandl8632cc22008-05-18 16:32:48 +0000245
246def get_pydoc_html(module):
247 "Returns pydoc generated output as html"
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000248 doc = pydoc.HTMLDoc()
249 output = doc.docmodule(module)
250 loc = doc.getdocloc(pydoc_mod) or ""
251 if loc:
252 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
253 return output.strip(), loc
Georg Brandl8632cc22008-05-18 16:32:48 +0000254
255def get_pydoc_text(module):
256 "Returns pydoc generated output as text"
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000257 doc = pydoc.TextDoc()
258 loc = doc.getdocloc(pydoc_mod) or ""
259 if loc:
260 loc = "\nMODULE DOCS\n " + loc + "\n"
261
262 output = doc.docmodule(module)
Georg Brandl8632cc22008-05-18 16:32:48 +0000263
264 # cleanup the extra text formatting that pydoc preforms
265 patt = re.compile('\b.')
266 output = patt.sub('', output)
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000267 return output.strip(), loc
Georg Brandl8632cc22008-05-18 16:32:48 +0000268
269def print_diffs(text1, text2):
270 "Prints unified diffs for two texts"
Georg Brandlfb3de1f2008-05-20 08:07:36 +0000271 lines1 = text1.splitlines(True)
272 lines2 = text2.splitlines(True)
273 diffs = difflib.unified_diff(lines1, lines2, n=0, fromfile='expected',
274 tofile='got')
275 print '\n' + ''.join(diffs)
Georg Brandl8632cc22008-05-18 16:32:48 +0000276
Georg Brandl8632cc22008-05-18 16:32:48 +0000277
Antoine Pitrouf41ffed2013-05-19 15:44:54 +0200278class PydocBaseTest(unittest.TestCase):
279
280 def _restricted_walk_packages(self, walk_packages, path=None):
281 """
282 A version of pkgutil.walk_packages() that will restrict itself to
283 a given path.
284 """
285 default_path = path or [os.path.dirname(__file__)]
286 def wrapper(path=None, prefix='', onerror=None):
287 return walk_packages(path or default_path, prefix, onerror)
288 return wrapper
289
290 @contextlib.contextmanager
291 def restrict_walk_packages(self, path=None):
292 walk_packages = pkgutil.walk_packages
293 pkgutil.walk_packages = self._restricted_walk_packages(walk_packages,
294 path)
295 try:
296 yield
297 finally:
298 pkgutil.walk_packages = walk_packages
299
300
301class PydocDocTest(unittest.TestCase):
Georg Brandl8632cc22008-05-18 16:32:48 +0000302
R. David Murrayf28fd242010-02-23 00:24:49 +0000303 @unittest.skipIf(sys.flags.optimize >= 2,
304 "Docstrings are omitted with -O2 and above")
Georg Brandl8632cc22008-05-18 16:32:48 +0000305 def test_html_doc(self):
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000306 result, doc_loc = get_pydoc_html(pydoc_mod)
Georg Brandlb7e419e2008-05-20 08:10:03 +0000307 mod_file = inspect.getabsfile(pydoc_mod)
Amaury Forgeot d'Arc8e8de4a2008-06-10 21:37:15 +0000308 if sys.platform == 'win32':
309 import nturl2path
310 mod_url = nturl2path.pathname2url(mod_file)
311 else:
312 mod_url = mod_file
Serhiy Storchaka72121c62013-01-27 19:45:49 +0200313 expected_html = expected_html_pattern % (
314 (mod_url, mod_file, doc_loc) +
315 expected_html_data_docstrings)
Georg Brandl8632cc22008-05-18 16:32:48 +0000316 if result != expected_html:
Georg Brandlfb3de1f2008-05-20 08:07:36 +0000317 print_diffs(expected_html, result)
Georg Brandl8632cc22008-05-18 16:32:48 +0000318 self.fail("outputs are not equal, see diff above")
319
R. David Murrayf28fd242010-02-23 00:24:49 +0000320 @unittest.skipIf(sys.flags.optimize >= 2,
321 "Docstrings are omitted with -O2 and above")
Georg Brandl8632cc22008-05-18 16:32:48 +0000322 def test_text_doc(self):
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000323 result, doc_loc = get_pydoc_text(pydoc_mod)
Serhiy Storchaka72121c62013-01-27 19:45:49 +0200324 expected_text = expected_text_pattern % (
325 (inspect.getabsfile(pydoc_mod), doc_loc) +
326 expected_text_data_docstrings)
Georg Brandl8632cc22008-05-18 16:32:48 +0000327 if result != expected_text:
Georg Brandlfb3de1f2008-05-20 08:07:36 +0000328 print_diffs(expected_text, result)
Georg Brandl8632cc22008-05-18 16:32:48 +0000329 self.fail("outputs are not equal, see diff above")
330
Brian Curtinaeb2e822010-03-31 03:10:21 +0000331 def test_issue8225(self):
332 # Test issue8225 to ensure no doc link appears for xml.etree
333 result, doc_loc = get_pydoc_text(xml.etree)
334 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
335
Benjamin Peterson75a55c32014-06-07 20:14:26 -0700336 def test_getpager_with_stdin_none(self):
337 previous_stdin = sys.stdin
338 try:
339 sys.stdin = None
340 pydoc.getpager() # Shouldn't fail.
341 finally:
342 sys.stdin = previous_stdin
343
R David Murrayc313b1d2012-04-23 13:27:11 -0400344 def test_non_str_name(self):
345 # issue14638
346 # Treat illegal (non-str) name like no name
347 class A:
348 __name__ = 42
349 class B:
350 pass
351 adoc = pydoc.render_doc(A())
352 bdoc = pydoc.render_doc(B())
353 self.assertEqual(adoc.replace("A", "B"), bdoc)
354
Benjamin Petersonf5c38da2008-05-18 20:48:07 +0000355 def test_not_here(self):
356 missing_module = "test.i_am_not_here"
357 result = run_pydoc(missing_module)
358 expected = missing_pattern % missing_module
359 self.assertEqual(expected, result,
360 "documentation for missing module found")
361
R. David Murrayd67ea7d2009-05-27 20:07:21 +0000362 def test_input_strip(self):
363 missing_module = " test.i_am_not_here "
364 result = run_pydoc(missing_module)
365 expected = missing_pattern % missing_module.strip()
366 self.assertEqual(expected, result,
367 "white space was not stripped from module name "
368 "or other error output mismatch")
369
Ezio Melottie511fc72010-02-16 23:26:09 +0000370 def test_stripid(self):
371 # test with strings, other implementations might have different repr()
372 stripid = pydoc.stripid
373 # strip the id
374 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
375 '<function stripid>')
376 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
377 '<function stripid>')
378 # nothing to strip, return the same text
379 self.assertEqual(stripid('42'), '42')
380 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
381 "<type 'exceptions.Exception'>")
382
Georg Brandl8632cc22008-05-18 16:32:48 +0000383
Antoine Pitrouf41ffed2013-05-19 15:44:54 +0200384class PydocImportTest(PydocBaseTest):
Ned Deily1a96f8d2011-10-06 14:17:34 -0700385
386 def setUp(self):
387 self.test_dir = os.mkdir(TESTFN)
388 self.addCleanup(rmtree, TESTFN)
389
390 def test_badimport(self):
391 # This tests the fix for issue 5230, where if pydoc found the module
392 # but the module had an internal import error pydoc would report no doc
393 # found.
394 modname = 'testmod_xyzzy'
395 testpairs = (
396 ('i_am_not_here', 'i_am_not_here'),
397 ('test.i_am_not_here_either', 'i_am_not_here_either'),
398 ('test.i_am_not_here.neither_am_i', 'i_am_not_here.neither_am_i'),
399 ('i_am_not_here.{}'.format(modname),
400 'i_am_not_here.{}'.format(modname)),
401 ('test.{}'.format(modname), modname),
402 )
403
404 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
405 for importstring, expectedinmsg in testpairs:
406 with open(sourcefn, 'w') as f:
407 f.write("import {}\n".format(importstring))
408 result = run_pydoc(modname, PYTHONPATH=TESTFN)
409 expected = badimport_pattern % (modname, expectedinmsg)
410 self.assertEqual(expected, result)
411
412 def test_apropos_with_bad_package(self):
413 # Issue 7425 - pydoc -k failed when bad package on path
414 pkgdir = os.path.join(TESTFN, "syntaxerr")
415 os.mkdir(pkgdir)
416 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
417 with open(badsyntax, 'w') as f:
418 f.write("invalid python syntax = $1\n")
Antoine Pitrouf41ffed2013-05-19 15:44:54 +0200419 with self.restrict_walk_packages(path=[TESTFN]):
420 with captured_stdout() as out:
421 with captured_stderr() as err:
422 pydoc.apropos('xyzzy')
423 # No result, no error
424 self.assertEqual(out.getvalue(), '')
425 self.assertEqual(err.getvalue(), '')
426 # The package name is still matched
427 with captured_stdout() as out:
428 with captured_stderr() as err:
429 pydoc.apropos('syntaxerr')
430 self.assertEqual(out.getvalue().strip(), 'syntaxerr')
431 self.assertEqual(err.getvalue(), '')
Ned Deily1a96f8d2011-10-06 14:17:34 -0700432
433 def test_apropos_with_unreadable_dir(self):
434 # Issue 7367 - pydoc -k failed when unreadable dir on path
435 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
436 os.mkdir(self.unreadable_dir, 0)
437 self.addCleanup(os.rmdir, self.unreadable_dir)
438 # Note, on Windows the directory appears to be still
439 # readable so this is not really testing the issue there
Antoine Pitrouf41ffed2013-05-19 15:44:54 +0200440 with self.restrict_walk_packages(path=[TESTFN]):
441 with captured_stdout() as out:
442 with captured_stderr() as err:
443 pydoc.apropos('SOMEKEY')
444 # No result, no error
445 self.assertEqual(out.getvalue(), '')
446 self.assertEqual(err.getvalue(), '')
Ned Deily1a96f8d2011-10-06 14:17:34 -0700447
448
Georg Brandl8632cc22008-05-18 16:32:48 +0000449class TestDescriptions(unittest.TestCase):
Benjamin Petersonf5c38da2008-05-18 20:48:07 +0000450
Georg Brandl8632cc22008-05-18 16:32:48 +0000451 def test_module(self):
452 # Check that pydocfodder module can be described
453 from test import pydocfodder
454 doc = pydoc.render_doc(pydocfodder)
Ezio Melottiaa980582010-01-23 23:04:36 +0000455 self.assertIn("pydocfodder", doc)
Georg Brandl8632cc22008-05-18 16:32:48 +0000456
457 def test_classic_class(self):
458 class C: "Classic class"
459 c = C()
Benjamin Petersonf5c38da2008-05-18 20:48:07 +0000460 self.assertEqual(pydoc.describe(C), 'class C')
461 self.assertEqual(pydoc.describe(c), 'instance of C')
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000462 expected = 'instance of C in module %s' % __name__
Ezio Melottiaa980582010-01-23 23:04:36 +0000463 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandl8632cc22008-05-18 16:32:48 +0000464
465 def test_class(self):
466 class C(object): "New-style class"
467 c = C()
468
Benjamin Petersonf5c38da2008-05-18 20:48:07 +0000469 self.assertEqual(pydoc.describe(C), 'class C')
470 self.assertEqual(pydoc.describe(c), 'C')
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000471 expected = 'C in module %s object' % __name__
Ezio Melottiaa980582010-01-23 23:04:36 +0000472 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandl8632cc22008-05-18 16:32:48 +0000473
Raymond Hettinger9aa5a342011-03-25 16:00:13 -0700474 def test_namedtuple_public_underscore(self):
475 NT = namedtuple('NT', ['abc', 'def'], rename=True)
476 with captured_stdout() as help_io:
Terry Jan Reedyc0e60472013-11-04 21:45:33 -0500477 pydoc.help(NT)
Raymond Hettinger9aa5a342011-03-25 16:00:13 -0700478 helptext = help_io.getvalue()
479 self.assertIn('_1', helptext)
480 self.assertIn('_replace', helptext)
481 self.assertIn('_asdict', helptext)
482
Georg Brandl8632cc22008-05-18 16:32:48 +0000483
R David Murray984f6302014-01-05 12:35:59 -0500484@unittest.skipUnless(test.test_support.have_unicode,
485 "test requires unicode support")
486class TestUnicode(unittest.TestCase):
487
488 def setUp(self):
489 # Better not to use unicode escapes in literals, lest the
490 # parser choke on it if Python has been built without
491 # unicode support.
492 self.Q = types.ModuleType(
493 'Q', 'Rational numbers: \xe2\x84\x9a'.decode('utf8'))
494 self.Q.__version__ = '\xe2\x84\x9a'.decode('utf8')
495 self.Q.__date__ = '\xe2\x84\x9a'.decode('utf8')
496 self.Q.__author__ = '\xe2\x84\x9a'.decode('utf8')
497 self.Q.__credits__ = '\xe2\x84\x9a'.decode('utf8')
498
499 self.assertIsInstance(self.Q.__doc__, unicode)
500
501 def test_render_doc(self):
502 # render_doc is robust against unicode in docstrings
503 doc = pydoc.render_doc(self.Q)
504 self.assertIsInstance(doc, str)
505
506 def test_encode(self):
507 # _encode is robust against characters out the specified encoding
508 self.assertEqual(pydoc._encode(self.Q.__doc__, 'ascii'), 'Rational numbers: &#8474;')
509
510 def test_pipepager(self):
511 # pipepager does not choke on unicode
512 doc = pydoc.render_doc(self.Q)
513
514 saved, os.popen = os.popen, open
515 try:
516 with test.test_support.temp_cwd():
517 pydoc.pipepager(doc, 'pipe')
518 self.assertEqual(open('pipe').read(), pydoc._encode(doc))
519 finally:
520 os.popen = saved
521
522 def test_tempfilepager(self):
523 # tempfilepager does not choke on unicode
524 doc = pydoc.render_doc(self.Q)
525
526 output = {}
527 def mock_system(cmd):
Serhiy Storchakaee105dc2014-01-10 22:43:03 +0200528 filename = cmd.strip()[1:-1]
529 self.assertEqual('"' + filename + '"', cmd.strip())
530 output['content'] = open(filename).read()
R David Murray984f6302014-01-05 12:35:59 -0500531 saved, os.system = os.system, mock_system
532 try:
533 pydoc.tempfilepager(doc, '')
534 self.assertEqual(output['content'], pydoc._encode(doc))
535 finally:
536 os.system = saved
537
538 def test_plainpager(self):
539 # plainpager does not choke on unicode
540 doc = pydoc.render_doc(self.Q)
541
542 # Note: captured_stdout is too permissive when it comes to
543 # unicode, and using it here would make the test always
544 # pass.
545 with test.test_support.temp_cwd():
546 with open('output', 'w') as f:
547 saved, sys.stdout = sys.stdout, f
548 try:
549 pydoc.plainpager(doc)
550 finally:
551 sys.stdout = saved
552 self.assertIn('Rational numbers:', open('output').read())
553
554 def test_ttypager(self):
555 # ttypager does not choke on unicode
556 doc = pydoc.render_doc(self.Q)
557 # Test ttypager
558 with test.test_support.temp_cwd(), test.test_support.captured_stdin():
559 with open('output', 'w') as f:
560 saved, sys.stdout = sys.stdout, f
561 try:
562 pydoc.ttypager(doc)
563 finally:
564 sys.stdout = saved
565 self.assertIn('Rational numbers:', open('output').read())
566
567 def test_htmlpage(self):
568 # html.page does not choke on unicode
569 with test.test_support.temp_cwd():
570 with captured_stdout() as output:
571 pydoc.writedoc(self.Q)
572 self.assertEqual(output.getvalue(), 'wrote Q.html\n')
573
Ezio Melottibdfa2e62011-04-28 07:59:33 +0300574class TestHelper(unittest.TestCase):
575 def test_keywords(self):
576 self.assertEqual(sorted(pydoc.Helper.keywords),
577 sorted(keyword.kwlist))
578
Éric Araujo9a528302011-07-29 17:34:35 +0200579 def test_builtin(self):
580 for name in ('str', 'str.translate', '__builtin__.str',
581 '__builtin__.str.translate'):
582 # test low-level function
583 self.assertIsNotNone(pydoc.locate(name))
584 # test high-level function
585 try:
586 pydoc.render_doc(name)
587 except ImportError:
Terry Jan Reedy72998182014-06-20 14:59:07 -0400588 self.fail('finding the doc of {!r} failed'.format(name))
Éric Araujo9a528302011-07-29 17:34:35 +0200589
590 for name in ('not__builtin__', 'strrr', 'strr.translate',
591 'str.trrrranslate', '__builtin__.strrr',
592 '__builtin__.str.trrranslate'):
593 self.assertIsNone(pydoc.locate(name))
594 self.assertRaises(ImportError, pydoc.render_doc, name)
595
Ezio Melottibdfa2e62011-04-28 07:59:33 +0300596
Georg Brandl8632cc22008-05-18 16:32:48 +0000597def test_main():
Ned Deily1a96f8d2011-10-06 14:17:34 -0700598 try:
Antoine Pitrouf41ffed2013-05-19 15:44:54 +0200599 test.test_support.run_unittest(PydocDocTest,
Ned Deily1a96f8d2011-10-06 14:17:34 -0700600 PydocImportTest,
601 TestDescriptions,
R David Murray984f6302014-01-05 12:35:59 -0500602 TestUnicode,
Ned Deily1a96f8d2011-10-06 14:17:34 -0700603 TestHelper)
604 finally:
605 reap_children()
Georg Brandl8632cc22008-05-18 16:32:48 +0000606
607if __name__ == "__main__":
608 test_main()