blob: 83f2ec94881b8e741f361848181d9fa2f42a243d [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
Georg Brandlb533e262008-05-25 18:19:30 +00005import difflib
Benjamin Peterson54237f92015-02-16 19:45:01 -05006import importlib.util
Georg Brandlb533e262008-05-25 18:19:30 +00007import inspect
Nick Coghlan7bb30b72010-12-03 09:29:11 +00008import pydoc
Benjamin Peterson54237f92015-02-16 19:45:01 -05009import py_compile
Ezio Melottib185a042011-04-28 07:42:55 +030010import keyword
Larry Hastings24a882b2014-02-20 23:34:46 -080011import _pickle
Antoine Pitrou916fc7b2013-05-19 15:44:54 +020012import pkgutil
Nick Coghlan7bb30b72010-12-03 09:29:11 +000013import re
Benjamin Peterson54237f92015-02-16 19:45:01 -050014import stat
Nick Coghlan7bb30b72010-12-03 09:29:11 +000015import string
Georg Brandlb533e262008-05-25 18:19:30 +000016import test.support
Nick Coghlan7bb30b72010-12-03 09:29:11 +000017import time
Ethan Furmanb0c84cd2013-10-20 22:37:39 -070018import types
Nick Coghlan7bb30b72010-12-03 09:29:11 +000019import unittest
Zachary Wareeb432142014-07-10 11:18:00 -050020import urllib.parse
Brian Curtin49c284c2010-03-31 03:19:28 +000021import xml.etree
Georg Brandld80d5f42010-12-03 07:47:22 +000022import textwrap
23from io import StringIO
Raymond Hettinger1103d052011-03-25 14:15:24 -070024from collections import namedtuple
Antoine Pitrouf7f54752011-07-15 22:42:12 +020025from test.script_helper import assert_python_ok
Antoine Pitroua6e81a22011-07-15 22:32:25 +020026from test.support import (
Ned Deily92a81a12011-10-06 14:19:03 -070027 TESTFN, rmtree,
Antoine Pitrou916fc7b2013-05-19 15:44:54 +020028 reap_children, reap_threads, captured_output, captured_stdout,
Stefan Krah5de32782014-01-18 23:18:39 +010029 captured_stderr, unlink, requires_docstrings
Antoine Pitroua6e81a22011-07-15 22:32:25 +020030)
Georg Brandlb533e262008-05-25 18:19:30 +000031from test import pydoc_mod
32
Victor Stinner62a68f22011-05-20 02:29:13 +020033try:
34 import threading
35except ImportError:
36 threading = None
37
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +020038class nonascii:
39 'Це не латиниця'
40 pass
41
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020042if test.support.HAVE_DOCSTRINGS:
43 expected_data_docstrings = (
44 'dictionary for instance variables (if defined)',
45 'list of weak references to the object (if defined)',
46 ) * 2
47else:
48 expected_data_docstrings = ('', '', '', '')
49
Barry Warsaw28a691b2010-04-17 00:19:56 +000050expected_text_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000051NAME
52 test.pydoc_mod - This is a test module for test_pydoc
Georg Brandlb533e262008-05-25 18:19:30 +000053%s
54CLASSES
55 builtins.object
56 A
57 B
Benjamin Petersoned1160b2014-06-07 16:44:00 -070058 C
Georg Brandlb533e262008-05-25 18:19:30 +000059\x20\x20\x20\x20
60 class A(builtins.object)
61 | Hello and goodbye
62 |\x20\x20
63 | Methods defined here:
64 |\x20\x20
65 | __init__()
66 | Wow, I have no function!
67 |\x20\x20
68 | ----------------------------------------------------------------------
69 | Data descriptors defined here:
70 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020071 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000072 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020073 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000074\x20\x20\x20\x20
75 class B(builtins.object)
76 | Data descriptors defined here:
77 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020078 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000079 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020080 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000081 |\x20\x20
82 | ----------------------------------------------------------------------
83 | Data and other attributes defined here:
84 |\x20\x20
85 | NO_MEANING = 'eggs'
Benjamin Petersoned1160b2014-06-07 16:44:00 -070086\x20\x20\x20\x20
87 class C(builtins.object)
88 | Methods defined here:
89 |\x20\x20
90 | get_answer(self)
91 | Return say_no()
92 |\x20\x20
93 | is_it_true(self)
94 | Return self.get_answer()
95 |\x20\x20
96 | say_no(self)
97 |\x20\x20
98 | ----------------------------------------------------------------------
99 | Data descriptors defined here:
100 |\x20\x20
101 | __dict__
102 | dictionary for instance variables (if defined)
103 |\x20\x20
104 | __weakref__
105 | list of weak references to the object (if defined)
Georg Brandlb533e262008-05-25 18:19:30 +0000106
107FUNCTIONS
108 doc_func()
109 This function solves all of the world's problems:
110 hunger
111 lack of Python
112 war
113\x20\x20\x20\x20
114 nodoc_func()
115
116DATA
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000117 __xyz__ = 'X, Y and Z'
Georg Brandlb533e262008-05-25 18:19:30 +0000118
119VERSION
120 1.2.3.4
121
122AUTHOR
123 Benjamin Peterson
124
125CREDITS
126 Nobody
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000127
128FILE
129 %s
Georg Brandlb533e262008-05-25 18:19:30 +0000130""".strip()
131
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200132expected_text_data_docstrings = tuple('\n | ' + s if s else ''
133 for s in expected_data_docstrings)
134
Barry Warsaw28a691b2010-04-17 00:19:56 +0000135expected_html_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +0000136<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
137<tr bgcolor="#7799ee">
138<td valign=bottom>&nbsp;<br>
139<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
140><td align=right valign=bottom
141><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
142 <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
143<p>
144<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
145<tr bgcolor="#ee77aa">
146<td colspan=3 valign=bottom>&nbsp;<br>
147<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
148\x20\x20\x20\x20
149<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
150<td width="100%%"><dl>
151<dt><font face="helvetica, arial"><a href="builtins.html#object">builtins.object</a>
152</font></dt><dd>
153<dl>
154<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
155</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700156</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#C">C</a>
Georg Brandlb533e262008-05-25 18:19:30 +0000157</font></dt></dl>
158</dd>
159</dl>
160 <p>
161<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
162<tr bgcolor="#ffc8d8">
163<td colspan=3 valign=bottom>&nbsp;<br>
164<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>
165\x20\x20\x20\x20
166<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
167<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
168<tr><td>&nbsp;</td>
169<td width="100%%">Methods defined here:<br>
170<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>
171
172<hr>
173Data descriptors defined here:<br>
174<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200175<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000176</dl>
177<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200178<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000179</dl>
180</td></tr></table> <p>
181<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
182<tr bgcolor="#ffc8d8">
183<td colspan=3 valign=bottom>&nbsp;<br>
184<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>
185\x20\x20\x20\x20
186<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
187<td width="100%%">Data descriptors defined here:<br>
188<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200189<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000190</dl>
191<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200192<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000193</dl>
194<hr>
195Data and other attributes defined here:<br>
196<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
197
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700198</td></tr></table> <p>
199<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
200<tr bgcolor="#ffc8d8">
201<td colspan=3 valign=bottom>&nbsp;<br>
202<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>
203\x20\x20\x20\x20
204<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
205<td width="100%%">Methods defined here:<br>
206<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>
207
208<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>
209
210<dl><dt><a name="C-say_no"><strong>say_no</strong></a>(self)</dt></dl>
211
212<hr>
213Data descriptors defined here:<br>
214<dl><dt><strong>__dict__</strong></dt>
215<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
216</dl>
217<dl><dt><strong>__weakref__</strong></dt>
218<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
219</dl>
Georg Brandlb533e262008-05-25 18:19:30 +0000220</td></tr></table></td></tr></table><p>
221<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
222<tr bgcolor="#eeaa77">
223<td colspan=3 valign=bottom>&nbsp;<br>
224<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
225\x20\x20\x20\x20
226<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
227<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>
228hunger<br>
229lack&nbsp;of&nbsp;Python<br>
230war</tt></dd></dl>
231 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
232</td></tr></table><p>
233<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
234<tr bgcolor="#55aa55">
235<td colspan=3 valign=bottom>&nbsp;<br>
236<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
237\x20\x20\x20\x20
238<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000239<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p>
Georg Brandlb533e262008-05-25 18:19:30 +0000240<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
241<tr bgcolor="#7799ee">
242<td colspan=3 valign=bottom>&nbsp;<br>
243<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
244\x20\x20\x20\x20
245<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
246<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
247<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
248<tr bgcolor="#7799ee">
249<td colspan=3 valign=bottom>&nbsp;<br>
250<font color="#ffffff" face="helvetica, arial"><big><strong>Credits</strong></big></font></td></tr>
251\x20\x20\x20\x20
252<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
253<td width="100%%">Nobody</td></tr></table>
Barry Warsaw28a691b2010-04-17 00:19:56 +0000254""".strip() # ' <- emacs turd
Georg Brandlb533e262008-05-25 18:19:30 +0000255
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200256expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;')
257 for s in expected_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000258
259# output pattern for missing module
260missing_pattern = "no Python documentation found for '%s'"
261
Benjamin Peterson0289b152009-06-28 17:22:03 +0000262# output pattern for module with bad imports
Brett Cannon679ecb52013-07-04 17:51:50 -0400263badimport_pattern = "problem in %s - ImportError: No module named %r"
Benjamin Peterson0289b152009-06-28 17:22:03 +0000264
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700265expected_dynamicattribute_pattern = """
266Help on class DA in module %s:
267
268class DA(builtins.object)
269 | Data descriptors defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200270 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700271 | __dict__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200272 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700273 | __weakref__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200274 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700275 | ham
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200276 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700277 | ----------------------------------------------------------------------
278 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200279 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700280 | ham = 'spam'
281""".strip()
282
283expected_virtualattribute_pattern1 = """
284Help on class Class in module %s:
285
286class Class(builtins.object)
287 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200288 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700289 | LIFE = 42
290""".strip()
291
292expected_virtualattribute_pattern2 = """
293Help on class Class1 in module %s:
294
295class Class1(builtins.object)
296 | Data and other attributes inherited from Meta1:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200297 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700298 | one = 1
299""".strip()
300
301expected_virtualattribute_pattern3 = """
302Help on class Class2 in module %s:
303
304class Class2(Class1)
305 | Method resolution order:
306 | Class2
307 | Class1
308 | builtins.object
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200309 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700310 | Data and other attributes inherited from Meta1:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200311 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700312 | one = 1
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200313 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700314 | ----------------------------------------------------------------------
315 | Data and other attributes inherited from Meta3:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200316 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700317 | three = 3
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200318 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700319 | ----------------------------------------------------------------------
320 | Data and other attributes inherited from Meta2:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200321 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700322 | two = 2
323""".strip()
324
325expected_missingattribute_pattern = """
326Help on class C in module %s:
327
328class C(builtins.object)
329 | Data and other attributes defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200330 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700331 | here = 'present!'
332""".strip()
333
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200334def run_pydoc(module_name, *args, **env):
Georg Brandlb533e262008-05-25 18:19:30 +0000335 """
336 Runs pydoc on the specified module. Returns the stripped
337 output of pydoc.
338 """
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200339 args = args + (module_name,)
Ned Deily92a81a12011-10-06 14:19:03 -0700340 # do not write bytecode files to avoid caching errors
341 rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200342 return out.strip()
Georg Brandlb533e262008-05-25 18:19:30 +0000343
344def get_pydoc_html(module):
345 "Returns pydoc generated output as html"
346 doc = pydoc.HTMLDoc()
347 output = doc.docmodule(module)
348 loc = doc.getdocloc(pydoc_mod) or ""
349 if loc:
350 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
351 return output.strip(), loc
352
353def get_pydoc_text(module):
354 "Returns pydoc generated output as text"
355 doc = pydoc.TextDoc()
356 loc = doc.getdocloc(pydoc_mod) or ""
357 if loc:
358 loc = "\nMODULE DOCS\n " + loc + "\n"
359
360 output = doc.docmodule(module)
361
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000362 # clean up the extra text formatting that pydoc performs
Georg Brandlb533e262008-05-25 18:19:30 +0000363 patt = re.compile('\b.')
364 output = patt.sub('', output)
365 return output.strip(), loc
366
367def print_diffs(text1, text2):
368 "Prints unified diffs for two texts"
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000369 # XXX now obsolete, use unittest built-in support
Ezio Melottid8b509b2011-09-28 17:37:55 +0300370 lines1 = text1.splitlines(keepends=True)
371 lines2 = text2.splitlines(keepends=True)
Georg Brandlb533e262008-05-25 18:19:30 +0000372 diffs = difflib.unified_diff(lines1, lines2, n=0, fromfile='expected',
373 tofile='got')
374 print('\n' + ''.join(diffs))
375
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000376def get_html_title(text):
Nick Coghlanecace282010-12-03 16:08:46 +0000377 # Bit of hack, but good enough for test purposes
378 header, _, _ = text.partition("</head>")
379 _, _, title = header.partition("<title>")
380 title, _, _ = title.partition("</title>")
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000381 return title
382
Georg Brandlb533e262008-05-25 18:19:30 +0000383
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200384class PydocBaseTest(unittest.TestCase):
385
386 def _restricted_walk_packages(self, walk_packages, path=None):
387 """
388 A version of pkgutil.walk_packages() that will restrict itself to
389 a given path.
390 """
391 default_path = path or [os.path.dirname(__file__)]
392 def wrapper(path=None, prefix='', onerror=None):
393 return walk_packages(path or default_path, prefix, onerror)
394 return wrapper
395
396 @contextlib.contextmanager
397 def restrict_walk_packages(self, path=None):
398 walk_packages = pkgutil.walk_packages
399 pkgutil.walk_packages = self._restricted_walk_packages(walk_packages,
400 path)
401 try:
402 yield
403 finally:
404 pkgutil.walk_packages = walk_packages
405
406
Georg Brandld2f38572011-01-30 08:37:19 +0000407class PydocDocTest(unittest.TestCase):
Georg Brandlb533e262008-05-25 18:19:30 +0000408
R. David Murray378c0cf2010-02-24 01:46:21 +0000409 @unittest.skipIf(sys.flags.optimize >= 2,
410 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000411 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
412 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100413 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000414 def test_html_doc(self):
415 result, doc_loc = get_pydoc_html(pydoc_mod)
416 mod_file = inspect.getabsfile(pydoc_mod)
Zachary Wareeb432142014-07-10 11:18:00 -0500417 mod_url = urllib.parse.quote(mod_file)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200418 expected_html = expected_html_pattern % (
419 (mod_url, mod_file, doc_loc) +
420 expected_html_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000421 if result != expected_html:
422 print_diffs(expected_html, result)
423 self.fail("outputs are not equal, see diff above")
424
R. David Murray378c0cf2010-02-24 01:46:21 +0000425 @unittest.skipIf(sys.flags.optimize >= 2,
426 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000427 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
428 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100429 @requires_docstrings
Georg Brandlb533e262008-05-25 18:19:30 +0000430 def test_text_doc(self):
431 result, doc_loc = get_pydoc_text(pydoc_mod)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200432 expected_text = expected_text_pattern % (
433 (doc_loc,) +
434 expected_text_data_docstrings +
435 (inspect.getabsfile(pydoc_mod),))
Georg Brandlb533e262008-05-25 18:19:30 +0000436 if result != expected_text:
437 print_diffs(expected_text, result)
438 self.fail("outputs are not equal, see diff above")
439
Serhiy Storchaka056eb022014-02-19 23:05:12 +0200440 def test_text_enum_member_with_value_zero(self):
441 # Test issue #20654 to ensure enum member with value 0 can be
442 # displayed. It used to throw KeyError: 'zero'.
443 import enum
444 class BinaryInteger(enum.IntEnum):
445 zero = 0
446 one = 1
447 doc = pydoc.render_doc(BinaryInteger)
448 self.assertIn('<BinaryInteger.zero: 0>', doc)
449
Brian Curtin49c284c2010-03-31 03:19:28 +0000450 def test_issue8225(self):
451 # Test issue8225 to ensure no doc link appears for xml.etree
452 result, doc_loc = get_pydoc_text(xml.etree)
453 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
454
Benjamin Peterson159824e2014-06-07 20:14:26 -0700455 def test_getpager_with_stdin_none(self):
456 previous_stdin = sys.stdin
457 try:
458 sys.stdin = None
459 pydoc.getpager() # Shouldn't fail.
460 finally:
461 sys.stdin = previous_stdin
462
R David Murrayc43125a2012-04-23 13:23:57 -0400463 def test_non_str_name(self):
464 # issue14638
465 # Treat illegal (non-str) name like no name
466 class A:
467 __name__ = 42
468 class B:
469 pass
470 adoc = pydoc.render_doc(A())
471 bdoc = pydoc.render_doc(B())
472 self.assertEqual(adoc.replace("A", "B"), bdoc)
473
Georg Brandlb533e262008-05-25 18:19:30 +0000474 def test_not_here(self):
475 missing_module = "test.i_am_not_here"
476 result = str(run_pydoc(missing_module), 'ascii')
477 expected = missing_pattern % missing_module
478 self.assertEqual(expected, result,
479 "documentation for missing module found")
480
Serhiy Storchaka4c094e52015-03-01 15:31:36 +0200481 @unittest.skipIf(sys.flags.optimize >= 2,
482 'Docstrings are omitted with -OO and above')
Serhiy Storchaka5e3d7a42015-02-20 23:46:06 +0200483 def test_not_ascii(self):
484 result = run_pydoc('test.test_pydoc.nonascii', PYTHONIOENCODING='ascii')
485 encoded = nonascii.__doc__.encode('ascii', 'backslashreplace')
486 self.assertIn(encoded, result)
487
R. David Murray1f1b9d32009-05-27 20:56:59 +0000488 def test_input_strip(self):
489 missing_module = " test.i_am_not_here "
490 result = str(run_pydoc(missing_module), 'ascii')
491 expected = missing_pattern % missing_module.strip()
492 self.assertEqual(expected, result)
493
Ezio Melotti412c95a2010-02-16 23:31:04 +0000494 def test_stripid(self):
495 # test with strings, other implementations might have different repr()
496 stripid = pydoc.stripid
497 # strip the id
498 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
499 '<function stripid>')
500 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
501 '<function stripid>')
502 # nothing to strip, return the same text
503 self.assertEqual(stripid('42'), '42')
504 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
505 "<type 'exceptions.Exception'>")
506
Georg Brandld80d5f42010-12-03 07:47:22 +0000507 @unittest.skipIf(sys.flags.optimize >= 2,
508 'Docstrings are omitted with -O2 and above')
Brett Cannon7a540732011-02-22 03:04:06 +0000509 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
510 'trace function introduces __locals__ unexpectedly')
Charles-François Natali57398c32014-06-20 22:59:12 +0100511 @requires_docstrings
Georg Brandld80d5f42010-12-03 07:47:22 +0000512 def test_help_output_redirect(self):
513 # issue 940286, if output is set in Helper, then all output from
514 # Helper.help should be redirected
515 old_pattern = expected_text_pattern
516 getpager_old = pydoc.getpager
517 getpager_new = lambda: (lambda x: x)
518 self.maxDiff = None
519
520 buf = StringIO()
521 helper = pydoc.Helper(output=buf)
522 unused, doc_loc = get_pydoc_text(pydoc_mod)
523 module = "test.pydoc_mod"
524 help_header = """
525 Help on module test.pydoc_mod in test:
526
527 """.lstrip()
528 help_header = textwrap.dedent(help_header)
529 expected_help_pattern = help_header + expected_text_pattern
530
531 pydoc.getpager = getpager_new
532 try:
533 with captured_output('stdout') as output, \
534 captured_output('stderr') as err:
535 helper.help(module)
536 result = buf.getvalue().strip()
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200537 expected_text = expected_help_pattern % (
538 (doc_loc,) +
539 expected_text_data_docstrings +
540 (inspect.getabsfile(pydoc_mod),))
Georg Brandld80d5f42010-12-03 07:47:22 +0000541 self.assertEqual('', output.getvalue())
542 self.assertEqual('', err.getvalue())
543 self.assertEqual(expected_text, result)
544 finally:
545 pydoc.getpager = getpager_old
546
Raymond Hettinger1103d052011-03-25 14:15:24 -0700547 def test_namedtuple_public_underscore(self):
548 NT = namedtuple('NT', ['abc', 'def'], rename=True)
549 with captured_stdout() as help_io:
Terry Jan Reedy5c811642013-11-04 21:43:26 -0500550 pydoc.help(NT)
Raymond Hettinger1103d052011-03-25 14:15:24 -0700551 helptext = help_io.getvalue()
552 self.assertIn('_1', helptext)
553 self.assertIn('_replace', helptext)
554 self.assertIn('_asdict', helptext)
555
Victor Stinnere6c910e2011-06-30 15:55:43 +0200556 def test_synopsis(self):
557 self.addCleanup(unlink, TESTFN)
558 for encoding in ('ISO-8859-1', 'UTF-8'):
559 with open(TESTFN, 'w', encoding=encoding) as script:
560 if encoding != 'UTF-8':
561 print('#coding: {}'.format(encoding), file=script)
562 print('"""line 1: h\xe9', file=script)
563 print('line 2: hi"""', file=script)
564 synopsis = pydoc.synopsis(TESTFN, {})
565 self.assertEqual(synopsis, 'line 1: h\xe9')
566
Serhiy Storchaka4c094e52015-03-01 15:31:36 +0200567 @unittest.skipIf(sys.flags.optimize >= 2,
568 'Docstrings are omitted with -OO and above')
Eric Snowaed5b222014-01-04 20:38:11 -0700569 def test_synopsis_sourceless(self):
570 expected = os.__doc__.splitlines()[0]
571 filename = os.__cached__
572 synopsis = pydoc.synopsis(filename)
573
574 self.assertEqual(synopsis, expected)
575
Benjamin Peterson54237f92015-02-16 19:45:01 -0500576 def test_synopsis_sourceless_empty_doc(self):
577 with test.support.temp_cwd() as test_dir:
578 init_path = os.path.join(test_dir, 'foomod42.py')
579 cached_path = importlib.util.cache_from_source(init_path)
580 with open(init_path, 'w') as fobj:
581 fobj.write("foo = 1")
582 py_compile.compile(init_path)
583 synopsis = pydoc.synopsis(init_path, {})
584 self.assertIsNone(synopsis)
585 synopsis_cached = pydoc.synopsis(cached_path, {})
586 self.assertIsNone(synopsis_cached)
587
R David Murray455f2962013-03-19 00:00:33 -0400588 def test_splitdoc_with_description(self):
589 example_string = "I Am A Doc\n\n\nHere is my description"
590 self.assertEqual(pydoc.splitdoc(example_string),
591 ('I Am A Doc', '\nHere is my description'))
592
593 def test_is_object_or_method(self):
594 doc = pydoc.Doc()
595 # Bound Method
596 self.assertTrue(pydoc._is_some_method(doc.fail))
597 # Method Descriptor
598 self.assertTrue(pydoc._is_some_method(int.__add__))
599 # String
600 self.assertFalse(pydoc._is_some_method("I am not a method"))
601
602 def test_is_package_when_not_package(self):
603 with test.support.temp_cwd() as test_dir:
604 self.assertFalse(pydoc.ispackage(test_dir))
605
606 def test_is_package_when_is_package(self):
607 with test.support.temp_cwd() as test_dir:
608 init_path = os.path.join(test_dir, '__init__.py')
609 open(init_path, 'w').close()
610 self.assertTrue(pydoc.ispackage(test_dir))
611 os.remove(init_path)
612
R David Murrayac0cea52013-03-19 02:47:44 -0400613 def test_allmethods(self):
614 # issue 17476: allmethods was no longer returning unbound methods.
615 # This test is a bit fragile in the face of changes to object and type,
616 # but I can't think of a better way to do it without duplicating the
617 # logic of the function under test.
618
619 class TestClass(object):
620 def method_returning_true(self):
621 return True
622
623 # What we expect to get back: everything on object...
624 expected = dict(vars(object))
625 # ...plus our unbound method...
626 expected['method_returning_true'] = TestClass.method_returning_true
627 # ...but not the non-methods on object.
628 del expected['__doc__']
629 del expected['__class__']
630 # inspect resolves descriptors on type into methods, but vars doesn't,
631 # so we need to update __subclasshook__.
632 expected['__subclasshook__'] = TestClass.__subclasshook__
633
634 methods = pydoc.allmethods(TestClass)
635 self.assertDictEqual(methods, expected)
636
Georg Brandlb533e262008-05-25 18:19:30 +0000637
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200638class PydocImportTest(PydocBaseTest):
Ned Deily92a81a12011-10-06 14:19:03 -0700639
640 def setUp(self):
641 self.test_dir = os.mkdir(TESTFN)
642 self.addCleanup(rmtree, TESTFN)
Benjamin Peterson54237f92015-02-16 19:45:01 -0500643 importlib.invalidate_caches()
Ned Deily92a81a12011-10-06 14:19:03 -0700644
645 def test_badimport(self):
646 # This tests the fix for issue 5230, where if pydoc found the module
647 # but the module had an internal import error pydoc would report no doc
648 # found.
649 modname = 'testmod_xyzzy'
650 testpairs = (
651 ('i_am_not_here', 'i_am_not_here'),
Brett Cannonfd074152012-04-14 14:10:13 -0400652 ('test.i_am_not_here_either', 'test.i_am_not_here_either'),
653 ('test.i_am_not_here.neither_am_i', 'test.i_am_not_here'),
654 ('i_am_not_here.{}'.format(modname), 'i_am_not_here'),
655 ('test.{}'.format(modname), 'test.{}'.format(modname)),
Ned Deily92a81a12011-10-06 14:19:03 -0700656 )
657
658 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
659 for importstring, expectedinmsg in testpairs:
660 with open(sourcefn, 'w') as f:
661 f.write("import {}\n".format(importstring))
662 result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii")
663 expected = badimport_pattern % (modname, expectedinmsg)
664 self.assertEqual(expected, result)
665
666 def test_apropos_with_bad_package(self):
667 # Issue 7425 - pydoc -k failed when bad package on path
668 pkgdir = os.path.join(TESTFN, "syntaxerr")
669 os.mkdir(pkgdir)
670 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
671 with open(badsyntax, 'w') as f:
672 f.write("invalid python syntax = $1\n")
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200673 with self.restrict_walk_packages(path=[TESTFN]):
674 with captured_stdout() as out:
675 with captured_stderr() as err:
676 pydoc.apropos('xyzzy')
677 # No result, no error
678 self.assertEqual(out.getvalue(), '')
679 self.assertEqual(err.getvalue(), '')
680 # The package name is still matched
681 with captured_stdout() as out:
682 with captured_stderr() as err:
683 pydoc.apropos('syntaxerr')
684 self.assertEqual(out.getvalue().strip(), 'syntaxerr')
685 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700686
687 def test_apropos_with_unreadable_dir(self):
688 # Issue 7367 - pydoc -k failed when unreadable dir on path
689 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
690 os.mkdir(self.unreadable_dir, 0)
691 self.addCleanup(os.rmdir, self.unreadable_dir)
692 # Note, on Windows the directory appears to be still
693 # readable so this is not really testing the issue there
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200694 with self.restrict_walk_packages(path=[TESTFN]):
695 with captured_stdout() as out:
696 with captured_stderr() as err:
697 pydoc.apropos('SOMEKEY')
698 # No result, no error
699 self.assertEqual(out.getvalue(), '')
700 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700701
Benjamin Peterson54237f92015-02-16 19:45:01 -0500702 def test_apropos_empty_doc(self):
703 pkgdir = os.path.join(TESTFN, 'walkpkg')
704 os.mkdir(pkgdir)
705 self.addCleanup(rmtree, pkgdir)
706 init_path = os.path.join(pkgdir, '__init__.py')
707 with open(init_path, 'w') as fobj:
708 fobj.write("foo = 1")
709 current_mode = stat.S_IMODE(os.stat(pkgdir).st_mode)
710 try:
711 os.chmod(pkgdir, current_mode & ~stat.S_IEXEC)
712 with self.restrict_walk_packages(path=[TESTFN]), captured_stdout() as stdout:
713 pydoc.apropos('')
714 self.assertIn('walkpkg', stdout.getvalue())
715 finally:
716 os.chmod(pkgdir, current_mode)
717
Eric Snowa46ef702014-02-22 13:57:08 -0700718 @unittest.skip('causes undesireable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700719 def test_modules(self):
720 # See Helper.listmodules().
721 num_header_lines = 2
722 num_module_lines_min = 5 # Playing it safe.
723 num_footer_lines = 3
724 expected = num_header_lines + num_module_lines_min + num_footer_lines
725
726 output = StringIO()
727 helper = pydoc.Helper(output=output)
728 helper('modules')
729 result = output.getvalue().strip()
730 num_lines = len(result.splitlines())
731
732 self.assertGreaterEqual(num_lines, expected)
733
Eric Snowa46ef702014-02-22 13:57:08 -0700734 @unittest.skip('causes undesireable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700735 def test_modules_search(self):
736 # See Helper.listmodules().
737 expected = 'pydoc - '
738
739 output = StringIO()
740 helper = pydoc.Helper(output=output)
741 with captured_stdout() as help_io:
742 helper('modules pydoc')
743 result = help_io.getvalue()
744
745 self.assertIn(expected, result)
746
Eric Snowa46ef702014-02-22 13:57:08 -0700747 @unittest.skip('some buildbots are not cooperating (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700748 def test_modules_search_builtin(self):
Eric Snow5ea97502014-01-04 23:04:27 -0700749 expected = 'gc - '
Eric Snowaed5b222014-01-04 20:38:11 -0700750
751 output = StringIO()
752 helper = pydoc.Helper(output=output)
753 with captured_stdout() as help_io:
Eric Snow5ea97502014-01-04 23:04:27 -0700754 helper('modules garbage')
Eric Snowaed5b222014-01-04 20:38:11 -0700755 result = help_io.getvalue()
756
757 self.assertTrue(result.startswith(expected))
758
759 def test_importfile(self):
760 loaded_pydoc = pydoc.importfile(pydoc.__file__)
761
Eric Snow3a62d142014-01-06 20:42:59 -0700762 self.assertIsNot(loaded_pydoc, pydoc)
Eric Snowaed5b222014-01-04 20:38:11 -0700763 self.assertEqual(loaded_pydoc.__name__, 'pydoc')
764 self.assertEqual(loaded_pydoc.__file__, pydoc.__file__)
Eric Snow3a62d142014-01-06 20:42:59 -0700765 self.assertEqual(loaded_pydoc.__spec__, pydoc.__spec__)
Eric Snowaed5b222014-01-04 20:38:11 -0700766
Ned Deily92a81a12011-10-06 14:19:03 -0700767
Georg Brandlb533e262008-05-25 18:19:30 +0000768class TestDescriptions(unittest.TestCase):
769
770 def test_module(self):
771 # Check that pydocfodder module can be described
772 from test import pydocfodder
773 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000774 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000775
Georg Brandlb533e262008-05-25 18:19:30 +0000776 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000777 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +0000778 c = C()
779
780 self.assertEqual(pydoc.describe(C), 'class C')
781 self.assertEqual(pydoc.describe(c), 'C')
782 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000783 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000784
Éric Araujoe64e51b2011-07-29 17:03:55 +0200785 def test_builtin(self):
786 for name in ('str', 'str.translate', 'builtins.str',
787 'builtins.str.translate'):
788 # test low-level function
789 self.assertIsNotNone(pydoc.locate(name))
790 # test high-level function
791 try:
792 pydoc.render_doc(name)
793 except ImportError:
Terry Jan Reedyfe928de2014-06-20 14:59:11 -0400794 self.fail('finding the doc of {!r} failed'.format(name))
Éric Araujoe64e51b2011-07-29 17:03:55 +0200795
796 for name in ('notbuiltins', 'strrr', 'strr.translate',
797 'str.trrrranslate', 'builtins.strrr',
798 'builtins.str.trrranslate'):
799 self.assertIsNone(pydoc.locate(name))
800 self.assertRaises(ImportError, pydoc.render_doc, name)
801
Larry Hastings24a882b2014-02-20 23:34:46 -0800802 @staticmethod
803 def _get_summary_line(o):
804 text = pydoc.plain(pydoc.render_doc(o))
805 lines = text.split('\n')
806 assert len(lines) >= 2
807 return lines[2]
808
809 # these should include "self"
810 def test_unbound_python_method(self):
811 self.assertEqual(self._get_summary_line(textwrap.TextWrapper.wrap),
812 "wrap(self, text)")
813
Stefan Krah5de32782014-01-18 23:18:39 +0100814 @requires_docstrings
Larry Hastings24a882b2014-02-20 23:34:46 -0800815 def test_unbound_builtin_method(self):
816 self.assertEqual(self._get_summary_line(_pickle.Pickler.dump),
817 "dump(self, obj, /)")
818
819 # these no longer include "self"
820 def test_bound_python_method(self):
821 t = textwrap.TextWrapper()
822 self.assertEqual(self._get_summary_line(t.wrap),
823 "wrap(text) method of textwrap.TextWrapper instance")
824
825 @requires_docstrings
826 def test_bound_builtin_method(self):
827 s = StringIO()
828 p = _pickle.Pickler(s)
829 self.assertEqual(self._get_summary_line(p.dump),
830 "dump(obj, /) method of _pickle.Pickler instance")
831
832 # this should *never* include self!
833 @requires_docstrings
834 def test_module_level_callable(self):
835 self.assertEqual(self._get_summary_line(os.stat),
836 "stat(path, *, dir_fd=None, follow_symlinks=True)")
Larry Hastings1abd7082014-01-16 14:15:03 -0800837
Georg Brandlb533e262008-05-25 18:19:30 +0000838
Victor Stinner62a68f22011-05-20 02:29:13 +0200839@unittest.skipUnless(threading, 'Threading required for this test.')
Georg Brandld2f38572011-01-30 08:37:19 +0000840class PydocServerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000841 """Tests for pydoc._start_server"""
842
843 def test_server(self):
844
845 # Minimal test that starts the server, then stops it.
846 def my_url_handler(url, content_type):
847 text = 'the URL sent was: (%s, %s)' % (url, content_type)
848 return text
849
850 serverthread = pydoc._start_server(my_url_handler, port=0)
Senthil Kumaran2a42a0b2014-09-17 13:17:58 +0800851 self.assertIn('localhost', serverthread.docserver.address)
852
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000853 starttime = time.time()
854 timeout = 1 #seconds
855
856 while serverthread.serving:
857 time.sleep(.01)
858 if serverthread.serving and time.time() - starttime > timeout:
859 serverthread.stop()
860 break
861
862 self.assertEqual(serverthread.error, None)
863
864
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200865class PydocUrlHandlerTest(PydocBaseTest):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000866 """Tests for pydoc._url_handler"""
867
868 def test_content_type_err(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000869 f = pydoc._url_handler
Georg Brandld2f38572011-01-30 08:37:19 +0000870 self.assertRaises(TypeError, f, 'A', '')
871 self.assertRaises(TypeError, f, 'B', 'foobar')
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000872
873 def test_url_requests(self):
874 # Test for the correct title in the html pages returned.
875 # This tests the different parts of the URL handler without
876 # getting too picky about the exact html.
877 requests = [
Georg Brandld2f38572011-01-30 08:37:19 +0000878 ("", "Pydoc: Index of Modules"),
879 ("get?key=", "Pydoc: Index of Modules"),
880 ("index", "Pydoc: Index of Modules"),
881 ("topics", "Pydoc: Topics"),
882 ("keywords", "Pydoc: Keywords"),
883 ("pydoc", "Pydoc: module pydoc"),
884 ("get?key=pydoc", "Pydoc: module pydoc"),
885 ("search?key=pydoc", "Pydoc: Search Results"),
886 ("topic?key=def", "Pydoc: KEYWORD def"),
887 ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
888 ("foobar", "Pydoc: Error - foobar"),
889 ("getfile?key=foobar", "Pydoc: Error - getfile?key=foobar"),
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000890 ]
891
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200892 with self.restrict_walk_packages():
893 for url, title in requests:
894 text = pydoc._url_handler(url, "text/html")
895 result = get_html_title(text)
896 self.assertEqual(result, title, text)
897
898 path = string.__file__
899 title = "Pydoc: getfile " + path
900 url = "getfile?key=" + path
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000901 text = pydoc._url_handler(url, "text/html")
902 result = get_html_title(text)
903 self.assertEqual(result, title)
904
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000905
Ezio Melottib185a042011-04-28 07:42:55 +0300906class TestHelper(unittest.TestCase):
907 def test_keywords(self):
908 self.assertEqual(sorted(pydoc.Helper.keywords),
909 sorted(keyword.kwlist))
910
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700911class PydocWithMetaClasses(unittest.TestCase):
Ethan Furman3f2f1922013-10-22 07:30:24 -0700912 @unittest.skipIf(sys.flags.optimize >= 2,
913 "Docstrings are omitted with -O2 and above")
914 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
915 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700916 def test_DynamicClassAttribute(self):
917 class Meta(type):
918 def __getattr__(self, name):
919 if name == 'ham':
920 return 'spam'
921 return super().__getattr__(name)
922 class DA(metaclass=Meta):
923 @types.DynamicClassAttribute
924 def ham(self):
925 return 'eggs'
Ethan Furman3f2f1922013-10-22 07:30:24 -0700926 expected_text_data_docstrings = tuple('\n | ' + s if s else ''
927 for s in expected_data_docstrings)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700928 output = StringIO()
929 helper = pydoc.Helper(output=output)
930 helper(DA)
Ethan Furman3f2f1922013-10-22 07:30:24 -0700931 expected_text = expected_dynamicattribute_pattern % (
932 (__name__,) + expected_text_data_docstrings[:2])
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700933 result = output.getvalue().strip()
934 if result != expected_text:
935 print_diffs(expected_text, result)
936 self.fail("outputs are not equal, see diff above")
937
Ethan Furman3f2f1922013-10-22 07:30:24 -0700938 @unittest.skipIf(sys.flags.optimize >= 2,
939 "Docstrings are omitted with -O2 and above")
940 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
941 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700942 def test_virtualClassAttributeWithOneMeta(self):
943 class Meta(type):
944 def __dir__(cls):
945 return ['__class__', '__module__', '__name__', 'LIFE']
946 def __getattr__(self, name):
947 if name =='LIFE':
948 return 42
949 return super().__getattr(name)
950 class Class(metaclass=Meta):
951 pass
952 output = StringIO()
953 helper = pydoc.Helper(output=output)
954 helper(Class)
955 expected_text = expected_virtualattribute_pattern1 % __name__
956 result = output.getvalue().strip()
957 if result != expected_text:
958 print_diffs(expected_text, result)
959 self.fail("outputs are not equal, see diff above")
960
Ethan Furman3f2f1922013-10-22 07:30:24 -0700961 @unittest.skipIf(sys.flags.optimize >= 2,
962 "Docstrings are omitted with -O2 and above")
963 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
964 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700965 def test_virtualClassAttributeWithTwoMeta(self):
966 class Meta1(type):
967 def __dir__(cls):
968 return ['__class__', '__module__', '__name__', 'one']
969 def __getattr__(self, name):
970 if name =='one':
971 return 1
972 return super().__getattr__(name)
973 class Meta2(type):
974 def __dir__(cls):
975 return ['__class__', '__module__', '__name__', 'two']
976 def __getattr__(self, name):
977 if name =='two':
978 return 2
979 return super().__getattr__(name)
980 class Meta3(Meta1, Meta2):
981 def __dir__(cls):
982 return list(sorted(set(
983 ['__class__', '__module__', '__name__', 'three'] +
984 Meta1.__dir__(cls) + Meta2.__dir__(cls))))
985 def __getattr__(self, name):
986 if name =='three':
987 return 3
988 return super().__getattr__(name)
989 class Class1(metaclass=Meta1):
990 pass
991 class Class2(Class1, metaclass=Meta3):
992 pass
993 fail1 = fail2 = False
994 output = StringIO()
995 helper = pydoc.Helper(output=output)
996 helper(Class1)
997 expected_text1 = expected_virtualattribute_pattern2 % __name__
998 result1 = output.getvalue().strip()
999 if result1 != expected_text1:
1000 print_diffs(expected_text1, result1)
1001 fail1 = True
1002 output = StringIO()
1003 helper = pydoc.Helper(output=output)
1004 helper(Class2)
1005 expected_text2 = expected_virtualattribute_pattern3 % __name__
1006 result2 = output.getvalue().strip()
1007 if result2 != expected_text2:
1008 print_diffs(expected_text2, result2)
1009 fail2 = True
1010 if fail1 or fail2:
1011 self.fail("outputs are not equal, see diff above")
1012
Ethan Furman3f2f1922013-10-22 07:30:24 -07001013 @unittest.skipIf(sys.flags.optimize >= 2,
1014 "Docstrings are omitted with -O2 and above")
1015 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
1016 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001017 def test_buggy_dir(self):
1018 class M(type):
1019 def __dir__(cls):
1020 return ['__class__', '__name__', 'missing', 'here']
1021 class C(metaclass=M):
1022 here = 'present!'
1023 output = StringIO()
1024 helper = pydoc.Helper(output=output)
1025 helper(C)
1026 expected_text = expected_missingattribute_pattern % __name__
1027 result = output.getvalue().strip()
1028 if result != expected_text:
1029 print_diffs(expected_text, result)
1030 self.fail("outputs are not equal, see diff above")
1031
Eric Snowaed5b222014-01-04 20:38:11 -07001032
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001033@reap_threads
Georg Brandlb533e262008-05-25 18:19:30 +00001034def test_main():
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001035 try:
1036 test.support.run_unittest(PydocDocTest,
Ned Deily92a81a12011-10-06 14:19:03 -07001037 PydocImportTest,
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001038 TestDescriptions,
1039 PydocServerTest,
1040 PydocUrlHandlerTest,
1041 TestHelper,
Ethan Furmanb0c84cd2013-10-20 22:37:39 -07001042 PydocWithMetaClasses,
Antoine Pitroua6e81a22011-07-15 22:32:25 +02001043 )
1044 finally:
1045 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +00001046
1047if __name__ == "__main__":
1048 test_main()