blob: c11c06b524e4cc8a5b8a9f22949b6b741378c9aa [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
Charles-François Natali94919a42014-06-20 22:57:19 +010017from test.test_support import (TESTFN, rmtree, reap_children, captured_stdout,
18 captured_stderr, requires_docstrings)
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
Charles-François Natali94919a42014-06-20 22:57:19 +0100303 @requires_docstrings
R. David Murrayf28fd242010-02-23 00:24:49 +0000304 @unittest.skipIf(sys.flags.optimize >= 2,
305 "Docstrings are omitted with -O2 and above")
Georg Brandl8632cc22008-05-18 16:32:48 +0000306 def test_html_doc(self):
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000307 result, doc_loc = get_pydoc_html(pydoc_mod)
Georg Brandlb7e419e2008-05-20 08:10:03 +0000308 mod_file = inspect.getabsfile(pydoc_mod)
Amaury Forgeot d'Arc8e8de4a2008-06-10 21:37:15 +0000309 if sys.platform == 'win32':
310 import nturl2path
311 mod_url = nturl2path.pathname2url(mod_file)
312 else:
313 mod_url = mod_file
Serhiy Storchaka72121c62013-01-27 19:45:49 +0200314 expected_html = expected_html_pattern % (
315 (mod_url, mod_file, doc_loc) +
316 expected_html_data_docstrings)
Georg Brandl8632cc22008-05-18 16:32:48 +0000317 if result != expected_html:
Georg Brandlfb3de1f2008-05-20 08:07:36 +0000318 print_diffs(expected_html, result)
Georg Brandl8632cc22008-05-18 16:32:48 +0000319 self.fail("outputs are not equal, see diff above")
320
Charles-François Natali94919a42014-06-20 22:57:19 +0100321 @requires_docstrings
R. David Murrayf28fd242010-02-23 00:24:49 +0000322 @unittest.skipIf(sys.flags.optimize >= 2,
323 "Docstrings are omitted with -O2 and above")
Georg Brandl8632cc22008-05-18 16:32:48 +0000324 def test_text_doc(self):
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000325 result, doc_loc = get_pydoc_text(pydoc_mod)
Serhiy Storchaka72121c62013-01-27 19:45:49 +0200326 expected_text = expected_text_pattern % (
327 (inspect.getabsfile(pydoc_mod), doc_loc) +
328 expected_text_data_docstrings)
Georg Brandl8632cc22008-05-18 16:32:48 +0000329 if result != expected_text:
Georg Brandlfb3de1f2008-05-20 08:07:36 +0000330 print_diffs(expected_text, result)
Georg Brandl8632cc22008-05-18 16:32:48 +0000331 self.fail("outputs are not equal, see diff above")
332
Brian Curtinaeb2e822010-03-31 03:10:21 +0000333 def test_issue8225(self):
334 # Test issue8225 to ensure no doc link appears for xml.etree
335 result, doc_loc = get_pydoc_text(xml.etree)
336 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
337
Benjamin Peterson75a55c32014-06-07 20:14:26 -0700338 def test_getpager_with_stdin_none(self):
339 previous_stdin = sys.stdin
340 try:
341 sys.stdin = None
342 pydoc.getpager() # Shouldn't fail.
343 finally:
344 sys.stdin = previous_stdin
345
R David Murrayc313b1d2012-04-23 13:27:11 -0400346 def test_non_str_name(self):
347 # issue14638
348 # Treat illegal (non-str) name like no name
349 class A:
350 __name__ = 42
351 class B:
352 pass
353 adoc = pydoc.render_doc(A())
354 bdoc = pydoc.render_doc(B())
355 self.assertEqual(adoc.replace("A", "B"), bdoc)
356
Benjamin Petersonf5c38da2008-05-18 20:48:07 +0000357 def test_not_here(self):
358 missing_module = "test.i_am_not_here"
359 result = run_pydoc(missing_module)
360 expected = missing_pattern % missing_module
361 self.assertEqual(expected, result,
362 "documentation for missing module found")
363
R. David Murrayd67ea7d2009-05-27 20:07:21 +0000364 def test_input_strip(self):
365 missing_module = " test.i_am_not_here "
366 result = run_pydoc(missing_module)
367 expected = missing_pattern % missing_module.strip()
368 self.assertEqual(expected, result,
369 "white space was not stripped from module name "
370 "or other error output mismatch")
371
Ezio Melottie511fc72010-02-16 23:26:09 +0000372 def test_stripid(self):
373 # test with strings, other implementations might have different repr()
374 stripid = pydoc.stripid
375 # strip the id
376 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
377 '<function stripid>')
378 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
379 '<function stripid>')
380 # nothing to strip, return the same text
381 self.assertEqual(stripid('42'), '42')
382 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
383 "<type 'exceptions.Exception'>")
384
Georg Brandl8632cc22008-05-18 16:32:48 +0000385
Antoine Pitrouf41ffed2013-05-19 15:44:54 +0200386class PydocImportTest(PydocBaseTest):
Ned Deily1a96f8d2011-10-06 14:17:34 -0700387
388 def setUp(self):
389 self.test_dir = os.mkdir(TESTFN)
390 self.addCleanup(rmtree, TESTFN)
391
392 def test_badimport(self):
393 # This tests the fix for issue 5230, where if pydoc found the module
394 # but the module had an internal import error pydoc would report no doc
395 # found.
396 modname = 'testmod_xyzzy'
397 testpairs = (
398 ('i_am_not_here', 'i_am_not_here'),
399 ('test.i_am_not_here_either', 'i_am_not_here_either'),
400 ('test.i_am_not_here.neither_am_i', 'i_am_not_here.neither_am_i'),
401 ('i_am_not_here.{}'.format(modname),
402 'i_am_not_here.{}'.format(modname)),
403 ('test.{}'.format(modname), modname),
404 )
405
406 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
407 for importstring, expectedinmsg in testpairs:
408 with open(sourcefn, 'w') as f:
409 f.write("import {}\n".format(importstring))
410 result = run_pydoc(modname, PYTHONPATH=TESTFN)
411 expected = badimport_pattern % (modname, expectedinmsg)
412 self.assertEqual(expected, result)
413
414 def test_apropos_with_bad_package(self):
415 # Issue 7425 - pydoc -k failed when bad package on path
416 pkgdir = os.path.join(TESTFN, "syntaxerr")
417 os.mkdir(pkgdir)
418 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
419 with open(badsyntax, 'w') as f:
420 f.write("invalid python syntax = $1\n")
Antoine Pitrouf41ffed2013-05-19 15:44:54 +0200421 with self.restrict_walk_packages(path=[TESTFN]):
422 with captured_stdout() as out:
423 with captured_stderr() as err:
424 pydoc.apropos('xyzzy')
425 # No result, no error
426 self.assertEqual(out.getvalue(), '')
427 self.assertEqual(err.getvalue(), '')
428 # The package name is still matched
429 with captured_stdout() as out:
430 with captured_stderr() as err:
431 pydoc.apropos('syntaxerr')
432 self.assertEqual(out.getvalue().strip(), 'syntaxerr')
433 self.assertEqual(err.getvalue(), '')
Ned Deily1a96f8d2011-10-06 14:17:34 -0700434
435 def test_apropos_with_unreadable_dir(self):
436 # Issue 7367 - pydoc -k failed when unreadable dir on path
437 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
438 os.mkdir(self.unreadable_dir, 0)
439 self.addCleanup(os.rmdir, self.unreadable_dir)
440 # Note, on Windows the directory appears to be still
441 # readable so this is not really testing the issue there
Antoine Pitrouf41ffed2013-05-19 15:44:54 +0200442 with self.restrict_walk_packages(path=[TESTFN]):
443 with captured_stdout() as out:
444 with captured_stderr() as err:
445 pydoc.apropos('SOMEKEY')
446 # No result, no error
447 self.assertEqual(out.getvalue(), '')
448 self.assertEqual(err.getvalue(), '')
Ned Deily1a96f8d2011-10-06 14:17:34 -0700449
450
Georg Brandl8632cc22008-05-18 16:32:48 +0000451class TestDescriptions(unittest.TestCase):
Benjamin Petersonf5c38da2008-05-18 20:48:07 +0000452
Georg Brandl8632cc22008-05-18 16:32:48 +0000453 def test_module(self):
454 # Check that pydocfodder module can be described
455 from test import pydocfodder
456 doc = pydoc.render_doc(pydocfodder)
Ezio Melottiaa980582010-01-23 23:04:36 +0000457 self.assertIn("pydocfodder", doc)
Georg Brandl8632cc22008-05-18 16:32:48 +0000458
459 def test_classic_class(self):
460 class C: "Classic class"
461 c = C()
Benjamin Petersonf5c38da2008-05-18 20:48:07 +0000462 self.assertEqual(pydoc.describe(C), 'class C')
463 self.assertEqual(pydoc.describe(c), 'instance of C')
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000464 expected = 'instance of C in module %s' % __name__
Ezio Melottiaa980582010-01-23 23:04:36 +0000465 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandl8632cc22008-05-18 16:32:48 +0000466
467 def test_class(self):
468 class C(object): "New-style class"
469 c = C()
470
Benjamin Petersonf5c38da2008-05-18 20:48:07 +0000471 self.assertEqual(pydoc.describe(C), 'class C')
472 self.assertEqual(pydoc.describe(c), 'C')
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000473 expected = 'C in module %s object' % __name__
Ezio Melottiaa980582010-01-23 23:04:36 +0000474 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandl8632cc22008-05-18 16:32:48 +0000475
Raymond Hettinger9aa5a342011-03-25 16:00:13 -0700476 def test_namedtuple_public_underscore(self):
477 NT = namedtuple('NT', ['abc', 'def'], rename=True)
478 with captured_stdout() as help_io:
Terry Jan Reedyc0e60472013-11-04 21:45:33 -0500479 pydoc.help(NT)
Raymond Hettinger9aa5a342011-03-25 16:00:13 -0700480 helptext = help_io.getvalue()
481 self.assertIn('_1', helptext)
482 self.assertIn('_replace', helptext)
483 self.assertIn('_asdict', helptext)
484
Georg Brandl8632cc22008-05-18 16:32:48 +0000485
R David Murray984f6302014-01-05 12:35:59 -0500486@unittest.skipUnless(test.test_support.have_unicode,
487 "test requires unicode support")
488class TestUnicode(unittest.TestCase):
489
490 def setUp(self):
491 # Better not to use unicode escapes in literals, lest the
492 # parser choke on it if Python has been built without
493 # unicode support.
494 self.Q = types.ModuleType(
495 'Q', 'Rational numbers: \xe2\x84\x9a'.decode('utf8'))
496 self.Q.__version__ = '\xe2\x84\x9a'.decode('utf8')
497 self.Q.__date__ = '\xe2\x84\x9a'.decode('utf8')
498 self.Q.__author__ = '\xe2\x84\x9a'.decode('utf8')
499 self.Q.__credits__ = '\xe2\x84\x9a'.decode('utf8')
500
501 self.assertIsInstance(self.Q.__doc__, unicode)
502
503 def test_render_doc(self):
504 # render_doc is robust against unicode in docstrings
505 doc = pydoc.render_doc(self.Q)
506 self.assertIsInstance(doc, str)
507
508 def test_encode(self):
509 # _encode is robust against characters out the specified encoding
510 self.assertEqual(pydoc._encode(self.Q.__doc__, 'ascii'), 'Rational numbers: &#8474;')
511
512 def test_pipepager(self):
513 # pipepager does not choke on unicode
514 doc = pydoc.render_doc(self.Q)
515
516 saved, os.popen = os.popen, open
517 try:
518 with test.test_support.temp_cwd():
519 pydoc.pipepager(doc, 'pipe')
520 self.assertEqual(open('pipe').read(), pydoc._encode(doc))
521 finally:
522 os.popen = saved
523
524 def test_tempfilepager(self):
525 # tempfilepager does not choke on unicode
526 doc = pydoc.render_doc(self.Q)
527
528 output = {}
529 def mock_system(cmd):
Serhiy Storchakaee105dc2014-01-10 22:43:03 +0200530 filename = cmd.strip()[1:-1]
531 self.assertEqual('"' + filename + '"', cmd.strip())
532 output['content'] = open(filename).read()
R David Murray984f6302014-01-05 12:35:59 -0500533 saved, os.system = os.system, mock_system
534 try:
535 pydoc.tempfilepager(doc, '')
536 self.assertEqual(output['content'], pydoc._encode(doc))
537 finally:
538 os.system = saved
539
540 def test_plainpager(self):
541 # plainpager does not choke on unicode
542 doc = pydoc.render_doc(self.Q)
543
544 # Note: captured_stdout is too permissive when it comes to
545 # unicode, and using it here would make the test always
546 # pass.
547 with test.test_support.temp_cwd():
548 with open('output', 'w') as f:
549 saved, sys.stdout = sys.stdout, f
550 try:
551 pydoc.plainpager(doc)
552 finally:
553 sys.stdout = saved
554 self.assertIn('Rational numbers:', open('output').read())
555
556 def test_ttypager(self):
557 # ttypager does not choke on unicode
558 doc = pydoc.render_doc(self.Q)
559 # Test ttypager
560 with test.test_support.temp_cwd(), test.test_support.captured_stdin():
561 with open('output', 'w') as f:
562 saved, sys.stdout = sys.stdout, f
563 try:
564 pydoc.ttypager(doc)
565 finally:
566 sys.stdout = saved
567 self.assertIn('Rational numbers:', open('output').read())
568
569 def test_htmlpage(self):
570 # html.page does not choke on unicode
571 with test.test_support.temp_cwd():
572 with captured_stdout() as output:
573 pydoc.writedoc(self.Q)
574 self.assertEqual(output.getvalue(), 'wrote Q.html\n')
575
Ezio Melottibdfa2e62011-04-28 07:59:33 +0300576class TestHelper(unittest.TestCase):
577 def test_keywords(self):
578 self.assertEqual(sorted(pydoc.Helper.keywords),
579 sorted(keyword.kwlist))
580
Éric Araujo9a528302011-07-29 17:34:35 +0200581 def test_builtin(self):
582 for name in ('str', 'str.translate', '__builtin__.str',
583 '__builtin__.str.translate'):
584 # test low-level function
585 self.assertIsNotNone(pydoc.locate(name))
586 # test high-level function
587 try:
588 pydoc.render_doc(name)
589 except ImportError:
Terry Jan Reedy72998182014-06-20 14:59:07 -0400590 self.fail('finding the doc of {!r} failed'.format(name))
Éric Araujo9a528302011-07-29 17:34:35 +0200591
592 for name in ('not__builtin__', 'strrr', 'strr.translate',
593 'str.trrrranslate', '__builtin__.strrr',
594 '__builtin__.str.trrranslate'):
595 self.assertIsNone(pydoc.locate(name))
596 self.assertRaises(ImportError, pydoc.render_doc, name)
597
Ezio Melottibdfa2e62011-04-28 07:59:33 +0300598
Georg Brandl8632cc22008-05-18 16:32:48 +0000599def test_main():
Ned Deily1a96f8d2011-10-06 14:17:34 -0700600 try:
Antoine Pitrouf41ffed2013-05-19 15:44:54 +0200601 test.test_support.run_unittest(PydocDocTest,
Ned Deily1a96f8d2011-10-06 14:17:34 -0700602 PydocImportTest,
603 TestDescriptions,
R David Murray984f6302014-01-05 12:35:59 -0500604 TestUnicode,
Ned Deily1a96f8d2011-10-06 14:17:34 -0700605 TestHelper)
606 finally:
607 reap_children()
Georg Brandl8632cc22008-05-18 16:32:48 +0000608
609if __name__ == "__main__":
610 test_main()