blob: 50ed4d51ec0e295c91097760e5dcae273b417301 [file] [log] [blame]
Georg Brandlb533e262008-05-25 18:19:30 +00001import os
Nick Coghlan7bb30b72010-12-03 09:29:11 +00002import sys
Éric Araujoe64e51b2011-07-29 17:03:55 +02003import builtins
Antoine Pitrou916fc7b2013-05-19 15:44:54 +02004import contextlib
Benjamin Peterson54237f92015-02-16 19:45:01 -05005import importlib.util
Georg Brandlb533e262008-05-25 18:19:30 +00006import inspect
Nick Coghlan7bb30b72010-12-03 09:29:11 +00007import pydoc
Benjamin Peterson54237f92015-02-16 19:45:01 -05008import py_compile
Ezio Melottib185a042011-04-28 07:42:55 +03009import keyword
Larry Hastings24a882b2014-02-20 23:34:46 -080010import _pickle
Antoine Pitrou916fc7b2013-05-19 15:44:54 +020011import pkgutil
Nick Coghlan7bb30b72010-12-03 09:29:11 +000012import re
Benjamin Peterson54237f92015-02-16 19:45:01 -050013import stat
Nick Coghlan7bb30b72010-12-03 09:29:11 +000014import string
Georg Brandlb533e262008-05-25 18:19:30 +000015import test.support
Nick Coghlan7bb30b72010-12-03 09:29:11 +000016import time
Ethan Furmanb0c84cd2013-10-20 22:37:39 -070017import types
Nick Coghlan7bb30b72010-12-03 09:29:11 +000018import unittest
Zachary Wareeb432142014-07-10 11:18:00 -050019import urllib.parse
Brian Curtin49c284c2010-03-31 03:19:28 +000020import xml.etree
Georg Brandld80d5f42010-12-03 07:47:22 +000021import textwrap
22from io import StringIO
Raymond Hettinger1103d052011-03-25 14:15:24 -070023from collections import namedtuple
Antoine Pitrouf7f54752011-07-15 22:42:12 +020024from test.script_helper import assert_python_ok
Antoine Pitroua6e81a22011-07-15 22:32:25 +020025from test.support import (
Ned Deily92a81a12011-10-06 14:19:03 -070026 TESTFN, rmtree,
Antoine Pitrou916fc7b2013-05-19 15:44:54 +020027 reap_children, reap_threads, captured_output, captured_stdout,
Stefan Krah5de32782014-01-18 23:18:39 +010028 captured_stderr, unlink, requires_docstrings
Antoine Pitroua6e81a22011-07-15 22:32:25 +020029)
Georg Brandlb533e262008-05-25 18:19:30 +000030from test import pydoc_mod
31
Victor Stinner62a68f22011-05-20 02:29:13 +020032try:
33 import threading
34except ImportError:
35 threading = None
36
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +020037class nonascii:
38 'Це не латиниця'
39 pass
40
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020041if test.support.HAVE_DOCSTRINGS:
42 expected_data_docstrings = (
43 'dictionary for instance variables (if defined)',
44 'list of weak references to the object (if defined)',
45 ) * 2
46else:
47 expected_data_docstrings = ('', '', '', '')
48
Barry Warsaw28a691b2010-04-17 00:19:56 +000049expected_text_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000050NAME
51 test.pydoc_mod - This is a test module for test_pydoc
Georg Brandlb533e262008-05-25 18:19:30 +000052%s
53CLASSES
54 builtins.object
55 A
56 B
Benjamin Petersoned1160b2014-06-07 16:44:00 -070057 C
Georg Brandlb533e262008-05-25 18:19:30 +000058\x20\x20\x20\x20
59 class A(builtins.object)
60 | Hello and goodbye
61 |\x20\x20
62 | Methods defined here:
63 |\x20\x20
64 | __init__()
65 | Wow, I have no function!
66 |\x20\x20
67 | ----------------------------------------------------------------------
68 | Data descriptors defined here:
69 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020070 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000071 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020072 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000073\x20\x20\x20\x20
74 class B(builtins.object)
75 | Data descriptors defined here:
76 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020077 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000078 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020079 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000080 |\x20\x20
81 | ----------------------------------------------------------------------
82 | Data and other attributes defined here:
83 |\x20\x20
84 | NO_MEANING = 'eggs'
Benjamin Petersoned1160b2014-06-07 16:44:00 -070085\x20\x20\x20\x20
86 class C(builtins.object)
87 | Methods defined here:
88 |\x20\x20
89 | get_answer(self)
90 | Return say_no()
91 |\x20\x20
92 | is_it_true(self)
93 | Return self.get_answer()
94 |\x20\x20
95 | say_no(self)
96 |\x20\x20
97 | ----------------------------------------------------------------------
98 | Data descriptors defined here:
99 |\x20\x20
100 | __dict__
101 | dictionary for instance variables (if defined)
102 |\x20\x20
103 | __weakref__
104 | list of weak references to the object (if defined)
Georg Brandlb533e262008-05-25 18:19:30 +0000105
106FUNCTIONS
107 doc_func()
108 This function solves all of the world's problems:
109 hunger
110 lack of Python
111 war
112\x20\x20\x20\x20
113 nodoc_func()
114
115DATA
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000116 __xyz__ = 'X, Y and Z'
Georg Brandlb533e262008-05-25 18:19:30 +0000117
118VERSION
119 1.2.3.4
120
121AUTHOR
122 Benjamin Peterson
123
124CREDITS
125 Nobody
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000126
127FILE
128 %s
Georg Brandlb533e262008-05-25 18:19:30 +0000129""".strip()
130
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200131expected_text_data_docstrings = tuple('\n | ' + s if s else ''
132 for s in expected_data_docstrings)
133
Barry Warsaw28a691b2010-04-17 00:19:56 +0000134expected_html_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +0000135<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
136<tr bgcolor="#7799ee">
137<td valign=bottom>&nbsp;<br>
138<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
139><td align=right valign=bottom
140><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
141 <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
142<p>
143<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
144<tr bgcolor="#ee77aa">
145<td colspan=3 valign=bottom>&nbsp;<br>
146<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
147\x20\x20\x20\x20
148<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
149<td width="100%%"><dl>
150<dt><font face="helvetica, arial"><a href="builtins.html#object">builtins.object</a>
151</font></dt><dd>
152<dl>
153<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
154</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700155</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#C">C</a>
Georg Brandlb533e262008-05-25 18:19:30 +0000156</font></dt></dl>
157</dd>
158</dl>
159 <p>
160<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
161<tr bgcolor="#ffc8d8">
162<td colspan=3 valign=bottom>&nbsp;<br>
163<font color="#000000" face="helvetica, arial"><a name="A">class <strong>A</strong></a>(<a href="builtins.html#object">builtins.object</a>)</font></td></tr>
164\x20\x20\x20\x20
165<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
166<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
167<tr><td>&nbsp;</td>
168<td width="100%%">Methods defined here:<br>
169<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>
170
171<hr>
172Data descriptors defined here:<br>
173<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200174<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000175</dl>
176<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200177<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000178</dl>
179</td></tr></table> <p>
180<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
181<tr bgcolor="#ffc8d8">
182<td colspan=3 valign=bottom>&nbsp;<br>
183<font color="#000000" face="helvetica, arial"><a name="B">class <strong>B</strong></a>(<a href="builtins.html#object">builtins.object</a>)</font></td></tr>
184\x20\x20\x20\x20
185<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
186<td width="100%%">Data descriptors defined here:<br>
187<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200188<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000189</dl>
190<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200191<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000192</dl>
193<hr>
194Data and other attributes defined here:<br>
195<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
196
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700197</td></tr></table> <p>
198<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
199<tr bgcolor="#ffc8d8">
200<td colspan=3 valign=bottom>&nbsp;<br>
201<font color="#000000" face="helvetica, arial"><a name="C">class <strong>C</strong></a>(<a href="builtins.html#object">builtins.object</a>)</font></td></tr>
202\x20\x20\x20\x20
203<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
204<td width="100%%">Methods defined here:<br>
205<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>
206
207<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>
208
209<dl><dt><a name="C-say_no"><strong>say_no</strong></a>(self)</dt></dl>
210
211<hr>
212Data descriptors defined here:<br>
213<dl><dt><strong>__dict__</strong></dt>
214<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
215</dl>
216<dl><dt><strong>__weakref__</strong></dt>
217<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
218</dl>
Georg Brandlb533e262008-05-25 18:19:30 +0000219</td></tr></table></td></tr></table><p>
220<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
221<tr bgcolor="#eeaa77">
222<td colspan=3 valign=bottom>&nbsp;<br>
223<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
224\x20\x20\x20\x20
225<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
226<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>
227hunger<br>
228lack&nbsp;of&nbsp;Python<br>
229war</tt></dd></dl>
230 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
231</td></tr></table><p>
232<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
233<tr bgcolor="#55aa55">
234<td colspan=3 valign=bottom>&nbsp;<br>
235<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
236\x20\x20\x20\x20
237<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000238<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p>
Georg Brandlb533e262008-05-25 18:19:30 +0000239<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
240<tr bgcolor="#7799ee">
241<td colspan=3 valign=bottom>&nbsp;<br>
242<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
243\x20\x20\x20\x20
244<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
245<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
246<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
247<tr bgcolor="#7799ee">
248<td colspan=3 valign=bottom>&nbsp;<br>
249<font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
250\x20\x20\x20\x20
251<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
252<td width="100%%">Nobody</td></tr></table>
Barry Warsaw28a691b2010-04-17 00:19:56 +0000253""".strip() # ' <- emacs turd
Georg Brandlb533e262008-05-25 18:19:30 +0000254
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200255expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;')
256 for s in expected_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000257
258# output pattern for missing module
Serhiy Storchaka1c205512015-03-01 00:42:54 +0200259missing_pattern = '''\
260No Python documentation found for %r.
261Use help() to get the interactive help utility.
262Use help(str) for help on the str class.'''.replace('\n', os.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000263
Benjamin Peterson0289b152009-06-28 17:22:03 +0000264# output pattern for module with bad imports
Brett Cannon679ecb52013-07-04 17:51:50 -0400265badimport_pattern = "problem in %s - ImportError: No module named %r"
Benjamin Peterson0289b152009-06-28 17:22:03 +0000266
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700267expected_dynamicattribute_pattern = """
268Help on class DA in module %s:
269
270class DA(builtins.object)
271 | Data descriptors defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200272 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700273 | __dict__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200274 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700275 | __weakref__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200276 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700277 | ham
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200278 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700279 | ----------------------------------------------------------------------
280 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200281 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700282 | ham = 'spam'
283""".strip()
284
285expected_virtualattribute_pattern1 = """
286Help on class Class in module %s:
287
288class Class(builtins.object)
289 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200290 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700291 | LIFE = 42
292""".strip()
293
294expected_virtualattribute_pattern2 = """
295Help on class Class1 in module %s:
296
297class Class1(builtins.object)
298 | Data and other attributes inherited from Meta1:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200299 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700300 | one = 1
301""".strip()
302
303expected_virtualattribute_pattern3 = """
304Help on class Class2 in module %s:
305
306class Class2(Class1)
307 | Method resolution order:
308 | Class2
309 | Class1
310 | builtins.object
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200311 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700312 | Data and other attributes inherited from Meta1:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200313 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700314 | one = 1
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200315 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700316 | ----------------------------------------------------------------------
317 | Data and other attributes inherited from Meta3:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200318 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700319 | three = 3
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200320 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700321 | ----------------------------------------------------------------------
322 | Data and other attributes inherited from Meta2:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200323 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700324 | two = 2
325""".strip()
326
327expected_missingattribute_pattern = """
328Help on class C in module %s:
329
330class C(builtins.object)
331 | Data and other attributes defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200332 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700333 | here = 'present!'
334""".strip()
335
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200336def run_pydoc(module_name, *args, **env):
Georg Brandlb533e262008-05-25 18:19:30 +0000337 """
338 Runs pydoc on the specified module. Returns the stripped
339 output of pydoc.
340 """
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200341 args = args + (module_name,)
Ned Deily92a81a12011-10-06 14:19:03 -0700342 # do not write bytecode files to avoid caching errors
343 rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200344 return out.strip()
Georg Brandlb533e262008-05-25 18:19:30 +0000345
346def get_pydoc_html(module):
347 "Returns pydoc generated output as html"
348 doc = pydoc.HTMLDoc()
349 output = doc.docmodule(module)
350 loc = doc.getdocloc(pydoc_mod) or ""
351 if loc:
352 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
353 return output.strip(), loc
354
355def get_pydoc_text(module):
356 "Returns pydoc generated output as text"
357 doc = pydoc.TextDoc()
358 loc = doc.getdocloc(pydoc_mod) or ""
359 if loc:
360 loc = "\nMODULE DOCS\n " + loc + "\n"
361
362 output = doc.docmodule(module)
363
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000364 # clean up the extra text formatting that pydoc performs
Georg Brandlb533e262008-05-25 18:19:30 +0000365 patt = re.compile('\b.')
366 output = patt.sub('', output)
367 return output.strip(), loc
368
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000369def get_html_title(text):
Nick Coghlanecace282010-12-03 16:08:46 +0000370 # Bit of hack, but good enough for test purposes
371 header, _, _ = text.partition("</head>")
372 _, _, title = header.partition("<title>")
373 title, _, _ = title.partition("</title>")
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000374 return title
375
Georg Brandlb533e262008-05-25 18:19:30 +0000376
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200377class PydocBaseTest(unittest.TestCase):
378
379 def _restricted_walk_packages(self, walk_packages, path=None):
380 """
381 A version of pkgutil.walk_packages() that will restrict itself to
382 a given path.
383 """
384 default_path = path or [os.path.dirname(__file__)]
385 def wrapper(path=None, prefix='', onerror=None):
386 return walk_packages(path or default_path, prefix, onerror)
387 return wrapper
388
389 @contextlib.contextmanager
390 def restrict_walk_packages(self, path=None):
391 walk_packages = pkgutil.walk_packages
392 pkgutil.walk_packages = self._restricted_walk_packages(walk_packages,
393 path)
394 try:
395 yield
396 finally:
397 pkgutil.walk_packages = walk_packages
398
399
Georg Brandld2f38572011-01-30 08:37:19 +0000400class PydocDocTest(unittest.TestCase):
Georg Brandlb533e262008-05-25 18:19:30 +0000401
R. David Murray378c0cf2010-02-24 01:46:21 +0000402 @unittest.skipIf(sys.flags.optimize >= 2,
403 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000404 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
405 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100406 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000407 def test_html_doc(self):
408 result, doc_loc = get_pydoc_html(pydoc_mod)
409 mod_file = inspect.getabsfile(pydoc_mod)
Zachary Wareeb432142014-07-10 11:18:00 -0500410 mod_url = urllib.parse.quote(mod_file)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200411 expected_html = expected_html_pattern % (
412 (mod_url, mod_file, doc_loc) +
413 expected_html_data_docstrings)
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700414 self.assertEqual(result, expected_html)
Georg Brandlb533e262008-05-25 18:19:30 +0000415
R. David Murray378c0cf2010-02-24 01:46:21 +0000416 @unittest.skipIf(sys.flags.optimize >= 2,
417 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000418 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
419 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100420 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000421 def test_text_doc(self):
422 result, doc_loc = get_pydoc_text(pydoc_mod)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200423 expected_text = expected_text_pattern % (
424 (doc_loc,) +
425 expected_text_data_docstrings +
426 (inspect.getabsfile(pydoc_mod),))
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700427 self.assertEqual(expected_text, result)
Georg Brandlb533e262008-05-25 18:19:30 +0000428
Serhiy Storchaka056eb022014-02-19 23:05:12 +0200429 def test_text_enum_member_with_value_zero(self):
430 # Test issue #20654 to ensure enum member with value 0 can be
431 # displayed. It used to throw KeyError: 'zero'.
432 import enum
433 class BinaryInteger(enum.IntEnum):
434 zero = 0
435 one = 1
436 doc = pydoc.render_doc(BinaryInteger)
437 self.assertIn('<BinaryInteger.zero: 0>', doc)
438
Brian Curtin49c284c2010-03-31 03:19:28 +0000439 def test_issue8225(self):
440 # Test issue8225 to ensure no doc link appears for xml.etree
441 result, doc_loc = get_pydoc_text(xml.etree)
442 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
443
Benjamin Peterson159824e2014-06-07 20:14:26 -0700444 def test_getpager_with_stdin_none(self):
445 previous_stdin = sys.stdin
446 try:
447 sys.stdin = None
448 pydoc.getpager() # Shouldn't fail.
449 finally:
450 sys.stdin = previous_stdin
451
R David Murrayc43125a2012-04-23 13:23:57 -0400452 def test_non_str_name(self):
453 # issue14638
454 # Treat illegal (non-str) name like no name
455 class A:
456 __name__ = 42
457 class B:
458 pass
459 adoc = pydoc.render_doc(A())
460 bdoc = pydoc.render_doc(B())
461 self.assertEqual(adoc.replace("A", "B"), bdoc)
462
Georg Brandlb533e262008-05-25 18:19:30 +0000463 def test_not_here(self):
464 missing_module = "test.i_am_not_here"
465 result = str(run_pydoc(missing_module), 'ascii')
466 expected = missing_pattern % missing_module
467 self.assertEqual(expected, result,
468 "documentation for missing module found")
469
Serhiy Storchaka4c094e52015-03-01 15:31:36 +0200470 @unittest.skipIf(sys.flags.optimize >= 2,
471 'Docstrings are omitted with -OO and above')
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +0200472 def test_not_ascii(self):
473 result = run_pydoc('test.test_pydoc.nonascii', PYTHONIOENCODING='ascii')
474 encoded = nonascii.__doc__.encode('ascii', 'backslashreplace')
475 self.assertIn(encoded, result)
476
R. David Murray1f1b9d32009-05-27 20:56:59 +0000477 def test_input_strip(self):
478 missing_module = " test.i_am_not_here "
479 result = str(run_pydoc(missing_module), 'ascii')
480 expected = missing_pattern % missing_module.strip()
481 self.assertEqual(expected, result)
482
Ezio Melotti412c95a2010-02-16 23:31:04 +0000483 def test_stripid(self):
484 # test with strings, other implementations might have different repr()
485 stripid = pydoc.stripid
486 # strip the id
487 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
488 '<function stripid>')
489 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
490 '<function stripid>')
491 # nothing to strip, return the same text
492 self.assertEqual(stripid('42'), '42')
493 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
494 "<type 'exceptions.Exception'>")
495
Georg Brandld80d5f42010-12-03 07:47:22 +0000496 @unittest.skipIf(sys.flags.optimize >= 2,
497 'Docstrings are omitted with -O2 and above')
Brett Cannon7a540732011-02-22 03:04:06 +0000498 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
499 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100500 @requires_docstrings
Georg Brandld80d5f42010-12-03 07:47:22 +0000501 def test_help_output_redirect(self):
502 # issue 940286, if output is set in Helper, then all output from
503 # Helper.help should be redirected
504 old_pattern = expected_text_pattern
505 getpager_old = pydoc.getpager
506 getpager_new = lambda: (lambda x: x)
507 self.maxDiff = None
508
509 buf = StringIO()
510 helper = pydoc.Helper(output=buf)
511 unused, doc_loc = get_pydoc_text(pydoc_mod)
512 module = "test.pydoc_mod"
513 help_header = """
514 Help on module test.pydoc_mod in test:
515
516 """.lstrip()
517 help_header = textwrap.dedent(help_header)
518 expected_help_pattern = help_header + expected_text_pattern
519
520 pydoc.getpager = getpager_new
521 try:
522 with captured_output('stdout') as output, \
523 captured_output('stderr') as err:
524 helper.help(module)
525 result = buf.getvalue().strip()
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200526 expected_text = expected_help_pattern % (
527 (doc_loc,) +
528 expected_text_data_docstrings +
529 (inspect.getabsfile(pydoc_mod),))
Georg Brandld80d5f42010-12-03 07:47:22 +0000530 self.assertEqual('', output.getvalue())
531 self.assertEqual('', err.getvalue())
532 self.assertEqual(expected_text, result)
533 finally:
534 pydoc.getpager = getpager_old
535
Raymond Hettinger1103d052011-03-25 14:15:24 -0700536 def test_namedtuple_public_underscore(self):
537 NT = namedtuple('NT', ['abc', 'def'], rename=True)
538 with captured_stdout() as help_io:
Terry Jan Reedy5c811642013-11-04 21:43:26 -0500539 pydoc.help(NT)
Raymond Hettinger1103d052011-03-25 14:15:24 -0700540 helptext = help_io.getvalue()
541 self.assertIn('_1', helptext)
542 self.assertIn('_replace', helptext)
543 self.assertIn('_asdict', helptext)
544
Victor Stinnere6c910e2011-06-30 15:55:43 +0200545 def test_synopsis(self):
546 self.addCleanup(unlink, TESTFN)
547 for encoding in ('ISO-8859-1', 'UTF-8'):
548 with open(TESTFN, 'w', encoding=encoding) as script:
549 if encoding != 'UTF-8':
550 print('#coding: {}'.format(encoding), file=script)
551 print('"""line 1: h\xe9', file=script)
552 print('line 2: hi"""', file=script)
553 synopsis = pydoc.synopsis(TESTFN, {})
554 self.assertEqual(synopsis, 'line 1: h\xe9')
555
Serhiy Storchaka4c094e52015-03-01 15:31:36 +0200556 @unittest.skipIf(sys.flags.optimize >= 2,
557 'Docstrings are omitted with -OO and above')
Eric Snowaed5b222014-01-04 20:38:11 -0700558 def test_synopsis_sourceless(self):
559 expected = os.__doc__.splitlines()[0]
560 filename = os.__cached__
561 synopsis = pydoc.synopsis(filename)
562
563 self.assertEqual(synopsis, expected)
564
Benjamin Peterson54237f92015-02-16 19:45:01 -0500565 def test_synopsis_sourceless_empty_doc(self):
566 with test.support.temp_cwd() as test_dir:
567 init_path = os.path.join(test_dir, 'foomod42.py')
568 cached_path = importlib.util.cache_from_source(init_path)
569 with open(init_path, 'w') as fobj:
570 fobj.write("foo = 1")
571 py_compile.compile(init_path)
572 synopsis = pydoc.synopsis(init_path, {})
573 self.assertIsNone(synopsis)
574 synopsis_cached = pydoc.synopsis(cached_path, {})
575 self.assertIsNone(synopsis_cached)
576
R David Murray455f2962013-03-19 00:00:33 -0400577 def test_splitdoc_with_description(self):
578 example_string = "I Am A Doc\n\n\nHere is my description"
579 self.assertEqual(pydoc.splitdoc(example_string),
580 ('I Am A Doc', '\nHere is my description'))
581
582 def test_is_object_or_method(self):
583 doc = pydoc.Doc()
584 # Bound Method
585 self.assertTrue(pydoc._is_some_method(doc.fail))
586 # Method Descriptor
587 self.assertTrue(pydoc._is_some_method(int.__add__))
588 # String
589 self.assertFalse(pydoc._is_some_method("I am not a method"))
590
591 def test_is_package_when_not_package(self):
592 with test.support.temp_cwd() as test_dir:
593 self.assertFalse(pydoc.ispackage(test_dir))
594
595 def test_is_package_when_is_package(self):
596 with test.support.temp_cwd() as test_dir:
597 init_path = os.path.join(test_dir, '__init__.py')
598 open(init_path, 'w').close()
599 self.assertTrue(pydoc.ispackage(test_dir))
600 os.remove(init_path)
601
R David Murrayac0cea52013-03-19 02:47:44 -0400602 def test_allmethods(self):
603 # issue 17476: allmethods was no longer returning unbound methods.
604 # This test is a bit fragile in the face of changes to object and type,
605 # but I can't think of a better way to do it without duplicating the
606 # logic of the function under test.
607
608 class TestClass(object):
609 def method_returning_true(self):
610 return True
611
612 # What we expect to get back: everything on object...
613 expected = dict(vars(object))
614 # ...plus our unbound method...
615 expected['method_returning_true'] = TestClass.method_returning_true
616 # ...but not the non-methods on object.
617 del expected['__doc__']
618 del expected['__class__']
619 # inspect resolves descriptors on type into methods, but vars doesn't,
620 # so we need to update __subclasshook__.
621 expected['__subclasshook__'] = TestClass.__subclasshook__
622
623 methods = pydoc.allmethods(TestClass)
624 self.assertDictEqual(methods, expected)
625
Georg Brandlb533e262008-05-25 18:19:30 +0000626
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200627class PydocImportTest(PydocBaseTest):
Ned Deily92a81a12011-10-06 14:19:03 -0700628
629 def setUp(self):
630 self.test_dir = os.mkdir(TESTFN)
631 self.addCleanup(rmtree, TESTFN)
Benjamin Peterson54237f92015-02-16 19:45:01 -0500632 importlib.invalidate_caches()
Ned Deily92a81a12011-10-06 14:19:03 -0700633
634 def test_badimport(self):
635 # This tests the fix for issue 5230, where if pydoc found the module
636 # but the module had an internal import error pydoc would report no doc
637 # found.
638 modname = 'testmod_xyzzy'
639 testpairs = (
640 ('i_am_not_here', 'i_am_not_here'),
Brett Cannonfd074152012-04-14 14:10:13 -0400641 ('test.i_am_not_here_either', 'test.i_am_not_here_either'),
642 ('test.i_am_not_here.neither_am_i', 'test.i_am_not_here'),
643 ('i_am_not_here.{}'.format(modname), 'i_am_not_here'),
644 ('test.{}'.format(modname), 'test.{}'.format(modname)),
Ned Deily92a81a12011-10-06 14:19:03 -0700645 )
646
647 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
648 for importstring, expectedinmsg in testpairs:
649 with open(sourcefn, 'w') as f:
650 f.write("import {}\n".format(importstring))
651 result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii")
652 expected = badimport_pattern % (modname, expectedinmsg)
653 self.assertEqual(expected, result)
654
655 def test_apropos_with_bad_package(self):
656 # Issue 7425 - pydoc -k failed when bad package on path
657 pkgdir = os.path.join(TESTFN, "syntaxerr")
658 os.mkdir(pkgdir)
659 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
660 with open(badsyntax, 'w') as f:
661 f.write("invalid python syntax = $1\n")
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200662 with self.restrict_walk_packages(path=[TESTFN]):
663 with captured_stdout() as out:
664 with captured_stderr() as err:
665 pydoc.apropos('xyzzy')
666 # No result, no error
667 self.assertEqual(out.getvalue(), '')
668 self.assertEqual(err.getvalue(), '')
669 # The package name is still matched
670 with captured_stdout() as out:
671 with captured_stderr() as err:
672 pydoc.apropos('syntaxerr')
673 self.assertEqual(out.getvalue().strip(), 'syntaxerr')
674 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700675
676 def test_apropos_with_unreadable_dir(self):
677 # Issue 7367 - pydoc -k failed when unreadable dir on path
678 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
679 os.mkdir(self.unreadable_dir, 0)
680 self.addCleanup(os.rmdir, self.unreadable_dir)
681 # Note, on Windows the directory appears to be still
682 # readable so this is not really testing the issue there
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200683 with self.restrict_walk_packages(path=[TESTFN]):
684 with captured_stdout() as out:
685 with captured_stderr() as err:
686 pydoc.apropos('SOMEKEY')
687 # No result, no error
688 self.assertEqual(out.getvalue(), '')
689 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700690
Benjamin Peterson54237f92015-02-16 19:45:01 -0500691 def test_apropos_empty_doc(self):
692 pkgdir = os.path.join(TESTFN, 'walkpkg')
693 os.mkdir(pkgdir)
694 self.addCleanup(rmtree, pkgdir)
695 init_path = os.path.join(pkgdir, '__init__.py')
696 with open(init_path, 'w') as fobj:
697 fobj.write("foo = 1")
698 current_mode = stat.S_IMODE(os.stat(pkgdir).st_mode)
699 try:
700 os.chmod(pkgdir, current_mode & ~stat.S_IEXEC)
701 with self.restrict_walk_packages(path=[TESTFN]), captured_stdout() as stdout:
702 pydoc.apropos('')
703 self.assertIn('walkpkg', stdout.getvalue())
704 finally:
705 os.chmod(pkgdir, current_mode)
706
Eric Snowa46ef702014-02-22 13:57:08 -0700707 @unittest.skip('causes undesireable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700708 def test_modules(self):
709 # See Helper.listmodules().
710 num_header_lines = 2
711 num_module_lines_min = 5 # Playing it safe.
712 num_footer_lines = 3
713 expected = num_header_lines + num_module_lines_min + num_footer_lines
714
715 output = StringIO()
716 helper = pydoc.Helper(output=output)
717 helper('modules')
718 result = output.getvalue().strip()
719 num_lines = len(result.splitlines())
720
721 self.assertGreaterEqual(num_lines, expected)
722
Eric Snowa46ef702014-02-22 13:57:08 -0700723 @unittest.skip('causes undesireable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700724 def test_modules_search(self):
725 # See Helper.listmodules().
726 expected = 'pydoc - '
727
728 output = StringIO()
729 helper = pydoc.Helper(output=output)
730 with captured_stdout() as help_io:
731 helper('modules pydoc')
732 result = help_io.getvalue()
733
734 self.assertIn(expected, result)
735
Eric Snowa46ef702014-02-22 13:57:08 -0700736 @unittest.skip('some buildbots are not cooperating (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700737 def test_modules_search_builtin(self):
Eric Snow5ea97502014-01-04 23:04:27 -0700738 expected = 'gc - '
Eric Snowaed5b222014-01-04 20:38:11 -0700739
740 output = StringIO()
741 helper = pydoc.Helper(output=output)
742 with captured_stdout() as help_io:
Eric Snow5ea97502014-01-04 23:04:27 -0700743 helper('modules garbage')
Eric Snowaed5b222014-01-04 20:38:11 -0700744 result = help_io.getvalue()
745
746 self.assertTrue(result.startswith(expected))
747
748 def test_importfile(self):
749 loaded_pydoc = pydoc.importfile(pydoc.__file__)
750
Eric Snow3a62d142014-01-06 20:42:59 -0700751 self.assertIsNot(loaded_pydoc, pydoc)
Eric Snowaed5b222014-01-04 20:38:11 -0700752 self.assertEqual(loaded_pydoc.__name__, 'pydoc')
753 self.assertEqual(loaded_pydoc.__file__, pydoc.__file__)
Eric Snow3a62d142014-01-06 20:42:59 -0700754 self.assertEqual(loaded_pydoc.__spec__, pydoc.__spec__)
Eric Snowaed5b222014-01-04 20:38:11 -0700755
Ned Deily92a81a12011-10-06 14:19:03 -0700756
Georg Brandlb533e262008-05-25 18:19:30 +0000757class TestDescriptions(unittest.TestCase):
758
759 def test_module(self):
760 # Check that pydocfodder module can be described
761 from test import pydocfodder
762 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000763 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000764
Georg Brandlb533e262008-05-25 18:19:30 +0000765 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000766 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +0000767 c = C()
768
769 self.assertEqual(pydoc.describe(C), 'class C')
770 self.assertEqual(pydoc.describe(c), 'C')
771 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000772 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000773
Éric Araujoe64e51b2011-07-29 17:03:55 +0200774 def test_builtin(self):
775 for name in ('str', 'str.translate', 'builtins.str',
776 'builtins.str.translate'):
777 # test low-level function
778 self.assertIsNotNone(pydoc.locate(name))
779 # test high-level function
780 try:
781 pydoc.render_doc(name)
782 except ImportError:
Terry Jan Reedyfe928de2014-06-20 14:59:11 -0400783 self.fail('finding the doc of {!r} failed'.format(name))
Éric Araujoe64e51b2011-07-29 17:03:55 +0200784
785 for name in ('notbuiltins', 'strrr', 'strr.translate',
786 'str.trrrranslate', 'builtins.strrr',
787 'builtins.str.trrranslate'):
788 self.assertIsNone(pydoc.locate(name))
789 self.assertRaises(ImportError, pydoc.render_doc, name)
790
Larry Hastings24a882b2014-02-20 23:34:46 -0800791 @staticmethod
792 def _get_summary_line(o):
793 text = pydoc.plain(pydoc.render_doc(o))
794 lines = text.split('\n')
795 assert len(lines) >= 2
796 return lines[2]
797
798 # these should include "self"
799 def test_unbound_python_method(self):
800 self.assertEqual(self._get_summary_line(textwrap.TextWrapper.wrap),
801 "wrap(self, text)")
802
Stefan Krah5de32782014-01-18 23:18:39 +0100803 @requires_docstrings
Larry Hastings24a882b2014-02-20 23:34:46 -0800804 def test_unbound_builtin_method(self):
805 self.assertEqual(self._get_summary_line(_pickle.Pickler.dump),
806 "dump(self, obj, /)")
807
808 # these no longer include "self"
809 def test_bound_python_method(self):
810 t = textwrap.TextWrapper()
811 self.assertEqual(self._get_summary_line(t.wrap),
812 "wrap(text) method of textwrap.TextWrapper instance")
813
814 @requires_docstrings
815 def test_bound_builtin_method(self):
816 s = StringIO()
817 p = _pickle.Pickler(s)
818 self.assertEqual(self._get_summary_line(p.dump),
819 "dump(obj, /) method of _pickle.Pickler instance")
820
821 # this should *never* include self!
822 @requires_docstrings
823 def test_module_level_callable(self):
824 self.assertEqual(self._get_summary_line(os.stat),
825 "stat(path, *, dir_fd=None, follow_symlinks=True)")
Larry Hastings1abd7082014-01-16 14:15:03 -0800826
Georg Brandlb533e262008-05-25 18:19:30 +0000827
Victor Stinner62a68f22011-05-20 02:29:13 +0200828@unittest.skipUnless(threading, 'Threading required for this test.')
Georg Brandld2f38572011-01-30 08:37:19 +0000829class PydocServerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000830 """Tests for pydoc._start_server"""
831
832 def test_server(self):
833
834 # Minimal test that starts the server, then stops it.
835 def my_url_handler(url, content_type):
836 text = 'the URL sent was: (%s, %s)' % (url, content_type)
837 return text
838
839 serverthread = pydoc._start_server(my_url_handler, port=0)
Senthil Kumaran2a42a0b2014-09-17 13:17:58 +0800840 self.assertIn('localhost', serverthread.docserver.address)
841
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000842 starttime = time.time()
843 timeout = 1 #seconds
844
845 while serverthread.serving:
846 time.sleep(.01)
847 if serverthread.serving and time.time() - starttime > timeout:
848 serverthread.stop()
849 break
850
851 self.assertEqual(serverthread.error, None)
852
853
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200854class PydocUrlHandlerTest(PydocBaseTest):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000855 """Tests for pydoc._url_handler"""
856
857 def test_content_type_err(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000858 f = pydoc._url_handler
Georg Brandld2f38572011-01-30 08:37:19 +0000859 self.assertRaises(TypeError, f, 'A', '')
860 self.assertRaises(TypeError, f, 'B', 'foobar')
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000861
862 def test_url_requests(self):
863 # Test for the correct title in the html pages returned.
864 # This tests the different parts of the URL handler without
865 # getting too picky about the exact html.
866 requests = [
Georg Brandld2f38572011-01-30 08:37:19 +0000867 ("", "Pydoc: Index of Modules"),
868 ("get?key=", "Pydoc: Index of Modules"),
869 ("index", "Pydoc: Index of Modules"),
870 ("topics", "Pydoc: Topics"),
871 ("keywords", "Pydoc: Keywords"),
872 ("pydoc", "Pydoc: module pydoc"),
873 ("get?key=pydoc", "Pydoc: module pydoc"),
874 ("search?key=pydoc", "Pydoc: Search Results"),
875 ("topic?key=def", "Pydoc: KEYWORD def"),
876 ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
877 ("foobar", "Pydoc: Error - foobar"),
878 ("getfile?key=foobar", "Pydoc: Error - getfile?key=foobar"),
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000879 ]
880
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200881 with self.restrict_walk_packages():
882 for url, title in requests:
883 text = pydoc._url_handler(url, "text/html")
884 result = get_html_title(text)
885 self.assertEqual(result, title, text)
886
887 path = string.__file__
888 title = "Pydoc: getfile " + path
889 url = "getfile?key=" + path
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000890 text = pydoc._url_handler(url, "text/html")
891 result = get_html_title(text)
892 self.assertEqual(result, title)
893
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000894
Ezio Melottib185a042011-04-28 07:42:55 +0300895class TestHelper(unittest.TestCase):
896 def test_keywords(self):
897 self.assertEqual(sorted(pydoc.Helper.keywords),
898 sorted(keyword.kwlist))
899
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700900class PydocWithMetaClasses(unittest.TestCase):
Ethan Furman3f2f1922013-10-22 07:30:24 -0700901 @unittest.skipIf(sys.flags.optimize >= 2,
902 "Docstrings are omitted with -O2 and above")
903 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
904 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700905 def test_DynamicClassAttribute(self):
906 class Meta(type):
907 def __getattr__(self, name):
908 if name == 'ham':
909 return 'spam'
910 return super().__getattr__(name)
911 class DA(metaclass=Meta):
912 @types.DynamicClassAttribute
913 def ham(self):
914 return 'eggs'
Ethan Furman3f2f1922013-10-22 07:30:24 -0700915 expected_text_data_docstrings = tuple('\n | ' + s if s else ''
916 for s in expected_data_docstrings)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700917 output = StringIO()
918 helper = pydoc.Helper(output=output)
919 helper(DA)
Ethan Furman3f2f1922013-10-22 07:30:24 -0700920 expected_text = expected_dynamicattribute_pattern % (
921 (__name__,) + expected_text_data_docstrings[:2])
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700922 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700923 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700924
Ethan Furman3f2f1922013-10-22 07:30:24 -0700925 @unittest.skipIf(sys.flags.optimize >= 2,
926 "Docstrings are omitted with -O2 and above")
927 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
928 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700929 def test_virtualClassAttributeWithOneMeta(self):
930 class Meta(type):
931 def __dir__(cls):
932 return ['__class__', '__module__', '__name__', 'LIFE']
933 def __getattr__(self, name):
934 if name =='LIFE':
935 return 42
936 return super().__getattr(name)
937 class Class(metaclass=Meta):
938 pass
939 output = StringIO()
940 helper = pydoc.Helper(output=output)
941 helper(Class)
942 expected_text = expected_virtualattribute_pattern1 % __name__
943 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700944 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700945
Ethan Furman3f2f1922013-10-22 07:30:24 -0700946 @unittest.skipIf(sys.flags.optimize >= 2,
947 "Docstrings are omitted with -O2 and above")
948 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
949 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700950 def test_virtualClassAttributeWithTwoMeta(self):
951 class Meta1(type):
952 def __dir__(cls):
953 return ['__class__', '__module__', '__name__', 'one']
954 def __getattr__(self, name):
955 if name =='one':
956 return 1
957 return super().__getattr__(name)
958 class Meta2(type):
959 def __dir__(cls):
960 return ['__class__', '__module__', '__name__', 'two']
961 def __getattr__(self, name):
962 if name =='two':
963 return 2
964 return super().__getattr__(name)
965 class Meta3(Meta1, Meta2):
966 def __dir__(cls):
967 return list(sorted(set(
968 ['__class__', '__module__', '__name__', 'three'] +
969 Meta1.__dir__(cls) + Meta2.__dir__(cls))))
970 def __getattr__(self, name):
971 if name =='three':
972 return 3
973 return super().__getattr__(name)
974 class Class1(metaclass=Meta1):
975 pass
976 class Class2(Class1, metaclass=Meta3):
977 pass
978 fail1 = fail2 = False
979 output = StringIO()
980 helper = pydoc.Helper(output=output)
981 helper(Class1)
982 expected_text1 = expected_virtualattribute_pattern2 % __name__
983 result1 = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700984 self.assertEqual(expected_text1, result1)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700985 output = StringIO()
986 helper = pydoc.Helper(output=output)
987 helper(Class2)
988 expected_text2 = expected_virtualattribute_pattern3 % __name__
989 result2 = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -0700990 self.assertEqual(expected_text2, result2)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700991
Ethan Furman3f2f1922013-10-22 07:30:24 -0700992 @unittest.skipIf(sys.flags.optimize >= 2,
993 "Docstrings are omitted with -O2 and above")
994 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
995 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700996 def test_buggy_dir(self):
997 class M(type):
998 def __dir__(cls):
999 return ['__class__', '__name__', 'missing', 'here']
1000 class C(metaclass=M):
1001 here = 'present!'
1002 output = StringIO()
1003 helper = pydoc.Helper(output=output)
1004 helper(C)
1005 expected_text = expected_missingattribute_pattern % __name__
1006 result = output.getvalue().strip()
Raymond Hettingerbb91c1d2014-06-21 12:08:22 -07001007 self.assertEqual(expected_text, result)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001008
Eric Snowaed5b222014-01-04 20:38:11 -07001009
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001010@reap_threads
Georg Brandlb533e262008-05-25 18:19:30 +00001011def test_main():
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001012 try:
1013 test.support.run_unittest(PydocDocTest,
Ned Deily92a81a12011-10-06 14:19:03 -07001014 PydocImportTest,
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001015 TestDescriptions,
1016 PydocServerTest,
1017 PydocUrlHandlerTest,
1018 TestHelper,
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001019 PydocWithMetaClasses,
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001020 )
1021 finally:
1022 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +00001023
1024if __name__ == "__main__":
1025 test_main()