test_pydoc.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. import os
  2. import sys
  3. import difflib
  4. import __builtin__
  5. import re
  6. import py_compile
  7. import pydoc
  8. import contextlib
  9. import inspect
  10. import keyword
  11. import pkgutil
  12. import unittest
  13. import xml.etree
  14. import types
  15. import test.test_support
  16. from collections import namedtuple
  17. from test.script_helper import assert_python_ok
  18. from test.test_support import (TESTFN, rmtree, reap_children, captured_stdout,
  19. captured_stderr, requires_docstrings)
  20. from test import pydoc_mod
  21. if test.test_support.HAVE_DOCSTRINGS:
  22. expected_data_docstrings = (
  23. 'dictionary for instance variables (if defined)',
  24. 'list of weak references to the object (if defined)',
  25. )
  26. else:
  27. expected_data_docstrings = ('', '')
  28. expected_text_pattern = \
  29. """
  30. NAME
  31. test.pydoc_mod - This is a test module for test_pydoc
  32. FILE
  33. %s
  34. %s
  35. CLASSES
  36. __builtin__.object
  37. B
  38. C
  39. A
  40. \x20\x20\x20\x20
  41. class A
  42. | Hello and goodbye
  43. |\x20\x20
  44. | Methods defined here:
  45. |\x20\x20
  46. | __init__()
  47. | Wow, I have no function!
  48. \x20\x20\x20\x20
  49. class B(__builtin__.object)
  50. | Data descriptors defined here:
  51. |\x20\x20
  52. | __dict__%s
  53. |\x20\x20
  54. | __weakref__%s
  55. |\x20\x20
  56. | ----------------------------------------------------------------------
  57. | Data and other attributes defined here:
  58. |\x20\x20
  59. | NO_MEANING = 'eggs'
  60. \x20\x20\x20\x20
  61. class C(__builtin__.object)
  62. | Methods defined here:
  63. |\x20\x20
  64. | get_answer(self)
  65. | Return say_no()
  66. |\x20\x20
  67. | is_it_true(self)
  68. | Return self.get_answer()
  69. |\x20\x20
  70. | say_no(self)
  71. |\x20\x20
  72. | ----------------------------------------------------------------------
  73. | Data descriptors defined here:
  74. |\x20\x20
  75. | __dict__
  76. | dictionary for instance variables (if defined)
  77. |\x20\x20
  78. | __weakref__
  79. | list of weak references to the object (if defined)
  80. FUNCTIONS
  81. doc_func()
  82. This function solves all of the world's problems:
  83. hunger
  84. lack of Python
  85. war
  86. \x20\x20\x20\x20
  87. nodoc_func()
  88. DATA
  89. __author__ = 'Benjamin Peterson'
  90. __credits__ = 'Nobody'
  91. __version__ = '1.2.3.4'
  92. VERSION
  93. 1.2.3.4
  94. AUTHOR
  95. Benjamin Peterson
  96. CREDITS
  97. Nobody
  98. """.strip()
  99. expected_text_data_docstrings = tuple('\n | ' + s if s else ''
  100. for s in expected_data_docstrings)
  101. expected_html_pattern = \
  102. """
  103. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
  104. <tr bgcolor="#7799ee">
  105. <td valign=bottom>&nbsp;<br>
  106. <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
  107. ><td align=right valign=bottom
  108. ><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
  109. <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
  110. <p>
  111. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
  112. <tr bgcolor="#ee77aa">
  113. <td colspan=3 valign=bottom>&nbsp;<br>
  114. <font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
  115. \x20\x20\x20\x20
  116. <tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
  117. <td width="100%%"><dl>
  118. <dt><font face="helvetica, arial"><a href="__builtin__.html#object">__builtin__.object</a>
  119. </font></dt><dd>
  120. <dl>
  121. <dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
  122. </font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#C">C</a>
  123. </font></dt></dl>
  124. </dd>
  125. <dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
  126. </font></dt></dl>
  127. <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="A">class <strong>A</strong></a></font></td></tr>
  132. \x20\x20\x20\x20
  133. <tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
  134. <td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
  135. <tr><td>&nbsp;</td>
  136. <td width="100%%">Methods defined here:<br>
  137. <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>
  138. </td></tr></table> <p>
  139. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
  140. <tr bgcolor="#ffc8d8">
  141. <td colspan=3 valign=bottom>&nbsp;<br>
  142. <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>
  143. \x20\x20\x20\x20
  144. <tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
  145. <td width="100%%">Data descriptors defined here:<br>
  146. <dl><dt><strong>__dict__</strong></dt>
  147. <dd><tt>%s</tt></dd>
  148. </dl>
  149. <dl><dt><strong>__weakref__</strong></dt>
  150. <dd><tt>%s</tt></dd>
  151. </dl>
  152. <hr>
  153. Data and other attributes defined here:<br>
  154. <dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
  155. </td></tr></table> <p>
  156. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
  157. <tr bgcolor="#ffc8d8">
  158. <td colspan=3 valign=bottom>&nbsp;<br>
  159. <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>
  160. \x20\x20\x20\x20
  161. <tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
  162. <td width="100%%">Methods defined here:<br>
  163. <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>
  164. <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>
  165. <dl><dt><a name="C-say_no"><strong>say_no</strong></a>(self)</dt></dl>
  166. <hr>
  167. Data descriptors defined here:<br>
  168. <dl><dt><strong>__dict__</strong></dt>
  169. <dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
  170. </dl>
  171. <dl><dt><strong>__weakref__</strong></dt>
  172. <dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
  173. </dl>
  174. </td></tr></table></td></tr></table><p>
  175. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
  176. <tr bgcolor="#eeaa77">
  177. <td colspan=3 valign=bottom>&nbsp;<br>
  178. <font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
  179. \x20\x20\x20\x20
  180. <tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
  181. <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>
  182. hunger<br>
  183. lack&nbsp;of&nbsp;Python<br>
  184. war</tt></dd></dl>
  185. <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
  186. </td></tr></table><p>
  187. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
  188. <tr bgcolor="#55aa55">
  189. <td colspan=3 valign=bottom>&nbsp;<br>
  190. <font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
  191. \x20\x20\x20\x20
  192. <tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
  193. <td width="100%%"><strong>__author__</strong> = 'Benjamin Peterson'<br>
  194. <strong>__credits__</strong> = 'Nobody'<br>
  195. <strong>__version__</strong> = '1.2.3.4'</td></tr></table><p>
  196. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
  197. <tr bgcolor="#7799ee">
  198. <td colspan=3 valign=bottom>&nbsp;<br>
  199. <font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
  200. \x20\x20\x20\x20
  201. <tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
  202. <td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
  203. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
  204. <tr bgcolor="#7799ee">
  205. <td colspan=3 valign=bottom>&nbsp;<br>
  206. <font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
  207. \x20\x20\x20\x20
  208. <tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
  209. <td width="100%%">Nobody</td></tr></table>
  210. """.strip()
  211. expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;')
  212. for s in expected_data_docstrings)
  213. # output pattern for missing module
  214. missing_pattern = "no Python documentation found for '%s'"
  215. # output pattern for module with bad imports
  216. badimport_pattern = "problem in %s - <type 'exceptions.ImportError'>: No module named %s"
  217. def run_pydoc(module_name, *args, **env):
  218. """
  219. Runs pydoc on the specified module. Returns the stripped
  220. output of pydoc.
  221. """
  222. args = args + (module_name,)
  223. # do not write bytecode files to avoid caching errors
  224. rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
  225. return out.strip()
  226. def get_pydoc_html(module):
  227. "Returns pydoc generated output as html"
  228. doc = pydoc.HTMLDoc()
  229. output = doc.docmodule(module)
  230. loc = doc.getdocloc(pydoc_mod) or ""
  231. if loc:
  232. loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
  233. return output.strip(), loc
  234. def get_pydoc_text(module):
  235. "Returns pydoc generated output as text"
  236. doc = pydoc.TextDoc()
  237. loc = doc.getdocloc(pydoc_mod) or ""
  238. if loc:
  239. loc = "\nMODULE DOCS\n " + loc + "\n"
  240. output = doc.docmodule(module)
  241. # cleanup the extra text formatting that pydoc preforms
  242. patt = re.compile('\b.')
  243. output = patt.sub('', output)
  244. return output.strip(), loc
  245. def print_diffs(text1, text2):
  246. "Prints unified diffs for two texts"
  247. lines1 = text1.splitlines(True)
  248. lines2 = text2.splitlines(True)
  249. diffs = difflib.unified_diff(lines1, lines2, n=0, fromfile='expected',
  250. tofile='got')
  251. print '\n' + ''.join(diffs)
  252. class PydocBaseTest(unittest.TestCase):
  253. def _restricted_walk_packages(self, walk_packages, path=None):
  254. """
  255. A version of pkgutil.walk_packages() that will restrict itself to
  256. a given path.
  257. """
  258. default_path = path or [os.path.dirname(__file__)]
  259. def wrapper(path=None, prefix='', onerror=None):
  260. return walk_packages(path or default_path, prefix, onerror)
  261. return wrapper
  262. @contextlib.contextmanager
  263. def restrict_walk_packages(self, path=None):
  264. walk_packages = pkgutil.walk_packages
  265. pkgutil.walk_packages = self._restricted_walk_packages(walk_packages,
  266. path)
  267. try:
  268. yield
  269. finally:
  270. pkgutil.walk_packages = walk_packages
  271. class PydocDocTest(unittest.TestCase):
  272. @requires_docstrings
  273. @unittest.skipIf(sys.flags.optimize >= 2,
  274. "Docstrings are omitted with -O2 and above")
  275. def test_html_doc(self):
  276. result, doc_loc = get_pydoc_html(pydoc_mod)
  277. mod_file = inspect.getabsfile(pydoc_mod)
  278. if sys.platform == 'win32':
  279. import nturl2path
  280. mod_url = nturl2path.pathname2url(mod_file)
  281. else:
  282. mod_url = mod_file
  283. expected_html = expected_html_pattern % (
  284. (mod_url, mod_file, doc_loc) +
  285. expected_html_data_docstrings)
  286. if result != expected_html:
  287. print_diffs(expected_html, result)
  288. self.fail("outputs are not equal, see diff above")
  289. @requires_docstrings
  290. @unittest.skipIf(sys.flags.optimize >= 2,
  291. "Docstrings are omitted with -O2 and above")
  292. def test_text_doc(self):
  293. result, doc_loc = get_pydoc_text(pydoc_mod)
  294. expected_text = expected_text_pattern % (
  295. (inspect.getabsfile(pydoc_mod), doc_loc) +
  296. expected_text_data_docstrings)
  297. if result != expected_text:
  298. print_diffs(expected_text, result)
  299. self.fail("outputs are not equal, see diff above")
  300. def test_issue8225(self):
  301. # Test issue8225 to ensure no doc link appears for xml.etree
  302. result, doc_loc = get_pydoc_text(xml.etree)
  303. self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
  304. def test_getpager_with_stdin_none(self):
  305. previous_stdin = sys.stdin
  306. try:
  307. sys.stdin = None
  308. pydoc.getpager() # Shouldn't fail.
  309. finally:
  310. sys.stdin = previous_stdin
  311. def test_non_str_name(self):
  312. # issue14638
  313. # Treat illegal (non-str) name like no name
  314. class A:
  315. __name__ = 42
  316. class B:
  317. pass
  318. adoc = pydoc.render_doc(A())
  319. bdoc = pydoc.render_doc(B())
  320. self.assertEqual(adoc.replace("A", "B"), bdoc)
  321. def test_not_here(self):
  322. missing_module = "test.i_am_not_here"
  323. result = run_pydoc(missing_module)
  324. expected = missing_pattern % missing_module
  325. self.assertEqual(expected, result,
  326. "documentation for missing module found")
  327. def test_input_strip(self):
  328. missing_module = " test.i_am_not_here "
  329. result = run_pydoc(missing_module)
  330. expected = missing_pattern % missing_module.strip()
  331. self.assertEqual(expected, result,
  332. "white space was not stripped from module name "
  333. "or other error output mismatch")
  334. def test_stripid(self):
  335. # test with strings, other implementations might have different repr()
  336. stripid = pydoc.stripid
  337. # strip the id
  338. self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
  339. '<function stripid>')
  340. self.assertEqual(stripid('<function stripid at 0x01F65390>'),
  341. '<function stripid>')
  342. # nothing to strip, return the same text
  343. self.assertEqual(stripid('42'), '42')
  344. self.assertEqual(stripid("<type 'exceptions.Exception'>"),
  345. "<type 'exceptions.Exception'>")
  346. def test_synopsis(self):
  347. with test.test_support.temp_cwd() as test_dir:
  348. init_path = os.path.join(test_dir, 'dt.py')
  349. with open(init_path, 'w') as fobj:
  350. fobj.write('''\
  351. """
  352. my doc
  353. second line
  354. """
  355. foo = 1
  356. ''')
  357. py_compile.compile(init_path)
  358. synopsis = pydoc.synopsis(init_path, {})
  359. self.assertEqual(synopsis, 'my doc')
  360. @unittest.skipIf(sys.flags.optimize >= 2,
  361. 'Docstrings are omitted with -OO and above')
  362. def test_synopsis_sourceless_empty_doc(self):
  363. with test.test_support.temp_cwd() as test_dir:
  364. init_path = os.path.join(test_dir, 'foomod42.py')
  365. cached_path = os.path.join(test_dir, 'foomod42.pyc')
  366. with open(init_path, 'w') as fobj:
  367. fobj.write("foo = 1")
  368. py_compile.compile(init_path)
  369. synopsis = pydoc.synopsis(init_path, {})
  370. self.assertIsNone(synopsis)
  371. synopsis_cached = pydoc.synopsis(cached_path, {})
  372. self.assertIsNone(synopsis_cached)
  373. class PydocImportTest(PydocBaseTest):
  374. def setUp(self):
  375. self.test_dir = os.mkdir(TESTFN)
  376. self.addCleanup(rmtree, TESTFN)
  377. def test_badimport(self):
  378. # This tests the fix for issue 5230, where if pydoc found the module
  379. # but the module had an internal import error pydoc would report no doc
  380. # found.
  381. modname = 'testmod_xyzzy'
  382. testpairs = (
  383. ('i_am_not_here', 'i_am_not_here'),
  384. ('test.i_am_not_here_either', 'i_am_not_here_either'),
  385. ('test.i_am_not_here.neither_am_i', 'i_am_not_here.neither_am_i'),
  386. ('i_am_not_here.{}'.format(modname),
  387. 'i_am_not_here.{}'.format(modname)),
  388. ('test.{}'.format(modname), modname),
  389. )
  390. sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
  391. for importstring, expectedinmsg in testpairs:
  392. with open(sourcefn, 'w') as f:
  393. f.write("import {}\n".format(importstring))
  394. result = run_pydoc(modname, PYTHONPATH=TESTFN)
  395. expected = badimport_pattern % (modname, expectedinmsg)
  396. self.assertEqual(expected, result)
  397. def test_apropos_with_bad_package(self):
  398. # Issue 7425 - pydoc -k failed when bad package on path
  399. pkgdir = os.path.join(TESTFN, "syntaxerr")
  400. os.mkdir(pkgdir)
  401. badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
  402. with open(badsyntax, 'w') as f:
  403. f.write("invalid python syntax = $1\n")
  404. with self.restrict_walk_packages(path=[TESTFN]):
  405. with captured_stdout() as out:
  406. with captured_stderr() as err:
  407. pydoc.apropos('xyzzy')
  408. # No result, no error
  409. self.assertEqual(out.getvalue(), '')
  410. self.assertEqual(err.getvalue(), '')
  411. # The package name is still matched
  412. with captured_stdout() as out:
  413. with captured_stderr() as err:
  414. pydoc.apropos('syntaxerr')
  415. self.assertEqual(out.getvalue().strip(), 'syntaxerr')
  416. self.assertEqual(err.getvalue(), '')
  417. def test_apropos_with_unreadable_dir(self):
  418. # Issue 7367 - pydoc -k failed when unreadable dir on path
  419. self.unreadable_dir = os.path.join(TESTFN, "unreadable")
  420. os.mkdir(self.unreadable_dir, 0)
  421. self.addCleanup(os.rmdir, self.unreadable_dir)
  422. # Note, on Windows the directory appears to be still
  423. # readable so this is not really testing the issue there
  424. with self.restrict_walk_packages(path=[TESTFN]):
  425. with captured_stdout() as out:
  426. with captured_stderr() as err:
  427. pydoc.apropos('SOMEKEY')
  428. # No result, no error
  429. self.assertEqual(out.getvalue(), '')
  430. self.assertEqual(err.getvalue(), '')
  431. class TestDescriptions(unittest.TestCase):
  432. def test_module(self):
  433. # Check that pydocfodder module can be described
  434. from test import pydocfodder
  435. doc = pydoc.render_doc(pydocfodder)
  436. self.assertIn("pydocfodder", doc)
  437. def test_classic_class(self):
  438. class C: "Classic class"
  439. c = C()
  440. self.assertEqual(pydoc.describe(C), 'class C')
  441. self.assertEqual(pydoc.describe(c), 'instance of C')
  442. expected = 'instance of C in module %s' % __name__
  443. self.assertIn(expected, pydoc.render_doc(c))
  444. def test_class(self):
  445. class C(object): "New-style class"
  446. c = C()
  447. self.assertEqual(pydoc.describe(C), 'class C')
  448. self.assertEqual(pydoc.describe(c), 'C')
  449. expected = 'C in module %s object' % __name__
  450. self.assertIn(expected, pydoc.render_doc(c))
  451. def test_namedtuple_public_underscore(self):
  452. NT = namedtuple('NT', ['abc', 'def'], rename=True)
  453. with captured_stdout() as help_io:
  454. pydoc.help(NT)
  455. helptext = help_io.getvalue()
  456. self.assertIn('_1', helptext)
  457. self.assertIn('_replace', helptext)
  458. self.assertIn('_asdict', helptext)
  459. @unittest.skipUnless(test.test_support.have_unicode,
  460. "test requires unicode support")
  461. class TestUnicode(unittest.TestCase):
  462. def setUp(self):
  463. # Better not to use unicode escapes in literals, lest the
  464. # parser choke on it if Python has been built without
  465. # unicode support.
  466. self.Q = types.ModuleType(
  467. 'Q', 'Rational numbers: \xe2\x84\x9a'.decode('utf8'))
  468. self.Q.__version__ = '\xe2\x84\x9a'.decode('utf8')
  469. self.Q.__date__ = '\xe2\x84\x9a'.decode('utf8')
  470. self.Q.__author__ = '\xe2\x84\x9a'.decode('utf8')
  471. self.Q.__credits__ = '\xe2\x84\x9a'.decode('utf8')
  472. self.assertIsInstance(self.Q.__doc__, unicode)
  473. def test_render_doc(self):
  474. # render_doc is robust against unicode in docstrings
  475. doc = pydoc.render_doc(self.Q)
  476. self.assertIsInstance(doc, str)
  477. def test_encode(self):
  478. # _encode is robust against characters out the specified encoding
  479. self.assertEqual(pydoc._encode(self.Q.__doc__, 'ascii'), 'Rational numbers: &#8474;')
  480. def test_pipepager(self):
  481. # pipepager does not choke on unicode
  482. doc = pydoc.render_doc(self.Q)
  483. saved, os.popen = os.popen, open
  484. try:
  485. with test.test_support.temp_cwd():
  486. pydoc.pipepager(doc, 'pipe')
  487. self.assertEqual(open('pipe').read(), pydoc._encode(doc))
  488. finally:
  489. os.popen = saved
  490. def test_tempfilepager(self):
  491. # tempfilepager does not choke on unicode
  492. doc = pydoc.render_doc(self.Q)
  493. output = {}
  494. def mock_system(cmd):
  495. filename = cmd.strip()[1:-1]
  496. self.assertEqual('"' + filename + '"', cmd.strip())
  497. output['content'] = open(filename).read()
  498. saved, os.system = os.system, mock_system
  499. try:
  500. pydoc.tempfilepager(doc, '')
  501. self.assertEqual(output['content'], pydoc._encode(doc))
  502. finally:
  503. os.system = saved
  504. def test_plainpager(self):
  505. # plainpager does not choke on unicode
  506. doc = pydoc.render_doc(self.Q)
  507. # Note: captured_stdout is too permissive when it comes to
  508. # unicode, and using it here would make the test always
  509. # pass.
  510. with test.test_support.temp_cwd():
  511. with open('output', 'w') as f:
  512. saved, sys.stdout = sys.stdout, f
  513. try:
  514. pydoc.plainpager(doc)
  515. finally:
  516. sys.stdout = saved
  517. self.assertIn('Rational numbers:', open('output').read())
  518. def test_ttypager(self):
  519. # ttypager does not choke on unicode
  520. doc = pydoc.render_doc(self.Q)
  521. # Test ttypager
  522. with test.test_support.temp_cwd(), test.test_support.captured_stdin():
  523. with open('output', 'w') as f:
  524. saved, sys.stdout = sys.stdout, f
  525. try:
  526. pydoc.ttypager(doc)
  527. finally:
  528. sys.stdout = saved
  529. self.assertIn('Rational numbers:', open('output').read())
  530. def test_htmlpage(self):
  531. # html.page does not choke on unicode
  532. with test.test_support.temp_cwd():
  533. with captured_stdout() as output:
  534. pydoc.writedoc(self.Q)
  535. self.assertEqual(output.getvalue(), 'wrote Q.html\n')
  536. class TestHelper(unittest.TestCase):
  537. def test_keywords(self):
  538. self.assertEqual(sorted(pydoc.Helper.keywords),
  539. sorted(keyword.kwlist))
  540. def test_builtin(self):
  541. for name in ('str', 'str.translate', '__builtin__.str',
  542. '__builtin__.str.translate'):
  543. # test low-level function
  544. self.assertIsNotNone(pydoc.locate(name))
  545. # test high-level function
  546. try:
  547. pydoc.render_doc(name)
  548. except ImportError:
  549. self.fail('finding the doc of {!r} failed'.format(name))
  550. for name in ('not__builtin__', 'strrr', 'strr.translate',
  551. 'str.trrrranslate', '__builtin__.strrr',
  552. '__builtin__.str.trrranslate'):
  553. self.assertIsNone(pydoc.locate(name))
  554. self.assertRaises(ImportError, pydoc.render_doc, name)
  555. def test_main():
  556. try:
  557. test.test_support.run_unittest(PydocDocTest,
  558. PydocImportTest,
  559. TestDescriptions,
  560. TestUnicode,
  561. TestHelper)
  562. finally:
  563. reap_children()
  564. if __name__ == "__main__":
  565. test_main()