Debian Codegraph @

Lib/test/test_pydoc/test_pydoc.py

raw
1 import datetime
2 import os
3 import sys
4 import contextlib
5 import importlib.util
6 import inspect
7 import io
8 import pydoc
9 import py_compile
10 import keyword
11 import _pickle
12 import pkgutil
13 import re
14 import stat
15 import tempfile
16 import test.support
17 import time
18 import types
19 import typing
20 import unittest
21 import unittest.mock
22 import urllib.parse
23 import xml.etree
24 import xml.etree.ElementTree
25 import textwrap
26 from io import StringIO
27 from collections import namedtuple
28 from urllib.request import urlopen, urlcleanup
29 from test import support
30 from test.support import import_helper
31 from test.support import os_helper
32 from test.support.script_helper import (assert_python_ok,
33 assert_python_failure, spawn_python)
34 from test.support import threading_helper
35 from test.support import (reap_children, captured_stdout,
36 captured_stderr, is_emscripten, is_wasi,
37 requires_docstrings, MISSING_C_DOCSTRINGS)
38 from test.support.os_helper import (TESTFN, rmtree, unlink)
39 from test.test_pydoc import pydoc_mod
40 from test.test_pydoc import pydocfodder
41
42
43 class nonascii:
44 'Це не латиниця'
45 pass
46
47 if test.support.HAVE_DOCSTRINGS:
48 expected_data_docstrings = (
49 'dictionary for instance variables',
50 'list of weak references to the object',
51 ) * 2
52 else:
53 expected_data_docstrings = ('', '', '', '')
54
55 expected_text_pattern = """
56 NAME
57 test.test_pydoc.pydoc_mod - This is a test module for test_pydoc
58 %s
59 CLASSES
60 builtins.object
61 A
62 B
63 C
64
65 class A(builtins.object)
66 | Hello and goodbye
67 |
68 | Methods defined here:
69 |
70 | __init__()
71 | Wow, I have no function!
72 |
73 | ----------------------------------------------------------------------
74 | Data descriptors defined here:
75 |
76 | __dict__%s
77 |
78 | __weakref__%s
79
80 class B(builtins.object)
81 | Data descriptors defined here:
82 |
83 | __dict__%s
84 |
85 | __weakref__%s
86 |
87 | ----------------------------------------------------------------------
88 | Data and other attributes defined here:
89 |
90 | NO_MEANING = 'eggs'
91 |
92 | __annotations__ = {'NO_MEANING': <class 'str'>}
93
94 class C(builtins.object)
95 | Methods defined here:
96 |
97 | get_answer(self)
98 | Return say_no()
99 |
100 | is_it_true(self)
101 | Return self.get_answer()
102 |
103 | say_no(self)
104 |
105 | ----------------------------------------------------------------------
106 | Class methods defined here:
107 |
108 | __class_getitem__(item)
109 |
110 | ----------------------------------------------------------------------
111 | Data descriptors defined here:
112 |
113 | __dict__
114 | dictionary for instance variables
115 |
116 | __weakref__
117 | list of weak references to the object
118
119 FUNCTIONS
120 doc_func()
121 This function solves all of the world's problems:
122 hunger
123 lack of Python
124 war
125
126 nodoc_func()
127
128 DATA
129 __xyz__ = 'X, Y and Z'
130 c_alias = test.test_pydoc.pydoc_mod.C[int]
131 list_alias1 = typing.List[int]
132 list_alias2 = list[int]
133 type_union1 = typing.Union[int, str]
134 type_union2 = int | str
135
136 VERSION
137 1.2.3.4
138
139 AUTHOR
140 Benjamin Peterson
141
142 CREDITS
143 Nobody
144
145 FILE
146 %s
147 """.strip()
148
149 expected_text_data_docstrings = tuple('\n | ' + s if s else ''
150 for s in expected_data_docstrings)
151
152 html2text_of_expected = """
153 test.test_pydoc.pydoc_mod (version 1.2.3.4)
154 This is a test module for test_pydoc
155
156 Modules
157 types
158 typing
159
160 Classes
161 builtins.object
162 A
163 B
164 C
165
166 class A(builtins.object)
167 Hello and goodbye
168
169 Methods defined here:
170 __init__()
171 Wow, I have no function!
172 ----------------------------------------------------------------------
173 Data descriptors defined here:
174 __dict__
175 dictionary for instance variables
176 __weakref__
177 list of weak references to the object
178
179 class B(builtins.object)
180 Data descriptors defined here:
181 __dict__
182 dictionary for instance variables
183 __weakref__
184 list of weak references to the object
185 ----------------------------------------------------------------------
186 Data and other attributes defined here:
187 NO_MEANING = 'eggs'
188 __annotations__ = {'NO_MEANING': <class 'str'>}
189
190
191 class C(builtins.object)
192 Methods defined here:
193 get_answer(self)
194 Return say_no()
195 is_it_true(self)
196 Return self.get_answer()
197 say_no(self)
198 ----------------------------------------------------------------------
199 Class methods defined here:
200 __class_getitem__(item)
201 ----------------------------------------------------------------------
202 Data descriptors defined here:
203 __dict__
204 dictionary for instance variables
205 __weakref__
206 list of weak references to the object
207
208 Functions
209 doc_func()
210 This function solves all of the world's problems:
211 hunger
212 lack of Python
213 war
214 nodoc_func()
215
216 Data
217 __xyz__ = 'X, Y and Z'
218 c_alias = test.test_pydoc.pydoc_mod.C[int]
219 list_alias1 = typing.List[int]
220 list_alias2 = list[int]
221 type_union1 = typing.Union[int, str]
222 type_union2 = int | str
223
224 Author
225 Benjamin Peterson
226
227 Credits
228 Nobody
229 """
230
231 expected_html_data_docstrings = tuple(s.replace(' ', '&nbsp;')
232 for s in expected_data_docstrings)
233
234 # output pattern for missing module
235 missing_pattern = '''\
236 No Python documentation found for %r.
237 Use help() to get the interactive help utility.
238 Use help(str) for help on the str class.'''.replace('\n', os.linesep)
239
240 # output pattern for module with bad imports
241 badimport_pattern = "problem in %s - ModuleNotFoundError: No module named %r"
242
243 expected_dynamicattribute_pattern = """
244 Help on class DA in module %s:
245
246 class DA(builtins.object)
247 | Data descriptors defined here:
248 |
249 | __dict__%s
250 |
251 | __weakref__%s
252 |
253 | ham
254 |
255 | ----------------------------------------------------------------------
256 | Data and other attributes inherited from Meta:
257 |
258 | ham = 'spam'
259 """.strip()
260
261 expected_virtualattribute_pattern1 = """
262 Help on class Class in module %s:
263
264 class Class(builtins.object)
265 | Data and other attributes inherited from Meta:
266 |
267 | LIFE = 42
268 """.strip()
269
270 expected_virtualattribute_pattern2 = """
271 Help on class Class1 in module %s:
272
273 class Class1(builtins.object)
274 | Data and other attributes inherited from Meta1:
275 |
276 | one = 1
277 """.strip()
278
279 expected_virtualattribute_pattern3 = """
280 Help on class Class2 in module %s:
281
282 class Class2(Class1)
283 | Method resolution order:
284 | Class2
285 | Class1
286 | builtins.object
287 |
288 | Data and other attributes inherited from Meta1:
289 |
290 | one = 1
291 |
292 | ----------------------------------------------------------------------
293 | Data and other attributes inherited from Meta3:
294 |
295 | three = 3
296 |
297 | ----------------------------------------------------------------------
298 | Data and other attributes inherited from Meta2:
299 |
300 | two = 2
301 """.strip()
302
303 expected_missingattribute_pattern = """
304 Help on class C in module %s:
305
306 class C(builtins.object)
307 | Data and other attributes defined here:
308 |
309 | here = 'present!'
310 """.strip()
311
312 def run_pydoc(module_name, *args, **env):
313 """
314 Runs pydoc on the specified module. Returns the stripped
315 output of pydoc.
316 """
317 args = args + (module_name,)
318 # do not write bytecode files to avoid caching errors
319 rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
320 return out.strip()
321
322 def run_pydoc_fail(module_name, *args, **env):
323 """
324 Runs pydoc on the specified module expecting a failure.
325 """
326 args = args + (module_name,)
327 rc, out, err = assert_python_failure('-B', pydoc.__file__, *args, **env)
328 return out.strip()
329
330 def get_pydoc_html(module):
331 "Returns pydoc generated output as html"
332 doc = pydoc.HTMLDoc()
333 output = doc.docmodule(module)
334 loc = doc.getdocloc(pydoc_mod) or ""
335 if loc:
336 loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
337 return output.strip(), loc
338
339 def clean_text(doc):
340 # clean up the extra text formatting that pydoc performs
341 return re.sub('\b.', '', doc)
342
343 def get_pydoc_link(module):
344 "Returns a documentation web link of a module"
345 abspath = os.path.abspath
346 dirname = os.path.dirname
347 basedir = dirname(dirname(dirname(abspath(__file__))))
348 doc = pydoc.TextDoc()
349 loc = doc.getdocloc(module, basedir=basedir)
350 return loc
351
352 def get_pydoc_text(module):
353 "Returns pydoc generated output as text"
354 doc = pydoc.TextDoc()
355 loc = doc.getdocloc(pydoc_mod) or ""
356 if loc:
357 loc = "\nMODULE DOCS\n " + loc + "\n"
358
359 output = doc.docmodule(module)
360 output = clean_text(output)
361 return output.strip(), loc
362
363 def get_html_title(text):
364 # Bit of hack, but good enough for test purposes
365 header, _, _ = text.partition("</head>")
366 _, _, title = header.partition("<title>")
367 title, _, _ = title.partition("</title>")
368 return title
369
370
371 def html2text(html):
372 """A quick and dirty implementation of html2text.
373
374 Tailored for pydoc tests only.
375 """
376 html = html.replace("<dd>", "\n")
377 html = html.replace("<hr>", "-"*70)
378 html = re.sub("<.*?>", "", html)
379 html = pydoc.replace(html, "&nbsp;", " ", "&gt;", ">", "&lt;", "<")
380 return html
381
382
383 class PydocBaseTest(unittest.TestCase):
384 def tearDown(self):
385 # Self-testing. Mocking only works if sys.modules['pydoc'] and pydoc
386 # are the same. But some pydoc functions reload the module and change
387 # sys.modules, so check that it was restored.
388 self.assertIs(sys.modules['pydoc'], pydoc)
389
390 def _restricted_walk_packages(self, walk_packages, path=None):
391 """
392 A version of pkgutil.walk_packages() that will restrict itself to
393 a given path.
394 """
395 default_path = path or [os.path.dirname(__file__)]
396 def wrapper(path=None, prefix='', onerror=None):
397 return walk_packages(path or default_path, prefix, onerror)
398 return wrapper
399
400 @contextlib.contextmanager
401 def restrict_walk_packages(self, path=None):
402 walk_packages = pkgutil.walk_packages
403 pkgutil.walk_packages = self._restricted_walk_packages(walk_packages,
404 path)
405 try:
406 yield
407 finally:
408 pkgutil.walk_packages = walk_packages
409
410 def call_url_handler(self, url, expected_title):
411 text = pydoc._url_handler(url, "text/html")
412 result = get_html_title(text)
413 # Check the title to ensure an unexpected error page was not returned
414 self.assertEqual(result, expected_title, text)
415 return text
416
417
418 class PydocDocTest(unittest.TestCase):
419 maxDiff = None
420 def tearDown(self):
421 self.assertIs(sys.modules['pydoc'], pydoc)
422
423 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
424 'trace function introduces __locals__ unexpectedly')
425 @requires_docstrings
426 def test_html_doc(self):
427 result, doc_loc = get_pydoc_html(pydoc_mod)
428 text_result = html2text(result)
429 text_lines = [line.strip() for line in text_result.splitlines()]
430 text_lines = [line for line in text_lines if line]
431 del text_lines[1]
432 expected_lines = html2text_of_expected.splitlines()
433 expected_lines = [line.strip() for line in expected_lines if line]
434 self.assertEqual(text_lines, expected_lines)
435 mod_file = inspect.getabsfile(pydoc_mod)
436 mod_url = urllib.parse.quote(mod_file)
437 self.assertIn(mod_url, result)
438 self.assertIn(mod_file, result)
439 self.assertIn(doc_loc, result)
440
441 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
442 'trace function introduces __locals__ unexpectedly')
443 @requires_docstrings
444 def test_text_doc(self):
445 result, doc_loc = get_pydoc_text(pydoc_mod)
446 expected_text = expected_text_pattern % (
447 (doc_loc,) +
448 expected_text_data_docstrings +
449 (inspect.getabsfile(pydoc_mod),))
450 self.assertEqual(expected_text, result)
451
452 def test_text_enum_member_with_value_zero(self):
453 # Test issue #20654 to ensure enum member with value 0 can be
454 # displayed. It used to throw KeyError: 'zero'.
455 import enum
456 class BinaryInteger(enum.IntEnum):
457 zero = 0
458 one = 1
459 doc = pydoc.render_doc(BinaryInteger)
460 self.assertIn('BinaryInteger.zero', doc)
461
462 def test_mixed_case_module_names_are_lower_cased(self):
463 # issue16484
464 doc_link = get_pydoc_link(xml.etree.ElementTree)
465 self.assertIn('xml.etree.elementtree', doc_link)
466
467 def test_issue8225(self):
468 # Test issue8225 to ensure no doc link appears for xml.etree
469 result, doc_loc = get_pydoc_text(xml.etree)
470 self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link")
471
472 def test_online_docs_link(self):
473 import encodings.idna
474 import importlib._bootstrap
475
476 module_docs = {
477 'encodings': 'codecs#module-encodings',
478 'encodings.idna': 'codecs#module-encodings.idna',
479 }
480
481 with unittest.mock.patch('pydoc_data.module_docs.module_docs', module_docs):
482 doc = pydoc.TextDoc()
483
484 basedir = os.path.dirname(encodings.__file__)
485 doc_link = doc.getdocloc(encodings, basedir=basedir)
486 self.assertIsNotNone(doc_link)
487 self.assertIn('codecs#module-encodings', doc_link)
488 self.assertNotIn('encodings.html', doc_link)
489
490 doc_link = doc.getdocloc(encodings.idna, basedir=basedir)
491 self.assertIsNotNone(doc_link)
492 self.assertIn('codecs#module-encodings.idna', doc_link)
493 self.assertNotIn('encodings.idna.html', doc_link)
494
495 doc_link = doc.getdocloc(importlib._bootstrap, basedir=basedir)
496 self.assertIsNone(doc_link)
497
498 def test_getpager_with_stdin_none(self):
499 previous_stdin = sys.stdin
500 try:
501 sys.stdin = None
502 pydoc.getpager() # Shouldn't fail.
503 finally:
504 sys.stdin = previous_stdin
505
506 def test_non_str_name(self):
507 # issue14638
508 # Treat illegal (non-str) name like no name
509
510 class A:
511 __name__ = 42
512 class B:
513 pass
514 adoc = pydoc.render_doc(A())
515 bdoc = pydoc.render_doc(B())
516 self.assertEqual(adoc.replace("A", "B"), bdoc)
517
518 def test_not_here(self):
519 missing_module = "test.i_am_not_here"
520 result = str(run_pydoc_fail(missing_module), 'ascii')
521 expected = missing_pattern % missing_module
522 self.assertEqual(expected, result,
523 "documentation for missing module found")
524
525 @requires_docstrings
526 def test_not_ascii(self):
527 result = run_pydoc('test.test_pydoc.test_pydoc.nonascii', PYTHONIOENCODING='ascii')
528 encoded = nonascii.__doc__.encode('ascii', 'backslashreplace')
529 self.assertIn(encoded, result)
530
531 def test_input_strip(self):
532 missing_module = " test.i_am_not_here "
533 result = str(run_pydoc_fail(missing_module), 'ascii')
534 expected = missing_pattern % missing_module.strip()
535 self.assertEqual(expected, result)
536
537 def test_stripid(self):
538 # test with strings, other implementations might have different repr()
539 stripid = pydoc.stripid
540 # strip the id
541 self.assertEqual(stripid('<function stripid at 0x88dcee4>'),
542 '<function stripid>')
543 self.assertEqual(stripid('<function stripid at 0x01F65390>'),
544 '<function stripid>')
545 # nothing to strip, return the same text
546 self.assertEqual(stripid('42'), '42')
547 self.assertEqual(stripid("<type 'exceptions.Exception'>"),
548 "<type 'exceptions.Exception'>")
549
550 def test_builtin_with_more_than_four_children(self):
551 """Tests help on builtin object which have more than four child classes.
552
553 When running help() on a builtin class which has child classes, it
554 should contain a "Built-in subclasses" section and only 4 classes
555 should be displayed with a hint on how many more subclasses are present.
556 For example:
557
558 >>> help(object)
559 Help on class object in module builtins:
560
561 class object
562 | The most base type
563 |
564 | Built-in subclasses:
565 | async_generator
566 | BaseException
567 | builtin_function_or_method
568 | bytearray
569 | ... and 82 other subclasses
570 """
571 doc = pydoc.TextDoc()
572 text = doc.docclass(object)
573 snip = (" | Built-in subclasses:\n"
574 " | async_generator\n"
575 " | BaseException\n"
576 " | builtin_function_or_method\n"
577 " | bytearray\n"
578 " | ... and \\d+ other subclasses")
579 self.assertRegex(text, snip)
580
581 def test_builtin_with_child(self):
582 """Tests help on builtin object which have only child classes.
583
584 When running help() on a builtin class which has child classes, it
585 should contain a "Built-in subclasses" section. For example:
586
587 >>> help(ArithmeticError)
588 Help on class ArithmeticError in module builtins:
589
590 class ArithmeticError(Exception)
591 | Base class for arithmetic errors.
592 |
593 ...
594 |
595 | Built-in subclasses:
596 | FloatingPointError
597 | OverflowError
598 | ZeroDivisionError
599 """
600 doc = pydoc.TextDoc()
601 text = doc.docclass(ArithmeticError)
602 snip = (" | Built-in subclasses:\n"
603 " | FloatingPointError\n"
604 " | OverflowError\n"
605 " | ZeroDivisionError")
606 self.assertIn(snip, text)
607
608 def test_builtin_with_grandchild(self):
609 """Tests help on builtin classes which have grandchild classes.
610
611 When running help() on a builtin class which has child classes, it
612 should contain a "Built-in subclasses" section. However, if it also has
613 grandchildren, these should not show up on the subclasses section.
614 For example:
615
616 >>> help(Exception)
617 Help on class Exception in module builtins:
618
619 class Exception(BaseException)
620 | Common base class for all non-exit exceptions.
621 |
622 ...
623 |
624 | Built-in subclasses:
625 | ArithmeticError
626 | AssertionError
627 | AttributeError
628 ...
629 """
630 doc = pydoc.TextDoc()
631 text = doc.docclass(Exception)
632 snip = (" | Built-in subclasses:\n"
633 " | ArithmeticError\n"
634 " | AssertionError\n"
635 " | AttributeError")
636 self.assertIn(snip, text)
637 # Testing that the grandchild ZeroDivisionError does not show up
638 self.assertNotIn('ZeroDivisionError', text)
639
640 def test_builtin_no_child(self):
641 """Tests help on builtin object which have no child classes.
642
643 When running help() on a builtin class which has no child classes, it
644 should not contain any "Built-in subclasses" section. For example:
645
646 >>> help(ZeroDivisionError)
647
648 Help on class ZeroDivisionError in module builtins:
649
650 class ZeroDivisionError(ArithmeticError)
651 | Second argument to a division or modulo operation was zero.
652 |
653 | Method resolution order:
654 | ZeroDivisionError
655 | ArithmeticError
656 | Exception
657 | BaseException
658 | object
659 |
660 | Methods defined here:
661 ...
662 """
663 doc = pydoc.TextDoc()
664 text = doc.docclass(ZeroDivisionError)
665 # Testing that the subclasses section does not appear
666 self.assertNotIn('Built-in subclasses', text)
667
668 def test_builtin_on_metaclasses(self):
669 """Tests help on metaclasses.
670
671 When running help() on a metaclasses such as type, it
672 should not contain any "Built-in subclasses" section.
673 """
674 doc = pydoc.TextDoc()
675 text = doc.docclass(type)
676 # Testing that the subclasses section does not appear
677 self.assertNotIn('Built-in subclasses', text)
678
679 def test_fail_help_cli(self):
680 elines = (missing_pattern % 'abd').splitlines()
681 with spawn_python("-c" "help()") as proc:
682 out, _ = proc.communicate(b"abd")
683 olines = out.decode().splitlines()[-9:-6]
684 olines[0] = olines[0].removeprefix('help> ')
685 self.assertEqual(elines, olines)
686
687 def test_fail_help_output_redirect(self):
688 with StringIO() as buf:
689 helper = pydoc.Helper(output=buf)
690 helper.help("abd")
691 expected = missing_pattern % "abd"
692 self.assertEqual(expected, buf.getvalue().strip().replace('\n', os.linesep))
693
694 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
695 'trace function introduces __locals__ unexpectedly')
696 @unittest.mock.patch('pydoc.pager')
697 @requires_docstrings
698 def test_help_output_redirect(self, pager_mock):
699 # issue 940286, if output is set in Helper, then all output from
700 # Helper.help should be redirected
701 self.maxDiff = None
702
703 unused, doc_loc = get_pydoc_text(pydoc_mod)
704 module = "test.test_pydoc.pydoc_mod"
705 help_header = """
706 Help on module test.test_pydoc.pydoc_mod in test.test_pydoc:
707
708 """.lstrip()
709 help_header = textwrap.dedent(help_header)
710 expected_help_pattern = help_header + expected_text_pattern
711
712 with captured_stdout() as output, captured_stderr() as err:
713 buf = StringIO()
714 helper = pydoc.Helper(output=buf)
715 helper.help(module)
716 result = buf.getvalue().strip()
717 expected_text = expected_help_pattern % (
718 (doc_loc,) +
719 expected_text_data_docstrings +
720 (inspect.getabsfile(pydoc_mod),))
721 self.assertEqual('', output.getvalue())
722 self.assertEqual('', err.getvalue())
723 self.assertEqual(expected_text, result)
724
725 pager_mock.assert_not_called()
726
727 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
728 'trace function introduces __locals__ unexpectedly')
729 @requires_docstrings
730 @unittest.mock.patch('pydoc.pager')
731 def test_help_output_redirect_various_requests(self, pager_mock):
732 # issue 940286, if output is set in Helper, then all output from
733 # Helper.help should be redirected
734
735 def run_pydoc_for_request(request, expected_text_part):
736 """Helper function to run pydoc with its output redirected"""
737 with captured_stdout() as output, captured_stderr() as err:
738 buf = StringIO()
739 helper = pydoc.Helper(output=buf)
740 helper.help(request)
741 result = buf.getvalue().strip()
742 self.assertEqual('', output.getvalue(), msg=f'failed on request "{request}"')
743 self.assertEqual('', err.getvalue(), msg=f'failed on request "{request}"')
744 self.assertIn(expected_text_part, result, msg=f'failed on request "{request}"')
745 pager_mock.assert_not_called()
746
747 self.maxDiff = None
748
749 # test for "keywords"
750 run_pydoc_for_request('keywords', 'Here is a list of the Python keywords.')
751 # test for "symbols"
752 run_pydoc_for_request('symbols', 'Here is a list of the punctuation symbols')
753 # test for "topics"
754 run_pydoc_for_request('topics', 'Here is a list of available topics.')
755 # test for "modules" skipped, see test_modules()
756 # test for symbol "%"
757 run_pydoc_for_request('%', 'The power operator')
758 # test for special True, False, None keywords
759 run_pydoc_for_request('True', 'class bool(int)')
760 run_pydoc_for_request('False', 'class bool(int)')
761 run_pydoc_for_request('None', 'class NoneType(object)')
762 # test for keyword "assert"
763 run_pydoc_for_request('assert', 'The "assert" statement')
764 # test for topic "TYPES"
765 run_pydoc_for_request('TYPES', 'The standard type hierarchy')
766 # test for "pydoc.Helper.help"
767 run_pydoc_for_request('pydoc.Helper.help', 'Help on function help in pydoc.Helper:')
768 # test for pydoc.Helper.help
769 run_pydoc_for_request(pydoc.Helper.help, 'Help on function help in module pydoc:')
770 # test for pydoc.Helper() instance skipped because it is always meant to be interactive
771
772 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
773 'trace function introduces __locals__ unexpectedly')
774 @requires_docstrings
775 def test_help_output_pager(self):
776 def run_pydoc_pager(request, what, expected_first_line):
777 with (captured_stdout() as output,
778 captured_stderr() as err,
779 unittest.mock.patch('pydoc.pager') as pager_mock,
780 self.subTest(repr(request))):
781 helper = pydoc.Helper()
782 helper.help(request)
783 self.assertEqual('', err.getvalue())
784 self.assertEqual('\n', output.getvalue())
785 pager_mock.assert_called_once()
786 result = clean_text(pager_mock.call_args.args[0])
787 self.assertEqual(result.splitlines()[0], expected_first_line)
788 self.assertEqual(pager_mock.call_args.args[1], f'Help on {what}')
789
790 run_pydoc_pager('%', 'EXPRESSIONS', 'Operator precedence')
791 run_pydoc_pager('True', 'bool object', 'Help on bool object:')
792 run_pydoc_pager(True, 'bool object', 'Help on bool object:')
793 run_pydoc_pager('assert', 'assert', 'The "assert" statement')
794 run_pydoc_pager('TYPES', 'TYPES', 'The standard type hierarchy')
795 run_pydoc_pager('pydoc.Helper.help', 'pydoc.Helper.help',
796 'Help on function help in pydoc.Helper:')
797 run_pydoc_pager(pydoc.Helper.help, 'Helper.help',
798 'Help on function help in module pydoc:')
799 run_pydoc_pager('str', 'str', 'Help on class str in module builtins:')
800 run_pydoc_pager(str, 'str', 'Help on class str in module builtins:')
801 run_pydoc_pager('str.upper', 'str.upper', 'Help on method_descriptor in str:')
802 run_pydoc_pager(str.upper, 'str.upper', 'Help on method_descriptor:')
803 run_pydoc_pager(str.__add__, 'str.__add__', 'Help on wrapper_descriptor:')
804 run_pydoc_pager(int.numerator, 'int.numerator',
805 'Help on getset descriptor builtins.int.numerator:')
806 run_pydoc_pager(list[int], 'list',
807 'Help on GenericAlias in module builtins:')
808 run_pydoc_pager('sys', 'sys', 'Help on built-in module sys:')
809 run_pydoc_pager(sys, 'sys', 'Help on built-in module sys:')
810
811 def test_showtopic(self):
812 with captured_stdout() as showtopic_io:
813 helper = pydoc.Helper()
814 helper.showtopic('with')
815 helptext = showtopic_io.getvalue()
816 self.assertIn('The "with" statement', helptext)
817
818 def test_fail_showtopic(self):
819 with captured_stdout() as showtopic_io:
820 helper = pydoc.Helper()
821 helper.showtopic('abd')
822 expected = "no documentation found for 'abd'"
823 self.assertEqual(expected, showtopic_io.getvalue().strip())
824
825 @unittest.mock.patch('pydoc.pager')
826 def test_fail_showtopic_output_redirect(self, pager_mock):
827 with StringIO() as buf:
828 helper = pydoc.Helper(output=buf)
829 helper.showtopic("abd")
830 expected = "no documentation found for 'abd'"
831 self.assertEqual(expected, buf.getvalue().strip())
832
833 pager_mock.assert_not_called()
834
835 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
836 'trace function introduces __locals__ unexpectedly')
837 @requires_docstrings
838 @unittest.mock.patch('pydoc.pager')
839 def test_showtopic_output_redirect(self, pager_mock):
840 # issue 940286, if output is set in Helper, then all output from
841 # Helper.showtopic should be redirected
842 self.maxDiff = None
843
844 with captured_stdout() as output, captured_stderr() as err:
845 buf = StringIO()
846 helper = pydoc.Helper(output=buf)
847 helper.showtopic('with')
848 result = buf.getvalue().strip()
849 self.assertEqual('', output.getvalue())
850 self.assertEqual('', err.getvalue())
851 self.assertIn('The "with" statement', result)
852
853 pager_mock.assert_not_called()
854
855 def test_lambda_with_return_annotation(self):
856 func = lambda a, b, c: 1
857 func.__annotations__ = {"return": int}
858 with captured_stdout() as help_io:
859 pydoc.help(func)
860 helptext = help_io.getvalue()
861 self.assertIn("lambda (a, b, c) -> int", helptext)
862
863 def test_lambda_without_return_annotation(self):
864 func = lambda a, b, c: 1
865 func.__annotations__ = {"a": int, "b": int, "c": int}
866 with captured_stdout() as help_io:
867 pydoc.help(func)
868 helptext = help_io.getvalue()
869 self.assertIn("lambda (a: int, b: int, c: int)", helptext)
870
871 def test_lambda_with_return_and_params_annotation(self):
872 func = lambda a, b, c: 1
873 func.__annotations__ = {"a": int, "b": int, "c": int, "return": int}
874 with captured_stdout() as help_io:
875 pydoc.help(func)
876 helptext = help_io.getvalue()
877 self.assertIn("lambda (a: int, b: int, c: int) -> int", helptext)
878
879 def test_namedtuple_fields(self):
880 Person = namedtuple('Person', ['nickname', 'firstname'])
881 with captured_stdout() as help_io:
882 pydoc.help(Person)
883 helptext = help_io.getvalue()
884 self.assertIn("nickname", helptext)
885 self.assertIn("firstname", helptext)
886 self.assertIn("Alias for field number 0", helptext)
887 self.assertIn("Alias for field number 1", helptext)
888
889 def test_namedtuple_public_underscore(self):
890 NT = namedtuple('NT', ['abc', 'def'], rename=True)
891 with captured_stdout() as help_io:
892 pydoc.help(NT)
893 helptext = help_io.getvalue()
894 self.assertIn('_1', helptext)
895 self.assertIn('_replace', helptext)
896 self.assertIn('_asdict', helptext)
897
898 def test_synopsis(self):
899 self.addCleanup(unlink, TESTFN)
900 for encoding in ('ISO-8859-1', 'UTF-8'):
901 with open(TESTFN, 'w', encoding=encoding) as script:
902 if encoding != 'UTF-8':
903 print('#coding: {}'.format(encoding), file=script)
904 print('"""line 1: h\xe9', file=script)
905 print('line 2: hi"""', file=script)
906 synopsis = pydoc.synopsis(TESTFN, {})
907 self.assertEqual(synopsis, 'line 1: h\xe9')
908
909 def test_source_synopsis(self):
910 def check(source, expected, encoding=None):
911 if isinstance(source, str):
912 source_file = StringIO(source)
913 else:
914 source_file = io.TextIOWrapper(io.BytesIO(source), encoding=encoding)
915 with source_file:
916 result = pydoc.source_synopsis(source_file)
917 self.assertEqual(result, expected)
918
919 check('"""Single line docstring."""',
920 'Single line docstring.')
921 check('"""First line of docstring.\nSecond line.\nThird line."""',
922 'First line of docstring.')
923 check('"""First line of docstring.\\nSecond line.\\nThird line."""',
924 'First line of docstring.')
925 check('""" Whitespace around docstring. """',
926 'Whitespace around docstring.')
927 check('import sys\n"""No docstring"""',
928 None)
929 check(' \n"""Docstring after empty line."""',
930 'Docstring after empty line.')
931 check('# Comment\n"""Docstring after comment."""',
932 'Docstring after comment.')
933 check(' # Indented comment\n"""Docstring after comment."""',
934 'Docstring after comment.')
935 check('""""""', # Empty docstring
936 '')
937 check('', # Empty file
938 None)
939 check('"""Embedded\0null byte"""',
940 None)
941 check('"""Embedded null byte"""\0',
942 None)
943 check('"""Café and résumé."""',
944 'Café and résumé.')
945 check("'''Triple single quotes'''",
946 'Triple single quotes')
947 check('"Single double quotes"',
948 'Single double quotes')
949 check("'Single single quotes'",
950 'Single single quotes')
951 check('"""split\\\nline"""',
952 'splitline')
953 check('"""Unrecognized escape \\sequence"""',
954 'Unrecognized escape \\sequence')
955 check('"""Invalid escape seq\\uence"""',
956 None)
957 check('r"""Raw \\stri\\ng"""',
958 'Raw \\stri\\ng')
959 check('b"""Bytes literal"""',
960 None)
961 check('f"""f-string"""',
962 None)
963 check('"""Concatenated""" \\\n"string" \'literals\'',
964 'Concatenatedstringliterals')
965 check('"""String""" + """expression"""',
966 None)
967 check('("""In parentheses""")',
968 'In parentheses')
969 check('("""Multiple lines """\n"""in parentheses""")',
970 'Multiple lines in parentheses')
971 check('()', # tuple
972 None)
973 check(b'# coding: iso-8859-15\n"""\xa4uro sign"""',
974 '€uro sign', encoding='iso-8859-15')
975 check(b'"""\xa4"""', # Decoding error
976 None, encoding='utf-8')
977
978 with tempfile.NamedTemporaryFile(mode='w+', encoding='utf-8') as temp_file:
979 temp_file.write('"""Real file test."""\n')
980 temp_file.flush()
981 temp_file.seek(0)
982 result = pydoc.source_synopsis(temp_file)
983 self.assertEqual(result, "Real file test.")
984
985 @requires_docstrings
986 def test_synopsis_sourceless(self):
987 os = import_helper.import_fresh_module('os')
988 expected = os.__doc__.splitlines()[0]
989 filename = os.__spec__.cached
990 synopsis = pydoc.synopsis(filename)
991
992 self.assertEqual(synopsis, expected)
993
994 def test_synopsis_sourceless_empty_doc(self):
995 with os_helper.temp_cwd() as test_dir:
996 init_path = os.path.join(test_dir, 'foomod42.py')
997 cached_path = importlib.util.cache_from_source(init_path)
998 with open(init_path, 'w') as fobj:
999 fobj.write("foo = 1")
1000 py_compile.compile(init_path)
1001 synopsis = pydoc.synopsis(init_path, {})
1002 self.assertIsNone(synopsis)
1003 synopsis_cached = pydoc.synopsis(cached_path, {})
1004 self.assertIsNone(synopsis_cached)
1005
1006 def test_splitdoc_with_description(self):
1007 example_string = "I Am A Doc\n\n\nHere is my description"
1008 self.assertEqual(pydoc.splitdoc(example_string),
1009 ('I Am A Doc', '\nHere is my description'))
1010
1011 def test_is_package_when_not_package(self):
1012 with os_helper.temp_cwd() as test_dir:
1013 with self.assertWarns(DeprecationWarning) as cm:
1014 self.assertFalse(pydoc.ispackage(test_dir))
1015 self.assertEqual(cm.filename, __file__)
1016
1017 def test_is_package_when_is_package(self):
1018 with os_helper.temp_cwd() as test_dir:
1019 init_path = os.path.join(test_dir, '__init__.py')
1020 open(init_path, 'w').close()
1021 with self.assertWarns(DeprecationWarning) as cm:
1022 self.assertTrue(pydoc.ispackage(test_dir))
1023 os.remove(init_path)
1024 self.assertEqual(cm.filename, __file__)
1025
1026 def test_allmethods(self):
1027 # issue 17476: allmethods was no longer returning unbound methods.
1028 # This test is a bit fragile in the face of changes to object and type,
1029 # but I can't think of a better way to do it without duplicating the
1030 # logic of the function under test.
1031
1032 class TestClass(object):
1033 def method_returning_true(self):
1034 return True
1035
1036 # What we expect to get back: everything on object...
1037 expected = dict(vars(object))
1038 # ...plus our unbound method...
1039 expected['method_returning_true'] = TestClass.method_returning_true
1040 # ...but not the non-methods on object.
1041 del expected['__doc__']
1042 del expected['__class__']
1043 # inspect resolves descriptors on type into methods, but vars doesn't,
1044 # so we need to update __subclasshook__ and __init_subclass__.
1045 expected['__subclasshook__'] = TestClass.__subclasshook__
1046 expected['__init_subclass__'] = TestClass.__init_subclass__
1047
1048 methods = pydoc.allmethods(TestClass)
1049 self.assertDictEqual(methods, expected)
1050
1051 @requires_docstrings
1052 def test_method_aliases(self):
1053 class A:
1054 def tkraise(self, aboveThis=None):
1055 """Raise this widget in the stacking order."""
1056 lift = tkraise
1057 def a_size(self):
1058 """Return size"""
1059 class B(A):
1060 def itemconfigure(self, tagOrId, cnf=None, **kw):
1061 """Configure resources of an item TAGORID."""
1062 itemconfig = itemconfigure
1063 b_size = A.a_size
1064
1065 doc = pydoc.render_doc(B)
1066 doc = clean_text(doc)
1067 self.assertEqual(doc, '''\
1068 Python Library Documentation: class B in module %s
1069
1070 class B(A)
1071 | Method resolution order:
1072 | B
1073 | A
1074 | builtins.object
1075 |
1076 | Methods defined here:
1077 |
1078 | b_size = a_size(self)
1079 |
1080 | itemconfig = itemconfigure(self, tagOrId, cnf=None, **kw)
1081 |
1082 | itemconfigure(self, tagOrId, cnf=None, **kw)
1083 | Configure resources of an item TAGORID.
1084 |
1085 | ----------------------------------------------------------------------
1086 | Methods inherited from A:
1087 |
1088 | a_size(self)
1089 | Return size
1090 |
1091 | lift = tkraise(self, aboveThis=None)
1092 |
1093 | tkraise(self, aboveThis=None)
1094 | Raise this widget in the stacking order.
1095 |
1096 | ----------------------------------------------------------------------
1097 | Data descriptors inherited from A:
1098 |
1099 | __dict__
1100 | dictionary for instance variables
1101 |
1102 | __weakref__
1103 | list of weak references to the object
1104 ''' % __name__)
1105
1106 doc = pydoc.render_doc(B, renderer=pydoc.HTMLDoc())
1107 expected_text = f"""
1108 Python Library Documentation
1109
1110 class B in module {__name__}
1111 class B(A)
1112 Method resolution order:
1113 B
1114 A
1115 builtins.object
1116
1117 Methods defined here:
1118 b_size = a_size(self)
1119 itemconfig = itemconfigure(self, tagOrId, cnf=None, **kw)
1120 itemconfigure(self, tagOrId, cnf=None, **kw)
1121 Configure resources of an item TAGORID.
1122
1123 Methods inherited from A:
1124 a_size(self)
1125 Return size
1126 lift = tkraise(self, aboveThis=None)
1127 tkraise(self, aboveThis=None)
1128 Raise this widget in the stacking order.
1129
1130 Data descriptors inherited from A:
1131 __dict__
1132 dictionary for instance variables
1133 __weakref__
1134 list of weak references to the object
1135 """
1136 as_text = html2text(doc)
1137 expected_lines = [line.strip() for line in expected_text.split("\n") if line]
1138 for expected_line in expected_lines:
1139 self.assertIn(expected_line, as_text)
1140
1141 def test_long_signatures(self):
1142 from collections.abc import Callable
1143 from typing import Literal, Annotated
1144
1145 class A:
1146 def __init__(self,
1147 arg1: Callable[[int, int, int], str],
1148 arg2: Literal['some value', 'other value'],
1149 arg3: Annotated[int, 'some docs about this type'],
1150 ) -> None:
1151 ...
1152
1153 doc = pydoc.render_doc(A)
1154 doc = clean_text(doc)
1155 self.assertEqual(doc, '''Python Library Documentation: class A in module %s
1156
1157 class A(builtins.object)
1158 | A(
1159 | arg1: collections.abc.Callable[[int, int, int], str],
1160 | arg2: Literal['some value', 'other value'],
1161 | arg3: Annotated[int, 'some docs about this type']
1162 | ) -> None
1163 |
1164 | Methods defined here:
1165 |
1166 | __init__(
1167 | self,
1168 | arg1: collections.abc.Callable[[int, int, int], str],
1169 | arg2: Literal['some value', 'other value'],
1170 | arg3: Annotated[int, 'some docs about this type']
1171 | ) -> None
1172 |
1173 | ----------------------------------------------------------------------
1174 | Data descriptors defined here:
1175 |
1176 | __dict__%s
1177 |
1178 | __weakref__%s
1179 ''' % (__name__,
1180 '' if MISSING_C_DOCSTRINGS else '\n | dictionary for instance variables',
1181 '' if MISSING_C_DOCSTRINGS else '\n | list of weak references to the object',
1182 ))
1183
1184 def func(
1185 arg1: Callable[[Annotated[int, 'Some doc']], str],
1186 arg2: Literal[1, 2, 3, 4, 5, 6, 7, 8],
1187 ) -> Annotated[int, 'Some other']:
1188 ...
1189
1190 doc = pydoc.render_doc(func)
1191 doc = clean_text(doc)
1192 self.assertEqual(doc, '''Python Library Documentation: function func in module %s
1193
1194 func(
1195 arg1: collections.abc.Callable[[typing.Annotated[int, 'Some doc']], str],
1196 arg2: Literal[1, 2, 3, 4, 5, 6, 7, 8]
1197 ) -> Annotated[int, 'Some other']
1198 ''' % __name__)
1199
1200 def function_with_really_long_name_so_annotations_can_be_rather_small(
1201 arg1: int,
1202 arg2: str,
1203 ):
1204 ...
1205
1206 doc = pydoc.render_doc(function_with_really_long_name_so_annotations_can_be_rather_small)
1207 doc = clean_text(doc)
1208 self.assertEqual(doc, '''Python Library Documentation: function function_with_really_long_name_so_annotations_can_be_rather_small in module %s
1209
1210 function_with_really_long_name_so_annotations_can_be_rather_small(
1211 arg1: int,
1212 arg2: str
1213 )
1214 ''' % __name__)
1215
1216 does_not_have_name = lambda \
1217 very_long_parameter_name_that_should_not_fit_into_a_single_line, \
1218 second_very_long_parameter_name: ...
1219
1220 doc = pydoc.render_doc(does_not_have_name)
1221 doc = clean_text(doc)
1222 self.assertEqual(doc, '''Python Library Documentation: function <lambda> in module %s
1223
1224 <lambda> lambda very_long_parameter_name_that_should_not_fit_into_a_single_line, second_very_long_parameter_name
1225 ''' % __name__)
1226
1227 def test__future__imports(self):
1228 # __future__ features are excluded from module help,
1229 # except when it's the __future__ module itself
1230 import __future__
1231 future_text, _ = get_pydoc_text(__future__)
1232 future_html, _ = get_pydoc_html(__future__)
1233 pydoc_mod_text, _ = get_pydoc_text(pydoc_mod)
1234 pydoc_mod_html, _ = get_pydoc_html(pydoc_mod)
1235
1236 for feature in __future__.all_feature_names:
1237 txt = f"{feature} = _Feature"
1238 html = f"<strong>{feature}</strong> = _Feature"
1239 self.assertIn(txt, future_text)
1240 self.assertIn(html, future_html)
1241 self.assertNotIn(txt, pydoc_mod_text)
1242 self.assertNotIn(html, pydoc_mod_html)
1243
1244
1245 class PydocImportTest(PydocBaseTest):
1246
1247 def setUp(self):
1248 self.test_dir = os.mkdir(TESTFN)
1249 self.addCleanup(rmtree, TESTFN)
1250 importlib.invalidate_caches()
1251
1252 def test_badimport(self):
1253 # This tests the fix for issue 5230, where if pydoc found the module
1254 # but the module had an internal import error pydoc would report no doc
1255 # found.
1256 modname = 'testmod_xyzzy'
1257 testpairs = (
1258 ('i_am_not_here', 'i_am_not_here'),
1259 ('test.i_am_not_here_either', 'test.i_am_not_here_either'),
1260 ('test.i_am_not_here.neither_am_i', 'test.i_am_not_here'),
1261 ('i_am_not_here.{}'.format(modname), 'i_am_not_here'),
1262 ('test.{}'.format(modname), 'test.{}'.format(modname)),
1263 )
1264
1265 sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
1266 for importstring, expectedinmsg in testpairs:
1267 with open(sourcefn, 'w') as f:
1268 f.write("import {}\n".format(importstring))
1269 result = run_pydoc_fail(modname, PYTHONPATH=TESTFN).decode("ascii")
1270 expected = badimport_pattern % (modname, expectedinmsg)
1271 self.assertEqual(expected, result)
1272
1273 def test_apropos_with_bad_package(self):
1274 # Issue 7425 - pydoc -k failed when bad package on path
1275 pkgdir = os.path.join(TESTFN, "syntaxerr")
1276 os.mkdir(pkgdir)
1277 badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
1278 with open(badsyntax, 'w') as f:
1279 f.write("invalid python syntax = $1\n")
1280 with self.restrict_walk_packages(path=[TESTFN]):
1281 with captured_stdout() as out:
1282 with captured_stderr() as err:
1283 pydoc.apropos('xyzzy')
1284 # No result, no error
1285 self.assertEqual(out.getvalue(), '')
1286 self.assertEqual(err.getvalue(), '')
1287 # The package name is still matched
1288 with captured_stdout() as out:
1289 with captured_stderr() as err:
1290 pydoc.apropos('syntaxerr')
1291 self.assertEqual(out.getvalue().strip(), 'syntaxerr')
1292 self.assertEqual(err.getvalue(), '')
1293
1294 def test_apropos_with_unreadable_dir(self):
1295 # Issue 7367 - pydoc -k failed when unreadable dir on path
1296 self.unreadable_dir = os.path.join(TESTFN, "unreadable")
1297 os.mkdir(self.unreadable_dir, 0)
1298 self.addCleanup(os.rmdir, self.unreadable_dir)
1299 # Note, on Windows the directory appears to be still
1300 # readable so this is not really testing the issue there
1301 with self.restrict_walk_packages(path=[TESTFN]):
1302 with captured_stdout() as out:
1303 with captured_stderr() as err:
1304 pydoc.apropos('SOMEKEY')
1305 # No result, no error
1306 self.assertEqual(out.getvalue(), '')
1307 self.assertEqual(err.getvalue(), '')
1308
1309 @os_helper.skip_unless_working_chmod
1310 @unittest.skipIf(is_emscripten, "cannot remove x bit")
1311 def test_apropos_empty_doc(self):
1312 pkgdir = os.path.join(TESTFN, 'walkpkg')
1313 os.mkdir(pkgdir)
1314 self.addCleanup(rmtree, pkgdir)
1315 init_path = os.path.join(pkgdir, '__init__.py')
1316 with open(init_path, 'w') as fobj:
1317 fobj.write("foo = 1")
1318 current_mode = stat.S_IMODE(os.stat(pkgdir).st_mode)
1319 try:
1320 os.chmod(pkgdir, current_mode & ~stat.S_IEXEC)
1321 with self.restrict_walk_packages(path=[TESTFN]), captured_stdout() as stdout:
1322 pydoc.apropos('')
1323 self.assertIn('walkpkg', stdout.getvalue())
1324 finally:
1325 os.chmod(pkgdir, current_mode)
1326
1327 def test_url_search_package_error(self):
1328 # URL handler search should cope with packages that raise exceptions
1329 pkgdir = os.path.join(TESTFN, "test_error_package")
1330 os.mkdir(pkgdir)
1331 init = os.path.join(pkgdir, "__init__.py")
1332 with open(init, "wt", encoding="ascii") as f:
1333 f.write("""raise ValueError("ouch")\n""")
1334 with self.restrict_walk_packages(path=[TESTFN]):
1335 # Package has to be importable for the error to have any effect
1336 saved_paths = tuple(sys.path)
1337 sys.path.insert(0, TESTFN)
1338 try:
1339 with self.assertRaisesRegex(ValueError, "ouch"):
1340 import test_error_package # Sanity check
1341
1342 text = self.call_url_handler("search?key=test_error_package",
1343 "Pydoc: Search Results")
1344 found = ('<a href="test_error_package.html">'
1345 'test_error_package</a>')
1346 self.assertIn(found, text)
1347 finally:
1348 sys.path[:] = saved_paths
1349
1350 @unittest.skip('causes undesirable side-effects (#20128)')
1351 def test_modules(self):
1352 # See Helper.listmodules().
1353 num_header_lines = 2
1354 num_module_lines_min = 5 # Playing it safe.
1355 num_footer_lines = 3
1356 expected = num_header_lines + num_module_lines_min + num_footer_lines
1357
1358 output = StringIO()
1359 helper = pydoc.Helper(output=output)
1360 helper('modules')
1361 result = output.getvalue().strip()
1362 num_lines = len(result.splitlines())
1363
1364 self.assertGreaterEqual(num_lines, expected)
1365
1366 @unittest.skip('causes undesirable side-effects (#20128)')
1367 def test_modules_search(self):
1368 # See Helper.listmodules().
1369 expected = 'pydoc - '
1370
1371 output = StringIO()
1372 helper = pydoc.Helper(output=output)
1373 with captured_stdout() as help_io:
1374 helper('modules pydoc')
1375 result = help_io.getvalue()
1376
1377 self.assertIn(expected, result)
1378
1379 @unittest.skip('some buildbots are not cooperating (#20128)')
1380 def test_modules_search_builtin(self):
1381 expected = 'gc - '
1382
1383 output = StringIO()
1384 helper = pydoc.Helper(output=output)
1385 with captured_stdout() as help_io:
1386 helper('modules garbage')
1387 result = help_io.getvalue()
1388
1389 self.assertTrue(result.startswith(expected))
1390
1391 def test_importfile(self):
1392 try:
1393 loaded_pydoc = pydoc.importfile(pydoc.__file__)
1394
1395 self.assertIsNot(loaded_pydoc, pydoc)
1396 self.assertEqual(loaded_pydoc.__name__, 'pydoc')
1397 self.assertEqual(loaded_pydoc.__file__, pydoc.__file__)
1398 self.assertEqual(loaded_pydoc.__spec__, pydoc.__spec__)
1399 finally:
1400 sys.modules['pydoc'] = pydoc
1401
1402
1403 class Rect:
1404 @property
1405 def area(self):
1406 '''Area of the rect'''
1407 return self.w * self.h
1408
1409
1410 class Square(Rect):
1411 area = property(lambda self: self.side**2)
1412
1413
1414 class TestDescriptions(unittest.TestCase):
1415 def tearDown(self):
1416 self.assertIs(sys.modules['pydoc'], pydoc)
1417
1418 def test_module(self):
1419 # Check that pydocfodder module can be described
1420 doc = pydoc.render_doc(pydocfodder)
1421 self.assertIn("pydocfodder", doc)
1422
1423 def test_class(self):
1424 class C: "New-style class"
1425 c = C()
1426
1427 self.assertEqual(pydoc.describe(C), 'class C')
1428 self.assertEqual(pydoc.describe(c), 'C')
1429 expected = 'C in module %s object' % __name__
1430 self.assertIn(expected, pydoc.render_doc(c))
1431
1432 def test_generic_alias(self):
1433 self.assertEqual(pydoc.describe(typing.List[int]), '_GenericAlias')
1434 doc = pydoc.render_doc(typing.List[int], renderer=pydoc.plaintext)
1435 self.assertIn('_GenericAlias in module typing', doc)
1436 self.assertIn('List = class list(object)', doc)
1437 if not MISSING_C_DOCSTRINGS:
1438 self.assertIn(list.__doc__.strip().splitlines()[0], doc)
1439
1440 self.assertEqual(pydoc.describe(list[int]), 'GenericAlias')
1441 doc = pydoc.render_doc(list[int], renderer=pydoc.plaintext)
1442 self.assertIn('GenericAlias in module builtins', doc)
1443 self.assertIn('\nclass list(object)', doc)
1444 if not MISSING_C_DOCSTRINGS:
1445 self.assertIn(list.__doc__.strip().splitlines()[0], doc)
1446
1447 def test_union_type(self):
1448 self.assertEqual(pydoc.describe(typing.Union[int, str]), '_UnionGenericAlias')
1449 doc = pydoc.render_doc(typing.Union[int, str], renderer=pydoc.plaintext)
1450 self.assertIn('_UnionGenericAlias in module typing', doc)
1451 self.assertIn('Union = typing.Union', doc)
1452 if typing.Union.__doc__:
1453 self.assertIn(typing.Union.__doc__.strip().splitlines()[0], doc)
1454
1455 self.assertEqual(pydoc.describe(int | str), 'UnionType')
1456 doc = pydoc.render_doc(int | str, renderer=pydoc.plaintext)
1457 self.assertIn('UnionType in module types object', doc)
1458 self.assertIn('\nclass UnionType(builtins.object)', doc)
1459 if not MISSING_C_DOCSTRINGS:
1460 self.assertIn(types.UnionType.__doc__.strip().splitlines()[0], doc)
1461
1462 def test_special_form(self):
1463 self.assertEqual(pydoc.describe(typing.NoReturn), '_SpecialForm')
1464 doc = pydoc.render_doc(typing.NoReturn, renderer=pydoc.plaintext)
1465 self.assertIn('_SpecialForm in module typing', doc)
1466 if typing.NoReturn.__doc__:
1467 self.assertIn('NoReturn = typing.NoReturn', doc)
1468 self.assertIn(typing.NoReturn.__doc__.strip().splitlines()[0], doc)
1469 else:
1470 self.assertIn('NoReturn = class _SpecialForm(_Final)', doc)
1471
1472 def test_typing_pydoc(self):
1473 def foo(data: typing.List[typing.Any],
1474 x: int) -> typing.Iterator[typing.Tuple[int, typing.Any]]:
1475 ...
1476 T = typing.TypeVar('T')
1477 class C(typing.Generic[T], typing.Mapping[int, str]): ...
1478 self.assertEqual(pydoc.render_doc(foo).splitlines()[-1],
1479 'f\x08fo\x08oo\x08o(data: List[Any], x: int)'
1480 ' -> Iterator[Tuple[int, Any]]')
1481 self.assertEqual(pydoc.render_doc(C).splitlines()[2],
1482 'class C\x08C(collections.abc.Mapping, typing.Generic)')
1483
1484 def test_builtin(self):
1485 for name in ('str', 'str.translate', 'builtins.str',
1486 'builtins.str.translate'):
1487 # test low-level function
1488 self.assertIsNotNone(pydoc.locate(name))
1489 # test high-level function
1490 try:
1491 pydoc.render_doc(name)
1492 except ImportError:
1493 self.fail('finding the doc of {!r} failed'.format(name))
1494
1495 for name in ('notbuiltins', 'strrr', 'strr.translate',
1496 'str.trrrranslate', 'builtins.strrr',
1497 'builtins.str.trrranslate'):
1498 self.assertIsNone(pydoc.locate(name))
1499 self.assertRaises(ImportError, pydoc.render_doc, name)
1500
1501 @staticmethod
1502 def _get_summary_line(o):
1503 text = pydoc.plain(pydoc.render_doc(o))
1504 lines = text.split('\n')
1505 assert len(lines) >= 2
1506 return lines[2]
1507
1508 @staticmethod
1509 def _get_summary_lines(o):
1510 text = pydoc.plain(pydoc.render_doc(o))
1511 lines = text.split('\n')
1512 return '\n'.join(lines[2:])
1513
1514 # these should include "self"
1515 def test_unbound_python_method(self):
1516 self.assertEqual(self._get_summary_line(textwrap.TextWrapper.wrap),
1517 "wrap(self, text)")
1518
1519 @requires_docstrings
1520 def test_unbound_builtin_method(self):
1521 self.assertEqual(self._get_summary_line(_pickle.Pickler.dump),
1522 "dump(self, obj, /) unbound _pickle.Pickler method")
1523
1524 # these no longer include "self"
1525 def test_bound_python_method(self):
1526 t = textwrap.TextWrapper()
1527 self.assertEqual(self._get_summary_line(t.wrap),
1528 "wrap(text) method of textwrap.TextWrapper instance")
1529 def test_field_order_for_named_tuples(self):
1530 Person = namedtuple('Person', ['nickname', 'firstname', 'agegroup'])
1531 s = pydoc.render_doc(Person)
1532 self.assertLess(s.index('nickname'), s.index('firstname'))
1533 self.assertLess(s.index('firstname'), s.index('agegroup'))
1534
1535 class NonIterableFields:
1536 _fields = None
1537
1538 class NonHashableFields:
1539 _fields = [[]]
1540
1541 # Make sure these doesn't fail
1542 pydoc.render_doc(NonIterableFields)
1543 pydoc.render_doc(NonHashableFields)
1544
1545 @requires_docstrings
1546 def test_bound_builtin_method(self):
1547 s = StringIO()
1548 p = _pickle.Pickler(s)
1549 self.assertEqual(self._get_summary_line(p.dump),
1550 "dump(obj, /) method of _pickle.Pickler instance")
1551
1552 # this should *never* include self!
1553 @requires_docstrings
1554 def test_module_level_callable(self):
1555 self.assertEqual(self._get_summary_line(os.stat),
1556 "stat(path, *, dir_fd=None, follow_symlinks=True)")
1557
1558 def test_module_level_callable_noargs(self):
1559 self.assertEqual(self._get_summary_line(time.time),
1560 "time()")
1561
1562 def test_module_level_callable_o(self):
1563 try:
1564 import _stat
1565 except ImportError:
1566 # stat.S_IMODE() and _stat.S_IMODE() have a different signature
1567 self.skipTest('_stat extension is missing')
1568
1569 self.assertEqual(self._get_summary_line(_stat.S_IMODE),
1570 "S_IMODE(object, /)")
1571
1572 def test_unbound_builtin_method_noargs(self):
1573 self.assertEqual(self._get_summary_line(str.lower),
1574 "lower(self, /) unbound builtins.str method")
1575
1576 def test_bound_builtin_method_noargs(self):
1577 self.assertEqual(self._get_summary_line(''.lower),
1578 "lower() method of builtins.str instance")
1579
1580 def test_unbound_builtin_method_o(self):
1581 self.assertEqual(self._get_summary_line(set.add),
1582 "add(self, object, /) unbound builtins.set method")
1583
1584 def test_bound_builtin_method_o(self):
1585 self.assertEqual(self._get_summary_line(set().add),
1586 "add(object, /) method of builtins.set instance")
1587
1588 def test_unbound_builtin_method_coexist_o(self):
1589 self.assertEqual(self._get_summary_line(set.__contains__),
1590 "__contains__(self, object, /) unbound builtins.set method")
1591
1592 def test_bound_builtin_method_coexist_o(self):
1593 self.assertEqual(self._get_summary_line(set().__contains__),
1594 "__contains__(object, /) method of builtins.set instance")
1595
1596 def test_unbound_builtin_classmethod_noargs(self):
1597 self.assertEqual(self._get_summary_line(datetime.datetime.__dict__['utcnow']),
1598 "utcnow(type, /) unbound datetime.datetime method")
1599
1600 def test_bound_builtin_classmethod_noargs(self):
1601 self.assertEqual(self._get_summary_line(datetime.datetime.utcnow),
1602 "utcnow() class method of datetime.datetime")
1603
1604 def test_unbound_builtin_classmethod_o(self):
1605 self.assertEqual(self._get_summary_line(dict.__dict__['__class_getitem__']),
1606 "__class_getitem__(type, object, /) unbound builtins.dict method")
1607
1608 def test_bound_builtin_classmethod_o(self):
1609 self.assertEqual(self._get_summary_line(dict.__class_getitem__),
1610 "__class_getitem__(object, /) class method of builtins.dict")
1611
1612 @support.cpython_only
1613 @requires_docstrings
1614 def test_module_level_callable_unrepresentable_default(self):
1615 _testcapi = import_helper.import_module("_testcapi")
1616 builtin = _testcapi.func_with_unrepresentable_signature
1617 self.assertEqual(self._get_summary_line(builtin),
1618 "func_with_unrepresentable_signature(a, b=<x>)")
1619
1620 @support.cpython_only
1621 @requires_docstrings
1622 def test_builtin_staticmethod_unrepresentable_default(self):
1623 self.assertEqual(self._get_summary_line(str.maketrans),
1624 "maketrans(x, y=<unrepresentable>, z=<unrepresentable>, /)")
1625 _testcapi = import_helper.import_module("_testcapi")
1626 cls = _testcapi.DocStringUnrepresentableSignatureTest
1627 self.assertEqual(self._get_summary_line(cls.staticmeth),
1628 "staticmeth(a, b=<x>)")
1629
1630 @support.cpython_only
1631 @requires_docstrings
1632 def test_unbound_builtin_method_unrepresentable_default(self):
1633 self.assertEqual(self._get_summary_line(dict.pop),
1634 "pop(self, key, default=<unrepresentable>, /) "
1635 "unbound builtins.dict method")
1636 _testcapi = import_helper.import_module("_testcapi")
1637 cls = _testcapi.DocStringUnrepresentableSignatureTest
1638 self.assertEqual(self._get_summary_line(cls.meth),
1639 "meth(self, /, a, b=<x>) unbound "
1640 "_testcapi.DocStringUnrepresentableSignatureTest method")
1641
1642 @support.cpython_only
1643 @requires_docstrings
1644 def test_bound_builtin_method_unrepresentable_default(self):
1645 self.assertEqual(self._get_summary_line({}.pop),
1646 "pop(key, default=<unrepresentable>, /) "
1647 "method of builtins.dict instance")
1648 _testcapi = import_helper.import_module("_testcapi")
1649 obj = _testcapi.DocStringUnrepresentableSignatureTest()
1650 self.assertEqual(self._get_summary_line(obj.meth),
1651 "meth(a, b=<x>) "
1652 "method of _testcapi.DocStringUnrepresentableSignatureTest instance")
1653
1654 @support.cpython_only
1655 @requires_docstrings
1656 def test_unbound_builtin_classmethod_unrepresentable_default(self):
1657 _testcapi = import_helper.import_module("_testcapi")
1658 cls = _testcapi.DocStringUnrepresentableSignatureTest
1659 descr = cls.__dict__['classmeth']
1660 self.assertEqual(self._get_summary_line(descr),
1661 "classmeth(type, /, a, b=<x>) unbound "
1662 "_testcapi.DocStringUnrepresentableSignatureTest method")
1663
1664 @support.cpython_only
1665 @requires_docstrings
1666 def test_bound_builtin_classmethod_unrepresentable_default(self):
1667 _testcapi = import_helper.import_module("_testcapi")
1668 cls = _testcapi.DocStringUnrepresentableSignatureTest
1669 self.assertEqual(self._get_summary_line(cls.classmeth),
1670 "classmeth(a, b=<x>) class method of "
1671 "_testcapi.DocStringUnrepresentableSignatureTest")
1672
1673 def test_overridden_text_signature(self):
1674 class C:
1675 def meth(*args, **kwargs):
1676 pass
1677 @classmethod
1678 def cmeth(*args, **kwargs):
1679 pass
1680 @staticmethod
1681 def smeth(*args, **kwargs):
1682 pass
1683 for text_signature, unbound, bound in [
1684 ("($slf)", "(slf, /)", "()"),
1685 ("($slf, /)", "(slf, /)", "()"),
1686 ("($slf, /, arg)", "(slf, /, arg)", "(arg)"),
1687 ("($slf, /, arg=<x>)", "(slf, /, arg=<x>)", "(arg=<x>)"),
1688 ("($slf, arg, /)", "(slf, arg, /)", "(arg, /)"),
1689 ("($slf, arg=<x>, /)", "(slf, arg=<x>, /)", "(arg=<x>, /)"),
1690 ("(/, slf, arg)", "(/, slf, arg)", "(/, slf, arg)"),
1691 ("(/, slf, arg=<x>)", "(/, slf, arg=<x>)", "(/, slf, arg=<x>)"),
1692 ("(slf, /, arg)", "(slf, /, arg)", "(arg)"),
1693 ("(slf, /, arg=<x>)", "(slf, /, arg=<x>)", "(arg=<x>)"),
1694 ("(slf, arg, /)", "(slf, arg, /)", "(arg, /)"),
1695 ("(slf, arg=<x>, /)", "(slf, arg=<x>, /)", "(arg=<x>, /)"),
1696 ]:
1697 with self.subTest(text_signature):
1698 C.meth.__text_signature__ = text_signature
1699 self.assertEqual(self._get_summary_line(C.meth),
1700 "meth" + unbound)
1701 self.assertEqual(self._get_summary_line(C().meth),
1702 "meth" + bound + " method of test.test_pydoc.test_pydoc.C instance")
1703 C.cmeth.__func__.__text_signature__ = text_signature
1704 self.assertEqual(self._get_summary_line(C.cmeth),
1705 "cmeth" + bound + " class method of test.test_pydoc.test_pydoc.C")
1706 C.smeth.__text_signature__ = text_signature
1707 self.assertEqual(self._get_summary_line(C.smeth),
1708 "smeth" + unbound)
1709
1710 @requires_docstrings
1711 def test_staticmethod(self):
1712 class X:
1713 @staticmethod
1714 def sm(x, y):
1715 '''A static method'''
1716 ...
1717 self.assertEqual(self._get_summary_lines(X.__dict__['sm']),
1718 'sm(x, y)\n'
1719 ' A static method\n')
1720 self.assertEqual(self._get_summary_lines(X.sm), """\
1721 sm(x, y)
1722 A static method
1723 """)
1724 self.assertIn("""
1725 | Static methods defined here:
1726 |
1727 | sm(x, y)
1728 | A static method
1729 """, pydoc.plain(pydoc.render_doc(X)))
1730
1731 @requires_docstrings
1732 def test_classmethod(self):
1733 class X:
1734 @classmethod
1735 def cm(cls, x):
1736 '''A class method'''
1737 ...
1738 self.assertEqual(self._get_summary_lines(X.__dict__['cm']),
1739 'cm(...)\n'
1740 ' A class method\n')
1741 self.assertEqual(self._get_summary_lines(X.cm), """\
1742 cm(x) class method of test.test_pydoc.test_pydoc.X
1743 A class method
1744 """)
1745 self.assertIn("""
1746 | Class methods defined here:
1747 |
1748 | cm(x)
1749 | A class method
1750 """, pydoc.plain(pydoc.render_doc(X)))
1751
1752 @requires_docstrings
1753 def test_getset_descriptor(self):
1754 # Currently these attributes are implemented as getset descriptors
1755 # in CPython.
1756 self.assertEqual(self._get_summary_line(int.numerator), "numerator")
1757 self.assertEqual(self._get_summary_line(float.real), "real")
1758 self.assertEqual(self._get_summary_line(Exception.args), "args")
1759 self.assertEqual(self._get_summary_line(memoryview.obj), "obj")
1760
1761 @requires_docstrings
1762 def test_member_descriptor(self):
1763 # Currently these attributes are implemented as member descriptors
1764 # in CPython.
1765 self.assertEqual(self._get_summary_line(complex.real), "real")
1766 self.assertEqual(self._get_summary_line(range.start), "start")
1767 self.assertEqual(self._get_summary_line(slice.start), "start")
1768 self.assertEqual(self._get_summary_line(property.fget), "fget")
1769 self.assertEqual(self._get_summary_line(StopIteration.value), "value")
1770
1771 @requires_docstrings
1772 def test_slot_descriptor(self):
1773 class Point:
1774 __slots__ = 'x', 'y'
1775 self.assertEqual(self._get_summary_line(Point.x), "x")
1776
1777 @requires_docstrings
1778 def test_dict_attr_descriptor(self):
1779 class NS:
1780 pass
1781 self.assertEqual(self._get_summary_line(NS.__dict__['__dict__']),
1782 "__dict__")
1783
1784 @requires_docstrings
1785 def test_structseq_member_descriptor(self):
1786 self.assertEqual(self._get_summary_line(type(sys.hash_info).width),
1787 "width")
1788 self.assertEqual(self._get_summary_line(type(sys.flags).debug),
1789 "debug")
1790 self.assertEqual(self._get_summary_line(type(sys.version_info).major),
1791 "major")
1792 self.assertEqual(self._get_summary_line(type(sys.float_info).max),
1793 "max")
1794
1795 @requires_docstrings
1796 def test_namedtuple_field_descriptor(self):
1797 Box = namedtuple('Box', ('width', 'height'))
1798 self.assertEqual(self._get_summary_lines(Box.width), """\
1799 Alias for field number 0
1800 """)
1801
1802 @requires_docstrings
1803 def test_property(self):
1804 self.assertEqual(self._get_summary_lines(Rect.area), """\
1805 area
1806 Area of the rect
1807 """)
1808 # inherits the docstring from Rect.area
1809 self.assertEqual(self._get_summary_lines(Square.area), """\
1810 area
1811 Area of the rect
1812 """)
1813 self.assertIn("""
1814 | area
1815 | Area of the rect
1816 """, pydoc.plain(pydoc.render_doc(Rect)))
1817
1818 @requires_docstrings
1819 def test_custom_non_data_descriptor(self):
1820 class Descr:
1821 def __get__(self, obj, cls):
1822 if obj is None:
1823 return self
1824 return 42
1825 class X:
1826 attr = Descr()
1827
1828 self.assertEqual(self._get_summary_lines(X.attr), f"""\
1829 <{__name__}.TestDescriptions.test_custom_non_data_descriptor.<locals>.Descr object>""")
1830
1831 X.attr.__doc__ = 'Custom descriptor'
1832 self.assertEqual(self._get_summary_lines(X.attr), f"""\
1833 <{__name__}.TestDescriptions.test_custom_non_data_descriptor.<locals>.Descr object>
1834 Custom descriptor
1835 """)
1836
1837 X.attr.__name__ = 'foo'
1838 self.assertEqual(self._get_summary_lines(X.attr), """\
1839 foo(...)
1840 Custom descriptor
1841 """)
1842
1843 @requires_docstrings
1844 def test_custom_data_descriptor(self):
1845 class Descr:
1846 def __get__(self, obj, cls):
1847 if obj is None:
1848 return self
1849 return 42
1850 def __set__(self, obj, cls):
1851 1/0
1852 class X:
1853 attr = Descr()
1854
1855 self.assertEqual(self._get_summary_lines(X.attr), "")
1856
1857 X.attr.__doc__ = 'Custom descriptor'
1858 self.assertEqual(self._get_summary_lines(X.attr), """\
1859 Custom descriptor
1860 """)
1861
1862 X.attr.__name__ = 'foo'
1863 self.assertEqual(self._get_summary_lines(X.attr), """\
1864 foo
1865 Custom descriptor
1866 """)
1867
1868 def test_async_annotation(self):
1869 async def coro_function(ign) -> int:
1870 return 1
1871
1872 text = pydoc.plain(pydoc.plaintext.document(coro_function))
1873 self.assertIn('async coro_function', text)
1874
1875 html = pydoc.HTMLDoc().document(coro_function)
1876 self.assertIn(
1877 'async <a name="-coro_function"><strong>coro_function',
1878 html)
1879
1880 def test_async_generator_annotation(self):
1881 async def an_async_generator():
1882 yield 1
1883
1884 text = pydoc.plain(pydoc.plaintext.document(an_async_generator))
1885 self.assertIn('async an_async_generator', text)
1886
1887 html = pydoc.HTMLDoc().document(an_async_generator)
1888 self.assertIn(
1889 'async <a name="-an_async_generator"><strong>an_async_generator',
1890 html)
1891
1892 @requires_docstrings
1893 def test_html_for_https_links(self):
1894 def a_fn_with_https_link():
1895 """a link https://localhost/"""
1896 pass
1897
1898 html = pydoc.HTMLDoc().document(a_fn_with_https_link)
1899 self.assertIn(
1900 '<a href="https://localhost/">https://localhost/</a>',
1901 html
1902 )
1903
1904 def test_module_none(self):
1905 # Issue #128772
1906 from test.test_pydoc import module_none
1907 pydoc.render_doc(module_none)
1908
1909
1910 class PydocFodderTest(unittest.TestCase):
1911 def tearDown(self):
1912 self.assertIs(sys.modules['pydoc'], pydoc)
1913
1914 def getsection(self, text, beginline, endline):
1915 lines = text.splitlines()
1916 beginindex, endindex = 0, None
1917 if beginline is not None:
1918 beginindex = lines.index(beginline)
1919 if endline is not None:
1920 endindex = lines.index(endline, beginindex)
1921 return lines[beginindex:endindex]
1922
1923 def test_text_doc_routines_in_class(self, cls=pydocfodder.B):
1924 doc = pydoc.TextDoc()
1925 result = doc.docclass(cls)
1926 result = clean_text(result)
1927 where = 'defined here' if cls is pydocfodder.B else 'inherited from B'
1928 lines = self.getsection(result, f' | Methods {where}:', ' | ' + '-'*70)
1929 self.assertIn(' | A_method_alias = A_method(self)', lines)
1930 self.assertIn(' | B_method_alias = B_method(self)', lines)
1931 self.assertIn(' | A_staticmethod(x, y) from test.test_pydoc.pydocfodder.A', lines)
1932 self.assertIn(' | A_staticmethod_alias = A_staticmethod(x, y)', lines)
1933 self.assertIn(' | global_func(x, y) from test.test_pydoc.pydocfodder', lines)
1934 self.assertIn(' | global_func_alias = global_func(x, y)', lines)
1935 self.assertIn(' | global_func2_alias = global_func2(x, y) from test.test_pydoc.pydocfodder', lines)
1936 if not support.MISSING_C_DOCSTRINGS:
1937 self.assertIn(' | count(self, value, /) from builtins.list', lines)
1938 self.assertIn(' | list_count = count(self, value, /)', lines)
1939 self.assertIn(' | __repr__(self, /) from builtins.object', lines)
1940 self.assertIn(' | object_repr = __repr__(self, /)', lines)
1941 else:
1942 self.assertIn(' | count(self, object, /) from builtins.list', lines)
1943 self.assertIn(' | list_count = count(self, object, /)', lines)
1944 self.assertIn(' | __repr__(...) from builtins.object', lines)
1945 self.assertIn(' | object_repr = __repr__(...)', lines)
1946
1947 lines = self.getsection(result, f' | Static methods {where}:', ' | ' + '-'*70)
1948 self.assertIn(' | A_classmethod_ref = A_classmethod(x) class method of test.test_pydoc.pydocfodder.A', lines)
1949 note = '' if cls is pydocfodder.B else ' class method of test.test_pydoc.pydocfodder.B'
1950 self.assertIn(' | B_classmethod_ref = B_classmethod(x)' + note, lines)
1951 self.assertIn(' | A_method_ref = A_method() method of test.test_pydoc.pydocfodder.A instance', lines)
1952 if not support.MISSING_C_DOCSTRINGS:
1953 self.assertIn(' | get(key, default=None, /) method of builtins.dict instance', lines)
1954 self.assertIn(' | dict_get = get(key, default=None, /) method of builtins.dict instance', lines)
1955 self.assertIn(' | sin(x, /)', lines)
1956 else:
1957 self.assertIn(' | get(...) method of builtins.dict instance', lines)
1958 self.assertIn(' | dict_get = get(...) method of builtins.dict instance', lines)
1959 self.assertIn(' | sin(object, /)', lines)
1960
1961 lines = self.getsection(result, f' | Class methods {where}:', ' | ' + '-'*70)
1962 self.assertIn(' | B_classmethod(x)', lines)
1963 self.assertIn(' | B_classmethod_alias = B_classmethod(x)', lines)
1964
1965 def test_html_doc_routines_in_class(self, cls=pydocfodder.B):
1966 doc = pydoc.HTMLDoc()
1967 result = doc.docclass(cls)
1968 result = html2text(result)
1969 where = 'defined here' if cls is pydocfodder.B else 'inherited from B'
1970 lines = self.getsection(result, f'Methods {where}:', '-'*70)
1971 self.assertIn('A_method_alias = A_method(self)', lines)
1972 self.assertIn('B_method_alias = B_method(self)', lines)
1973 self.assertIn('A_staticmethod(x, y) from test.test_pydoc.pydocfodder.A', lines)
1974 self.assertIn('A_staticmethod_alias = A_staticmethod(x, y)', lines)
1975 self.assertIn('global_func(x, y) from test.test_pydoc.pydocfodder', lines)
1976 self.assertIn('global_func_alias = global_func(x, y)', lines)
1977 self.assertIn('global_func2_alias = global_func2(x, y) from test.test_pydoc.pydocfodder', lines)
1978 if not support.MISSING_C_DOCSTRINGS:
1979 self.assertIn('count(self, value, /) from builtins.list', lines)
1980 self.assertIn('list_count = count(self, value, /)', lines)
1981 self.assertIn('__repr__(self, /) from builtins.object', lines)
1982 self.assertIn('object_repr = __repr__(self, /)', lines)
1983 else:
1984 self.assertIn('count(self, object, /) from builtins.list', lines)
1985 self.assertIn('list_count = count(self, object, /)', lines)
1986 self.assertIn('__repr__(...) from builtins.object', lines)
1987 self.assertIn('object_repr = __repr__(...)', lines)
1988
1989 lines = self.getsection(result, f'Static methods {where}:', '-'*70)
1990 self.assertIn('A_classmethod_ref = A_classmethod(x) class method of test.test_pydoc.pydocfodder.A', lines)
1991 note = '' if cls is pydocfodder.B else ' class method of test.test_pydoc.pydocfodder.B'
1992 self.assertIn('B_classmethod_ref = B_classmethod(x)' + note, lines)
1993 self.assertIn('A_method_ref = A_method() method of test.test_pydoc.pydocfodder.A instance', lines)
1994
1995 lines = self.getsection(result, f'Class methods {where}:', '-'*70)
1996 self.assertIn('B_classmethod(x)', lines)
1997 self.assertIn('B_classmethod_alias = B_classmethod(x)', lines)
1998
1999 def test_text_doc_inherited_routines_in_class(self):
2000 self.test_text_doc_routines_in_class(pydocfodder.D)
2001
2002 def test_html_doc_inherited_routines_in_class(self):
2003 self.test_html_doc_routines_in_class(pydocfodder.D)
2004
2005 def test_text_doc_routines_in_module(self):
2006 doc = pydoc.TextDoc()
2007 result = doc.docmodule(pydocfodder)
2008 result = clean_text(result)
2009 lines = self.getsection(result, 'FUNCTIONS', 'FILE')
2010 # function alias
2011 self.assertIn(' global_func_alias = global_func(x, y)', lines)
2012 self.assertIn(' A_staticmethod(x, y)', lines)
2013 self.assertIn(' A_staticmethod_alias = A_staticmethod(x, y)', lines)
2014 # bound class methods
2015 self.assertIn(' A_classmethod(x) class method of A', lines)
2016 self.assertIn(' A_classmethod2 = A_classmethod(x) class method of A', lines)
2017 self.assertIn(' A_classmethod3 = A_classmethod(x) class method of B', lines)
2018 # bound methods
2019 self.assertIn(' A_method() method of A instance', lines)
2020 self.assertIn(' A_method2 = A_method() method of A instance', lines)
2021 self.assertIn(' A_method3 = A_method() method of B instance', lines)
2022 self.assertIn(' A_staticmethod_ref = A_staticmethod(x, y)', lines)
2023 self.assertIn(' A_staticmethod_ref2 = A_staticmethod(y) method of B instance', lines)
2024 if not support.MISSING_C_DOCSTRINGS:
2025 self.assertIn(' get(key, default=None, /) method of builtins.dict instance', lines)
2026 self.assertIn(' dict_get = get(key, default=None, /) method of builtins.dict instance', lines)
2027 else:
2028 self.assertIn(' get(...) method of builtins.dict instance', lines)
2029 self.assertIn(' dict_get = get(...) method of builtins.dict instance', lines)
2030
2031 # unbound methods
2032 self.assertIn(' B_method(self)', lines)
2033 self.assertIn(' B_method2 = B_method(self)', lines)
2034 if not support.MISSING_C_DOCSTRINGS:
2035 self.assertIn(' count(self, value, /) unbound builtins.list method', lines)
2036 self.assertIn(' list_count = count(self, value, /) unbound builtins.list method', lines)
2037 self.assertIn(' __repr__(self, /) unbound builtins.object method', lines)
2038 self.assertIn(' object_repr = __repr__(self, /) unbound builtins.object method', lines)
2039 else:
2040 self.assertIn(' count(self, object, /) unbound builtins.list method', lines)
2041 self.assertIn(' list_count = count(self, object, /) unbound builtins.list method', lines)
2042 self.assertIn(' __repr__(...) unbound builtins.object method', lines)
2043 self.assertIn(' object_repr = __repr__(...) unbound builtins.object method', lines)
2044
2045 # builtin functions
2046 if not support.MISSING_C_DOCSTRINGS:
2047 self.assertIn(' sin(x, /)', lines)
2048 else:
2049 self.assertIn(' sin(object, /)', lines)
2050
2051 def test_html_doc_routines_in_module(self):
2052 doc = pydoc.HTMLDoc()
2053 result = doc.docmodule(pydocfodder)
2054 result = html2text(result)
2055 lines = self.getsection(result, ' Functions', None)
2056 # function alias
2057 self.assertIn(' global_func_alias = global_func(x, y)', lines)
2058 self.assertIn(' A_staticmethod(x, y)', lines)
2059 self.assertIn(' A_staticmethod_alias = A_staticmethod(x, y)', lines)
2060 # bound class methods
2061 self.assertIn('A_classmethod(x) class method of A', lines)
2062 self.assertIn(' A_classmethod2 = A_classmethod(x) class method of A', lines)
2063 self.assertIn(' A_classmethod3 = A_classmethod(x) class method of B', lines)
2064 # bound methods
2065 self.assertIn(' A_method() method of A instance', lines)
2066 self.assertIn(' A_method2 = A_method() method of A instance', lines)
2067 self.assertIn(' A_method3 = A_method() method of B instance', lines)
2068 self.assertIn(' A_staticmethod_ref = A_staticmethod(x, y)', lines)
2069 self.assertIn(' A_staticmethod_ref2 = A_staticmethod(y) method of B instance', lines)
2070 if not support.MISSING_C_DOCSTRINGS:
2071 self.assertIn(' get(key, default=None, /) method of builtins.dict instance', lines)
2072 self.assertIn(' dict_get = get(key, default=None, /) method of builtins.dict instance', lines)
2073 else:
2074 self.assertIn(' get(...) method of builtins.dict instance', lines)
2075 self.assertIn(' dict_get = get(...) method of builtins.dict instance', lines)
2076 # unbound methods
2077 self.assertIn(' B_method(self)', lines)
2078 self.assertIn(' B_method2 = B_method(self)', lines)
2079 if not support.MISSING_C_DOCSTRINGS:
2080 self.assertIn(' count(self, value, /) unbound builtins.list method', lines)
2081 self.assertIn(' list_count = count(self, value, /) unbound builtins.list method', lines)
2082 self.assertIn(' __repr__(self, /) unbound builtins.object method', lines)
2083 self.assertIn(' object_repr = __repr__(self, /) unbound builtins.object method', lines)
2084 else:
2085 self.assertIn(' count(self, object, /) unbound builtins.list method', lines)
2086 self.assertIn(' list_count = count(self, object, /) unbound builtins.list method', lines)
2087 self.assertIn(' __repr__(...) unbound builtins.object method', lines)
2088 self.assertIn(' object_repr = __repr__(...) unbound builtins.object method', lines)
2089
2090 # builtin functions
2091 if not support.MISSING_C_DOCSTRINGS:
2092 self.assertIn(' sin(x, /)', lines)
2093 else:
2094 self.assertIn(' sin(object, /)', lines)
2095
2096
2097 @unittest.skipIf(
2098 is_emscripten or is_wasi,
2099 "Socket server not available on Emscripten/WASI."
2100 )
2101 class PydocServerTest(unittest.TestCase):
2102 """Tests for pydoc._start_server"""
2103 def tearDown(self):
2104 self.assertIs(sys.modules['pydoc'], pydoc)
2105
2106 def test_server(self):
2107 # Minimal test that starts the server, checks that it works, then stops
2108 # it and checks its cleanup.
2109 def my_url_handler(url, content_type):
2110 text = 'the URL sent was: (%s, %s)' % (url, content_type)
2111 return text
2112
2113 serverthread = pydoc._start_server(
2114 my_url_handler,
2115 hostname='localhost',
2116 port=0,
2117 )
2118 self.assertEqual(serverthread.error, None)
2119 self.assertTrue(serverthread.serving)
2120 self.addCleanup(
2121 lambda: serverthread.stop() if serverthread.serving else None
2122 )
2123 self.assertIn('localhost', serverthread.url)
2124
2125 self.addCleanup(urlcleanup)
2126 self.assertEqual(
2127 b'the URL sent was: (/test, text/html)',
2128 urlopen(urllib.parse.urljoin(serverthread.url, '/test')).read(),
2129 )
2130 self.assertEqual(
2131 b'the URL sent was: (/test.css, text/css)',
2132 urlopen(urllib.parse.urljoin(serverthread.url, '/test.css')).read(),
2133 )
2134
2135 serverthread.stop()
2136 self.assertFalse(serverthread.serving)
2137 self.assertIsNone(serverthread.docserver)
2138 self.assertIsNone(serverthread.url)
2139
2140
2141 class PydocUrlHandlerTest(PydocBaseTest):
2142 """Tests for pydoc._url_handler"""
2143
2144 def test_content_type_err(self):
2145 f = pydoc._url_handler
2146 self.assertRaises(TypeError, f, 'A', '')
2147 self.assertRaises(TypeError, f, 'B', 'foobar')
2148
2149 def test_url_requests(self):
2150 # Test for the correct title in the html pages returned.
2151 # This tests the different parts of the URL handler without
2152 # getting too picky about the exact html.
2153 requests = [
2154 ("", "Pydoc: Index of Modules"),
2155 ("get?key=", "Pydoc: Index of Modules"),
2156 ("index", "Pydoc: Index of Modules"),
2157 ("topics", "Pydoc: Topics"),
2158 ("keywords", "Pydoc: Keywords"),
2159 ("pydoc", "Pydoc: module pydoc"),
2160 ("get?key=pydoc", "Pydoc: module pydoc"),
2161 ("search?key=pydoc", "Pydoc: Search Results"),
2162 ("topic?key=def", "Pydoc: KEYWORD def"),
2163 ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
2164 ("foobar", "Pydoc: Error - foobar"),
2165 ]
2166
2167 self.assertIs(sys.modules['pydoc'], pydoc)
2168 try:
2169 with self.restrict_walk_packages():
2170 for url, title in requests:
2171 self.call_url_handler(url, title)
2172 finally:
2173 # Some requests reload the module and change sys.modules.
2174 sys.modules['pydoc'] = pydoc
2175
2176
2177 class TestHelper(unittest.TestCase):
2178 def mock_interactive_session(self, inputs):
2179 """
2180 Given a list of inputs, run an interactive help session. Returns a string
2181 of what would be shown on screen.
2182 """
2183 input_iter = iter(inputs)
2184
2185 def mock_getline(prompt):
2186 output.write(prompt)
2187 next_input = next(input_iter)
2188 output.write(next_input + os.linesep)
2189 return next_input
2190
2191 with captured_stdout() as output:
2192 helper = pydoc.Helper(output=output)
2193 with unittest.mock.patch.object(helper, "getline", mock_getline):
2194 helper.interact()
2195
2196 # handle different line endings across platforms consistently
2197 return output.getvalue().strip().splitlines(keepends=False)
2198
2199 def test_keywords(self):
2200 self.assertEqual(sorted(pydoc.Helper.keywords),
2201 sorted(keyword.kwlist))
2202
2203 def test_interact_empty_line_continues(self):
2204 # gh-138568: test pressing Enter without input should continue in help session
2205 self.assertEqual(
2206 self.mock_interactive_session(["", " ", "quit"]),
2207 ["help> ", "help> ", "help> quit"],
2208 )
2209
2210 def test_interact_quit_commands_exit(self):
2211 quit_commands = ["quit", "q", "exit"]
2212 for quit_cmd in quit_commands:
2213 with self.subTest(quit_command=quit_cmd):
2214 self.assertEqual(
2215 self.mock_interactive_session([quit_cmd]),
2216 [f"help> {quit_cmd}"],
2217 )
2218
2219
2220 class PydocWithMetaClasses(unittest.TestCase):
2221 def tearDown(self):
2222 self.assertIs(sys.modules['pydoc'], pydoc)
2223
2224 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
2225 'trace function introduces __locals__ unexpectedly')
2226 @requires_docstrings
2227 def test_DynamicClassAttribute(self):
2228 class Meta(type):
2229 def __getattr__(self, name):
2230 if name == 'ham':
2231 return 'spam'
2232 return super().__getattr__(name)
2233 class DA(metaclass=Meta):
2234 @types.DynamicClassAttribute
2235 def ham(self):
2236 return 'eggs'
2237 expected_text_data_docstrings = tuple('\n | ' + s if s else ''
2238 for s in expected_data_docstrings)
2239 output = StringIO()
2240 helper = pydoc.Helper(output=output)
2241 helper(DA)
2242 expected_text = expected_dynamicattribute_pattern % (
2243 (__name__,) + expected_text_data_docstrings[:2])
2244 result = output.getvalue().strip()
2245 self.assertEqual(expected_text, result)
2246
2247 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
2248 'trace function introduces __locals__ unexpectedly')
2249 @requires_docstrings
2250 def test_virtualClassAttributeWithOneMeta(self):
2251 class Meta(type):
2252 def __dir__(cls):
2253 return ['__class__', '__module__', '__name__', 'LIFE']
2254 def __getattr__(self, name):
2255 if name =='LIFE':
2256 return 42
2257 return super().__getattr(name)
2258 class Class(metaclass=Meta):
2259 pass
2260 output = StringIO()
2261 helper = pydoc.Helper(output=output)
2262 helper(Class)
2263 expected_text = expected_virtualattribute_pattern1 % __name__
2264 result = output.getvalue().strip()
2265 self.assertEqual(expected_text, result)
2266
2267 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
2268 'trace function introduces __locals__ unexpectedly')
2269 @requires_docstrings
2270 def test_virtualClassAttributeWithTwoMeta(self):
2271 class Meta1(type):
2272 def __dir__(cls):
2273 return ['__class__', '__module__', '__name__', 'one']
2274 def __getattr__(self, name):
2275 if name =='one':
2276 return 1
2277 return super().__getattr__(name)
2278 class Meta2(type):
2279 def __dir__(cls):
2280 return ['__class__', '__module__', '__name__', 'two']
2281 def __getattr__(self, name):
2282 if name =='two':
2283 return 2
2284 return super().__getattr__(name)
2285 class Meta3(Meta1, Meta2):
2286 def __dir__(cls):
2287 return list(sorted(set(
2288 ['__class__', '__module__', '__name__', 'three'] +
2289 Meta1.__dir__(cls) + Meta2.__dir__(cls))))
2290 def __getattr__(self, name):
2291 if name =='three':
2292 return 3
2293 return super().__getattr__(name)
2294 class Class1(metaclass=Meta1):
2295 pass
2296 class Class2(Class1, metaclass=Meta3):
2297 pass
2298 output = StringIO()
2299 helper = pydoc.Helper(output=output)
2300 helper(Class1)
2301 expected_text1 = expected_virtualattribute_pattern2 % __name__
2302 result1 = output.getvalue().strip()
2303 self.assertEqual(expected_text1, result1)
2304 output = StringIO()
2305 helper = pydoc.Helper(output=output)
2306 helper(Class2)
2307 expected_text2 = expected_virtualattribute_pattern3 % __name__
2308 result2 = output.getvalue().strip()
2309 self.assertEqual(expected_text2, result2)
2310
2311 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
2312 'trace function introduces __locals__ unexpectedly')
2313 @requires_docstrings
2314 def test_buggy_dir(self):
2315 class M(type):
2316 def __dir__(cls):
2317 return ['__class__', '__name__', 'missing', 'here']
2318 class C(metaclass=M):
2319 here = 'present!'
2320 output = StringIO()
2321 helper = pydoc.Helper(output=output)
2322 helper(C)
2323 expected_text = expected_missingattribute_pattern % __name__
2324 result = output.getvalue().strip()
2325 self.assertEqual(expected_text, result)
2326
2327 def test_resolve_false(self):
2328 # Issue #23008: pydoc enum.{,Int}Enum failed
2329 # because bool(enum.Enum) is False.
2330 with captured_stdout() as help_io:
2331 pydoc.help('enum.Enum')
2332 helptext = help_io.getvalue()
2333 self.assertIn('class Enum', helptext)
2334
2335
2336 class TestInternalUtilities(unittest.TestCase):
2337
2338 def setUp(self):
2339 tmpdir = tempfile.TemporaryDirectory()
2340 self.argv0dir = tmpdir.name
2341 self.argv0 = os.path.join(tmpdir.name, "nonexistent")
2342 self.addCleanup(tmpdir.cleanup)
2343 self.abs_curdir = abs_curdir = os.getcwd()
2344 self.curdir_spellings = ["", os.curdir, abs_curdir]
2345
2346 def _get_revised_path(self, given_path, argv0=None):
2347 # Checking that pydoc.cli() actually calls pydoc._get_revised_path()
2348 # is handled via code review (at least for now).
2349 if argv0 is None:
2350 argv0 = self.argv0
2351 return pydoc._get_revised_path(given_path, argv0)
2352
2353 def _get_starting_path(self):
2354 # Get a copy of sys.path without the current directory.
2355 clean_path = sys.path.copy()
2356 for spelling in self.curdir_spellings:
2357 for __ in range(clean_path.count(spelling)):
2358 clean_path.remove(spelling)
2359 return clean_path
2360
2361 def test_sys_path_adjustment_adds_missing_curdir(self):
2362 clean_path = self._get_starting_path()
2363 expected_path = [self.abs_curdir] + clean_path
2364 self.assertEqual(self._get_revised_path(clean_path), expected_path)
2365
2366 def test_sys_path_adjustment_removes_argv0_dir(self):
2367 clean_path = self._get_starting_path()
2368 expected_path = [self.abs_curdir] + clean_path
2369 leading_argv0dir = [self.argv0dir] + clean_path
2370 self.assertEqual(self._get_revised_path(leading_argv0dir), expected_path)
2371 trailing_argv0dir = clean_path + [self.argv0dir]
2372 self.assertEqual(self._get_revised_path(trailing_argv0dir), expected_path)
2373
2374 def test_sys_path_adjustment_protects_pydoc_dir(self):
2375 def _get_revised_path(given_path):
2376 return self._get_revised_path(given_path, argv0=pydoc.__file__)
2377 clean_path = self._get_starting_path()
2378 leading_argv0dir = [self.argv0dir] + clean_path
2379 expected_path = [self.abs_curdir] + leading_argv0dir
2380 self.assertEqual(_get_revised_path(leading_argv0dir), expected_path)
2381 trailing_argv0dir = clean_path + [self.argv0dir]
2382 expected_path = [self.abs_curdir] + trailing_argv0dir
2383 self.assertEqual(_get_revised_path(trailing_argv0dir), expected_path)
2384
2385 def test_sys_path_adjustment_when_curdir_already_included(self):
2386 clean_path = self._get_starting_path()
2387 for spelling in self.curdir_spellings:
2388 with self.subTest(curdir_spelling=spelling):
2389 # If curdir is already present, no alterations are made at all
2390 leading_curdir = [spelling] + clean_path
2391 self.assertIsNone(self._get_revised_path(leading_curdir))
2392 trailing_curdir = clean_path + [spelling]
2393 self.assertIsNone(self._get_revised_path(trailing_curdir))
2394 leading_argv0dir = [self.argv0dir] + leading_curdir
2395 self.assertIsNone(self._get_revised_path(leading_argv0dir))
2396 trailing_argv0dir = trailing_curdir + [self.argv0dir]
2397 self.assertIsNone(self._get_revised_path(trailing_argv0dir))
2398
2399
2400 def setUpModule():
2401 thread_info = threading_helper.threading_setup()
2402 unittest.addModuleCleanup(threading_helper.threading_cleanup, *thread_info)
2403 unittest.addModuleCleanup(reap_children)
2404
2405
2406 if __name__ == "__main__":
2407 unittest.main()