blob: 61f52aad83d699124ed1ec702203457ddf370618 [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
41 A
42\x20\x20\x20\x20
43 class A
44 | Hello and goodbye
45 |\x20\x20
46 | Methods defined here:
47 |\x20\x20
48 | __init__()
49 | Wow, I have no function!
50\x20\x20\x20\x20
51 class B(__builtin__.object)
52 | Data descriptors defined here:
53 |\x20\x20
Serhiy Storchaka72121c62013-01-27 19:45:49 +020054 | __dict__%s
Georg Brandl8632cc22008-05-18 16:32:48 +000055 |\x20\x20
Serhiy Storchaka72121c62013-01-27 19:45:49 +020056 | __weakref__%s
Georg Brandl8632cc22008-05-18 16:32:48 +000057 |\x20\x20
58 | ----------------------------------------------------------------------
59 | Data and other attributes defined here:
60 |\x20\x20
61 | NO_MEANING = 'eggs'
62
63FUNCTIONS
64 doc_func()
65 This function solves all of the world's problems:
66 hunger
67 lack of Python
68 war
69\x20\x20\x20\x20
70 nodoc_func()
71
72DATA
73 __author__ = 'Benjamin Peterson'
74 __credits__ = 'Nobody'
Georg Brandl8632cc22008-05-18 16:32:48 +000075 __version__ = '1.2.3.4'
76
77VERSION
78 1.2.3.4
79
80AUTHOR
81 Benjamin Peterson
82
83CREDITS
84 Nobody
85""".strip()
86
Serhiy Storchaka72121c62013-01-27 19:45:49 +020087expected_text_data_docstrings = tuple('\n | ' + s if s else ''
88 for s in expected_data_docstrings)
89
Georg Brandl8632cc22008-05-18 16:32:48 +000090expected_html_pattern = \
91"""
92<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
93<tr bgcolor="#7799ee">
94<td valign=bottom>&nbsp;<br>
95<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
96><td align=right valign=bottom
Benjamin Peterson3a7305e2008-05-22 23:09:26 +000097><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 +000098 <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
99<p>
100<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
101<tr bgcolor="#ee77aa">
102<td colspan=3 valign=bottom>&nbsp;<br>
103<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
104\x20\x20\x20\x20
105<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
106<td width="100%%"><dl>
107<dt><font face="helvetica, arial"><a href="__builtin__.html#object">__builtin__.object</a>
108</font></dt><dd>
109<dl>
110<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
111</font></dt></dl>
112</dd>
113<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
114</font></dt></dl>
115 <p>
116<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
117<tr bgcolor="#ffc8d8">
118<td colspan=3 valign=bottom>&nbsp;<br>
119<font color="#000000" face="helvetica, arial"><a name="A">class <strong>A</strong></a></font></td></tr>
120\x20\x20\x20\x20
121<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
122<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
123<tr><td>&nbsp;</td>
124<td width="100%%">Methods defined here:<br>
125<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>
126
127</td></tr></table> <p>
128<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
129<tr bgcolor="#ffc8d8">
130<td colspan=3 valign=bottom>&nbsp;<br>
131<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>
132\x20\x20\x20\x20
133<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
134<td width="100%%">Data descriptors defined here:<br>
135<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka72121c62013-01-27 19:45:49 +0200136<dd><tt>%s</tt></dd>
Georg Brandl8632cc22008-05-18 16:32:48 +0000137</dl>
138<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka72121c62013-01-27 19:45:49 +0200139<dd><tt>%s</tt></dd>
Georg Brandl8632cc22008-05-18 16:32:48 +0000140</dl>
141<hr>
142Data and other attributes defined here:<br>
143<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
144
145</td></tr></table></td></tr></table><p>
146<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
147<tr bgcolor="#eeaa77">
148<td colspan=3 valign=bottom>&nbsp;<br>
149<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
150\x20\x20\x20\x20
151<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
152<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>
153hunger<br>
154lack&nbsp;of&nbsp;Python<br>
155war</tt></dd></dl>
156 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
157</td></tr></table><p>
158<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
159<tr bgcolor="#55aa55">
160<td colspan=3 valign=bottom>&nbsp;<br>
161<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
162\x20\x20\x20\x20
163<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
164<td width="100%%"><strong>__author__</strong> = 'Benjamin Peterson'<br>
165<strong>__credits__</strong> = 'Nobody'<br>
Georg Brandl8632cc22008-05-18 16:32:48 +0000166<strong>__version__</strong> = '1.2.3.4'</td></tr></table><p>
167<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
168<tr bgcolor="#7799ee">
169<td colspan=3 valign=bottom>&nbsp;<br>
170<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
171\x20\x20\x20\x20
172<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
173<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
174<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
175<tr bgcolor="#7799ee">
176<td colspan=3 valign=bottom>&nbsp;<br>
177<font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
178\x20\x20\x20\x20
179<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
180<td width="100%%">Nobody</td></tr></table>
181""".strip()
182
Serhiy Storchaka72121c62013-01-27 19:45:49 +0200183expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;')
184 for s in expected_data_docstrings)
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000185
Georg Brandl8632cc22008-05-18 16:32:48 +0000186# output pattern for missing module
187missing_pattern = "no Python documentation found for '%s'"
188
R. David Murrayef087da2009-06-23 18:02:46 +0000189# output pattern for module with bad imports
190badimport_pattern = "problem in %s - <type 'exceptions.ImportError'>: No module named %s"
191
Ned Deily1a96f8d2011-10-06 14:17:34 -0700192def run_pydoc(module_name, *args, **env):
Georg Brandl8632cc22008-05-18 16:32:48 +0000193 """
194 Runs pydoc on the specified module. Returns the stripped
195 output of pydoc.
196 """
Ned Deily1a96f8d2011-10-06 14:17:34 -0700197 args = args + (module_name,)
198 # do not write bytecode files to avoid caching errors
199 rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
200 return out.strip()
Georg Brandl8632cc22008-05-18 16:32:48 +0000201
202def get_pydoc_html(module):
203 "Returns pydoc generated output as html"
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000204 doc = pydoc.HTMLDoc()
205 output = doc.docmodule(module)
206 loc = doc.getdocloc(pydoc_mod) or ""
207 if loc:
208 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
209 return output.strip(), loc
Georg Brandl8632cc22008-05-18 16:32:48 +0000210
211def get_pydoc_text(module):
212 "Returns pydoc generated output as text"
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000213 doc = pydoc.TextDoc()
214 loc = doc.getdocloc(pydoc_mod) or ""
215 if loc:
216 loc = "\nMODULE DOCS\n " + loc + "\n"
217
218 output = doc.docmodule(module)
Georg Brandl8632cc22008-05-18 16:32:48 +0000219
220 # cleanup the extra text formatting that pydoc preforms
221 patt = re.compile('\b.')
222 output = patt.sub('', output)
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000223 return output.strip(), loc
Georg Brandl8632cc22008-05-18 16:32:48 +0000224
225def print_diffs(text1, text2):
226 "Prints unified diffs for two texts"
Georg Brandlfb3de1f2008-05-20 08:07:36 +0000227 lines1 = text1.splitlines(True)
228 lines2 = text2.splitlines(True)
229 diffs = difflib.unified_diff(lines1, lines2, n=0, fromfile='expected',
230 tofile='got')
231 print '\n' + ''.join(diffs)
Georg Brandl8632cc22008-05-18 16:32:48 +0000232
Georg Brandl8632cc22008-05-18 16:32:48 +0000233
Antoine Pitrouf41ffed2013-05-19 15:44:54 +0200234class PydocBaseTest(unittest.TestCase):
235
236 def _restricted_walk_packages(self, walk_packages, path=None):
237 """
238 A version of pkgutil.walk_packages() that will restrict itself to
239 a given path.
240 """
241 default_path = path or [os.path.dirname(__file__)]
242 def wrapper(path=None, prefix='', onerror=None):
243 return walk_packages(path or default_path, prefix, onerror)
244 return wrapper
245
246 @contextlib.contextmanager
247 def restrict_walk_packages(self, path=None):
248 walk_packages = pkgutil.walk_packages
249 pkgutil.walk_packages = self._restricted_walk_packages(walk_packages,
250 path)
251 try:
252 yield
253 finally:
254 pkgutil.walk_packages = walk_packages
255
256
257class PydocDocTest(unittest.TestCase):
Georg Brandl8632cc22008-05-18 16:32:48 +0000258
R. David Murrayf28fd242010-02-23 00:24:49 +0000259 @unittest.skipIf(sys.flags.optimize >= 2,
260 "Docstrings are omitted with -O2 and above")
Georg Brandl8632cc22008-05-18 16:32:48 +0000261 def test_html_doc(self):
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000262 result, doc_loc = get_pydoc_html(pydoc_mod)
Georg Brandlb7e419e2008-05-20 08:10:03 +0000263 mod_file = inspect.getabsfile(pydoc_mod)
Amaury Forgeot d'Arc8e8de4a2008-06-10 21:37:15 +0000264 if sys.platform == 'win32':
265 import nturl2path
266 mod_url = nturl2path.pathname2url(mod_file)
267 else:
268 mod_url = mod_file
Serhiy Storchaka72121c62013-01-27 19:45:49 +0200269 expected_html = expected_html_pattern % (
270 (mod_url, mod_file, doc_loc) +
271 expected_html_data_docstrings)
Georg Brandl8632cc22008-05-18 16:32:48 +0000272 if result != expected_html:
Georg Brandlfb3de1f2008-05-20 08:07:36 +0000273 print_diffs(expected_html, result)
Georg Brandl8632cc22008-05-18 16:32:48 +0000274 self.fail("outputs are not equal, see diff above")
275
R. David Murrayf28fd242010-02-23 00:24:49 +0000276 @unittest.skipIf(sys.flags.optimize >= 2,
277 "Docstrings are omitted with -O2 and above")
Georg Brandl8632cc22008-05-18 16:32:48 +0000278 def test_text_doc(self):
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000279 result, doc_loc = get_pydoc_text(pydoc_mod)
Serhiy Storchaka72121c62013-01-27 19:45:49 +0200280 expected_text = expected_text_pattern % (
281 (inspect.getabsfile(pydoc_mod), doc_loc) +
282 expected_text_data_docstrings)
Georg Brandl8632cc22008-05-18 16:32:48 +0000283 if result != expected_text:
Georg Brandlfb3de1f2008-05-20 08:07:36 +0000284 print_diffs(expected_text, result)
Georg Brandl8632cc22008-05-18 16:32:48 +0000285 self.fail("outputs are not equal, see diff above")
286
Brian Curtinaeb2e822010-03-31 03:10:21 +0000287 def test_issue8225(self):
288 # Test issue8225 to ensure no doc link appears for xml.etree
289 result, doc_loc = get_pydoc_text(xml.etree)
290 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
291
R David Murrayc313b1d2012-04-23 13:27:11 -0400292 def test_non_str_name(self):
293 # issue14638
294 # Treat illegal (non-str) name like no name
295 class A:
296 __name__ = 42
297 class B:
298 pass
299 adoc = pydoc.render_doc(A())
300 bdoc = pydoc.render_doc(B())
301 self.assertEqual(adoc.replace("A", "B"), bdoc)
302
Benjamin Petersonf5c38da2008-05-18 20:48:07 +0000303 def test_not_here(self):
304 missing_module = "test.i_am_not_here"
305 result = run_pydoc(missing_module)
306 expected = missing_pattern % missing_module
307 self.assertEqual(expected, result,
308 "documentation for missing module found")
309
R. David Murrayd67ea7d2009-05-27 20:07:21 +0000310 def test_input_strip(self):
311 missing_module = " test.i_am_not_here "
312 result = run_pydoc(missing_module)
313 expected = missing_pattern % missing_module.strip()
314 self.assertEqual(expected, result,
315 "white space was not stripped from module name "
316 "or other error output mismatch")
317
Ezio Melottie511fc72010-02-16 23:26:09 +0000318 def test_stripid(self):
319 # test with strings, other implementations might have different repr()
320 stripid = pydoc.stripid
321 # strip the id
322 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
323 '<function stripid>')
324 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
325 '<function stripid>')
326 # nothing to strip, return the same text
327 self.assertEqual(stripid('42'), '42')
328 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
329 "<type 'exceptions.Exception'>")
330
Georg Brandl8632cc22008-05-18 16:32:48 +0000331
Antoine Pitrouf41ffed2013-05-19 15:44:54 +0200332class PydocImportTest(PydocBaseTest):
Ned Deily1a96f8d2011-10-06 14:17:34 -0700333
334 def setUp(self):
335 self.test_dir = os.mkdir(TESTFN)
336 self.addCleanup(rmtree, TESTFN)
337
338 def test_badimport(self):
339 # This tests the fix for issue 5230, where if pydoc found the module
340 # but the module had an internal import error pydoc would report no doc
341 # found.
342 modname = 'testmod_xyzzy'
343 testpairs = (
344 ('i_am_not_here', 'i_am_not_here'),
345 ('test.i_am_not_here_either', 'i_am_not_here_either'),
346 ('test.i_am_not_here.neither_am_i', 'i_am_not_here.neither_am_i'),
347 ('i_am_not_here.{}'.format(modname),
348 'i_am_not_here.{}'.format(modname)),
349 ('test.{}'.format(modname), modname),
350 )
351
352 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
353 for importstring, expectedinmsg in testpairs:
354 with open(sourcefn, 'w') as f:
355 f.write("import {}\n".format(importstring))
356 result = run_pydoc(modname, PYTHONPATH=TESTFN)
357 expected = badimport_pattern % (modname, expectedinmsg)
358 self.assertEqual(expected, result)
359
360 def test_apropos_with_bad_package(self):
361 # Issue 7425 - pydoc -k failed when bad package on path
362 pkgdir = os.path.join(TESTFN, "syntaxerr")
363 os.mkdir(pkgdir)
364 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
365 with open(badsyntax, 'w') as f:
366 f.write("invalid python syntax = $1\n")
Antoine Pitrouf41ffed2013-05-19 15:44:54 +0200367 with self.restrict_walk_packages(path=[TESTFN]):
368 with captured_stdout() as out:
369 with captured_stderr() as err:
370 pydoc.apropos('xyzzy')
371 # No result, no error
372 self.assertEqual(out.getvalue(), '')
373 self.assertEqual(err.getvalue(), '')
374 # The package name is still matched
375 with captured_stdout() as out:
376 with captured_stderr() as err:
377 pydoc.apropos('syntaxerr')
378 self.assertEqual(out.getvalue().strip(), 'syntaxerr')
379 self.assertEqual(err.getvalue(), '')
Ned Deily1a96f8d2011-10-06 14:17:34 -0700380
381 def test_apropos_with_unreadable_dir(self):
382 # Issue 7367 - pydoc -k failed when unreadable dir on path
383 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
384 os.mkdir(self.unreadable_dir, 0)
385 self.addCleanup(os.rmdir, self.unreadable_dir)
386 # Note, on Windows the directory appears to be still
387 # readable so this is not really testing the issue there
Antoine Pitrouf41ffed2013-05-19 15:44:54 +0200388 with self.restrict_walk_packages(path=[TESTFN]):
389 with captured_stdout() as out:
390 with captured_stderr() as err:
391 pydoc.apropos('SOMEKEY')
392 # No result, no error
393 self.assertEqual(out.getvalue(), '')
394 self.assertEqual(err.getvalue(), '')
Ned Deily1a96f8d2011-10-06 14:17:34 -0700395
396
Georg Brandl8632cc22008-05-18 16:32:48 +0000397class TestDescriptions(unittest.TestCase):
Benjamin Petersonf5c38da2008-05-18 20:48:07 +0000398
Georg Brandl8632cc22008-05-18 16:32:48 +0000399 def test_module(self):
400 # Check that pydocfodder module can be described
401 from test import pydocfodder
402 doc = pydoc.render_doc(pydocfodder)
Ezio Melottiaa980582010-01-23 23:04:36 +0000403 self.assertIn("pydocfodder", doc)
Georg Brandl8632cc22008-05-18 16:32:48 +0000404
405 def test_classic_class(self):
406 class C: "Classic class"
407 c = C()
Benjamin Petersonf5c38da2008-05-18 20:48:07 +0000408 self.assertEqual(pydoc.describe(C), 'class C')
409 self.assertEqual(pydoc.describe(c), 'instance of C')
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000410 expected = 'instance of C in module %s' % __name__
Ezio Melottiaa980582010-01-23 23:04:36 +0000411 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandl8632cc22008-05-18 16:32:48 +0000412
413 def test_class(self):
414 class C(object): "New-style class"
415 c = C()
416
Benjamin Petersonf5c38da2008-05-18 20:48:07 +0000417 self.assertEqual(pydoc.describe(C), 'class C')
418 self.assertEqual(pydoc.describe(c), 'C')
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000419 expected = 'C in module %s object' % __name__
Ezio Melottiaa980582010-01-23 23:04:36 +0000420 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandl8632cc22008-05-18 16:32:48 +0000421
Raymond Hettinger9aa5a342011-03-25 16:00:13 -0700422 def test_namedtuple_public_underscore(self):
423 NT = namedtuple('NT', ['abc', 'def'], rename=True)
424 with captured_stdout() as help_io:
Terry Jan Reedyc0e60472013-11-04 21:45:33 -0500425 pydoc.help(NT)
Raymond Hettinger9aa5a342011-03-25 16:00:13 -0700426 helptext = help_io.getvalue()
427 self.assertIn('_1', helptext)
428 self.assertIn('_replace', helptext)
429 self.assertIn('_asdict', helptext)
430
Georg Brandl8632cc22008-05-18 16:32:48 +0000431
R David Murray984f6302014-01-05 12:35:59 -0500432@unittest.skipUnless(test.test_support.have_unicode,
433 "test requires unicode support")
434class TestUnicode(unittest.TestCase):
435
436 def setUp(self):
437 # Better not to use unicode escapes in literals, lest the
438 # parser choke on it if Python has been built without
439 # unicode support.
440 self.Q = types.ModuleType(
441 'Q', 'Rational numbers: \xe2\x84\x9a'.decode('utf8'))
442 self.Q.__version__ = '\xe2\x84\x9a'.decode('utf8')
443 self.Q.__date__ = '\xe2\x84\x9a'.decode('utf8')
444 self.Q.__author__ = '\xe2\x84\x9a'.decode('utf8')
445 self.Q.__credits__ = '\xe2\x84\x9a'.decode('utf8')
446
447 self.assertIsInstance(self.Q.__doc__, unicode)
448
449 def test_render_doc(self):
450 # render_doc is robust against unicode in docstrings
451 doc = pydoc.render_doc(self.Q)
452 self.assertIsInstance(doc, str)
453
454 def test_encode(self):
455 # _encode is robust against characters out the specified encoding
456 self.assertEqual(pydoc._encode(self.Q.__doc__, 'ascii'), 'Rational numbers: &#8474;')
457
458 def test_pipepager(self):
459 # pipepager does not choke on unicode
460 doc = pydoc.render_doc(self.Q)
461
462 saved, os.popen = os.popen, open
463 try:
464 with test.test_support.temp_cwd():
465 pydoc.pipepager(doc, 'pipe')
466 self.assertEqual(open('pipe').read(), pydoc._encode(doc))
467 finally:
468 os.popen = saved
469
470 def test_tempfilepager(self):
471 # tempfilepager does not choke on unicode
472 doc = pydoc.render_doc(self.Q)
473
474 output = {}
475 def mock_system(cmd):
476 import ast
477 output['content'] = open(ast.literal_eval(cmd.strip())).read()
478 saved, os.system = os.system, mock_system
479 try:
480 pydoc.tempfilepager(doc, '')
481 self.assertEqual(output['content'], pydoc._encode(doc))
482 finally:
483 os.system = saved
484
485 def test_plainpager(self):
486 # plainpager does not choke on unicode
487 doc = pydoc.render_doc(self.Q)
488
489 # Note: captured_stdout is too permissive when it comes to
490 # unicode, and using it here would make the test always
491 # pass.
492 with test.test_support.temp_cwd():
493 with open('output', 'w') as f:
494 saved, sys.stdout = sys.stdout, f
495 try:
496 pydoc.plainpager(doc)
497 finally:
498 sys.stdout = saved
499 self.assertIn('Rational numbers:', open('output').read())
500
501 def test_ttypager(self):
502 # ttypager does not choke on unicode
503 doc = pydoc.render_doc(self.Q)
504 # Test ttypager
505 with test.test_support.temp_cwd(), test.test_support.captured_stdin():
506 with open('output', 'w') as f:
507 saved, sys.stdout = sys.stdout, f
508 try:
509 pydoc.ttypager(doc)
510 finally:
511 sys.stdout = saved
512 self.assertIn('Rational numbers:', open('output').read())
513
514 def test_htmlpage(self):
515 # html.page does not choke on unicode
516 with test.test_support.temp_cwd():
517 with captured_stdout() as output:
518 pydoc.writedoc(self.Q)
519 self.assertEqual(output.getvalue(), 'wrote Q.html\n')
520
Ezio Melottibdfa2e62011-04-28 07:59:33 +0300521class TestHelper(unittest.TestCase):
522 def test_keywords(self):
523 self.assertEqual(sorted(pydoc.Helper.keywords),
524 sorted(keyword.kwlist))
525
Éric Araujo9a528302011-07-29 17:34:35 +0200526 def test_builtin(self):
527 for name in ('str', 'str.translate', '__builtin__.str',
528 '__builtin__.str.translate'):
529 # test low-level function
530 self.assertIsNotNone(pydoc.locate(name))
531 # test high-level function
532 try:
533 pydoc.render_doc(name)
534 except ImportError:
535 self.fail('finding the doc of {!r} failed'.format(o))
536
537 for name in ('not__builtin__', 'strrr', 'strr.translate',
538 'str.trrrranslate', '__builtin__.strrr',
539 '__builtin__.str.trrranslate'):
540 self.assertIsNone(pydoc.locate(name))
541 self.assertRaises(ImportError, pydoc.render_doc, name)
542
Ezio Melottibdfa2e62011-04-28 07:59:33 +0300543
Georg Brandl8632cc22008-05-18 16:32:48 +0000544def test_main():
Ned Deily1a96f8d2011-10-06 14:17:34 -0700545 try:
Antoine Pitrouf41ffed2013-05-19 15:44:54 +0200546 test.test_support.run_unittest(PydocDocTest,
Ned Deily1a96f8d2011-10-06 14:17:34 -0700547 PydocImportTest,
548 TestDescriptions,
R David Murray984f6302014-01-05 12:35:59 -0500549 TestUnicode,
Ned Deily1a96f8d2011-10-06 14:17:34 -0700550 TestHelper)
551 finally:
552 reap_children()
Georg Brandl8632cc22008-05-18 16:32:48 +0000553
554if __name__ == "__main__":
555 test_main()