blob: 83aad0b3b4aada57e9445d5ba0c84aa2039835a3 [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
Berker Peksagdc9d41d2015-02-20 12:10:33 +02006import py_compile
Georg Brandl8632cc22008-05-18 16:32:48 +00007import pydoc
Antoine Pitrouf41ffed2013-05-19 15:44:54 +02008import contextlib
Georg Brandlb7e419e2008-05-20 08:10:03 +00009import inspect
Ezio Melottibdfa2e62011-04-28 07:59:33 +030010import keyword
Antoine Pitrouf41ffed2013-05-19 15:44:54 +020011import pkgutil
Georg Brandl8632cc22008-05-18 16:32:48 +000012import unittest
Brian Curtinaeb2e822010-03-31 03:10:21 +000013import xml.etree
R David Murray984f6302014-01-05 12:35:59 -050014import types
Georg Brandl8632cc22008-05-18 16:32:48 +000015import test.test_support
Martin Pantere52140c2016-06-12 05:25:16 +000016import xml.etree.ElementTree
Raymond Hettinger9aa5a342011-03-25 16:00:13 -070017from collections import namedtuple
Ned Deily1a96f8d2011-10-06 14:17:34 -070018from test.script_helper import assert_python_ok
Charles-François Natali94919a42014-06-20 22:57:19 +010019from test.test_support import (TESTFN, rmtree, reap_children, captured_stdout,
20 captured_stderr, requires_docstrings)
Benjamin Petersonf5c38da2008-05-18 20:48:07 +000021
Georg Brandl8632cc22008-05-18 16:32:48 +000022from test import pydoc_mod
23
Serhiy Storchaka72121c62013-01-27 19:45:49 +020024if test.test_support.HAVE_DOCSTRINGS:
25 expected_data_docstrings = (
26 'dictionary for instance variables (if defined)',
27 'list of weak references to the object (if defined)',
28 )
29else:
30 expected_data_docstrings = ('', '')
31
Georg Brandl8632cc22008-05-18 16:32:48 +000032expected_text_pattern = \
33"""
34NAME
35 test.pydoc_mod - This is a test module for test_pydoc
36
37FILE
38 %s
Benjamin Peterson3a7305e2008-05-22 23:09:26 +000039%s
Georg Brandl8632cc22008-05-18 16:32:48 +000040CLASSES
41 __builtin__.object
42 B
Benjamin Petersonc3e1e902014-06-07 16:44:00 -070043 C
Georg Brandl8632cc22008-05-18 16:32:48 +000044 A
45\x20\x20\x20\x20
46 class A
47 | Hello and goodbye
48 |\x20\x20
49 | Methods defined here:
50 |\x20\x20
51 | __init__()
52 | Wow, I have no function!
53\x20\x20\x20\x20
54 class B(__builtin__.object)
55 | Data descriptors defined here:
56 |\x20\x20
Serhiy Storchaka72121c62013-01-27 19:45:49 +020057 | __dict__%s
Georg Brandl8632cc22008-05-18 16:32:48 +000058 |\x20\x20
Serhiy Storchaka72121c62013-01-27 19:45:49 +020059 | __weakref__%s
Georg Brandl8632cc22008-05-18 16:32:48 +000060 |\x20\x20
61 | ----------------------------------------------------------------------
62 | Data and other attributes defined here:
63 |\x20\x20
64 | NO_MEANING = 'eggs'
Benjamin Petersonc3e1e902014-06-07 16:44:00 -070065\x20\x20\x20\x20
66 class C(__builtin__.object)
67 | Methods defined here:
68 |\x20\x20
69 | get_answer(self)
70 | Return say_no()
71 |\x20\x20
72 | is_it_true(self)
73 | Return self.get_answer()
74 |\x20\x20
75 | say_no(self)
76 |\x20\x20
77 | ----------------------------------------------------------------------
78 | Data descriptors defined here:
79 |\x20\x20
80 | __dict__
81 | dictionary for instance variables (if defined)
82 |\x20\x20
83 | __weakref__
84 | list of weak references to the object (if defined)
Georg Brandl8632cc22008-05-18 16:32:48 +000085
86FUNCTIONS
87 doc_func()
88 This function solves all of the world's problems:
89 hunger
90 lack of Python
91 war
92\x20\x20\x20\x20
93 nodoc_func()
94
95DATA
96 __author__ = 'Benjamin Peterson'
97 __credits__ = 'Nobody'
Georg Brandl8632cc22008-05-18 16:32:48 +000098 __version__ = '1.2.3.4'
99
100VERSION
101 1.2.3.4
102
103AUTHOR
104 Benjamin Peterson
105
106CREDITS
107 Nobody
108""".strip()
109
Serhiy Storchaka72121c62013-01-27 19:45:49 +0200110expected_text_data_docstrings = tuple('\n | ' + s if s else ''
111 for s in expected_data_docstrings)
112
Georg Brandl8632cc22008-05-18 16:32:48 +0000113expected_html_pattern = \
114"""
115<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
116<tr bgcolor="#7799ee">
117<td valign=bottom>&nbsp;<br>
118<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
119><td align=right valign=bottom
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000120><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 +0000121 <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
122<p>
123<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
124<tr bgcolor="#ee77aa">
125<td colspan=3 valign=bottom>&nbsp;<br>
126<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
127\x20\x20\x20\x20
128<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
129<td width="100%%"><dl>
130<dt><font face="helvetica, arial"><a href="__builtin__.html#object">__builtin__.object</a>
131</font></dt><dd>
132<dl>
133<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
Benjamin Petersonc3e1e902014-06-07 16:44:00 -0700134</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#C">C</a>
Georg Brandl8632cc22008-05-18 16:32:48 +0000135</font></dt></dl>
136</dd>
137<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
138</font></dt></dl>
139 <p>
140<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
141<tr bgcolor="#ffc8d8">
142<td colspan=3 valign=bottom>&nbsp;<br>
143<font color="#000000" face="helvetica, arial"><a name="A">class <strong>A</strong></a></font></td></tr>
144\x20\x20\x20\x20
145<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
146<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
147<tr><td>&nbsp;</td>
148<td width="100%%">Methods defined here:<br>
149<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>
150
151</td></tr></table> <p>
152<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
153<tr bgcolor="#ffc8d8">
154<td colspan=3 valign=bottom>&nbsp;<br>
155<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>
156\x20\x20\x20\x20
157<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
158<td width="100%%">Data descriptors defined here:<br>
159<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka72121c62013-01-27 19:45:49 +0200160<dd><tt>%s</tt></dd>
Georg Brandl8632cc22008-05-18 16:32:48 +0000161</dl>
162<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka72121c62013-01-27 19:45:49 +0200163<dd><tt>%s</tt></dd>
Georg Brandl8632cc22008-05-18 16:32:48 +0000164</dl>
165<hr>
166Data and other attributes defined here:<br>
167<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
168
Benjamin Petersonc3e1e902014-06-07 16:44:00 -0700169</td></tr></table> <p>
170<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
171<tr bgcolor="#ffc8d8">
172<td colspan=3 valign=bottom>&nbsp;<br>
173<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>
174\x20\x20\x20\x20
175<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
176<td width="100%%">Methods defined here:<br>
177<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>
178
179<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>
180
181<dl><dt><a name="C-say_no"><strong>say_no</strong></a>(self)</dt></dl>
182
183<hr>
184Data descriptors defined here:<br>
185<dl><dt><strong>__dict__</strong></dt>
186<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
187</dl>
188<dl><dt><strong>__weakref__</strong></dt>
189<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
190</dl>
Georg Brandl8632cc22008-05-18 16:32:48 +0000191</td></tr></table></td></tr></table><p>
192<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
193<tr bgcolor="#eeaa77">
194<td colspan=3 valign=bottom>&nbsp;<br>
195<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
196\x20\x20\x20\x20
197<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
198<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>
199hunger<br>
200lack&nbsp;of&nbsp;Python<br>
201war</tt></dd></dl>
202 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
203</td></tr></table><p>
204<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
205<tr bgcolor="#55aa55">
206<td colspan=3 valign=bottom>&nbsp;<br>
207<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
208\x20\x20\x20\x20
209<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
210<td width="100%%"><strong>__author__</strong> = 'Benjamin Peterson'<br>
211<strong>__credits__</strong> = 'Nobody'<br>
Georg Brandl8632cc22008-05-18 16:32:48 +0000212<strong>__version__</strong> = '1.2.3.4'</td></tr></table><p>
213<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
214<tr bgcolor="#7799ee">
215<td colspan=3 valign=bottom>&nbsp;<br>
216<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
217\x20\x20\x20\x20
218<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
219<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
220<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
221<tr bgcolor="#7799ee">
222<td colspan=3 valign=bottom>&nbsp;<br>
223<font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
224\x20\x20\x20\x20
225<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
226<td width="100%%">Nobody</td></tr></table>
227""".strip()
228
Serhiy Storchaka72121c62013-01-27 19:45:49 +0200229expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;')
230 for s in expected_data_docstrings)
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000231
Georg Brandl8632cc22008-05-18 16:32:48 +0000232# output pattern for missing module
233missing_pattern = "no Python documentation found for '%s'"
234
R. David Murrayef087da2009-06-23 18:02:46 +0000235# output pattern for module with bad imports
236badimport_pattern = "problem in %s - <type 'exceptions.ImportError'>: No module named %s"
237
Ned Deily1a96f8d2011-10-06 14:17:34 -0700238def run_pydoc(module_name, *args, **env):
Georg Brandl8632cc22008-05-18 16:32:48 +0000239 """
240 Runs pydoc on the specified module. Returns the stripped
241 output of pydoc.
242 """
Ned Deily1a96f8d2011-10-06 14:17:34 -0700243 args = args + (module_name,)
244 # do not write bytecode files to avoid caching errors
245 rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
246 return out.strip()
Georg Brandl8632cc22008-05-18 16:32:48 +0000247
248def get_pydoc_html(module):
249 "Returns pydoc generated output as html"
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000250 doc = pydoc.HTMLDoc()
251 output = doc.docmodule(module)
252 loc = doc.getdocloc(pydoc_mod) or ""
253 if loc:
254 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
255 return output.strip(), loc
Georg Brandl8632cc22008-05-18 16:32:48 +0000256
Martin Pantere52140c2016-06-12 05:25:16 +0000257def get_pydoc_link(module):
258 "Returns a documentation web link of a module"
259 dirname = os.path.dirname
Victor Stinnerfd6736d2017-07-27 18:05:44 +0200260 basedir = dirname(dirname(os.path.realpath(__file__)))
Martin Pantere52140c2016-06-12 05:25:16 +0000261 doc = pydoc.TextDoc()
262 loc = doc.getdocloc(module, basedir=basedir)
263 return loc
264
Georg Brandl8632cc22008-05-18 16:32:48 +0000265def get_pydoc_text(module):
266 "Returns pydoc generated output as text"
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000267 doc = pydoc.TextDoc()
268 loc = doc.getdocloc(pydoc_mod) or ""
269 if loc:
270 loc = "\nMODULE DOCS\n " + loc + "\n"
271
272 output = doc.docmodule(module)
Georg Brandl8632cc22008-05-18 16:32:48 +0000273
274 # cleanup the extra text formatting that pydoc preforms
275 patt = re.compile('\b.')
276 output = patt.sub('', output)
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000277 return output.strip(), loc
Georg Brandl8632cc22008-05-18 16:32:48 +0000278
279def print_diffs(text1, text2):
280 "Prints unified diffs for two texts"
Georg Brandlfb3de1f2008-05-20 08:07:36 +0000281 lines1 = text1.splitlines(True)
282 lines2 = text2.splitlines(True)
283 diffs = difflib.unified_diff(lines1, lines2, n=0, fromfile='expected',
284 tofile='got')
285 print '\n' + ''.join(diffs)
Georg Brandl8632cc22008-05-18 16:32:48 +0000286
Georg Brandl8632cc22008-05-18 16:32:48 +0000287
Antoine Pitrouf41ffed2013-05-19 15:44:54 +0200288class PydocBaseTest(unittest.TestCase):
289
290 def _restricted_walk_packages(self, walk_packages, path=None):
291 """
292 A version of pkgutil.walk_packages() that will restrict itself to
293 a given path.
294 """
295 default_path = path or [os.path.dirname(__file__)]
296 def wrapper(path=None, prefix='', onerror=None):
297 return walk_packages(path or default_path, prefix, onerror)
298 return wrapper
299
300 @contextlib.contextmanager
301 def restrict_walk_packages(self, path=None):
302 walk_packages = pkgutil.walk_packages
303 pkgutil.walk_packages = self._restricted_walk_packages(walk_packages,
304 path)
305 try:
306 yield
307 finally:
308 pkgutil.walk_packages = walk_packages
309
310
311class PydocDocTest(unittest.TestCase):
Georg Brandl8632cc22008-05-18 16:32:48 +0000312
Charles-François Natali94919a42014-06-20 22:57:19 +0100313 @requires_docstrings
R. David Murrayf28fd242010-02-23 00:24:49 +0000314 @unittest.skipIf(sys.flags.optimize >= 2,
315 "Docstrings are omitted with -O2 and above")
Georg Brandl8632cc22008-05-18 16:32:48 +0000316 def test_html_doc(self):
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000317 result, doc_loc = get_pydoc_html(pydoc_mod)
Georg Brandlb7e419e2008-05-20 08:10:03 +0000318 mod_file = inspect.getabsfile(pydoc_mod)
Amaury Forgeot d'Arc8e8de4a2008-06-10 21:37:15 +0000319 if sys.platform == 'win32':
320 import nturl2path
321 mod_url = nturl2path.pathname2url(mod_file)
322 else:
323 mod_url = mod_file
Serhiy Storchaka72121c62013-01-27 19:45:49 +0200324 expected_html = expected_html_pattern % (
325 (mod_url, mod_file, doc_loc) +
326 expected_html_data_docstrings)
Georg Brandl8632cc22008-05-18 16:32:48 +0000327 if result != expected_html:
Georg Brandlfb3de1f2008-05-20 08:07:36 +0000328 print_diffs(expected_html, result)
Georg Brandl8632cc22008-05-18 16:32:48 +0000329 self.fail("outputs are not equal, see diff above")
330
Charles-François Natali94919a42014-06-20 22:57:19 +0100331 @requires_docstrings
R. David Murrayf28fd242010-02-23 00:24:49 +0000332 @unittest.skipIf(sys.flags.optimize >= 2,
333 "Docstrings are omitted with -O2 and above")
Georg Brandl8632cc22008-05-18 16:32:48 +0000334 def test_text_doc(self):
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000335 result, doc_loc = get_pydoc_text(pydoc_mod)
Serhiy Storchaka72121c62013-01-27 19:45:49 +0200336 expected_text = expected_text_pattern % (
337 (inspect.getabsfile(pydoc_mod), doc_loc) +
338 expected_text_data_docstrings)
Georg Brandl8632cc22008-05-18 16:32:48 +0000339 if result != expected_text:
Georg Brandlfb3de1f2008-05-20 08:07:36 +0000340 print_diffs(expected_text, result)
Georg Brandl8632cc22008-05-18 16:32:48 +0000341 self.fail("outputs are not equal, see diff above")
342
Martin Pantere52140c2016-06-12 05:25:16 +0000343 def test_mixed_case_module_names_are_lower_cased(self):
344 # issue16484
345 doc_link = get_pydoc_link(xml.etree.ElementTree)
346 self.assertIn('xml.etree.elementtree', doc_link)
347
Brian Curtinaeb2e822010-03-31 03:10:21 +0000348 def test_issue8225(self):
349 # Test issue8225 to ensure no doc link appears for xml.etree
350 result, doc_loc = get_pydoc_text(xml.etree)
351 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
352
Benjamin Peterson75a55c32014-06-07 20:14:26 -0700353 def test_getpager_with_stdin_none(self):
354 previous_stdin = sys.stdin
355 try:
356 sys.stdin = None
357 pydoc.getpager() # Shouldn't fail.
358 finally:
359 sys.stdin = previous_stdin
360
R David Murrayc313b1d2012-04-23 13:27:11 -0400361 def test_non_str_name(self):
362 # issue14638
363 # Treat illegal (non-str) name like no name
364 class A:
365 __name__ = 42
366 class B:
367 pass
368 adoc = pydoc.render_doc(A())
369 bdoc = pydoc.render_doc(B())
370 self.assertEqual(adoc.replace("A", "B"), bdoc)
371
Benjamin Petersonf5c38da2008-05-18 20:48:07 +0000372 def test_not_here(self):
373 missing_module = "test.i_am_not_here"
374 result = run_pydoc(missing_module)
375 expected = missing_pattern % missing_module
376 self.assertEqual(expected, result,
377 "documentation for missing module found")
378
R. David Murrayd67ea7d2009-05-27 20:07:21 +0000379 def test_input_strip(self):
380 missing_module = " test.i_am_not_here "
381 result = run_pydoc(missing_module)
382 expected = missing_pattern % missing_module.strip()
383 self.assertEqual(expected, result,
384 "white space was not stripped from module name "
385 "or other error output mismatch")
386
Ezio Melottie511fc72010-02-16 23:26:09 +0000387 def test_stripid(self):
388 # test with strings, other implementations might have different repr()
389 stripid = pydoc.stripid
390 # strip the id
391 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
392 '<function stripid>')
393 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
394 '<function stripid>')
395 # nothing to strip, return the same text
396 self.assertEqual(stripid('42'), '42')
397 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
398 "<type 'exceptions.Exception'>")
399
Berker Peksagdc9d41d2015-02-20 12:10:33 +0200400 def test_synopsis(self):
401 with test.test_support.temp_cwd() as test_dir:
402 init_path = os.path.join(test_dir, 'dt.py')
403 with open(init_path, 'w') as fobj:
404 fobj.write('''\
405"""
406my doc
407
408second line
409"""
410foo = 1
411''')
412 py_compile.compile(init_path)
413 synopsis = pydoc.synopsis(init_path, {})
414 self.assertEqual(synopsis, 'my doc')
415
Serhiy Storchaka2b8c00d2015-03-01 15:31:21 +0200416 @unittest.skipIf(sys.flags.optimize >= 2,
417 'Docstrings are omitted with -OO and above')
Berker Peksagdc9d41d2015-02-20 12:10:33 +0200418 def test_synopsis_sourceless_empty_doc(self):
419 with test.test_support.temp_cwd() as test_dir:
420 init_path = os.path.join(test_dir, 'foomod42.py')
421 cached_path = os.path.join(test_dir, 'foomod42.pyc')
422 with open(init_path, 'w') as fobj:
423 fobj.write("foo = 1")
424 py_compile.compile(init_path)
425 synopsis = pydoc.synopsis(init_path, {})
426 self.assertIsNone(synopsis)
427 synopsis_cached = pydoc.synopsis(cached_path, {})
428 self.assertIsNone(synopsis_cached)
429
Georg Brandl8632cc22008-05-18 16:32:48 +0000430
Antoine Pitrouf41ffed2013-05-19 15:44:54 +0200431class PydocImportTest(PydocBaseTest):
Ned Deily1a96f8d2011-10-06 14:17:34 -0700432
433 def setUp(self):
434 self.test_dir = os.mkdir(TESTFN)
435 self.addCleanup(rmtree, TESTFN)
436
437 def test_badimport(self):
438 # This tests the fix for issue 5230, where if pydoc found the module
439 # but the module had an internal import error pydoc would report no doc
440 # found.
441 modname = 'testmod_xyzzy'
442 testpairs = (
443 ('i_am_not_here', 'i_am_not_here'),
444 ('test.i_am_not_here_either', 'i_am_not_here_either'),
445 ('test.i_am_not_here.neither_am_i', 'i_am_not_here.neither_am_i'),
446 ('i_am_not_here.{}'.format(modname),
447 'i_am_not_here.{}'.format(modname)),
448 ('test.{}'.format(modname), modname),
449 )
450
451 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
452 for importstring, expectedinmsg in testpairs:
453 with open(sourcefn, 'w') as f:
454 f.write("import {}\n".format(importstring))
455 result = run_pydoc(modname, PYTHONPATH=TESTFN)
456 expected = badimport_pattern % (modname, expectedinmsg)
457 self.assertEqual(expected, result)
458
459 def test_apropos_with_bad_package(self):
460 # Issue 7425 - pydoc -k failed when bad package on path
461 pkgdir = os.path.join(TESTFN, "syntaxerr")
462 os.mkdir(pkgdir)
463 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
464 with open(badsyntax, 'w') as f:
465 f.write("invalid python syntax = $1\n")
Antoine Pitrouf41ffed2013-05-19 15:44:54 +0200466 with self.restrict_walk_packages(path=[TESTFN]):
467 with captured_stdout() as out:
468 with captured_stderr() as err:
469 pydoc.apropos('xyzzy')
470 # No result, no error
471 self.assertEqual(out.getvalue(), '')
472 self.assertEqual(err.getvalue(), '')
473 # The package name is still matched
474 with captured_stdout() as out:
475 with captured_stderr() as err:
476 pydoc.apropos('syntaxerr')
477 self.assertEqual(out.getvalue().strip(), 'syntaxerr')
478 self.assertEqual(err.getvalue(), '')
Ned Deily1a96f8d2011-10-06 14:17:34 -0700479
480 def test_apropos_with_unreadable_dir(self):
481 # Issue 7367 - pydoc -k failed when unreadable dir on path
482 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
483 os.mkdir(self.unreadable_dir, 0)
484 self.addCleanup(os.rmdir, self.unreadable_dir)
485 # Note, on Windows the directory appears to be still
486 # readable so this is not really testing the issue there
Antoine Pitrouf41ffed2013-05-19 15:44:54 +0200487 with self.restrict_walk_packages(path=[TESTFN]):
488 with captured_stdout() as out:
489 with captured_stderr() as err:
490 pydoc.apropos('SOMEKEY')
491 # No result, no error
492 self.assertEqual(out.getvalue(), '')
493 self.assertEqual(err.getvalue(), '')
Ned Deily1a96f8d2011-10-06 14:17:34 -0700494
495
Georg Brandl8632cc22008-05-18 16:32:48 +0000496class TestDescriptions(unittest.TestCase):
Benjamin Petersonf5c38da2008-05-18 20:48:07 +0000497
Georg Brandl8632cc22008-05-18 16:32:48 +0000498 def test_module(self):
499 # Check that pydocfodder module can be described
500 from test import pydocfodder
501 doc = pydoc.render_doc(pydocfodder)
Ezio Melottiaa980582010-01-23 23:04:36 +0000502 self.assertIn("pydocfodder", doc)
Georg Brandl8632cc22008-05-18 16:32:48 +0000503
504 def test_classic_class(self):
505 class C: "Classic class"
506 c = C()
Benjamin Petersonf5c38da2008-05-18 20:48:07 +0000507 self.assertEqual(pydoc.describe(C), 'class C')
508 self.assertEqual(pydoc.describe(c), 'instance of C')
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000509 expected = 'instance of C in module %s' % __name__
Ezio Melottiaa980582010-01-23 23:04:36 +0000510 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandl8632cc22008-05-18 16:32:48 +0000511
512 def test_class(self):
513 class C(object): "New-style class"
514 c = C()
515
Benjamin Petersonf5c38da2008-05-18 20:48:07 +0000516 self.assertEqual(pydoc.describe(C), 'class C')
517 self.assertEqual(pydoc.describe(c), 'C')
Benjamin Peterson3a7305e2008-05-22 23:09:26 +0000518 expected = 'C in module %s object' % __name__
Ezio Melottiaa980582010-01-23 23:04:36 +0000519 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandl8632cc22008-05-18 16:32:48 +0000520
Raymond Hettinger9aa5a342011-03-25 16:00:13 -0700521 def test_namedtuple_public_underscore(self):
522 NT = namedtuple('NT', ['abc', 'def'], rename=True)
523 with captured_stdout() as help_io:
Terry Jan Reedyc0e60472013-11-04 21:45:33 -0500524 pydoc.help(NT)
Raymond Hettinger9aa5a342011-03-25 16:00:13 -0700525 helptext = help_io.getvalue()
526 self.assertIn('_1', helptext)
527 self.assertIn('_replace', helptext)
528 self.assertIn('_asdict', helptext)
529
Georg Brandl8632cc22008-05-18 16:32:48 +0000530
R David Murray984f6302014-01-05 12:35:59 -0500531@unittest.skipUnless(test.test_support.have_unicode,
532 "test requires unicode support")
533class TestUnicode(unittest.TestCase):
534
535 def setUp(self):
536 # Better not to use unicode escapes in literals, lest the
537 # parser choke on it if Python has been built without
538 # unicode support.
539 self.Q = types.ModuleType(
540 'Q', 'Rational numbers: \xe2\x84\x9a'.decode('utf8'))
541 self.Q.__version__ = '\xe2\x84\x9a'.decode('utf8')
542 self.Q.__date__ = '\xe2\x84\x9a'.decode('utf8')
543 self.Q.__author__ = '\xe2\x84\x9a'.decode('utf8')
544 self.Q.__credits__ = '\xe2\x84\x9a'.decode('utf8')
545
546 self.assertIsInstance(self.Q.__doc__, unicode)
547
548 def test_render_doc(self):
549 # render_doc is robust against unicode in docstrings
550 doc = pydoc.render_doc(self.Q)
551 self.assertIsInstance(doc, str)
552
553 def test_encode(self):
554 # _encode is robust against characters out the specified encoding
555 self.assertEqual(pydoc._encode(self.Q.__doc__, 'ascii'), 'Rational numbers: &#8474;')
556
557 def test_pipepager(self):
558 # pipepager does not choke on unicode
559 doc = pydoc.render_doc(self.Q)
560
561 saved, os.popen = os.popen, open
562 try:
563 with test.test_support.temp_cwd():
564 pydoc.pipepager(doc, 'pipe')
565 self.assertEqual(open('pipe').read(), pydoc._encode(doc))
566 finally:
567 os.popen = saved
568
569 def test_tempfilepager(self):
570 # tempfilepager does not choke on unicode
571 doc = pydoc.render_doc(self.Q)
572
573 output = {}
574 def mock_system(cmd):
Serhiy Storchakaee105dc2014-01-10 22:43:03 +0200575 filename = cmd.strip()[1:-1]
576 self.assertEqual('"' + filename + '"', cmd.strip())
577 output['content'] = open(filename).read()
R David Murray984f6302014-01-05 12:35:59 -0500578 saved, os.system = os.system, mock_system
579 try:
580 pydoc.tempfilepager(doc, '')
581 self.assertEqual(output['content'], pydoc._encode(doc))
582 finally:
583 os.system = saved
584
585 def test_plainpager(self):
586 # plainpager does not choke on unicode
587 doc = pydoc.render_doc(self.Q)
588
589 # Note: captured_stdout is too permissive when it comes to
590 # unicode, and using it here would make the test always
591 # pass.
592 with test.test_support.temp_cwd():
593 with open('output', 'w') as f:
594 saved, sys.stdout = sys.stdout, f
595 try:
596 pydoc.plainpager(doc)
597 finally:
598 sys.stdout = saved
599 self.assertIn('Rational numbers:', open('output').read())
600
601 def test_ttypager(self):
602 # ttypager does not choke on unicode
603 doc = pydoc.render_doc(self.Q)
604 # Test ttypager
605 with test.test_support.temp_cwd(), test.test_support.captured_stdin():
606 with open('output', 'w') as f:
607 saved, sys.stdout = sys.stdout, f
608 try:
609 pydoc.ttypager(doc)
610 finally:
611 sys.stdout = saved
612 self.assertIn('Rational numbers:', open('output').read())
613
614 def test_htmlpage(self):
615 # html.page does not choke on unicode
616 with test.test_support.temp_cwd():
617 with captured_stdout() as output:
618 pydoc.writedoc(self.Q)
619 self.assertEqual(output.getvalue(), 'wrote Q.html\n')
620
Ezio Melottibdfa2e62011-04-28 07:59:33 +0300621class TestHelper(unittest.TestCase):
622 def test_keywords(self):
623 self.assertEqual(sorted(pydoc.Helper.keywords),
624 sorted(keyword.kwlist))
625
Éric Araujo9a528302011-07-29 17:34:35 +0200626 def test_builtin(self):
627 for name in ('str', 'str.translate', '__builtin__.str',
628 '__builtin__.str.translate'):
629 # test low-level function
630 self.assertIsNotNone(pydoc.locate(name))
631 # test high-level function
632 try:
633 pydoc.render_doc(name)
634 except ImportError:
Terry Jan Reedy72998182014-06-20 14:59:07 -0400635 self.fail('finding the doc of {!r} failed'.format(name))
Éric Araujo9a528302011-07-29 17:34:35 +0200636
637 for name in ('not__builtin__', 'strrr', 'strr.translate',
638 'str.trrrranslate', '__builtin__.strrr',
639 '__builtin__.str.trrranslate'):
640 self.assertIsNone(pydoc.locate(name))
641 self.assertRaises(ImportError, pydoc.render_doc, name)
642
Ezio Melottibdfa2e62011-04-28 07:59:33 +0300643
Georg Brandl8632cc22008-05-18 16:32:48 +0000644def test_main():
Ned Deily1a96f8d2011-10-06 14:17:34 -0700645 try:
Antoine Pitrouf41ffed2013-05-19 15:44:54 +0200646 test.test_support.run_unittest(PydocDocTest,
Ned Deily1a96f8d2011-10-06 14:17:34 -0700647 PydocImportTest,
648 TestDescriptions,
R David Murray984f6302014-01-05 12:35:59 -0500649 TestUnicode,
Ned Deily1a96f8d2011-10-06 14:17:34 -0700650 TestHelper)
651 finally:
652 reap_children()
Georg Brandl8632cc22008-05-18 16:32:48 +0000653
654if __name__ == "__main__":
655 test_main()