blob: 8d85c140717b45636fb4ccab5291a09ee6534b72 [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
Georg Brandlb533e262008-05-25 18:19:30 +00006import inspect
Nick Coghlan7bb30b72010-12-03 09:29:11 +00007import pydoc
Ezio Melottib185a042011-04-28 07:42:55 +03008import keyword
Larry Hastings24a882b2014-02-20 23:34:46 -08009import _pickle
Antoine Pitrou916fc7b2013-05-19 15:44:54 +020010import pkgutil
Nick Coghlan7bb30b72010-12-03 09:29:11 +000011import re
12import string
Georg Brandlb533e262008-05-25 18:19:30 +000013import test.support
Nick Coghlan7bb30b72010-12-03 09:29:11 +000014import time
Ethan Furmanb0c84cd2013-10-20 22:37:39 -070015import types
Nick Coghlan7bb30b72010-12-03 09:29:11 +000016import unittest
Brian Curtin49c284c2010-03-31 03:19:28 +000017import xml.etree
Georg Brandld80d5f42010-12-03 07:47:22 +000018import textwrap
19from io import StringIO
Raymond Hettinger1103d052011-03-25 14:15:24 -070020from collections import namedtuple
Antoine Pitrouf7f54752011-07-15 22:42:12 +020021from test.script_helper import assert_python_ok
Antoine Pitroua6e81a22011-07-15 22:32:25 +020022from test.support import (
Ned Deily92a81a12011-10-06 14:19:03 -070023 TESTFN, rmtree,
Antoine Pitrou916fc7b2013-05-19 15:44:54 +020024 reap_children, reap_threads, captured_output, captured_stdout,
Stefan Krah5de32782014-01-18 23:18:39 +010025 captured_stderr, unlink, requires_docstrings
Antoine Pitroua6e81a22011-07-15 22:32:25 +020026)
Georg Brandlb533e262008-05-25 18:19:30 +000027from test import pydoc_mod
28
Victor Stinner62a68f22011-05-20 02:29:13 +020029try:
30 import threading
31except ImportError:
32 threading = None
33
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020034if test.support.HAVE_DOCSTRINGS:
35 expected_data_docstrings = (
36 'dictionary for instance variables (if defined)',
37 'list of weak references to the object (if defined)',
38 ) * 2
39else:
40 expected_data_docstrings = ('', '', '', '')
41
Barry Warsaw28a691b2010-04-17 00:19:56 +000042expected_text_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +000043NAME
44 test.pydoc_mod - This is a test module for test_pydoc
Georg Brandlb533e262008-05-25 18:19:30 +000045%s
46CLASSES
47 builtins.object
48 A
49 B
Benjamin Petersoned1160b2014-06-07 16:44:00 -070050 C
Georg Brandlb533e262008-05-25 18:19:30 +000051\x20\x20\x20\x20
52 class A(builtins.object)
53 | Hello and goodbye
54 |\x20\x20
55 | Methods defined here:
56 |\x20\x20
57 | __init__()
58 | Wow, I have no function!
59 |\x20\x20
60 | ----------------------------------------------------------------------
61 | Data descriptors defined here:
62 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020063 | __dict__%s
Georg Brandlb533e262008-05-25 18:19:30 +000064 |\x20\x20
Serhiy Storchaka9d0add02013-01-27 19:47:45 +020065 | __weakref__%s
Georg Brandlb533e262008-05-25 18:19:30 +000066\x20\x20\x20\x20
67 class B(builtins.object)
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
74 | ----------------------------------------------------------------------
75 | Data and other attributes defined here:
76 |\x20\x20
77 | NO_MEANING = 'eggs'
Benjamin Petersoned1160b2014-06-07 16:44:00 -070078\x20\x20\x20\x20
79 class C(builtins.object)
80 | Methods defined here:
81 |\x20\x20
82 | get_answer(self)
83 | Return say_no()
84 |\x20\x20
85 | is_it_true(self)
86 | Return self.get_answer()
87 |\x20\x20
88 | say_no(self)
89 |\x20\x20
90 | ----------------------------------------------------------------------
91 | Data descriptors defined here:
92 |\x20\x20
93 | __dict__
94 | dictionary for instance variables (if defined)
95 |\x20\x20
96 | __weakref__
97 | list of weak references to the object (if defined)
Georg Brandlb533e262008-05-25 18:19:30 +000098
99FUNCTIONS
100 doc_func()
101 This function solves all of the world's problems:
102 hunger
103 lack of Python
104 war
105\x20\x20\x20\x20
106 nodoc_func()
107
108DATA
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000109 __xyz__ = 'X, Y and Z'
Georg Brandlb533e262008-05-25 18:19:30 +0000110
111VERSION
112 1.2.3.4
113
114AUTHOR
115 Benjamin Peterson
116
117CREDITS
118 Nobody
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000119
120FILE
121 %s
Georg Brandlb533e262008-05-25 18:19:30 +0000122""".strip()
123
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200124expected_text_data_docstrings = tuple('\n | ' + s if s else ''
125 for s in expected_data_docstrings)
126
Barry Warsaw28a691b2010-04-17 00:19:56 +0000127expected_html_pattern = """
Georg Brandlb533e262008-05-25 18:19:30 +0000128<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
129<tr bgcolor="#7799ee">
130<td valign=bottom>&nbsp;<br>
131<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
132><td align=right valign=bottom
133><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:%s">%s</a>%s</font></td></tr></table>
134 <p><tt>This&nbsp;is&nbsp;a&nbsp;test&nbsp;module&nbsp;for&nbsp;test_pydoc</tt></p>
135<p>
136<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
137<tr bgcolor="#ee77aa">
138<td colspan=3 valign=bottom>&nbsp;<br>
139<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
140\x20\x20\x20\x20
141<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
142<td width="100%%"><dl>
143<dt><font face="helvetica, arial"><a href="builtins.html#object">builtins.object</a>
144</font></dt><dd>
145<dl>
146<dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#A">A</a>
147</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#B">B</a>
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700148</font></dt><dt><font face="helvetica, arial"><a href="test.pydoc_mod.html#C">C</a>
Georg Brandlb533e262008-05-25 18:19:30 +0000149</font></dt></dl>
150</dd>
151</dl>
152 <p>
153<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
154<tr bgcolor="#ffc8d8">
155<td colspan=3 valign=bottom>&nbsp;<br>
156<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>
157\x20\x20\x20\x20
158<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
159<td colspan=2><tt>Hello&nbsp;and&nbsp;goodbye<br>&nbsp;</tt></td></tr>
160<tr><td>&nbsp;</td>
161<td width="100%%">Methods defined here:<br>
162<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>
163
164<hr>
165Data descriptors defined here:<br>
166<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200167<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000168</dl>
169<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200170<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000171</dl>
172</td></tr></table> <p>
173<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
174<tr bgcolor="#ffc8d8">
175<td colspan=3 valign=bottom>&nbsp;<br>
176<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>
177\x20\x20\x20\x20
178<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
179<td width="100%%">Data descriptors defined here:<br>
180<dl><dt><strong>__dict__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200181<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000182</dl>
183<dl><dt><strong>__weakref__</strong></dt>
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200184<dd><tt>%s</tt></dd>
Georg Brandlb533e262008-05-25 18:19:30 +0000185</dl>
186<hr>
187Data and other attributes defined here:<br>
188<dl><dt><strong>NO_MEANING</strong> = 'eggs'</dl>
189
Benjamin Petersoned1160b2014-06-07 16:44:00 -0700190</td></tr></table> <p>
191<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
192<tr bgcolor="#ffc8d8">
193<td colspan=3 valign=bottom>&nbsp;<br>
194<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>
195\x20\x20\x20\x20
196<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
197<td width="100%%">Methods defined here:<br>
198<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>
199
200<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>
201
202<dl><dt><a name="C-say_no"><strong>say_no</strong></a>(self)</dt></dl>
203
204<hr>
205Data descriptors defined here:<br>
206<dl><dt><strong>__dict__</strong></dt>
207<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
208</dl>
209<dl><dt><strong>__weakref__</strong></dt>
210<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
211</dl>
Georg Brandlb533e262008-05-25 18:19:30 +0000212</td></tr></table></td></tr></table><p>
213<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
214<tr bgcolor="#eeaa77">
215<td colspan=3 valign=bottom>&nbsp;<br>
216<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
217\x20\x20\x20\x20
218<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
219<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>
220hunger<br>
221lack&nbsp;of&nbsp;Python<br>
222war</tt></dd></dl>
223 <dl><dt><a name="-nodoc_func"><strong>nodoc_func</strong></a>()</dt></dl>
224</td></tr></table><p>
225<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
226<tr bgcolor="#55aa55">
227<td colspan=3 valign=bottom>&nbsp;<br>
228<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
229\x20\x20\x20\x20
230<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
Alexander Belopolskya47bbf52010-11-18 01:52:54 +0000231<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p>
Georg Brandlb533e262008-05-25 18:19:30 +0000232<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
233<tr bgcolor="#7799ee">
234<td colspan=3 valign=bottom>&nbsp;<br>
235<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
236\x20\x20\x20\x20
237<tr><td bgcolor="#7799ee"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
238<td width="100%%">Benjamin&nbsp;Peterson</td></tr></table><p>
239<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>Credits</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%%">Nobody</td></tr></table>
Barry Warsaw28a691b2010-04-17 00:19:56 +0000246""".strip() # ' <- emacs turd
Georg Brandlb533e262008-05-25 18:19:30 +0000247
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200248expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;')
249 for s in expected_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000250
251# output pattern for missing module
252missing_pattern = "no Python documentation found for '%s'"
253
Benjamin Peterson0289b152009-06-28 17:22:03 +0000254# output pattern for module with bad imports
Brett Cannon679ecb52013-07-04 17:51:50 -0400255badimport_pattern = "problem in %s - ImportError: No module named %r"
Benjamin Peterson0289b152009-06-28 17:22:03 +0000256
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700257expected_dynamicattribute_pattern = """
258Help on class DA in module %s:
259
260class DA(builtins.object)
261 | Data descriptors defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200262 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700263 | __dict__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200264 |\x20\x20
Ethan Furman3f2f1922013-10-22 07:30:24 -0700265 | __weakref__%s
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200266 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700267 | ham
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200268 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700269 | ----------------------------------------------------------------------
270 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200271 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700272 | ham = 'spam'
273""".strip()
274
275expected_virtualattribute_pattern1 = """
276Help on class Class in module %s:
277
278class Class(builtins.object)
279 | Data and other attributes inherited from Meta:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200280 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700281 | LIFE = 42
282""".strip()
283
284expected_virtualattribute_pattern2 = """
285Help on class Class1 in module %s:
286
287class Class1(builtins.object)
288 | Data and other attributes inherited from Meta1:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200289 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700290 | one = 1
291""".strip()
292
293expected_virtualattribute_pattern3 = """
294Help on class Class2 in module %s:
295
296class Class2(Class1)
297 | Method resolution order:
298 | Class2
299 | Class1
300 | builtins.object
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200301 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700302 | Data and other attributes inherited from Meta1:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200303 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700304 | one = 1
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200305 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700306 | ----------------------------------------------------------------------
307 | Data and other attributes inherited from Meta3:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200308 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700309 | three = 3
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200310 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700311 | ----------------------------------------------------------------------
312 | Data and other attributes inherited from Meta2:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200313 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700314 | two = 2
315""".strip()
316
317expected_missingattribute_pattern = """
318Help on class C in module %s:
319
320class C(builtins.object)
321 | Data and other attributes defined here:
Charles-François Natali1a82f7e2013-10-21 14:46:34 +0200322 |\x20\x20
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700323 | here = 'present!'
324""".strip()
325
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200326def run_pydoc(module_name, *args, **env):
Georg Brandlb533e262008-05-25 18:19:30 +0000327 """
328 Runs pydoc on the specified module. Returns the stripped
329 output of pydoc.
330 """
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200331 args = args + (module_name,)
Ned Deily92a81a12011-10-06 14:19:03 -0700332 # do not write bytecode files to avoid caching errors
333 rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
Antoine Pitrouf7f54752011-07-15 22:42:12 +0200334 return out.strip()
Georg Brandlb533e262008-05-25 18:19:30 +0000335
336def get_pydoc_html(module):
337 "Returns pydoc generated output as html"
338 doc = pydoc.HTMLDoc()
339 output = doc.docmodule(module)
340 loc = doc.getdocloc(pydoc_mod) or ""
341 if loc:
342 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
343 return output.strip(), loc
344
345def get_pydoc_text(module):
346 "Returns pydoc generated output as text"
347 doc = pydoc.TextDoc()
348 loc = doc.getdocloc(pydoc_mod) or ""
349 if loc:
350 loc = "\nMODULE DOCS\n " + loc + "\n"
351
352 output = doc.docmodule(module)
353
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000354 # clean up the extra text formatting that pydoc performs
Georg Brandlb533e262008-05-25 18:19:30 +0000355 patt = re.compile('\b.')
356 output = patt.sub('', output)
357 return output.strip(), loc
358
359def print_diffs(text1, text2):
360 "Prints unified diffs for two texts"
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000361 # XXX now obsolete, use unittest built-in support
Ezio Melottid8b509b2011-09-28 17:37:55 +0300362 lines1 = text1.splitlines(keepends=True)
363 lines2 = text2.splitlines(keepends=True)
Georg Brandlb533e262008-05-25 18:19:30 +0000364 diffs = difflib.unified_diff(lines1, lines2, n=0, fromfile='expected',
365 tofile='got')
366 print('\n' + ''.join(diffs))
367
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000368def get_html_title(text):
Nick Coghlanecace282010-12-03 16:08:46 +0000369 # Bit of hack, but good enough for test purposes
370 header, _, _ = text.partition("</head>")
371 _, _, title = header.partition("<title>")
372 title, _, _ = title.partition("</title>")
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000373 return title
374
Georg Brandlb533e262008-05-25 18:19:30 +0000375
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200376class PydocBaseTest(unittest.TestCase):
377
378 def _restricted_walk_packages(self, walk_packages, path=None):
379 """
380 A version of pkgutil.walk_packages() that will restrict itself to
381 a given path.
382 """
383 default_path = path or [os.path.dirname(__file__)]
384 def wrapper(path=None, prefix='', onerror=None):
385 return walk_packages(path or default_path, prefix, onerror)
386 return wrapper
387
388 @contextlib.contextmanager
389 def restrict_walk_packages(self, path=None):
390 walk_packages = pkgutil.walk_packages
391 pkgutil.walk_packages = self._restricted_walk_packages(walk_packages,
392 path)
393 try:
394 yield
395 finally:
396 pkgutil.walk_packages = walk_packages
397
398
Georg Brandld2f38572011-01-30 08:37:19 +0000399class PydocDocTest(unittest.TestCase):
Georg Brandlb533e262008-05-25 18:19:30 +0000400
R. David Murray378c0cf2010-02-24 01:46:21 +0000401 @unittest.skipIf(sys.flags.optimize >= 2,
402 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000403 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
404 'trace function introduces __locals__ unexpectedly')
Georg Brandlb533e262008-05-25 18:19:30 +0000405 def test_html_doc(self):
406 result, doc_loc = get_pydoc_html(pydoc_mod)
407 mod_file = inspect.getabsfile(pydoc_mod)
Benjamin Petersonc5e94642008-06-14 23:04:46 +0000408 if sys.platform == 'win32':
409 import nturl2path
410 mod_url = nturl2path.pathname2url(mod_file)
411 else:
412 mod_url = mod_file
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200413 expected_html = expected_html_pattern % (
414 (mod_url, mod_file, doc_loc) +
415 expected_html_data_docstrings)
Georg Brandlb533e262008-05-25 18:19:30 +0000416 if result != expected_html:
417 print_diffs(expected_html, result)
418 self.fail("outputs are not equal, see diff above")
419
R. David Murray378c0cf2010-02-24 01:46:21 +0000420 @unittest.skipIf(sys.flags.optimize >= 2,
421 "Docstrings are omitted with -O2 and above")
Brett Cannon7a540732011-02-22 03:04:06 +0000422 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
423 'trace function introduces __locals__ unexpectedly')
Georg Brandlb533e262008-05-25 18:19:30 +0000424 def test_text_doc(self):
425 result, doc_loc = get_pydoc_text(pydoc_mod)
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200426 expected_text = expected_text_pattern % (
427 (doc_loc,) +
428 expected_text_data_docstrings +
429 (inspect.getabsfile(pydoc_mod),))
Georg Brandlb533e262008-05-25 18:19:30 +0000430 if result != expected_text:
431 print_diffs(expected_text, result)
432 self.fail("outputs are not equal, see diff above")
433
Serhiy Storchaka056eb022014-02-19 23:05:12 +0200434 def test_text_enum_member_with_value_zero(self):
435 # Test issue #20654 to ensure enum member with value 0 can be
436 # displayed. It used to throw KeyError: 'zero'.
437 import enum
438 class BinaryInteger(enum.IntEnum):
439 zero = 0
440 one = 1
441 doc = pydoc.render_doc(BinaryInteger)
442 self.assertIn('<BinaryInteger.zero: 0>', doc)
443
Brian Curtin49c284c2010-03-31 03:19:28 +0000444 def test_issue8225(self):
445 # Test issue8225 to ensure no doc link appears for xml.etree
446 result, doc_loc = get_pydoc_text(xml.etree)
447 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
448
Benjamin Peterson159824e2014-06-07 20:14:26 -0700449 def test_getpager_with_stdin_none(self):
450 previous_stdin = sys.stdin
451 try:
452 sys.stdin = None
453 pydoc.getpager() # Shouldn't fail.
454 finally:
455 sys.stdin = previous_stdin
456
R David Murrayc43125a2012-04-23 13:23:57 -0400457 def test_non_str_name(self):
458 # issue14638
459 # Treat illegal (non-str) name like no name
460 class A:
461 __name__ = 42
462 class B:
463 pass
464 adoc = pydoc.render_doc(A())
465 bdoc = pydoc.render_doc(B())
466 self.assertEqual(adoc.replace("A", "B"), bdoc)
467
Georg Brandlb533e262008-05-25 18:19:30 +0000468 def test_not_here(self):
469 missing_module = "test.i_am_not_here"
470 result = str(run_pydoc(missing_module), 'ascii')
471 expected = missing_pattern % missing_module
472 self.assertEqual(expected, result,
473 "documentation for missing module found")
474
R. David Murray1f1b9d32009-05-27 20:56:59 +0000475 def test_input_strip(self):
476 missing_module = " test.i_am_not_here "
477 result = str(run_pydoc(missing_module), 'ascii')
478 expected = missing_pattern % missing_module.strip()
479 self.assertEqual(expected, result)
480
Ezio Melotti412c95a2010-02-16 23:31:04 +0000481 def test_stripid(self):
482 # test with strings, other implementations might have different repr()
483 stripid = pydoc.stripid
484 # strip the id
485 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
486 '<function stripid>')
487 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
488 '<function stripid>')
489 # nothing to strip, return the same text
490 self.assertEqual(stripid('42'), '42')
491 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
492 "<type 'exceptions.Exception'>")
493
Georg Brandld80d5f42010-12-03 07:47:22 +0000494 @unittest.skipIf(sys.flags.optimize >= 2,
495 'Docstrings are omitted with -O2 and above')
Brett Cannon7a540732011-02-22 03:04:06 +0000496 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
497 'trace function introduces __locals__ unexpectedly')
Georg Brandld80d5f42010-12-03 07:47:22 +0000498 def test_help_output_redirect(self):
499 # issue 940286, if output is set in Helper, then all output from
500 # Helper.help should be redirected
501 old_pattern = expected_text_pattern
502 getpager_old = pydoc.getpager
503 getpager_new = lambda: (lambda x: x)
504 self.maxDiff = None
505
506 buf = StringIO()
507 helper = pydoc.Helper(output=buf)
508 unused, doc_loc = get_pydoc_text(pydoc_mod)
509 module = "test.pydoc_mod"
510 help_header = """
511 Help on module test.pydoc_mod in test:
512
513 """.lstrip()
514 help_header = textwrap.dedent(help_header)
515 expected_help_pattern = help_header + expected_text_pattern
516
517 pydoc.getpager = getpager_new
518 try:
519 with captured_output('stdout') as output, \
520 captured_output('stderr') as err:
521 helper.help(module)
522 result = buf.getvalue().strip()
Serhiy Storchaka9d0add02013-01-27 19:47:45 +0200523 expected_text = expected_help_pattern % (
524 (doc_loc,) +
525 expected_text_data_docstrings +
526 (inspect.getabsfile(pydoc_mod),))
Georg Brandld80d5f42010-12-03 07:47:22 +0000527 self.assertEqual('', output.getvalue())
528 self.assertEqual('', err.getvalue())
529 self.assertEqual(expected_text, result)
530 finally:
531 pydoc.getpager = getpager_old
532
Raymond Hettinger1103d052011-03-25 14:15:24 -0700533 def test_namedtuple_public_underscore(self):
534 NT = namedtuple('NT', ['abc', 'def'], rename=True)
535 with captured_stdout() as help_io:
Terry Jan Reedy5c811642013-11-04 21:43:26 -0500536 pydoc.help(NT)
Raymond Hettinger1103d052011-03-25 14:15:24 -0700537 helptext = help_io.getvalue()
538 self.assertIn('_1', helptext)
539 self.assertIn('_replace', helptext)
540 self.assertIn('_asdict', helptext)
541
Victor Stinnere6c910e2011-06-30 15:55:43 +0200542 def test_synopsis(self):
543 self.addCleanup(unlink, TESTFN)
544 for encoding in ('ISO-8859-1', 'UTF-8'):
545 with open(TESTFN, 'w', encoding=encoding) as script:
546 if encoding != 'UTF-8':
547 print('#coding: {}'.format(encoding), file=script)
548 print('"""line 1: h\xe9', file=script)
549 print('line 2: hi"""', file=script)
550 synopsis = pydoc.synopsis(TESTFN, {})
551 self.assertEqual(synopsis, 'line 1: h\xe9')
552
Eric Snowaed5b222014-01-04 20:38:11 -0700553 def test_synopsis_sourceless(self):
554 expected = os.__doc__.splitlines()[0]
555 filename = os.__cached__
556 synopsis = pydoc.synopsis(filename)
557
558 self.assertEqual(synopsis, expected)
559
R David Murray455f2962013-03-19 00:00:33 -0400560 def test_splitdoc_with_description(self):
561 example_string = "I Am A Doc\n\n\nHere is my description"
562 self.assertEqual(pydoc.splitdoc(example_string),
563 ('I Am A Doc', '\nHere is my description'))
564
565 def test_is_object_or_method(self):
566 doc = pydoc.Doc()
567 # Bound Method
568 self.assertTrue(pydoc._is_some_method(doc.fail))
569 # Method Descriptor
570 self.assertTrue(pydoc._is_some_method(int.__add__))
571 # String
572 self.assertFalse(pydoc._is_some_method("I am not a method"))
573
574 def test_is_package_when_not_package(self):
575 with test.support.temp_cwd() as test_dir:
576 self.assertFalse(pydoc.ispackage(test_dir))
577
578 def test_is_package_when_is_package(self):
579 with test.support.temp_cwd() as test_dir:
580 init_path = os.path.join(test_dir, '__init__.py')
581 open(init_path, 'w').close()
582 self.assertTrue(pydoc.ispackage(test_dir))
583 os.remove(init_path)
584
R David Murrayac0cea52013-03-19 02:47:44 -0400585 def test_allmethods(self):
586 # issue 17476: allmethods was no longer returning unbound methods.
587 # This test is a bit fragile in the face of changes to object and type,
588 # but I can't think of a better way to do it without duplicating the
589 # logic of the function under test.
590
591 class TestClass(object):
592 def method_returning_true(self):
593 return True
594
595 # What we expect to get back: everything on object...
596 expected = dict(vars(object))
597 # ...plus our unbound method...
598 expected['method_returning_true'] = TestClass.method_returning_true
599 # ...but not the non-methods on object.
600 del expected['__doc__']
601 del expected['__class__']
602 # inspect resolves descriptors on type into methods, but vars doesn't,
603 # so we need to update __subclasshook__.
604 expected['__subclasshook__'] = TestClass.__subclasshook__
605
606 methods = pydoc.allmethods(TestClass)
607 self.assertDictEqual(methods, expected)
608
Georg Brandlb533e262008-05-25 18:19:30 +0000609
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200610class PydocImportTest(PydocBaseTest):
Ned Deily92a81a12011-10-06 14:19:03 -0700611
612 def setUp(self):
613 self.test_dir = os.mkdir(TESTFN)
614 self.addCleanup(rmtree, TESTFN)
615
616 def test_badimport(self):
617 # This tests the fix for issue 5230, where if pydoc found the module
618 # but the module had an internal import error pydoc would report no doc
619 # found.
620 modname = 'testmod_xyzzy'
621 testpairs = (
622 ('i_am_not_here', 'i_am_not_here'),
Brett Cannonfd074152012-04-14 14:10:13 -0400623 ('test.i_am_not_here_either', 'test.i_am_not_here_either'),
624 ('test.i_am_not_here.neither_am_i', 'test.i_am_not_here'),
625 ('i_am_not_here.{}'.format(modname), 'i_am_not_here'),
626 ('test.{}'.format(modname), 'test.{}'.format(modname)),
Ned Deily92a81a12011-10-06 14:19:03 -0700627 )
628
629 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
630 for importstring, expectedinmsg in testpairs:
631 with open(sourcefn, 'w') as f:
632 f.write("import {}\n".format(importstring))
633 result = run_pydoc(modname, PYTHONPATH=TESTFN).decode("ascii")
634 expected = badimport_pattern % (modname, expectedinmsg)
635 self.assertEqual(expected, result)
636
637 def test_apropos_with_bad_package(self):
638 # Issue 7425 - pydoc -k failed when bad package on path
639 pkgdir = os.path.join(TESTFN, "syntaxerr")
640 os.mkdir(pkgdir)
641 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
642 with open(badsyntax, 'w') as f:
643 f.write("invalid python syntax = $1\n")
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200644 with self.restrict_walk_packages(path=[TESTFN]):
645 with captured_stdout() as out:
646 with captured_stderr() as err:
647 pydoc.apropos('xyzzy')
648 # No result, no error
649 self.assertEqual(out.getvalue(), '')
650 self.assertEqual(err.getvalue(), '')
651 # The package name is still matched
652 with captured_stdout() as out:
653 with captured_stderr() as err:
654 pydoc.apropos('syntaxerr')
655 self.assertEqual(out.getvalue().strip(), 'syntaxerr')
656 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700657
658 def test_apropos_with_unreadable_dir(self):
659 # Issue 7367 - pydoc -k failed when unreadable dir on path
660 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
661 os.mkdir(self.unreadable_dir, 0)
662 self.addCleanup(os.rmdir, self.unreadable_dir)
663 # Note, on Windows the directory appears to be still
664 # readable so this is not really testing the issue there
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200665 with self.restrict_walk_packages(path=[TESTFN]):
666 with captured_stdout() as out:
667 with captured_stderr() as err:
668 pydoc.apropos('SOMEKEY')
669 # No result, no error
670 self.assertEqual(out.getvalue(), '')
671 self.assertEqual(err.getvalue(), '')
Ned Deily92a81a12011-10-06 14:19:03 -0700672
Eric Snowa46ef702014-02-22 13:57:08 -0700673 @unittest.skip('causes undesireable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700674 def test_modules(self):
675 # See Helper.listmodules().
676 num_header_lines = 2
677 num_module_lines_min = 5 # Playing it safe.
678 num_footer_lines = 3
679 expected = num_header_lines + num_module_lines_min + num_footer_lines
680
681 output = StringIO()
682 helper = pydoc.Helper(output=output)
683 helper('modules')
684 result = output.getvalue().strip()
685 num_lines = len(result.splitlines())
686
687 self.assertGreaterEqual(num_lines, expected)
688
Eric Snowa46ef702014-02-22 13:57:08 -0700689 @unittest.skip('causes undesireable side-effects (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700690 def test_modules_search(self):
691 # See Helper.listmodules().
692 expected = 'pydoc - '
693
694 output = StringIO()
695 helper = pydoc.Helper(output=output)
696 with captured_stdout() as help_io:
697 helper('modules pydoc')
698 result = help_io.getvalue()
699
700 self.assertIn(expected, result)
701
Eric Snowa46ef702014-02-22 13:57:08 -0700702 @unittest.skip('some buildbots are not cooperating (#20128)')
Eric Snowaed5b222014-01-04 20:38:11 -0700703 def test_modules_search_builtin(self):
Eric Snow5ea97502014-01-04 23:04:27 -0700704 expected = 'gc - '
Eric Snowaed5b222014-01-04 20:38:11 -0700705
706 output = StringIO()
707 helper = pydoc.Helper(output=output)
708 with captured_stdout() as help_io:
Eric Snow5ea97502014-01-04 23:04:27 -0700709 helper('modules garbage')
Eric Snowaed5b222014-01-04 20:38:11 -0700710 result = help_io.getvalue()
711
712 self.assertTrue(result.startswith(expected))
713
714 def test_importfile(self):
715 loaded_pydoc = pydoc.importfile(pydoc.__file__)
716
Eric Snow3a62d142014-01-06 20:42:59 -0700717 self.assertIsNot(loaded_pydoc, pydoc)
Eric Snowaed5b222014-01-04 20:38:11 -0700718 self.assertEqual(loaded_pydoc.__name__, 'pydoc')
719 self.assertEqual(loaded_pydoc.__file__, pydoc.__file__)
Eric Snow3a62d142014-01-06 20:42:59 -0700720 self.assertEqual(loaded_pydoc.__spec__, pydoc.__spec__)
Eric Snowaed5b222014-01-04 20:38:11 -0700721
Ned Deily92a81a12011-10-06 14:19:03 -0700722
Georg Brandlb533e262008-05-25 18:19:30 +0000723class TestDescriptions(unittest.TestCase):
724
725 def test_module(self):
726 # Check that pydocfodder module can be described
727 from test import pydocfodder
728 doc = pydoc.render_doc(pydocfodder)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000729 self.assertIn("pydocfodder", doc)
Georg Brandlb533e262008-05-25 18:19:30 +0000730
Georg Brandlb533e262008-05-25 18:19:30 +0000731 def test_class(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000732 class C: "New-style class"
Georg Brandlb533e262008-05-25 18:19:30 +0000733 c = C()
734
735 self.assertEqual(pydoc.describe(C), 'class C')
736 self.assertEqual(pydoc.describe(c), 'C')
737 expected = 'C in module %s object' % __name__
Benjamin Peterson577473f2010-01-19 00:09:57 +0000738 self.assertIn(expected, pydoc.render_doc(c))
Georg Brandlb533e262008-05-25 18:19:30 +0000739
Éric Araujoe64e51b2011-07-29 17:03:55 +0200740 def test_builtin(self):
741 for name in ('str', 'str.translate', 'builtins.str',
742 'builtins.str.translate'):
743 # test low-level function
744 self.assertIsNotNone(pydoc.locate(name))
745 # test high-level function
746 try:
747 pydoc.render_doc(name)
748 except ImportError:
Terry Jan Reedyfe928de2014-06-20 14:59:11 -0400749 self.fail('finding the doc of {!r} failed'.format(name))
Éric Araujoe64e51b2011-07-29 17:03:55 +0200750
751 for name in ('notbuiltins', 'strrr', 'strr.translate',
752 'str.trrrranslate', 'builtins.strrr',
753 'builtins.str.trrranslate'):
754 self.assertIsNone(pydoc.locate(name))
755 self.assertRaises(ImportError, pydoc.render_doc, name)
756
Larry Hastings24a882b2014-02-20 23:34:46 -0800757 @staticmethod
758 def _get_summary_line(o):
759 text = pydoc.plain(pydoc.render_doc(o))
760 lines = text.split('\n')
761 assert len(lines) >= 2
762 return lines[2]
763
764 # these should include "self"
765 def test_unbound_python_method(self):
766 self.assertEqual(self._get_summary_line(textwrap.TextWrapper.wrap),
767 "wrap(self, text)")
768
Stefan Krah5de32782014-01-18 23:18:39 +0100769 @requires_docstrings
Larry Hastings24a882b2014-02-20 23:34:46 -0800770 def test_unbound_builtin_method(self):
771 self.assertEqual(self._get_summary_line(_pickle.Pickler.dump),
772 "dump(self, obj, /)")
773
774 # these no longer include "self"
775 def test_bound_python_method(self):
776 t = textwrap.TextWrapper()
777 self.assertEqual(self._get_summary_line(t.wrap),
778 "wrap(text) method of textwrap.TextWrapper instance")
779
780 @requires_docstrings
781 def test_bound_builtin_method(self):
782 s = StringIO()
783 p = _pickle.Pickler(s)
784 self.assertEqual(self._get_summary_line(p.dump),
785 "dump(obj, /) method of _pickle.Pickler instance")
786
787 # this should *never* include self!
788 @requires_docstrings
789 def test_module_level_callable(self):
790 self.assertEqual(self._get_summary_line(os.stat),
791 "stat(path, *, dir_fd=None, follow_symlinks=True)")
Larry Hastings1abd7082014-01-16 14:15:03 -0800792
Georg Brandlb533e262008-05-25 18:19:30 +0000793
Victor Stinner62a68f22011-05-20 02:29:13 +0200794@unittest.skipUnless(threading, 'Threading required for this test.')
Georg Brandld2f38572011-01-30 08:37:19 +0000795class PydocServerTest(unittest.TestCase):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000796 """Tests for pydoc._start_server"""
797
798 def test_server(self):
799
800 # Minimal test that starts the server, then stops it.
801 def my_url_handler(url, content_type):
802 text = 'the URL sent was: (%s, %s)' % (url, content_type)
803 return text
804
805 serverthread = pydoc._start_server(my_url_handler, port=0)
806 starttime = time.time()
807 timeout = 1 #seconds
808
809 while serverthread.serving:
810 time.sleep(.01)
811 if serverthread.serving and time.time() - starttime > timeout:
812 serverthread.stop()
813 break
814
815 self.assertEqual(serverthread.error, None)
816
817
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200818class PydocUrlHandlerTest(PydocBaseTest):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000819 """Tests for pydoc._url_handler"""
820
821 def test_content_type_err(self):
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000822 f = pydoc._url_handler
Georg Brandld2f38572011-01-30 08:37:19 +0000823 self.assertRaises(TypeError, f, 'A', '')
824 self.assertRaises(TypeError, f, 'B', 'foobar')
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000825
826 def test_url_requests(self):
827 # Test for the correct title in the html pages returned.
828 # This tests the different parts of the URL handler without
829 # getting too picky about the exact html.
830 requests = [
Georg Brandld2f38572011-01-30 08:37:19 +0000831 ("", "Pydoc: Index of Modules"),
832 ("get?key=", "Pydoc: Index of Modules"),
833 ("index", "Pydoc: Index of Modules"),
834 ("topics", "Pydoc: Topics"),
835 ("keywords", "Pydoc: Keywords"),
836 ("pydoc", "Pydoc: module pydoc"),
837 ("get?key=pydoc", "Pydoc: module pydoc"),
838 ("search?key=pydoc", "Pydoc: Search Results"),
839 ("topic?key=def", "Pydoc: KEYWORD def"),
840 ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
841 ("foobar", "Pydoc: Error - foobar"),
842 ("getfile?key=foobar", "Pydoc: Error - getfile?key=foobar"),
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000843 ]
844
Antoine Pitrou916fc7b2013-05-19 15:44:54 +0200845 with self.restrict_walk_packages():
846 for url, title in requests:
847 text = pydoc._url_handler(url, "text/html")
848 result = get_html_title(text)
849 self.assertEqual(result, title, text)
850
851 path = string.__file__
852 title = "Pydoc: getfile " + path
853 url = "getfile?key=" + path
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000854 text = pydoc._url_handler(url, "text/html")
855 result = get_html_title(text)
856 self.assertEqual(result, title)
857
Nick Coghlan7bb30b72010-12-03 09:29:11 +0000858
Ezio Melottib185a042011-04-28 07:42:55 +0300859class TestHelper(unittest.TestCase):
860 def test_keywords(self):
861 self.assertEqual(sorted(pydoc.Helper.keywords),
862 sorted(keyword.kwlist))
863
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700864class PydocWithMetaClasses(unittest.TestCase):
Ethan Furman3f2f1922013-10-22 07:30:24 -0700865 @unittest.skipIf(sys.flags.optimize >= 2,
866 "Docstrings are omitted with -O2 and above")
867 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
868 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700869 def test_DynamicClassAttribute(self):
870 class Meta(type):
871 def __getattr__(self, name):
872 if name == 'ham':
873 return 'spam'
874 return super().__getattr__(name)
875 class DA(metaclass=Meta):
876 @types.DynamicClassAttribute
877 def ham(self):
878 return 'eggs'
Ethan Furman3f2f1922013-10-22 07:30:24 -0700879 expected_text_data_docstrings = tuple('\n | ' + s if s else ''
880 for s in expected_data_docstrings)
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700881 output = StringIO()
882 helper = pydoc.Helper(output=output)
883 helper(DA)
Ethan Furman3f2f1922013-10-22 07:30:24 -0700884 expected_text = expected_dynamicattribute_pattern % (
885 (__name__,) + expected_text_data_docstrings[:2])
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700886 result = output.getvalue().strip()
887 if result != expected_text:
888 print_diffs(expected_text, result)
889 self.fail("outputs are not equal, see diff above")
890
Ethan Furman3f2f1922013-10-22 07:30:24 -0700891 @unittest.skipIf(sys.flags.optimize >= 2,
892 "Docstrings are omitted with -O2 and above")
893 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
894 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700895 def test_virtualClassAttributeWithOneMeta(self):
896 class Meta(type):
897 def __dir__(cls):
898 return ['__class__', '__module__', '__name__', 'LIFE']
899 def __getattr__(self, name):
900 if name =='LIFE':
901 return 42
902 return super().__getattr(name)
903 class Class(metaclass=Meta):
904 pass
905 output = StringIO()
906 helper = pydoc.Helper(output=output)
907 helper(Class)
908 expected_text = expected_virtualattribute_pattern1 % __name__
909 result = output.getvalue().strip()
910 if result != expected_text:
911 print_diffs(expected_text, result)
912 self.fail("outputs are not equal, see diff above")
913
Ethan Furman3f2f1922013-10-22 07:30:24 -0700914 @unittest.skipIf(sys.flags.optimize >= 2,
915 "Docstrings are omitted with -O2 and above")
916 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
917 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700918 def test_virtualClassAttributeWithTwoMeta(self):
919 class Meta1(type):
920 def __dir__(cls):
921 return ['__class__', '__module__', '__name__', 'one']
922 def __getattr__(self, name):
923 if name =='one':
924 return 1
925 return super().__getattr__(name)
926 class Meta2(type):
927 def __dir__(cls):
928 return ['__class__', '__module__', '__name__', 'two']
929 def __getattr__(self, name):
930 if name =='two':
931 return 2
932 return super().__getattr__(name)
933 class Meta3(Meta1, Meta2):
934 def __dir__(cls):
935 return list(sorted(set(
936 ['__class__', '__module__', '__name__', 'three'] +
937 Meta1.__dir__(cls) + Meta2.__dir__(cls))))
938 def __getattr__(self, name):
939 if name =='three':
940 return 3
941 return super().__getattr__(name)
942 class Class1(metaclass=Meta1):
943 pass
944 class Class2(Class1, metaclass=Meta3):
945 pass
946 fail1 = fail2 = False
947 output = StringIO()
948 helper = pydoc.Helper(output=output)
949 helper(Class1)
950 expected_text1 = expected_virtualattribute_pattern2 % __name__
951 result1 = output.getvalue().strip()
952 if result1 != expected_text1:
953 print_diffs(expected_text1, result1)
954 fail1 = True
955 output = StringIO()
956 helper = pydoc.Helper(output=output)
957 helper(Class2)
958 expected_text2 = expected_virtualattribute_pattern3 % __name__
959 result2 = output.getvalue().strip()
960 if result2 != expected_text2:
961 print_diffs(expected_text2, result2)
962 fail2 = True
963 if fail1 or fail2:
964 self.fail("outputs are not equal, see diff above")
965
Ethan Furman3f2f1922013-10-22 07:30:24 -0700966 @unittest.skipIf(sys.flags.optimize >= 2,
967 "Docstrings are omitted with -O2 and above")
968 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
969 'trace function introduces __locals__ unexpectedly')
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700970 def test_buggy_dir(self):
971 class M(type):
972 def __dir__(cls):
973 return ['__class__', '__name__', 'missing', 'here']
974 class C(metaclass=M):
975 here = 'present!'
976 output = StringIO()
977 helper = pydoc.Helper(output=output)
978 helper(C)
979 expected_text = expected_missingattribute_pattern % __name__
980 result = output.getvalue().strip()
981 if result != expected_text:
982 print_diffs(expected_text, result)
983 self.fail("outputs are not equal, see diff above")
984
Eric Snowaed5b222014-01-04 20:38:11 -0700985
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200986@reap_threads
Georg Brandlb533e262008-05-25 18:19:30 +0000987def test_main():
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200988 try:
989 test.support.run_unittest(PydocDocTest,
Ned Deily92a81a12011-10-06 14:19:03 -0700990 PydocImportTest,
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200991 TestDescriptions,
992 PydocServerTest,
993 PydocUrlHandlerTest,
994 TestHelper,
Ethan Furmanb0c84cd2013-10-20 22:37:39 -0700995 PydocWithMetaClasses,
Antoine Pitroua6e81a22011-07-15 22:32:25 +0200996 )
997 finally:
998 reap_children()
Georg Brandlb533e262008-05-25 18:19:30 +0000999
1000if __name__ == "__main__":
1001 test_main()