PageRenderTime 47ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/test/test_pydoc.py

https://bitbucket.org/kkris/pypy
Python | 397 lines | 353 code | 8 blank | 36 comment | 1 complexity | c0049be04802651e7ebfdb44ef8ade0a MD5 | raw file
  1. import os
  2. import sys
  3. import difflib
  4. import __builtin__
  5. import re
  6. import pydoc
  7. import inspect
  8. import keyword
  9. import unittest
  10. import xml.etree
  11. import test.test_support
  12. from collections import namedtuple
  13. from test.script_helper import assert_python_ok
  14. from test.test_support import (
  15. TESTFN, rmtree, reap_children, captured_stdout)
  16. from test import pydoc_mod
  17. expected_text_pattern = \
  18. """
  19. NAME
  20. test.pydoc_mod - This is a test module for test_pydoc
  21. FILE
  22. %s
  23. %s
  24. CLASSES
  25. __builtin__.object
  26. B
  27. A
  28. \x20\x20\x20\x20
  29. class A
  30. | Hello and goodbye
  31. |\x20\x20
  32. | Methods defined here:
  33. |\x20\x20
  34. | __init__()
  35. | Wow, I have no function!
  36. \x20\x20\x20\x20
  37. class B(__builtin__.object)
  38. | Data descriptors defined here:
  39. |\x20\x20
  40. | __dict__
  41. | dictionary for instance variables (if defined)
  42. |\x20\x20
  43. | __weakref__
  44. | list of weak references to the object (if defined)
  45. |\x20\x20
  46. | ----------------------------------------------------------------------
  47. | Data and other attributes defined here:
  48. |\x20\x20
  49. | NO_MEANING = 'eggs'
  50. FUNCTIONS
  51. doc_func()
  52. This function solves all of the world's problems:
  53. hunger
  54. lack of Python
  55. war
  56. \x20\x20\x20\x20
  57. nodoc_func()
  58. DATA
  59. __author__ = 'Benjamin Peterson'
  60. __credits__ = 'Nobody'
  61. __version__ = '1.2.3.4'
  62. VERSION
  63. 1.2.3.4
  64. AUTHOR
  65. Benjamin Peterson
  66. CREDITS
  67. Nobody
  68. """.strip()
  69. expected_html_pattern = \
  70. """
  71. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
  72. <tr bgcolor="#7799ee">
  73. <td valign=bottom>&nbsp;<br>
  74. <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
  75. ><td align=right valign=bottom
  76. ><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
  77. <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
  78. <p>
  79. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
  80. <tr bgcolor="#ee77aa">
  81. <td colspan=3 valign=bottom>&nbsp;<br>
  82. <font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
  83. \x20\x20\x20\x20
  84. <tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
  85. <td width="100%%"><dl>
  86. <dt><font face="helvetica, arial"><a href="__builtin__.html#object">__builtin__.object</a>
  87. </font></dt><dd>
  88. <dl>
  89. <dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
  90. </font></dt></dl>
  91. </dd>
  92. <dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
  93. </font></dt></dl>
  94. <p>
  95. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
  96. <tr bgcolor="#ffc8d8">
  97. <td colspan=3 valign=bottom>&nbsp;<br>
  98. <font color="#000000" face="helvetica, arial"><a name="A">class <strong>A</strong></a></font></td></tr>
  99. \x20\x20\x20\x20
  100. <tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
  101. <td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
  102. <tr><td>&nbsp;</td>
  103. <td width="100%%">Methods defined here:<br>
  104. <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>
  105. </td></tr></table> <p>
  106. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
  107. <tr bgcolor="#ffc8d8">
  108. <td colspan=3 valign=bottom>&nbsp;<br>
  109. <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>
  110. \x20\x20\x20\x20
  111. <tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
  112. <td width="100%%">Data descriptors defined here:<br>
  113. <dl><dt><strong>__dict__</strong></dt>
  114. <dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
  115. </dl>
  116. <dl><dt><strong>__weakref__</strong></dt>
  117. <dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
  118. </dl>
  119. <hr>
  120. Data and other attributes defined here:<br>
  121. <dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
  122. </td></tr></table></td></tr></table><p>
  123. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
  124. <tr bgcolor="#eeaa77">
  125. <td colspan=3 valign=bottom>&nbsp;<br>
  126. <font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
  127. \x20\x20\x20\x20
  128. <tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
  129. <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>
  130. hunger<br>
  131. lack&nbsp;of&nbsp;Python<br>
  132. war</tt></dd></dl>
  133. <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
  134. </td></tr></table><p>
  135. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
  136. <tr bgcolor="#55aa55">
  137. <td colspan=3 valign=bottom>&nbsp;<br>
  138. <font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
  139. \x20\x20\x20\x20
  140. <tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
  141. <td width="100%%"><strong>__author__</strong> = 'Benjamin Peterson'<br>
  142. <strong>__credits__</strong> = 'Nobody'<br>
  143. <strong>__version__</strong> = '1.2.3.4'</td></tr></table><p>
  144. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
  145. <tr bgcolor="#7799ee">
  146. <td colspan=3 valign=bottom>&nbsp;<br>
  147. <font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
  148. \x20\x20\x20\x20
  149. <tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
  150. <td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
  151. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
  152. <tr bgcolor="#7799ee">
  153. <td colspan=3 valign=bottom>&nbsp;<br>
  154. <font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
  155. \x20\x20\x20\x20
  156. <tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
  157. <td width="100%%">Nobody</td></tr></table>
  158. """.strip()
  159. # output pattern for missing module
  160. missing_pattern = "no Python documentation found for '%s'"
  161. # output pattern for module with bad imports
  162. badimport_pattern = "problem in %s - <type 'exceptions.ImportError'>: No module named %s"
  163. def run_pydoc(module_name, *args, **env):
  164. """
  165. Runs pydoc on the specified module. Returns the stripped
  166. output of pydoc.
  167. """
  168. args = args + (module_name,)
  169. # do not write bytecode files to avoid caching errors
  170. rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
  171. return out.strip()
  172. def get_pydoc_html(module):
  173. "Returns pydoc generated output as html"
  174. doc = pydoc.HTMLDoc()
  175. output = doc.docmodule(module)
  176. loc = doc.getdocloc(pydoc_mod) or ""
  177. if loc:
  178. loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
  179. return output.strip(), loc
  180. def get_pydoc_text(module):
  181. "Returns pydoc generated output as text"
  182. doc = pydoc.TextDoc()
  183. loc = doc.getdocloc(pydoc_mod) or ""
  184. if loc:
  185. loc = "\nMODULE DOCS\n " + loc + "\n"
  186. output = doc.docmodule(module)
  187. # cleanup the extra text formatting that pydoc preforms
  188. patt = re.compile('\b.')
  189. output = patt.sub('', output)
  190. return output.strip(), loc
  191. def print_diffs(text1, text2):
  192. "Prints unified diffs for two texts"
  193. lines1 = text1.splitlines(True)
  194. lines2 = text2.splitlines(True)
  195. diffs = difflib.unified_diff(lines1, lines2, n=0, fromfile='expected',
  196. tofile='got')
  197. print '\n' + ''.join(diffs)
  198. class PyDocDocTest(unittest.TestCase):
  199. @unittest.skipIf(sys.flags.optimize >= 2,
  200. "Docstrings are omitted with -O2 and above")
  201. def test_html_doc(self):
  202. result, doc_loc = get_pydoc_html(pydoc_mod)
  203. mod_file = inspect.getabsfile(pydoc_mod)
  204. if sys.platform == 'win32':
  205. import nturl2path
  206. mod_url = nturl2path.pathname2url(mod_file)
  207. else:
  208. mod_url = mod_file
  209. expected_html = expected_html_pattern % (mod_url, mod_file, doc_loc)
  210. if result != expected_html:
  211. print_diffs(expected_html, result)
  212. self.fail("outputs are not equal, see diff above")
  213. @unittest.skipIf(sys.flags.optimize >= 2,
  214. "Docstrings are omitted with -O2 and above")
  215. def test_text_doc(self):
  216. result, doc_loc = get_pydoc_text(pydoc_mod)
  217. expected_text = expected_text_pattern % \
  218. (inspect.getabsfile(pydoc_mod), doc_loc)
  219. if result != expected_text:
  220. print_diffs(expected_text, result)
  221. self.fail("outputs are not equal, see diff above")
  222. def test_issue8225(self):
  223. # Test issue8225 to ensure no doc link appears for xml.etree
  224. result, doc_loc = get_pydoc_text(xml.etree)
  225. self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
  226. def test_not_here(self):
  227. missing_module = "test.i_am_not_here"
  228. result = run_pydoc(missing_module)
  229. expected = missing_pattern % missing_module
  230. self.assertEqual(expected, result,
  231. "documentation for missing module found")
  232. def test_input_strip(self):
  233. missing_module = " test.i_am_not_here "
  234. result = run_pydoc(missing_module)
  235. expected = missing_pattern % missing_module.strip()
  236. self.assertEqual(expected, result,
  237. "white space was not stripped from module name "
  238. "or other error output mismatch")
  239. def test_stripid(self):
  240. # test with strings, other implementations might have different repr()
  241. stripid = pydoc.stripid
  242. # strip the id
  243. self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
  244. '<function stripid>')
  245. self.assertEqual(stripid('<function stripid at 0x01F65390>'),
  246. '<function stripid>')
  247. # nothing to strip, return the same text
  248. self.assertEqual(stripid('42'), '42')
  249. self.assertEqual(stripid("<type 'exceptions.Exception'>"),
  250. "<type 'exceptions.Exception'>")
  251. class PydocImportTest(unittest.TestCase):
  252. def setUp(self):
  253. self.test_dir = os.mkdir(TESTFN)
  254. self.addCleanup(rmtree, TESTFN)
  255. def test_badimport(self):
  256. # This tests the fix for issue 5230, where if pydoc found the module
  257. # but the module had an internal import error pydoc would report no doc
  258. # found.
  259. modname = 'testmod_xyzzy'
  260. testpairs = (
  261. ('i_am_not_here', 'i_am_not_here'),
  262. ('test.i_am_not_here_either', 'test.i_am_not_here_either'),
  263. ('test.i_am_not_here.neither_am_i', 'test.i_am_not_here'),
  264. ('i_am_not_here.{}'.format(modname), 'i_am_not_here'),
  265. ('test.{}'.format(modname), 'test.{}'.format(modname)),
  266. )
  267. sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
  268. for importstring, expectedinmsg in testpairs:
  269. with open(sourcefn, 'w') as f:
  270. f.write("import {}\n".format(importstring))
  271. result = run_pydoc(modname, PYTHONPATH=TESTFN)
  272. expected = badimport_pattern % (modname, expectedinmsg)
  273. self.assertEqual(expected, result)
  274. def test_apropos_with_bad_package(self):
  275. # Issue 7425 - pydoc -k failed when bad package on path
  276. pkgdir = os.path.join(TESTFN, "syntaxerr")
  277. os.mkdir(pkgdir)
  278. badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
  279. with open(badsyntax, 'w') as f:
  280. f.write("invalid python syntax = $1\n")
  281. result = run_pydoc('zqwykjv', '-k', PYTHONPATH=TESTFN)
  282. self.assertEqual('', result)
  283. def test_apropos_with_unreadable_dir(self):
  284. # Issue 7367 - pydoc -k failed when unreadable dir on path
  285. self.unreadable_dir = os.path.join(TESTFN, "unreadable")
  286. os.mkdir(self.unreadable_dir, 0)
  287. self.addCleanup(os.rmdir, self.unreadable_dir)
  288. # Note, on Windows the directory appears to be still
  289. # readable so this is not really testing the issue there
  290. result = run_pydoc('zqwykjv', '-k', PYTHONPATH=TESTFN)
  291. self.assertEqual('', result)
  292. class TestDescriptions(unittest.TestCase):
  293. def test_module(self):
  294. # Check that pydocfodder module can be described
  295. from test import pydocfodder
  296. doc = pydoc.render_doc(pydocfodder)
  297. self.assertIn("pydocfodder", doc)
  298. def test_classic_class(self):
  299. class C: "Classic class"
  300. c = C()
  301. self.assertEqual(pydoc.describe(C), 'class C')
  302. self.assertEqual(pydoc.describe(c), 'instance of C')
  303. expected = 'instance of C in module %s' % __name__
  304. self.assertIn(expected, pydoc.render_doc(c))
  305. def test_class(self):
  306. class C(object): "New-style class"
  307. c = C()
  308. self.assertEqual(pydoc.describe(C), 'class C')
  309. self.assertEqual(pydoc.describe(c), 'C')
  310. expected = 'C in module %s object' % __name__
  311. self.assertIn(expected, pydoc.render_doc(c))
  312. def test_namedtuple_public_underscore(self):
  313. NT = namedtuple('NT', ['abc', 'def'], rename=True)
  314. with captured_stdout() as help_io:
  315. help(NT)
  316. helptext = help_io.getvalue()
  317. self.assertIn('_1', helptext)
  318. self.assertIn('_replace', helptext)
  319. self.assertIn('_asdict', helptext)
  320. class TestHelper(unittest.TestCase):
  321. def test_keywords(self):
  322. self.assertEqual(sorted(pydoc.Helper.keywords),
  323. sorted(keyword.kwlist))
  324. def test_builtin(self):
  325. for name in ('str', 'str.translate', '__builtin__.str',
  326. '__builtin__.str.translate'):
  327. # test low-level function
  328. self.assertIsNotNone(pydoc.locate(name))
  329. # test high-level function
  330. try:
  331. pydoc.render_doc(name)
  332. except ImportError:
  333. self.fail('finding the doc of {!r} failed'.format(o))
  334. for name in ('not__builtin__', 'strrr', 'strr.translate',
  335. 'str.trrrranslate', '__builtin__.strrr',
  336. '__builtin__.str.trrranslate'):
  337. self.assertIsNone(pydoc.locate(name))
  338. self.assertRaises(ImportError, pydoc.render_doc, name)
  339. def test_main():
  340. try:
  341. test.test_support.run_unittest(PyDocDocTest,
  342. PydocImportTest,
  343. TestDescriptions,
  344. TestHelper)
  345. finally:
  346. reap_children()
  347. if __name__ == "__main__":
  348. test_main()