Home | History | Annotate | Download | only in test
      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 import xml.etree.ElementTree
     17 from collections import namedtuple
     18 from test.script_helper import assert_python_ok
     19 from test.test_support import (TESTFN, rmtree, reap_children, captured_stdout,
     20                                captured_stderr, requires_docstrings)
     21 
     22 from test import pydoc_mod
     23 
     24 if 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         )
     29 else:
     30     expected_data_docstrings = ('', '')
     31 
     32 expected_text_pattern = \
     33 """
     34 NAME
     35     test.pydoc_mod - This is a test module for test_pydoc
     36 
     37 FILE
     38     %s
     39 %s
     40 CLASSES
     41     __builtin__.object
     42         B
     43         C
     44     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
     57      |  __dict__%s
     58      |\x20\x20
     59      |  __weakref__%s
     60      |\x20\x20
     61      |  ----------------------------------------------------------------------
     62      |  Data and other attributes defined here:
     63      |\x20\x20
     64      |  NO_MEANING = 'eggs'
     65 \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)
     85 
     86 FUNCTIONS
     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 
     95 DATA
     96     __author__ = 'Benjamin Peterson'
     97     __credits__ = 'Nobody'
     98     __version__ = '1.2.3.4'
     99 
    100 VERSION
    101     1.2.3.4
    102 
    103 AUTHOR
    104     Benjamin Peterson
    105 
    106 CREDITS
    107     Nobody
    108 """.strip()
    109 
    110 expected_text_data_docstrings = tuple('\n     |      ' + s if s else ''
    111                                       for s in expected_data_docstrings)
    112 
    113 expected_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
    120 ><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
    121     <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>
    134 </font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#C">C</a>
    135 </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>
    160 <dd><tt>%s</tt></dd>
    161 </dl>
    162 <dl><dt><strong>__weakref__</strong></dt>
    163 <dd><tt>%s</tt></dd>
    164 </dl>
    165 <hr>
    166 Data and other attributes defined here:<br>
    167 <dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
    168 
    169 </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>
    184 Data 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>
    191 </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>
    199 hunger<br>
    200 lack&nbsp;of&nbsp;Python<br>
    201 war</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>
    212 <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 
    229 expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;')
    230                                       for s in expected_data_docstrings)
    231 
    232 # output pattern for missing module
    233 missing_pattern = "no Python documentation found for '%s'"
    234 
    235 # output pattern for module with bad imports
    236 badimport_pattern = "problem in %s - <type 'exceptions.ImportError'>: No module named %s"
    237 
    238 def run_pydoc(module_name, *args, **env):
    239     """
    240     Runs pydoc on the specified module. Returns the stripped
    241     output of pydoc.
    242     """
    243     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()
    247 
    248 def get_pydoc_html(module):
    249     "Returns pydoc generated output as html"
    250     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
    256 
    257 def get_pydoc_link(module):
    258     "Returns a documentation web link of a module"
    259     dirname = os.path.dirname
    260     basedir = dirname(dirname(__file__))
    261     doc = pydoc.TextDoc()
    262     loc = doc.getdocloc(module, basedir=basedir)
    263     return loc
    264 
    265 def get_pydoc_text(module):
    266     "Returns pydoc generated output as text"
    267     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)
    273 
    274     # cleanup the extra text formatting that pydoc preforms
    275     patt = re.compile('\b.')
    276     output = patt.sub('', output)
    277     return output.strip(), loc
    278 
    279 def print_diffs(text1, text2):
    280     "Prints unified diffs for two texts"
    281     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)
    286 
    287 
    288 class 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 
    311 class PydocDocTest(unittest.TestCase):
    312 
    313     @requires_docstrings
    314     @unittest.skipIf(sys.flags.optimize >= 2,
    315                      "Docstrings are omitted with -O2 and above")
    316     def test_html_doc(self):
    317         result, doc_loc = get_pydoc_html(pydoc_mod)
    318         mod_file = inspect.getabsfile(pydoc_mod)
    319         if sys.platform == 'win32':
    320             import nturl2path
    321             mod_url = nturl2path.pathname2url(mod_file)
    322         else:
    323             mod_url = mod_file
    324         expected_html = expected_html_pattern % (
    325                         (mod_url, mod_file, doc_loc) +
    326                         expected_html_data_docstrings)
    327         if result != expected_html:
    328             print_diffs(expected_html, result)
    329             self.fail("outputs are not equal, see diff above")
    330 
    331     @requires_docstrings
    332     @unittest.skipIf(sys.flags.optimize >= 2,
    333                      "Docstrings are omitted with -O2 and above")
    334     def test_text_doc(self):
    335         result, doc_loc = get_pydoc_text(pydoc_mod)
    336         expected_text = expected_text_pattern % (
    337                         (inspect.getabsfile(pydoc_mod), doc_loc) +
    338                         expected_text_data_docstrings)
    339         if result != expected_text:
    340             print_diffs(expected_text, result)
    341             self.fail("outputs are not equal, see diff above")
    342 
    343     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 
    348     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 
    353     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 
    361     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 
    372     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 
    379     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 
    387     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 
    400     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 """
    406 my doc
    407 
    408 second line
    409 """
    410 foo = 1
    411 ''')
    412             py_compile.compile(init_path)
    413             synopsis = pydoc.synopsis(init_path, {})
    414             self.assertEqual(synopsis, 'my doc')
    415 
    416     @unittest.skipIf(sys.flags.optimize >= 2,
    417                      'Docstrings are omitted with -OO and above')
    418     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 
    430 
    431 class PydocImportTest(PydocBaseTest):
    432 
    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")
    466         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(), '')
    479 
    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
    487         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(), '')
    494 
    495 
    496 class TestDescriptions(unittest.TestCase):
    497 
    498     def test_module(self):
    499         # Check that pydocfodder module can be described
    500         from test import pydocfodder
    501         doc = pydoc.render_doc(pydocfodder)
    502         self.assertIn("pydocfodder", doc)
    503 
    504     def test_classic_class(self):
    505         class C: "Classic class"
    506         c = C()
    507         self.assertEqual(pydoc.describe(C), 'class C')
    508         self.assertEqual(pydoc.describe(c), 'instance of C')
    509         expected = 'instance of C in module %s' % __name__
    510         self.assertIn(expected, pydoc.render_doc(c))
    511 
    512     def test_class(self):
    513         class C(object): "New-style class"
    514         c = C()
    515 
    516         self.assertEqual(pydoc.describe(C), 'class C')
    517         self.assertEqual(pydoc.describe(c), 'C')
    518         expected = 'C in module %s object' % __name__
    519         self.assertIn(expected, pydoc.render_doc(c))
    520 
    521     def test_namedtuple_public_underscore(self):
    522         NT = namedtuple('NT', ['abc', 'def'], rename=True)
    523         with captured_stdout() as help_io:
    524             pydoc.help(NT)
    525         helptext = help_io.getvalue()
    526         self.assertIn('_1', helptext)
    527         self.assertIn('_replace', helptext)
    528         self.assertIn('_asdict', helptext)
    529 
    530 
    531 @unittest.skipUnless(test.test_support.have_unicode,
    532                      "test requires unicode support")
    533 class 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):
    575             filename = cmd.strip()[1:-1]
    576             self.assertEqual('"' + filename + '"', cmd.strip())
    577             output['content'] = open(filename).read()
    578         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 
    621 class TestHelper(unittest.TestCase):
    622     def test_keywords(self):
    623         self.assertEqual(sorted(pydoc.Helper.keywords),
    624                          sorted(keyword.kwlist))
    625 
    626     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:
    635                 self.fail('finding the doc of {!r} failed'.format(name))
    636 
    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 
    643 
    644 def test_main():
    645     try:
    646         test.test_support.run_unittest(PydocDocTest,
    647                                        PydocImportTest,
    648                                        TestDescriptions,
    649                                        TestUnicode,
    650                                        TestHelper)
    651     finally:
    652         reap_children()
    653 
    654 if __name__ == "__main__":
    655     test_main()
    656