| 1 |
import os |
| 2 |
import sys |
| 3 |
import contextlib |
| 4 |
import importlib.util |
| 5 |
import inspect |
| 6 |
import pydoc |
| 7 |
import py_compile |
| 8 |
import keyword |
| 9 |
import pkgutil |
| 10 |
import re |
| 11 |
import stat |
| 12 |
import tempfile |
| 13 |
import test.support |
| 14 |
import types |
| 15 |
import typing |
| 16 |
import unittest |
| 17 |
import urllib.parse |
| 18 |
import xml.etree |
| 19 |
import xml.etree.ElementTree |
| 20 |
import textwrap |
| 21 |
from io import StringIO |
| 22 |
from collections import namedtuple |
| 23 |
from urllib.request import urlopen, urlcleanup |
| 24 |
from test import support |
| 25 |
from test.support import import_helper |
| 26 |
from test.support import os_helper |
| 27 |
from test.support.script_helper import (assert_python_ok, |
| 28 |
assert_python_failure, spawn_python) |
| 29 |
from test.support import threading_helper |
| 30 |
from test.support import (reap_children, captured_output, captured_stdout, |
| 31 |
captured_stderr, is_emscripten, is_wasi, |
| 32 |
requires_docstrings, MISSING_C_DOCSTRINGS) |
| 33 |
from test.support.os_helper import (TESTFN, rmtree, unlink) |
| 34 |
from test.test_pydoc import pydoc_mod |
| 35 |
from test.test_pydoc import pydocfodder |
| 36 |
|
| 37 |
|
| 38 |
class nonascii: |
| 39 |
'Це не латиниця' |
| 40 |
pass |
| 41 |
|
| 42 |
if test.support.HAVE_DOCSTRINGS: |
| 43 |
expected_data_docstrings = ( |
| 44 |
'dictionary for instance variables', |
| 45 |
'list of weak references to the object', |
| 46 |
) * 2 |
| 47 |
else: |
| 48 |
expected_data_docstrings = ('', '', '', '') |
| 49 |
|
| 50 |
expected_text_pattern = """ |
| 51 |
NAME |
| 52 |
test.test_pydoc.pydoc_mod - This is a test module for test_pydoc |
| 53 |
%s |
| 54 |
CLASSES |
| 55 |
builtins.object |
| 56 |
A |
| 57 |
B |
| 58 |
C |
| 59 |
\x20\x20\x20\x20 |
| 60 |
class A(builtins.object) |
| 61 |
| Hello and goodbye |
| 62 |
|\x20\x20 |
| 63 |
| Methods defined here: |
| 64 |
|\x20\x20 |
| 65 |
| __init__() |
| 66 |
| Wow, I have no function! |
| 67 |
|\x20\x20 |
| 68 |
| ---------------------------------------------------------------------- |
| 69 |
| Data descriptors defined here: |
| 70 |
|\x20\x20 |
| 71 |
| __dict__%s |
| 72 |
|\x20\x20 |
| 73 |
| __weakref__%s |
| 74 |
\x20\x20\x20\x20 |
| 75 |
class B(builtins.object) |
| 76 |
| Data descriptors defined here: |
| 77 |
|\x20\x20 |
| 78 |
| __dict__%s |
| 79 |
|\x20\x20 |
| 80 |
| __weakref__%s |
| 81 |
|\x20\x20 |
| 82 |
| ---------------------------------------------------------------------- |
| 83 |
| Data and other attributes defined here: |
| 84 |
|\x20\x20 |
| 85 |
| NO_MEANING = 'eggs' |
| 86 |
|\x20\x20 |
| 87 |
| __annotations__ = {'NO_MEANING': <class 'str'>} |
| 88 |
\x20\x20\x20\x20 |
| 89 |
class C(builtins.object) |
| 90 |
| Methods defined here: |
| 91 |
|\x20\x20 |
| 92 |
| get_answer(self) |
| 93 |
| Return say_no() |
| 94 |
|\x20\x20 |
| 95 |
| is_it_true(self) |
| 96 |
| Return self.get_answer() |
| 97 |
|\x20\x20 |
| 98 |
| say_no(self) |
| 99 |
|\x20\x20 |
| 100 |
| ---------------------------------------------------------------------- |
| 101 |
| Class methods defined here: |
| 102 |
|\x20\x20 |
| 103 |
| __class_getitem__(item) |
| 104 |
|\x20\x20 |
| 105 |
| ---------------------------------------------------------------------- |
| 106 |
| Data descriptors defined here: |
| 107 |
|\x20\x20 |
| 108 |
| __dict__ |
| 109 |
| dictionary for instance variables |
| 110 |
|\x20\x20 |
| 111 |
| __weakref__ |
| 112 |
| list of weak references to the object |
| 113 |
|
| 114 |
FUNCTIONS |
| 115 |
doc_func() |
| 116 |
This function solves all of the world's problems: |
| 117 |
hunger |
| 118 |
lack of Python |
| 119 |
war |
| 120 |
\x20\x20\x20\x20 |
| 121 |
nodoc_func() |
| 122 |
|
| 123 |
DATA |
| 124 |
__xyz__ = 'X, Y and Z' |
| 125 |
c_alias = test.test_pydoc.pydoc_mod.C[int] |
| 126 |
list_alias1 = typing.List[int] |
| 127 |
list_alias2 = list[int] |
| 128 |
type_union1 = typing.Union[int, str] |
| 129 |
type_union2 = int | str |
| 130 |
|
| 131 |
VERSION |
| 132 |
1.2.3.4 |
| 133 |
|
| 134 |
AUTHOR |
| 135 |
Benjamin Peterson |
| 136 |
|
| 137 |
CREDITS |
| 138 |
Nobody |
| 139 |
|
| 140 |
FILE |
| 141 |
%s |
| 142 |
""".strip() |
| 143 |
|
| 144 |
expected_text_data_docstrings = tuple('\n | ' + s if s else '' |
| 145 |
for s in expected_data_docstrings) |
| 146 |
|
| 147 |
html2text_of_expected = """ |
| 148 |
test.test_pydoc.pydoc_mod (version 1.2.3.4) |
| 149 |
This is a test module for test_pydoc |
| 150 |
|
| 151 |
Modules |
| 152 |
types |
| 153 |
typing |
| 154 |
|
| 155 |
Classes |
| 156 |
builtins.object |
| 157 |
A |
| 158 |
B |
| 159 |
C |
| 160 |
|
| 161 |
class A(builtins.object) |
| 162 |
Hello and goodbye |
| 163 |
|
| 164 |
Methods defined here: |
| 165 |
__init__() |
| 166 |
Wow, I have no function! |
| 167 |
---------------------------------------------------------------------- |
| 168 |
Data descriptors defined here: |
| 169 |
__dict__ |
| 170 |
dictionary for instance variables |
| 171 |
__weakref__ |
| 172 |
list of weak references to the object |
| 173 |
|
| 174 |
class B(builtins.object) |
| 175 |
Data descriptors defined here: |
| 176 |
__dict__ |
| 177 |
dictionary for instance variables |
| 178 |
__weakref__ |
| 179 |
list of weak references to the object |
| 180 |
---------------------------------------------------------------------- |
| 181 |
Data and other attributes defined here: |
| 182 |
NO_MEANING = 'eggs' |
| 183 |
__annotations__ = {'NO_MEANING': <class 'str'>} |
| 184 |
|
| 185 |
|
| 186 |
class C(builtins.object) |
| 187 |
Methods defined here: |
| 188 |
get_answer(self) |
| 189 |
Return say_no() |
| 190 |
is_it_true(self) |
| 191 |
Return self.get_answer() |
| 192 |
say_no(self) |
| 193 |
---------------------------------------------------------------------- |
| 194 |
Class methods defined here: |
| 195 |
__class_getitem__(item) |
| 196 |
---------------------------------------------------------------------- |
| 197 |
Data descriptors defined here: |
| 198 |
__dict__ |
| 199 |
dictionary for instance variables |
| 200 |
__weakref__ |
| 201 |
list of weak references to the object |
| 202 |
|
| 203 |
Functions |
| 204 |
doc_func() |
| 205 |
This function solves all of the world's problems: |
| 206 |
hunger |
| 207 |
lack of Python |
| 208 |
war |
| 209 |
nodoc_func() |
| 210 |
|
| 211 |
Data |
| 212 |
__xyz__ = 'X, Y and Z' |
| 213 |
c_alias = test.test_pydoc.pydoc_mod.C[int] |
| 214 |
list_alias1 = typing.List[int] |
| 215 |
list_alias2 = list[int] |
| 216 |
type_union1 = typing.Union[int, str] |
| 217 |
type_union2 = int | str |
| 218 |
|
| 219 |
Author |
| 220 |
Benjamin Peterson |
| 221 |
|
| 222 |
Credits |
| 223 |
Nobody |
| 224 |
""" |
| 225 |
|
| 226 |
expected_html_data_docstrings = tuple(s.replace(' ', ' ') |
| 227 |
for s in expected_data_docstrings) |
| 228 |
|
| 229 |
|
| 230 |
missing_pattern = '''\ |
| 231 |
No Python documentation found for %r. |
| 232 |
Use help() to get the interactive help utility. |
| 233 |
Use help(str) for help on the str class.'''.replace('\n', os.linesep) |
| 234 |
|
| 235 |
|
| 236 |
badimport_pattern = "problem in %s - ModuleNotFoundError: No module named %r" |
| 237 |
|
| 238 |
expected_dynamicattribute_pattern = """ |
| 239 |
Help on class DA in module %s: |
| 240 |
|
| 241 |
class DA(builtins.object) |
| 242 |
| Data descriptors defined here: |
| 243 |
|\x20\x20 |
| 244 |
| __dict__%s |
| 245 |
|\x20\x20 |
| 246 |
| __weakref__%s |
| 247 |
|\x20\x20 |
| 248 |
| ham |
| 249 |
|\x20\x20 |
| 250 |
| ---------------------------------------------------------------------- |
| 251 |
| Data and other attributes inherited from Meta: |
| 252 |
|\x20\x20 |
| 253 |
| ham = 'spam' |
| 254 |
""".strip() |
| 255 |
|
| 256 |
expected_virtualattribute_pattern1 = """ |
| 257 |
Help on class Class in module %s: |
| 258 |
|
| 259 |
class Class(builtins.object) |
| 260 |
| Data and other attributes inherited from Meta: |
| 261 |
|\x20\x20 |
| 262 |
| LIFE = 42 |
| 263 |
""".strip() |
| 264 |
|
| 265 |
expected_virtualattribute_pattern2 = """ |
| 266 |
Help on class Class1 in module %s: |
| 267 |
|
| 268 |
class Class1(builtins.object) |
| 269 |
| Data and other attributes inherited from Meta1: |
| 270 |
|\x20\x20 |
| 271 |
| one = 1 |
| 272 |
""".strip() |
| 273 |
|
| 274 |
expected_virtualattribute_pattern3 = """ |
| 275 |
Help on class Class2 in module %s: |
| 276 |
|
| 277 |
class Class2(Class1) |
| 278 |
| Method resolution order: |
| 279 |
| Class2 |
| 280 |
| Class1 |
| 281 |
| builtins.object |
| 282 |
|\x20\x20 |
| 283 |
| Data and other attributes inherited from Meta1: |
| 284 |
|\x20\x20 |
| 285 |
| one = 1 |
| 286 |
|\x20\x20 |
| 287 |
| ---------------------------------------------------------------------- |
| 288 |
| Data and other attributes inherited from Meta3: |
| 289 |
|\x20\x20 |
| 290 |
| three = 3 |
| 291 |
|\x20\x20 |
| 292 |
| ---------------------------------------------------------------------- |
| 293 |
| Data and other attributes inherited from Meta2: |
| 294 |
|\x20\x20 |
| 295 |
| two = 2 |
| 296 |
""".strip() |
| 297 |
|
| 298 |
expected_missingattribute_pattern = """ |
| 299 |
Help on class C in module %s: |
| 300 |
|
| 301 |
class C(builtins.object) |
| 302 |
| Data and other attributes defined here: |
| 303 |
|\x20\x20 |
| 304 |
| here = 'present!' |
| 305 |
""".strip() |
| 306 |
|
| 307 |
def run_pydoc(module_name, *args, **env): |
| 308 |
""" |
| 309 |
Runs pydoc on the specified module. Returns the stripped |
| 310 |
output of pydoc. |
| 311 |
""" |
| 312 |
args = args + (module_name,) |
| 313 |
|
| 314 |
rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env) |
| 315 |
return out.strip() |
| 316 |
|
| 317 |
def run_pydoc_fail(module_name, *args, **env): |
| 318 |
""" |
| 319 |
Runs pydoc on the specified module expecting a failure. |
| 320 |
""" |
| 321 |
args = args + (module_name,) |
| 322 |
rc, out, err = assert_python_failure('-B', pydoc.__file__, *args, **env) |
| 323 |
return out.strip() |
| 324 |
|
| 325 |
def get_pydoc_html(module): |
| 326 |
"Returns pydoc generated output as html" |
| 327 |
doc = pydoc.HTMLDoc() |
| 328 |
output = doc.docmodule(module) |
| 329 |
loc = doc.getdocloc(pydoc_mod) or "" |
| 330 |
if loc: |
| 331 |
loc = "<br><a href=\"" + loc + "\">Module Docs</a>" |
| 332 |
return output.strip(), loc |
| 333 |
|
| 334 |
def clean_text(doc): |
| 335 |
|
| 336 |
return re.sub('\b.', '', doc) |
| 337 |
|
| 338 |
def get_pydoc_link(module): |
| 339 |
"Returns a documentation web link of a module" |
| 340 |
abspath = os.path.abspath |
| 341 |
dirname = os.path.dirname |
| 342 |
basedir = dirname(dirname(dirname(abspath(__file__)))) |
| 343 |
doc = pydoc.TextDoc() |
| 344 |
loc = doc.getdocloc(module, basedir=basedir) |
| 345 |
return loc |
| 346 |
|
| 347 |
def get_pydoc_text(module): |
| 348 |
"Returns pydoc generated output as text" |
| 349 |
doc = pydoc.TextDoc() |
| 350 |
loc = doc.getdocloc(pydoc_mod) or "" |
| 351 |
if loc: |
| 352 |
loc = "\nMODULE DOCS\n " + loc + "\n" |
| 353 |
|
| 354 |
output = doc.docmodule(module) |
| 355 |
output = clean_text(output) |
| 356 |
return output.strip(), loc |
| 357 |
|
| 358 |
def get_html_title(text): |
| 359 |
|
| 360 |
header, _, _ = text.partition("</head>") |
| 361 |
_, _, title = header.partition("<title>") |
| 362 |
title, _, _ = title.partition("</title>") |
| 363 |
return title |
| 364 |
|
| 365 |
|
| 366 |
def html2text(html): |
| 367 |
"""A quick and dirty implementation of html2text. |
| 368 |
|
| 369 |
Tailored for pydoc tests only. |
| 370 |
""" |
| 371 |
html = html.replace("<dd>", "\n") |
| 372 |
html = html.replace("<hr>", "-"*70) |
| 373 |
html = re.sub("<.*?>", "", html) |
| 374 |
html = pydoc.replace(html, " ", " ", ">", ">", "<", "<") |
| 375 |
return html |
| 376 |
|
| 377 |
|
| 378 |
class PydocBaseTest(unittest.TestCase): |
| 379 |
|
| 380 |
def _restricted_walk_packages(self, walk_packages, path=None): |
| 381 |
""" |
| 382 |
A version of pkgutil.walk_packages() that will restrict itself to |
| 383 |
a given path. |
| 384 |
""" |
| 385 |
default_path = path or [os.path.dirname(__file__)] |
| 386 |
def wrapper(path=None, prefix='', onerror=None): |
| 387 |
return walk_packages(path or default_path, prefix, onerror) |
| 388 |
return wrapper |
| 389 |
|
| 390 |
@contextlib.contextmanager |
| 391 |
def restrict_walk_packages(self, path=None): |
| 392 |
walk_packages = pkgutil.walk_packages |
| 393 |
pkgutil.walk_packages = self._restricted_walk_packages(walk_packages, |
| 394 |
path) |
| 395 |
try: |
| 396 |
yield |
| 397 |
finally: |
| 398 |
pkgutil.walk_packages = walk_packages |
| 399 |
|
| 400 |
def call_url_handler(self, url, expected_title): |
| 401 |
text = pydoc._url_handler(url, "text/html") |
| 402 |
result = get_html_title(text) |
| 403 |
|
| 404 |
self.assertEqual(result, expected_title, text) |
| 405 |
return text |
| 406 |
|
| 407 |
|
| 408 |
class PydocDocTest(unittest.TestCase): |
| 409 |
maxDiff = None |
| 410 |
|
| 411 |
@unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), |
| 412 |
'trace function introduces __locals__ unexpectedly') |
| 413 |
@requires_docstrings |
| 414 |
def test_html_doc(self): |
| 415 |
result, doc_loc = get_pydoc_html(pydoc_mod) |
| 416 |
text_result = html2text(result) |
| 417 |
text_lines = [line.strip() for line in text_result.splitlines()] |
| 418 |
text_lines = [line for line in text_lines if line] |
| 419 |
del text_lines[1] |
| 420 |
expected_lines = html2text_of_expected.splitlines() |
| 421 |
expected_lines = [line.strip() for line in expected_lines if line] |
| 422 |
self.assertEqual(text_lines, expected_lines) |
| 423 |
mod_file = inspect.getabsfile(pydoc_mod) |
| 424 |
mod_url = urllib.parse.quote(mod_file) |
| 425 |
self.assertIn(mod_url, result) |
| 426 |
self.assertIn(mod_file, result) |
| 427 |
self.assertIn(doc_loc, result) |
| 428 |
|
| 429 |
@unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), |
| 430 |
'trace function introduces __locals__ unexpectedly') |
| 431 |
@requires_docstrings |
| 432 |
def test_text_doc(self): |
| 433 |
result, doc_loc = get_pydoc_text(pydoc_mod) |
| 434 |
expected_text = expected_text_pattern % ( |
| 435 |
(doc_loc,) + |
| 436 |
expected_text_data_docstrings + |
| 437 |
(inspect.getabsfile(pydoc_mod),)) |
| 438 |
self.assertEqual(expected_text, result) |
| 439 |
|
| 440 |
def test_text_enum_member_with_value_zero(self): |
| 441 |
|
| 442 |
|
| 443 |
import enum |
| 444 |
class BinaryInteger(enum.IntEnum): |
| 445 |
zero = 0 |
| 446 |
one = 1 |
| 447 |
doc = pydoc.render_doc(BinaryInteger) |
| 448 |
self.assertIn('BinaryInteger.zero', doc) |
| 449 |
|
| 450 |
def test_mixed_case_module_names_are_lower_cased(self): |
| 451 |
|
| 452 |
doc_link = get_pydoc_link(xml.etree.ElementTree) |
| 453 |
self.assertIn('xml.etree.elementtree', doc_link) |
| 454 |
|
| 455 |
def test_issue8225(self): |
| 456 |
|
| 457 |
result, doc_loc = get_pydoc_text(xml.etree) |
| 458 |
self.assertEqual(doc_loc, "", "MODULE DOCS incorrectly includes a link") |
| 459 |
|
| 460 |
def test_getpager_with_stdin_none(self): |
| 461 |
previous_stdin = sys.stdin |
| 462 |
try: |
| 463 |
sys.stdin = None |
| 464 |
pydoc.getpager() |
| 465 |
finally: |
| 466 |
sys.stdin = previous_stdin |
| 467 |
|
| 468 |
def test_non_str_name(self): |
| 469 |
|
| 470 |
|
| 471 |
|
| 472 |
class A: |
| 473 |
__name__ = 42 |
| 474 |
class B: |
| 475 |
pass |
| 476 |
adoc = pydoc.render_doc(A()) |
| 477 |
bdoc = pydoc.render_doc(B()) |
| 478 |
self.assertEqual(adoc.replace("A", "B"), bdoc) |
| 479 |
|
| 480 |
def test_not_here(self): |
| 481 |
missing_module = "test.i_am_not_here" |
| 482 |
result = str(run_pydoc_fail(missing_module), 'ascii') |
| 483 |
expected = missing_pattern % missing_module |
| 484 |
self.assertEqual(expected, result, |
| 485 |
"documentation for missing module found") |
| 486 |
|
| 487 |
@requires_docstrings |
| 488 |
def test_not_ascii(self): |
| 489 |
result = run_pydoc('test.test_pydoc.test_pydoc.nonascii', PYTHONIOENCODING='ascii') |
| 490 |
encoded = nonascii.__doc__.encode('ascii', 'backslashreplace') |
| 491 |
self.assertIn(encoded, result) |
| 492 |
|
| 493 |
def test_input_strip(self): |
| 494 |
missing_module = " test.i_am_not_here " |
| 495 |
result = str(run_pydoc_fail(missing_module), 'ascii') |
| 496 |
expected = missing_pattern % missing_module.strip() |
| 497 |
self.assertEqual(expected, result) |
| 498 |
|
| 499 |
def test_stripid(self): |
| 500 |
|
| 501 |
stripid = pydoc.stripid |
| 502 |
|
| 503 |
self.assertEqual(stripid('<function stripid at 0x88dcee4>'), |
| 504 |
'<function stripid>') |
| 505 |
self.assertEqual(stripid('<function stripid at 0x01F65390>'), |
| 506 |
'<function stripid>') |
| 507 |
|
| 508 |
self.assertEqual(stripid('42'), '42') |
| 509 |
self.assertEqual(stripid("<type 'exceptions.Exception'>"), |
| 510 |
"<type 'exceptions.Exception'>") |
| 511 |
|
| 512 |
def test_builtin_with_more_than_four_children(self): |
| 513 |
"""Tests help on builtin object which have more than four child classes. |
| 514 |
|
| 515 |
When running help() on a builtin class which has child classes, it |
| 516 |
should contain a "Built-in subclasses" section and only 4 classes |
| 517 |
should be displayed with a hint on how many more subclasses are present. |
| 518 |
For example: |
| 519 |
|
| 520 |
>>> help(object) |
| 521 |
Help on class object in module builtins: |
| 522 |
|
| 523 |
class object |
| 524 |
| The most base type |
| 525 |
| |
| 526 |
| Built-in subclasses: |
| 527 |
| async_generator |
| 528 |
| BaseException |
| 529 |
| builtin_function_or_method |
| 530 |
| bytearray |
| 531 |
| ... and 82 other subclasses |
| 532 |
""" |
| 533 |
doc = pydoc.TextDoc() |
| 534 |
text = doc.docclass(object) |
| 535 |
snip = (" | Built-in subclasses:\n" |
| 536 |
" | async_generator\n" |
| 537 |
" | BaseException\n" |
| 538 |
" | builtin_function_or_method\n" |
| 539 |
" | bytearray\n" |
| 540 |
" | ... and \\d+ other subclasses") |
| 541 |
self.assertRegex(text, snip) |
| 542 |
|
| 543 |
def test_builtin_with_child(self): |
| 544 |
"""Tests help on builtin object which have only child classes. |
| 545 |
|
| 546 |
When running help() on a builtin class which has child classes, it |
| 547 |
should contain a "Built-in subclasses" section. For example: |
| 548 |
|
| 549 |
>>> help(ArithmeticError) |
| 550 |
Help on class ArithmeticError in module builtins: |
| 551 |
|
| 552 |
class ArithmeticError(Exception) |
| 553 |
| Base class for arithmetic errors. |
| 554 |
| |
| 555 |
... |
| 556 |
| |
| 557 |
| Built-in subclasses: |
| 558 |
| FloatingPointError |
| 559 |
| OverflowError |
| 560 |
| ZeroDivisionError |
| 561 |
""" |
| 562 |
doc = pydoc.TextDoc() |
| 563 |
text = doc.docclass(ArithmeticError) |
| 564 |
snip = (" | Built-in subclasses:\n" |
| 565 |
" | FloatingPointError\n" |
| 566 |
" | OverflowError\n" |
| 567 |
" | ZeroDivisionError") |
| 568 |
self.assertIn(snip, text) |
| 569 |
|
| 570 |
def test_builtin_with_grandchild(self): |
| 571 |
"""Tests help on builtin classes which have grandchild classes. |
| 572 |
|
| 573 |
When running help() on a builtin class which has child classes, it |
| 574 |
should contain a "Built-in subclasses" section. However, if it also has |
| 575 |
grandchildren, these should not show up on the subclasses section. |
| 576 |
For example: |
| 577 |
|
| 578 |
>>> help(Exception) |
| 579 |
Help on class Exception in module builtins: |
| 580 |
|
| 581 |
class Exception(BaseException) |
| 582 |
| Common base class for all non-exit exceptions. |
| 583 |
| |
| 584 |
... |
| 585 |
| |
| 586 |
| Built-in subclasses: |
| 587 |
| ArithmeticError |
| 588 |
| AssertionError |
| 589 |
| AttributeError |
| 590 |
... |
| 591 |
""" |
| 592 |
doc = pydoc.TextDoc() |
| 593 |
text = doc.docclass(Exception) |
| 594 |
snip = (" | Built-in subclasses:\n" |
| 595 |
" | ArithmeticError\n" |
| 596 |
" | AssertionError\n" |
| 597 |
" | AttributeError") |
| 598 |
self.assertIn(snip, text) |
| 599 |
|
| 600 |
self.assertNotIn('ZeroDivisionError', text) |
| 601 |
|
| 602 |
def test_builtin_no_child(self): |
| 603 |
"""Tests help on builtin object which have no child classes. |
| 604 |
|
| 605 |
When running help() on a builtin class which has no child classes, it |
| 606 |
should not contain any "Built-in subclasses" section. For example: |
| 607 |
|
| 608 |
>>> help(ZeroDivisionError) |
| 609 |
|
| 610 |
Help on class ZeroDivisionError in module builtins: |
| 611 |
|
| 612 |
class ZeroDivisionError(ArithmeticError) |
| 613 |
| Second argument to a division or modulo operation was zero. |
| 614 |
| |
| 615 |
| Method resolution order: |
| 616 |
| ZeroDivisionError |
| 617 |
| ArithmeticError |
| 618 |
| Exception |
| 619 |
| BaseException |
| 620 |
| object |
| 621 |
| |
| 622 |
| Methods defined here: |
| 623 |
... |
| 624 |
""" |
| 625 |
doc = pydoc.TextDoc() |
| 626 |
text = doc.docclass(ZeroDivisionError) |
| 627 |
|
| 628 |
self.assertNotIn('Built-in subclasses', text) |
| 629 |
|
| 630 |
def test_builtin_on_metaclasses(self): |
| 631 |
"""Tests help on metaclasses. |
| 632 |
|
| 633 |
When running help() on a metaclasses such as type, it |
| 634 |
should not contain any "Built-in subclasses" section. |
| 635 |
""" |
| 636 |
doc = pydoc.TextDoc() |
| 637 |
text = doc.docclass(type) |
| 638 |
|
| 639 |
self.assertNotIn('Built-in subclasses', text) |
| 640 |
|
| 641 |
def test_fail_help_cli(self): |
| 642 |
elines = (missing_pattern % 'abd').splitlines() |
| 643 |
with spawn_python("-c" "help()") as proc: |
| 644 |
out, _ = proc.communicate(b"abd") |
| 645 |
olines = out.decode().splitlines()[-9:-6] |
| 646 |
olines[0] = olines[0].removeprefix('help> ') |
| 647 |
self.assertEqual(elines, olines) |
| 648 |
|
| 649 |
def test_fail_help_output_redirect(self): |
| 650 |
with StringIO() as buf: |
| 651 |
helper = pydoc.Helper(output=buf) |
| 652 |
helper.help("abd") |
| 653 |
expected = missing_pattern % "abd" |
| 654 |
self.assertEqual(expected, buf.getvalue().strip().replace('\n', os.linesep)) |
| 655 |
|
| 656 |
@unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), |
| 657 |
'trace function introduces __locals__ unexpectedly') |
| 658 |
@requires_docstrings |
| 659 |
def test_help_output_redirect(self): |
| 660 |
|
| 661 |
|
| 662 |
getpager_old = pydoc.getpager |
| 663 |
getpager_new = lambda: (lambda x: x) |
| 664 |
self.maxDiff = None |
| 665 |
|
| 666 |
buf = StringIO() |
| 667 |
helper = pydoc.Helper(output=buf) |
| 668 |
unused, doc_loc = get_pydoc_text(pydoc_mod) |
| 669 |
module = "test.test_pydoc.pydoc_mod" |
| 670 |
help_header = """ |
| 671 |
Help on module test.test_pydoc.pydoc_mod in test.test_pydoc: |
| 672 |
|
| 673 |
""".lstrip() |
| 674 |
help_header = textwrap.dedent(help_header) |
| 675 |
expected_help_pattern = help_header + expected_text_pattern |
| 676 |
|
| 677 |
pydoc.getpager = getpager_new |
| 678 |
try: |
| 679 |
with captured_output('stdout') as output, \ |
| 680 |
captured_output('stderr') as err: |
| 681 |
helper.help(module) |
| 682 |
result = buf.getvalue().strip() |
| 683 |
expected_text = expected_help_pattern % ( |
| 684 |
(doc_loc,) + |
| 685 |
expected_text_data_docstrings + |
| 686 |
(inspect.getabsfile(pydoc_mod),)) |
| 687 |
self.assertEqual('', output.getvalue()) |
| 688 |
self.assertEqual('', err.getvalue()) |
| 689 |
self.assertEqual(expected_text, result) |
| 690 |
finally: |
| 691 |
pydoc.getpager = getpager_old |
| 692 |
|
| 693 |
def test_lambda_with_return_annotation(self): |
| 694 |
func = lambda a, b, c: 1 |
| 695 |
func.__annotations__ = {"return": int} |
| 696 |
with captured_output('stdout') as help_io: |
| 697 |
pydoc.help(func) |
| 698 |
helptext = help_io.getvalue() |
| 699 |
self.assertIn("lambda (a, b, c) -> int", helptext) |
| 700 |
|
| 701 |
def test_lambda_without_return_annotation(self): |
| 702 |
func = lambda a, b, c: 1 |
| 703 |
func.__annotations__ = {"a": int, "b": int, "c": int} |
| 704 |
with captured_output('stdout') as help_io: |
| 705 |
pydoc.help(func) |
| 706 |
helptext = help_io.getvalue() |
| 707 |
self.assertIn("lambda (a: int, b: int, c: int)", helptext) |
| 708 |
|
| 709 |
def test_lambda_with_return_and_params_annotation(self): |
| 710 |
func = lambda a, b, c: 1 |
| 711 |
func.__annotations__ = {"a": int, "b": int, "c": int, "return": int} |
| 712 |
with captured_output('stdout') as help_io: |
| 713 |
pydoc.help(func) |
| 714 |
helptext = help_io.getvalue() |
| 715 |
self.assertIn("lambda (a: int, b: int, c: int) -> int", helptext) |
| 716 |
|
| 717 |
def test_namedtuple_fields(self): |
| 718 |
Person = namedtuple('Person', ['nickname', 'firstname']) |
| 719 |
with captured_stdout() as help_io: |
| 720 |
pydoc.help(Person) |
| 721 |
helptext = help_io.getvalue() |
| 722 |
self.assertIn("nickname", helptext) |
| 723 |
self.assertIn("firstname", helptext) |
| 724 |
self.assertIn("Alias for field number 0", helptext) |
| 725 |
self.assertIn("Alias for field number 1", helptext) |
| 726 |
|
| 727 |
def test_namedtuple_public_underscore(self): |
| 728 |
NT = namedtuple('NT', ['abc', 'def'], rename=True) |
| 729 |
with captured_stdout() as help_io: |
| 730 |
pydoc.help(NT) |
| 731 |
helptext = help_io.getvalue() |
| 732 |
self.assertIn('_1', helptext) |
| 733 |
self.assertIn('_replace', helptext) |
| 734 |
self.assertIn('_asdict', helptext) |
| 735 |
|
| 736 |
def test_synopsis(self): |
| 737 |
self.addCleanup(unlink, TESTFN) |
| 738 |
for encoding in ('ISO-8859-1', 'UTF-8'): |
| 739 |
with open(TESTFN, 'w', encoding=encoding) as script: |
| 740 |
if encoding != 'UTF-8': |
| 741 |
print('#coding: {}'.format(encoding), file=script) |
| 742 |
print('"""line 1: h\xe9', file=script) |
| 743 |
print('line 2: hi"""', file=script) |
| 744 |
synopsis = pydoc.synopsis(TESTFN, {}) |
| 745 |
self.assertEqual(synopsis, 'line 1: h\xe9') |
| 746 |
|
| 747 |
@requires_docstrings |
| 748 |
def test_synopsis_sourceless(self): |
| 749 |
os = import_helper.import_fresh_module('os') |
| 750 |
expected = os.__doc__.splitlines()[0] |
| 751 |
filename = os.__cached__ |
| 752 |
synopsis = pydoc.synopsis(filename) |
| 753 |
|
| 754 |
self.assertEqual(synopsis, expected) |
| 755 |
|
| 756 |
def test_synopsis_sourceless_empty_doc(self): |
| 757 |
with os_helper.temp_cwd() as test_dir: |
| 758 |
init_path = os.path.join(test_dir, 'foomod42.py') |
| 759 |
cached_path = importlib.util.cache_from_source(init_path) |
| 760 |
with open(init_path, 'w') as fobj: |
| 761 |
fobj.write("foo = 1") |
| 762 |
py_compile.compile(init_path) |
| 763 |
synopsis = pydoc.synopsis(init_path, {}) |
| 764 |
self.assertIsNone(synopsis) |
| 765 |
synopsis_cached = pydoc.synopsis(cached_path, {}) |
| 766 |
self.assertIsNone(synopsis_cached) |
| 767 |
|
| 768 |
def test_splitdoc_with_description(self): |
| 769 |
example_string = "I Am A Doc\n\n\nHere is my description" |
| 770 |
self.assertEqual(pydoc.splitdoc(example_string), |
| 771 |
('I Am A Doc', '\nHere is my description')) |
| 772 |
|
| 773 |
def test_is_package_when_not_package(self): |
| 774 |
with os_helper.temp_cwd() as test_dir: |
| 775 |
self.assertFalse(pydoc.ispackage(test_dir)) |
| 776 |
|
| 777 |
def test_is_package_when_is_package(self): |
| 778 |
with os_helper.temp_cwd() as test_dir: |
| 779 |
init_path = os.path.join(test_dir, '__init__.py') |
| 780 |
open(init_path, 'w').close() |
| 781 |
self.assertTrue(pydoc.ispackage(test_dir)) |
| 782 |
os.remove(init_path) |
| 783 |
|
| 784 |
def test_allmethods(self): |
| 785 |
|
| 786 |
|
| 787 |
|
| 788 |
|
| 789 |
|
| 790 |
class TestClass(object): |
| 791 |
def method_returning_true(self): |
| 792 |
return True |
| 793 |
|
| 794 |
|
| 795 |
expected = dict(vars(object)) |
| 796 |
|
| 797 |
expected['method_returning_true'] = TestClass.method_returning_true |
| 798 |
|
| 799 |
del expected['__doc__'] |
| 800 |
del expected['__class__'] |
| 801 |
|
| 802 |
|
| 803 |
expected['__subclasshook__'] = TestClass.__subclasshook__ |
| 804 |
expected['__init_subclass__'] = TestClass.__init_subclass__ |
| 805 |
|
| 806 |
|
| 807 |
if isinstance(expected.get('__new__'), staticmethod): |
| 808 |
expected['__new__'] = getattr(object, '__new__') |
| 809 |
|
| 810 |
methods = pydoc.allmethods(TestClass) |
| 811 |
self.assertDictEqual(methods, expected) |
| 812 |
|
| 813 |
@requires_docstrings |
| 814 |
def test_method_aliases(self): |
| 815 |
class A: |
| 816 |
def tkraise(self, aboveThis=None): |
| 817 |
"""Raise this widget in the stacking order.""" |
| 818 |
lift = tkraise |
| 819 |
def a_size(self): |
| 820 |
"""Return size""" |
| 821 |
class B(A): |
| 822 |
def itemconfigure(self, tagOrId, cnf=None, **kw): |
| 823 |
"""Configure resources of an item TAGORID.""" |
| 824 |
itemconfig = itemconfigure |
| 825 |
b_size = A.a_size |
| 826 |
|
| 827 |
doc = pydoc.render_doc(B) |
| 828 |
doc = clean_text(doc) |
| 829 |
self.assertEqual(doc, '''\ |
| 830 |
Python Library Documentation: class B in module %s |
| 831 |
|
| 832 |
class B(A) |
| 833 |
| Method resolution order: |
| 834 |
| B |
| 835 |
| A |
| 836 |
| builtins.object |
| 837 |
|\x20\x20 |
| 838 |
| Methods defined here: |
| 839 |
|\x20\x20 |
| 840 |
| b_size = a_size(self) |
| 841 |
|\x20\x20 |
| 842 |
| itemconfig = itemconfigure(self, tagOrId, cnf=None, **kw) |
| 843 |
|\x20\x20 |
| 844 |
| itemconfigure(self, tagOrId, cnf=None, **kw) |
| 845 |
| Configure resources of an item TAGORID. |
| 846 |
|\x20\x20 |
| 847 |
| ---------------------------------------------------------------------- |
| 848 |
| Methods inherited from A: |
| 849 |
|\x20\x20 |
| 850 |
| a_size(self) |
| 851 |
| Return size |
| 852 |
|\x20\x20 |
| 853 |
| lift = tkraise(self, aboveThis=None) |
| 854 |
|\x20\x20 |
| 855 |
| tkraise(self, aboveThis=None) |
| 856 |
| Raise this widget in the stacking order. |
| 857 |
|\x20\x20 |
| 858 |
| ---------------------------------------------------------------------- |
| 859 |
| Data descriptors inherited from A: |
| 860 |
|\x20\x20 |
| 861 |
| __dict__ |
| 862 |
| dictionary for instance variables |
| 863 |
|\x20\x20 |
| 864 |
| __weakref__ |
| 865 |
| list of weak references to the object |
| 866 |
''' % __name__) |
| 867 |
|
| 868 |
doc = pydoc.render_doc(B, renderer=pydoc.HTMLDoc()) |
| 869 |
expected_text = f""" |
| 870 |
Python Library Documentation |
| 871 |
|
| 872 |
class B in module {__name__} |
| 873 |
class B(A) |
| 874 |
Method resolution order: |
| 875 |
B |
| 876 |
A |
| 877 |
builtins.object |
| 878 |
|
| 879 |
Methods defined here: |
| 880 |
b_size = a_size(self) |
| 881 |
itemconfig = itemconfigure(self, tagOrId, cnf=None, **kw) |
| 882 |
itemconfigure(self, tagOrId, cnf=None, **kw) |
| 883 |
Configure resources of an item TAGORID. |
| 884 |
|
| 885 |
Methods inherited from A: |
| 886 |
a_size(self) |
| 887 |
Return size |
| 888 |
lift = tkraise(self, aboveThis=None) |
| 889 |
tkraise(self, aboveThis=None) |
| 890 |
Raise this widget in the stacking order. |
| 891 |
|
| 892 |
Data descriptors inherited from A: |
| 893 |
__dict__ |
| 894 |
dictionary for instance variables |
| 895 |
__weakref__ |
| 896 |
list of weak references to the object |
| 897 |
""" |
| 898 |
as_text = html2text(doc) |
| 899 |
expected_lines = [line.strip() for line in expected_text.split("\n") if line] |
| 900 |
for expected_line in expected_lines: |
| 901 |
self.assertIn(expected_line, as_text) |
| 902 |
|
| 903 |
def test__future__imports(self): |
| 904 |
|
| 905 |
|
| 906 |
import __future__ |
| 907 |
future_text, _ = get_pydoc_text(__future__) |
| 908 |
future_html, _ = get_pydoc_html(__future__) |
| 909 |
pydoc_mod_text, _ = get_pydoc_text(pydoc_mod) |
| 910 |
pydoc_mod_html, _ = get_pydoc_html(pydoc_mod) |
| 911 |
|
| 912 |
for feature in __future__.all_feature_names: |
| 913 |
txt = f"{feature} = _Feature" |
| 914 |
html = f"<strong>{feature}</strong> = _Feature" |
| 915 |
self.assertIn(txt, future_text) |
| 916 |
self.assertIn(html, future_html) |
| 917 |
self.assertNotIn(txt, pydoc_mod_text) |
| 918 |
self.assertNotIn(html, pydoc_mod_html) |
| 919 |
|
| 920 |
|
| 921 |
class PydocImportTest(PydocBaseTest): |
| 922 |
|
| 923 |
def setUp(self): |
| 924 |
self.test_dir = os.mkdir(TESTFN) |
| 925 |
self.addCleanup(rmtree, TESTFN) |
| 926 |
importlib.invalidate_caches() |
| 927 |
|
| 928 |
def test_badimport(self): |
| 929 |
|
| 930 |
|
| 931 |
|
| 932 |
modname = 'testmod_xyzzy' |
| 933 |
testpairs = ( |
| 934 |
('i_am_not_here', 'i_am_not_here'), |
| 935 |
('test.i_am_not_here_either', 'test.i_am_not_here_either'), |
| 936 |
('test.i_am_not_here.neither_am_i', 'test.i_am_not_here'), |
| 937 |
('i_am_not_here.{}'.format(modname), 'i_am_not_here'), |
| 938 |
('test.{}'.format(modname), 'test.{}'.format(modname)), |
| 939 |
) |
| 940 |
|
| 941 |
sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py" |
| 942 |
for importstring, expectedinmsg in testpairs: |
| 943 |
with open(sourcefn, 'w') as f: |
| 944 |
f.write("import {}\n".format(importstring)) |
| 945 |
result = run_pydoc_fail(modname, PYTHONPATH=TESTFN).decode("ascii") |
| 946 |
expected = badimport_pattern % (modname, expectedinmsg) |
| 947 |
self.assertEqual(expected, result) |
| 948 |
|
| 949 |
def test_apropos_with_bad_package(self): |
| 950 |
|
| 951 |
pkgdir = os.path.join(TESTFN, "syntaxerr") |
| 952 |
os.mkdir(pkgdir) |
| 953 |
badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py" |
| 954 |
with open(badsyntax, 'w') as f: |
| 955 |
f.write("invalid python syntax = $1\n") |
| 956 |
with self.restrict_walk_packages(path=[TESTFN]): |
| 957 |
with captured_stdout() as out: |
| 958 |
with captured_stderr() as err: |
| 959 |
pydoc.apropos('xyzzy') |
| 960 |
|
| 961 |
self.assertEqual(out.getvalue(), '') |
| 962 |
self.assertEqual(err.getvalue(), '') |
| 963 |
|
| 964 |
with captured_stdout() as out: |
| 965 |
with captured_stderr() as err: |
| 966 |
pydoc.apropos('syntaxerr') |
| 967 |
self.assertEqual(out.getvalue().strip(), 'syntaxerr') |
| 968 |
self.assertEqual(err.getvalue(), '') |
| 969 |
|
| 970 |
def test_apropos_with_unreadable_dir(self): |
| 971 |
|
| 972 |
self.unreadable_dir = os.path.join(TESTFN, "unreadable") |
| 973 |
os.mkdir(self.unreadable_dir, 0) |
| 974 |
self.addCleanup(os.rmdir, self.unreadable_dir) |
| 975 |
|
| 976 |
|
| 977 |
with self.restrict_walk_packages(path=[TESTFN]): |
| 978 |
with captured_stdout() as out: |
| 979 |
with captured_stderr() as err: |
| 980 |
pydoc.apropos('SOMEKEY') |
| 981 |
|
| 982 |
self.assertEqual(out.getvalue(), '') |
| 983 |
self.assertEqual(err.getvalue(), '') |
| 984 |
|
| 985 |
@os_helper.skip_unless_working_chmod |
| 986 |
@unittest.skipIf(is_emscripten, "cannot remove x bit") |
| 987 |
def test_apropos_empty_doc(self): |
| 988 |
pkgdir = os.path.join(TESTFN, 'walkpkg') |
| 989 |
os.mkdir(pkgdir) |
| 990 |
self.addCleanup(rmtree, pkgdir) |
| 991 |
init_path = os.path.join(pkgdir, '__init__.py') |
| 992 |
with open(init_path, 'w') as fobj: |
| 993 |
fobj.write("foo = 1") |
| 994 |
current_mode = stat.S_IMODE(os.stat(pkgdir).st_mode) |
| 995 |
try: |
| 996 |
os.chmod(pkgdir, current_mode & ~stat.S_IEXEC) |
| 997 |
with self.restrict_walk_packages(path=[TESTFN]), captured_stdout() as stdout: |
| 998 |
pydoc.apropos('') |
| 999 |
self.assertIn('walkpkg', stdout.getvalue()) |
| 1000 |
finally: |
| 1001 |
os.chmod(pkgdir, current_mode) |
| 1002 |
|
| 1003 |
def test_url_search_package_error(self): |
| 1004 |
|
| 1005 |
pkgdir = os.path.join(TESTFN, "test_error_package") |
| 1006 |
os.mkdir(pkgdir) |
| 1007 |
init = os.path.join(pkgdir, "__init__.py") |
| 1008 |
with open(init, "wt", encoding="ascii") as f: |
| 1009 |
f.write("""raise ValueError("ouch")\n""") |
| 1010 |
with self.restrict_walk_packages(path=[TESTFN]): |
| 1011 |
|
| 1012 |
saved_paths = tuple(sys.path) |
| 1013 |
sys.path.insert(0, TESTFN) |
| 1014 |
try: |
| 1015 |
with self.assertRaisesRegex(ValueError, "ouch"): |
| 1016 |
import test_error_package |
| 1017 |
|
| 1018 |
text = self.call_url_handler("search?key=test_error_package", |
| 1019 |
"Pydoc: Search Results") |
| 1020 |
found = ('<a href="test_error_package.html">' |
| 1021 |
'test_error_package</a>') |
| 1022 |
self.assertIn(found, text) |
| 1023 |
finally: |
| 1024 |
sys.path[:] = saved_paths |
| 1025 |
|
| 1026 |
@unittest.skip('causes undesirable side-effects (#20128)') |
| 1027 |
def test_modules(self): |
| 1028 |
|
| 1029 |
num_header_lines = 2 |
| 1030 |
num_module_lines_min = 5 |
| 1031 |
num_footer_lines = 3 |
| 1032 |
expected = num_header_lines + num_module_lines_min + num_footer_lines |
| 1033 |
|
| 1034 |
output = StringIO() |
| 1035 |
helper = pydoc.Helper(output=output) |
| 1036 |
helper('modules') |
| 1037 |
result = output.getvalue().strip() |
| 1038 |
num_lines = len(result.splitlines()) |
| 1039 |
|
| 1040 |
self.assertGreaterEqual(num_lines, expected) |
| 1041 |
|
| 1042 |
@unittest.skip('causes undesirable side-effects (#20128)') |
| 1043 |
def test_modules_search(self): |
| 1044 |
|
| 1045 |
expected = 'pydoc - ' |
| 1046 |
|
| 1047 |
output = StringIO() |
| 1048 |
helper = pydoc.Helper(output=output) |
| 1049 |
with captured_stdout() as help_io: |
| 1050 |
helper('modules pydoc') |
| 1051 |
result = help_io.getvalue() |
| 1052 |
|
| 1053 |
self.assertIn(expected, result) |
| 1054 |
|
| 1055 |
@unittest.skip('some buildbots are not cooperating (#20128)') |
| 1056 |
def test_modules_search_builtin(self): |
| 1057 |
expected = 'gc - ' |
| 1058 |
|
| 1059 |
output = StringIO() |
| 1060 |
helper = pydoc.Helper(output=output) |
| 1061 |
with captured_stdout() as help_io: |
| 1062 |
helper('modules garbage') |
| 1063 |
result = help_io.getvalue() |
| 1064 |
|
| 1065 |
self.assertTrue(result.startswith(expected)) |
| 1066 |
|
| 1067 |
def test_importfile(self): |
| 1068 |
loaded_pydoc = pydoc.importfile(pydoc.__file__) |
| 1069 |
|
| 1070 |
self.assertIsNot(loaded_pydoc, pydoc) |
| 1071 |
self.assertEqual(loaded_pydoc.__name__, 'pydoc') |
| 1072 |
self.assertEqual(loaded_pydoc.__file__, pydoc.__file__) |
| 1073 |
self.assertEqual(loaded_pydoc.__spec__, pydoc.__spec__) |
| 1074 |
|
| 1075 |
|
| 1076 |
class TestDescriptions(unittest.TestCase): |
| 1077 |
|
| 1078 |
def test_module(self): |
| 1079 |
|
| 1080 |
doc = pydoc.render_doc(pydocfodder) |
| 1081 |
self.assertIn("pydocfodder", doc) |
| 1082 |
|
| 1083 |
def test_class(self): |
| 1084 |
class C: "New-style class" |
| 1085 |
c = C() |
| 1086 |
|
| 1087 |
self.assertEqual(pydoc.describe(C), 'class C') |
| 1088 |
self.assertEqual(pydoc.describe(c), 'C') |
| 1089 |
expected = 'C in module %s object' % __name__ |
| 1090 |
self.assertIn(expected, pydoc.render_doc(c)) |
| 1091 |
|
| 1092 |
def test_generic_alias(self): |
| 1093 |
self.assertEqual(pydoc.describe(typing.List[int]), '_GenericAlias') |
| 1094 |
doc = pydoc.render_doc(typing.List[int], renderer=pydoc.plaintext) |
| 1095 |
self.assertIn('_GenericAlias in module typing', doc) |
| 1096 |
self.assertIn('List = class list(object)', doc) |
| 1097 |
if not MISSING_C_DOCSTRINGS: |
| 1098 |
self.assertIn(list.__doc__.strip().splitlines()[0], doc) |
| 1099 |
|
| 1100 |
self.assertEqual(pydoc.describe(list[int]), 'GenericAlias') |
| 1101 |
doc = pydoc.render_doc(list[int], renderer=pydoc.plaintext) |
| 1102 |
self.assertIn('GenericAlias in module builtins', doc) |
| 1103 |
self.assertIn('\nclass list(object)', doc) |
| 1104 |
if not MISSING_C_DOCSTRINGS: |
| 1105 |
self.assertIn(list.__doc__.strip().splitlines()[0], doc) |
| 1106 |
|
| 1107 |
def test_union_type(self): |
| 1108 |
self.assertEqual(pydoc.describe(typing.Union[int, str]), '_UnionGenericAlias') |
| 1109 |
doc = pydoc.render_doc(typing.Union[int, str], renderer=pydoc.plaintext) |
| 1110 |
self.assertIn('_UnionGenericAlias in module typing', doc) |
| 1111 |
self.assertIn('Union = typing.Union', doc) |
| 1112 |
if typing.Union.__doc__: |
| 1113 |
self.assertIn(typing.Union.__doc__.strip().splitlines()[0], doc) |
| 1114 |
|
| 1115 |
self.assertEqual(pydoc.describe(int | str), 'UnionType') |
| 1116 |
doc = pydoc.render_doc(int | str, renderer=pydoc.plaintext) |
| 1117 |
if sys.implementation.name == "pypy": |
| 1118 |
self.assertIn('UnionType in module _pypy_generic_alias object', doc) |
| 1119 |
else: |
| 1120 |
self.assertIn('UnionType in module types object', doc) |
| 1121 |
self.assertIn('\nclass UnionType(builtins.object)', doc) |
| 1122 |
if not MISSING_C_DOCSTRINGS: |
| 1123 |
self.assertIn(types.UnionType.__doc__.strip().splitlines()[0], doc) |
| 1124 |
|
| 1125 |
def test_special_form(self): |
| 1126 |
self.assertEqual(pydoc.describe(typing.NoReturn), '_SpecialForm') |
| 1127 |
doc = pydoc.render_doc(typing.NoReturn, renderer=pydoc.plaintext) |
| 1128 |
self.assertIn('_SpecialForm in module typing', doc) |
| 1129 |
if typing.NoReturn.__doc__: |
| 1130 |
self.assertIn('NoReturn = typing.NoReturn', doc) |
| 1131 |
self.assertIn(typing.NoReturn.__doc__.strip().splitlines()[0], doc) |
| 1132 |
else: |
| 1133 |
self.assertIn('NoReturn = class _SpecialForm(_Final)', doc) |
| 1134 |
|
| 1135 |
def test_typing_pydoc(self): |
| 1136 |
def foo(data: typing.List[typing.Any], |
| 1137 |
x: int) -> typing.Iterator[typing.Tuple[int, typing.Any]]: |
| 1138 |
... |
| 1139 |
T = typing.TypeVar('T') |
| 1140 |
class C(typing.Generic[T], typing.Mapping[int, str]): ... |
| 1141 |
self.assertEqual(pydoc.render_doc(foo).splitlines()[-1], |
| 1142 |
'f\x08fo\x08oo\x08o(data: List[Any], x: int)' |
| 1143 |
' -> Iterator[Tuple[int, Any]]') |
| 1144 |
self.assertEqual(pydoc.render_doc(C).splitlines()[2], |
| 1145 |
'class C\x08C(collections.abc.Mapping, typing.Generic)') |
| 1146 |
|
| 1147 |
def test_builtin(self): |
| 1148 |
for name in ('str', 'str.translate', 'builtins.str', |
| 1149 |
'builtins.str.translate'): |
| 1150 |
|
| 1151 |
self.assertIsNotNone(pydoc.locate(name)) |
| 1152 |
|
| 1153 |
try: |
| 1154 |
pydoc.render_doc(name) |
| 1155 |
except ImportError: |
| 1156 |
self.fail('finding the doc of {!r} failed'.format(name)) |
| 1157 |
|
| 1158 |
for name in ('notbuiltins', 'strrr', 'strr.translate', |
| 1159 |
'str.trrrranslate', 'builtins.strrr', |
| 1160 |
'builtins.str.trrranslate'): |
| 1161 |
self.assertIsNone(pydoc.locate(name)) |
| 1162 |
self.assertRaises(ImportError, pydoc.render_doc, name) |
| 1163 |
|
| 1164 |
@staticmethod |
| 1165 |
def _get_summary_line(o): |
| 1166 |
text = pydoc.plain(pydoc.render_doc(o)) |
| 1167 |
lines = text.split('\n') |
| 1168 |
assert len(lines) >= 2 |
| 1169 |
return lines[2] |
| 1170 |
|
| 1171 |
@staticmethod |
| 1172 |
def _get_summary_lines(o): |
| 1173 |
text = pydoc.plain(pydoc.render_doc(o)) |
| 1174 |
lines = text.split('\n') |
| 1175 |
return '\n'.join(lines[2:]) |
| 1176 |
|
| 1177 |
|
| 1178 |
def test_unbound_python_method(self): |
| 1179 |
self.assertEqual(self._get_summary_line(textwrap.TextWrapper.wrap), |
| 1180 |
"wrap(self, text)") |
| 1181 |
|
| 1182 |
@support.cpython_only |
| 1183 |
@requires_docstrings |
| 1184 |
def test_unbound_builtin_method(self): |
| 1185 |
import _pickle |
| 1186 |
self.assertEqual(self._get_summary_line(_pickle.Pickler.dump), |
| 1187 |
"dump(self, obj, /) unbound _pickle.Pickler method") |
| 1188 |
|
| 1189 |
|
| 1190 |
def test_bound_python_method(self): |
| 1191 |
t = textwrap.TextWrapper() |
| 1192 |
self.assertEqual(self._get_summary_line(t.wrap), |
| 1193 |
"wrap(text) method of textwrap.TextWrapper instance") |
| 1194 |
|
| 1195 |
def test_field_order_for_named_tuples(self): |
| 1196 |
Person = namedtuple('Person', ['nickname', 'firstname', 'agegroup']) |
| 1197 |
s = pydoc.render_doc(Person) |
| 1198 |
self.assertLess(s.index('nickname'), s.index('firstname')) |
| 1199 |
self.assertLess(s.index('firstname'), s.index('agegroup')) |
| 1200 |
|
| 1201 |
class NonIterableFields: |
| 1202 |
_fields = None |
| 1203 |
|
| 1204 |
class NonHashableFields: |
| 1205 |
_fields = [[]] |
| 1206 |
|
| 1207 |
|
| 1208 |
pydoc.render_doc(NonIterableFields) |
| 1209 |
pydoc.render_doc(NonHashableFields) |
| 1210 |
|
| 1211 |
@support.cpython_only |
| 1212 |
@requires_docstrings |
| 1213 |
def test_bound_builtin_method(self): |
| 1214 |
import _pickle |
| 1215 |
s = StringIO() |
| 1216 |
p = _pickle.Pickler(s) |
| 1217 |
self.assertEqual(self._get_summary_line(p.dump), |
| 1218 |
"dump(obj, /) method of _pickle.Pickler instance") |
| 1219 |
|
| 1220 |
|
| 1221 |
@requires_docstrings |
| 1222 |
def test_module_level_callable(self): |
| 1223 |
self.assertEqual(self._get_summary_line(os.stat), |
| 1224 |
"stat(path, *, dir_fd=None, follow_symlinks=True)") |
| 1225 |
|
| 1226 |
def test_unbound_builtin_method_noargs(self): |
| 1227 |
self.assertEqual(self._get_summary_line(str.lower), |
| 1228 |
"lower(self, /) unbound builtins.str method") |
| 1229 |
|
| 1230 |
def test_bound_builtin_method_noargs(self): |
| 1231 |
self.assertEqual(self._get_summary_line(''.lower), |
| 1232 |
"lower() method of builtins.str instance") |
| 1233 |
|
| 1234 |
@requires_docstrings |
| 1235 |
def test_staticmethod(self): |
| 1236 |
class X: |
| 1237 |
@staticmethod |
| 1238 |
def sm(x, y): |
| 1239 |
'''A static method''' |
| 1240 |
... |
| 1241 |
self.assertEqual(self._get_summary_lines(X.__dict__['sm']), |
| 1242 |
'sm(x, y)\n' |
| 1243 |
' A static method\n') |
| 1244 |
self.assertEqual(self._get_summary_lines(X.sm), """\ |
| 1245 |
sm(x, y) |
| 1246 |
A static method |
| 1247 |
""") |
| 1248 |
self.assertIn(""" |
| 1249 |
| Static methods defined here: |
| 1250 |
|\x20\x20 |
| 1251 |
| sm(x, y) |
| 1252 |
| A static method |
| 1253 |
""", pydoc.plain(pydoc.render_doc(X))) |
| 1254 |
|
| 1255 |
@requires_docstrings |
| 1256 |
def test_classmethod(self): |
| 1257 |
class X: |
| 1258 |
@classmethod |
| 1259 |
def cm(cls, x): |
| 1260 |
'''A class method''' |
| 1261 |
... |
| 1262 |
self.assertEqual(self._get_summary_lines(X.__dict__['cm']), |
| 1263 |
'cm(...)\n' |
| 1264 |
' A class method\n') |
| 1265 |
self.assertEqual(self._get_summary_lines(X.cm), """\ |
| 1266 |
cm(x) class method of test.test_pydoc.test_pydoc.X |
| 1267 |
A class method |
| 1268 |
""") |
| 1269 |
self.assertIn(""" |
| 1270 |
| Class methods defined here: |
| 1271 |
|\x20\x20 |
| 1272 |
| cm(x) |
| 1273 |
| A class method |
| 1274 |
""", pydoc.plain(pydoc.render_doc(X))) |
| 1275 |
|
| 1276 |
@requires_docstrings |
| 1277 |
def test_getset_descriptor(self): |
| 1278 |
|
| 1279 |
|
| 1280 |
self.assertEqual(self._get_summary_line(int.numerator), "numerator") |
| 1281 |
self.assertEqual(self._get_summary_line(float.real), "real") |
| 1282 |
self.assertEqual(self._get_summary_line(Exception.args), "args") |
| 1283 |
self.assertEqual(self._get_summary_line(memoryview.obj), "obj") |
| 1284 |
|
| 1285 |
@requires_docstrings |
| 1286 |
def test_member_descriptor(self): |
| 1287 |
|
| 1288 |
|
| 1289 |
self.assertEqual(self._get_summary_line(complex.real), "real") |
| 1290 |
self.assertEqual(self._get_summary_line(range.start), "start") |
| 1291 |
self.assertEqual(self._get_summary_line(slice.start), "start") |
| 1292 |
self.assertEqual(self._get_summary_line(property.fget), "fget") |
| 1293 |
self.assertEqual(self._get_summary_line(StopIteration.value), "value") |
| 1294 |
|
| 1295 |
@requires_docstrings |
| 1296 |
def test_slot_descriptor(self): |
| 1297 |
class Point: |
| 1298 |
__slots__ = 'x', 'y' |
| 1299 |
self.assertEqual(self._get_summary_line(Point.x), "x") |
| 1300 |
|
| 1301 |
@requires_docstrings |
| 1302 |
def test_dict_attr_descriptor(self): |
| 1303 |
class NS: |
| 1304 |
pass |
| 1305 |
self.assertEqual(self._get_summary_line(NS.__dict__['__dict__']), |
| 1306 |
"__dict__") |
| 1307 |
|
| 1308 |
@requires_docstrings |
| 1309 |
def test_structseq_member_descriptor(self): |
| 1310 |
self.assertEqual(self._get_summary_line(type(sys.hash_info).width), |
| 1311 |
"width") |
| 1312 |
self.assertEqual(self._get_summary_line(type(sys.flags).debug), |
| 1313 |
"debug") |
| 1314 |
self.assertEqual(self._get_summary_line(type(sys.version_info).major), |
| 1315 |
"major") |
| 1316 |
self.assertEqual(self._get_summary_line(type(sys.float_info).max), |
| 1317 |
"max") |
| 1318 |
|
| 1319 |
@requires_docstrings |
| 1320 |
def test_namedtuple_field_descriptor(self): |
| 1321 |
Box = namedtuple('Box', ('width', 'height')) |
| 1322 |
self.assertEqual(self._get_summary_lines(Box.width), """\ |
| 1323 |
Alias for field number 0 |
| 1324 |
""") |
| 1325 |
|
| 1326 |
@requires_docstrings |
| 1327 |
def test_property(self): |
| 1328 |
class Rect: |
| 1329 |
@property |
| 1330 |
def area(self): |
| 1331 |
'''Area of the rect''' |
| 1332 |
return self.w * self.h |
| 1333 |
|
| 1334 |
self.assertEqual(self._get_summary_lines(Rect.area), """\ |
| 1335 |
Area of the rect |
| 1336 |
""") |
| 1337 |
self.assertIn(""" |
| 1338 |
| area |
| 1339 |
| Area of the rect |
| 1340 |
""", pydoc.plain(pydoc.render_doc(Rect))) |
| 1341 |
|
| 1342 |
@requires_docstrings |
| 1343 |
def test_custom_non_data_descriptor(self): |
| 1344 |
class Descr: |
| 1345 |
def __get__(self, obj, cls): |
| 1346 |
if obj is None: |
| 1347 |
return self |
| 1348 |
return 42 |
| 1349 |
class X: |
| 1350 |
attr = Descr() |
| 1351 |
|
| 1352 |
self.assertEqual(self._get_summary_lines(X.attr), f"""\ |
| 1353 |
<{__name__}.TestDescriptions.test_custom_non_data_descriptor.<locals>.Descr object>""") |
| 1354 |
|
| 1355 |
X.attr.__doc__ = 'Custom descriptor' |
| 1356 |
self.assertEqual(self._get_summary_lines(X.attr), f"""\ |
| 1357 |
<{__name__}.TestDescriptions.test_custom_non_data_descriptor.<locals>.Descr object> |
| 1358 |
Custom descriptor |
| 1359 |
""") |
| 1360 |
|
| 1361 |
X.attr.__name__ = 'foo' |
| 1362 |
self.assertEqual(self._get_summary_lines(X.attr), """\ |
| 1363 |
foo(...) |
| 1364 |
Custom descriptor |
| 1365 |
""") |
| 1366 |
|
| 1367 |
@requires_docstrings |
| 1368 |
def test_custom_data_descriptor(self): |
| 1369 |
class Descr: |
| 1370 |
def __get__(self, obj, cls): |
| 1371 |
if obj is None: |
| 1372 |
return self |
| 1373 |
return 42 |
| 1374 |
def __set__(self, obj, cls): |
| 1375 |
1/0 |
| 1376 |
class X: |
| 1377 |
attr = Descr() |
| 1378 |
|
| 1379 |
self.assertEqual(self._get_summary_lines(X.attr), "") |
| 1380 |
|
| 1381 |
X.attr.__doc__ = 'Custom descriptor' |
| 1382 |
self.assertEqual(self._get_summary_lines(X.attr), """\ |
| 1383 |
Custom descriptor |
| 1384 |
""") |
| 1385 |
|
| 1386 |
X.attr.__name__ = 'foo' |
| 1387 |
self.assertEqual(self._get_summary_lines(X.attr), """\ |
| 1388 |
foo |
| 1389 |
Custom descriptor |
| 1390 |
""") |
| 1391 |
|
| 1392 |
def test_async_annotation(self): |
| 1393 |
async def coro_function(ign) -> int: |
| 1394 |
return 1 |
| 1395 |
|
| 1396 |
text = pydoc.plain(pydoc.plaintext.document(coro_function)) |
| 1397 |
self.assertIn('async coro_function', text) |
| 1398 |
|
| 1399 |
html = pydoc.HTMLDoc().document(coro_function) |
| 1400 |
self.assertIn( |
| 1401 |
'async <a name="-coro_function"><strong>coro_function', |
| 1402 |
html) |
| 1403 |
|
| 1404 |
def test_async_generator_annotation(self): |
| 1405 |
async def an_async_generator(): |
| 1406 |
yield 1 |
| 1407 |
|
| 1408 |
text = pydoc.plain(pydoc.plaintext.document(an_async_generator)) |
| 1409 |
self.assertIn('async an_async_generator', text) |
| 1410 |
|
| 1411 |
html = pydoc.HTMLDoc().document(an_async_generator) |
| 1412 |
self.assertIn( |
| 1413 |
'async <a name="-an_async_generator"><strong>an_async_generator', |
| 1414 |
html) |
| 1415 |
|
| 1416 |
@requires_docstrings |
| 1417 |
def test_html_for_https_links(self): |
| 1418 |
def a_fn_with_https_link(): |
| 1419 |
"""a link https://localhost/""" |
| 1420 |
pass |
| 1421 |
|
| 1422 |
html = pydoc.HTMLDoc().document(a_fn_with_https_link) |
| 1423 |
self.assertIn( |
| 1424 |
'<a href="https://localhost/">https://localhost/</a>', |
| 1425 |
html |
| 1426 |
) |
| 1427 |
|
| 1428 |
|
| 1429 |
class PydocFodderTest(unittest.TestCase): |
| 1430 |
|
| 1431 |
def getsection(self, text, beginline, endline): |
| 1432 |
lines = text.splitlines() |
| 1433 |
beginindex, endindex = 0, None |
| 1434 |
if beginline is not None: |
| 1435 |
beginindex = lines.index(beginline) |
| 1436 |
if endline is not None: |
| 1437 |
endindex = lines.index(endline, beginindex) |
| 1438 |
return lines[beginindex:endindex] |
| 1439 |
|
| 1440 |
def test_text_doc_routines_in_class(self, cls=pydocfodder.B): |
| 1441 |
doc = pydoc.TextDoc() |
| 1442 |
result = doc.docclass(cls) |
| 1443 |
result = clean_text(result) |
| 1444 |
where = 'defined here' if cls is pydocfodder.B else 'inherited from B' |
| 1445 |
lines = self.getsection(result, f' | Methods {where}:', ' | ' + '-'*70) |
| 1446 |
self.assertIn(' | A_method_alias = A_method(self)', lines) |
| 1447 |
self.assertIn(' | B_method_alias = B_method(self)', lines) |
| 1448 |
self.assertIn(' | A_staticmethod(x, y) from test.test_pydoc.pydocfodder.A', lines) |
| 1449 |
self.assertIn(' | A_staticmethod_alias = A_staticmethod(x, y)', lines) |
| 1450 |
self.assertIn(' | global_func(x, y) from test.test_pydoc.pydocfodder', lines) |
| 1451 |
self.assertIn(' | global_func_alias = global_func(x, y)', lines) |
| 1452 |
self.assertIn(' | global_func2_alias = global_func2(x, y) from test.test_pydoc.pydocfodder', lines) |
| 1453 |
self.assertIn(' | __repr__(self, /) from builtins.object', lines) |
| 1454 |
self.assertIn(' | object_repr = __repr__(self, /)', lines) |
| 1455 |
|
| 1456 |
lines = self.getsection(result, f' | Static methods {where}:', ' | ' + '-'*70) |
| 1457 |
self.assertIn(' | A_classmethod_ref = A_classmethod(x) class method of test.test_pydoc.pydocfodder.A', lines) |
| 1458 |
note = '' if cls is pydocfodder.B else ' class method of test.test_pydoc.pydocfodder.B' |
| 1459 |
self.assertIn(' | B_classmethod_ref = B_classmethod(x)' + note, lines) |
| 1460 |
self.assertIn(' | A_method_ref = A_method() method of test.test_pydoc.pydocfodder.A instance', lines) |
| 1461 |
self.assertIn(' | get(key, default=None, /) method of builtins.dict instance', lines) |
| 1462 |
self.assertIn(' | dict_get = get(key, default=None, /) method of builtins.dict instance', lines) |
| 1463 |
|
| 1464 |
lines = self.getsection(result, f' | Class methods {where}:', ' | ' + '-'*70) |
| 1465 |
self.assertIn(' | B_classmethod(x)', lines) |
| 1466 |
self.assertIn(' | B_classmethod_alias = B_classmethod(x)', lines) |
| 1467 |
|
| 1468 |
def test_html_doc_routines_in_class(self, cls=pydocfodder.B): |
| 1469 |
doc = pydoc.HTMLDoc() |
| 1470 |
result = doc.docclass(cls) |
| 1471 |
result = html2text(result) |
| 1472 |
where = 'defined here' if cls is pydocfodder.B else 'inherited from B' |
| 1473 |
lines = self.getsection(result, f'Methods {where}:', '-'*70) |
| 1474 |
self.assertIn('A_method_alias = A_method(self)', lines) |
| 1475 |
self.assertIn('B_method_alias = B_method(self)', lines) |
| 1476 |
self.assertIn('A_staticmethod(x, y) from test.test_pydoc.pydocfodder.A', lines) |
| 1477 |
self.assertIn('A_staticmethod_alias = A_staticmethod(x, y)', lines) |
| 1478 |
self.assertIn('global_func(x, y) from test.test_pydoc.pydocfodder', lines) |
| 1479 |
self.assertIn('global_func_alias = global_func(x, y)', lines) |
| 1480 |
self.assertIn('global_func2_alias = global_func2(x, y) from test.test_pydoc.pydocfodder', lines) |
| 1481 |
self.assertIn('__repr__(self, /) from builtins.object', lines) |
| 1482 |
self.assertIn('object_repr = __repr__(self, /)', lines) |
| 1483 |
|
| 1484 |
lines = self.getsection(result, f'Static methods {where}:', '-'*70) |
| 1485 |
self.assertIn('A_classmethod_ref = A_classmethod(x) class method of test.test_pydoc.pydocfodder.A', lines) |
| 1486 |
note = '' if cls is pydocfodder.B else ' class method of test.test_pydoc.pydocfodder.B' |
| 1487 |
self.assertIn('B_classmethod_ref = B_classmethod(x)' + note, lines) |
| 1488 |
self.assertIn('A_method_ref = A_method() method of test.test_pydoc.pydocfodder.A instance', lines) |
| 1489 |
|
| 1490 |
lines = self.getsection(result, f'Class methods {where}:', '-'*70) |
| 1491 |
self.assertIn('B_classmethod(x)', lines) |
| 1492 |
self.assertIn('B_classmethod_alias = B_classmethod(x)', lines) |
| 1493 |
|
| 1494 |
def test_text_doc_inherited_routines_in_class(self): |
| 1495 |
self.test_text_doc_routines_in_class(pydocfodder.D) |
| 1496 |
|
| 1497 |
def test_html_doc_inherited_routines_in_class(self): |
| 1498 |
self.test_html_doc_routines_in_class(pydocfodder.D) |
| 1499 |
|
| 1500 |
def test_text_doc_routines_in_module(self): |
| 1501 |
doc = pydoc.TextDoc() |
| 1502 |
result = doc.docmodule(pydocfodder) |
| 1503 |
result = clean_text(result) |
| 1504 |
lines = self.getsection(result, 'FUNCTIONS', 'FILE') |
| 1505 |
|
| 1506 |
self.assertIn(' global_func_alias = global_func(x, y)', lines) |
| 1507 |
self.assertIn(' A_staticmethod(x, y)', lines) |
| 1508 |
self.assertIn(' A_staticmethod_alias = A_staticmethod(x, y)', lines) |
| 1509 |
|
| 1510 |
self.assertIn(' A_classmethod(x) class method of A', lines) |
| 1511 |
self.assertIn(' A_classmethod2 = A_classmethod(x) class method of A', lines) |
| 1512 |
self.assertIn(' A_classmethod3 = A_classmethod(x) class method of B', lines) |
| 1513 |
|
| 1514 |
self.assertIn(' A_method() method of A instance', lines) |
| 1515 |
self.assertIn(' A_method2 = A_method() method of A instance', lines) |
| 1516 |
self.assertIn(' A_method3 = A_method() method of B instance', lines) |
| 1517 |
self.assertIn(' A_staticmethod_ref = A_staticmethod(x, y)', lines) |
| 1518 |
self.assertIn(' A_staticmethod_ref2 = A_staticmethod(y) method of B instance', lines) |
| 1519 |
self.assertIn(' get(key, default=None, /) method of builtins.dict instance', lines) |
| 1520 |
self.assertIn(' dict_get = get(key, default=None, /) method of builtins.dict instance', lines) |
| 1521 |
|
| 1522 |
self.assertIn(' B_method(self)', lines) |
| 1523 |
self.assertIn(' B_method2 = B_method(self)', lines) |
| 1524 |
|
| 1525 |
def test_html_doc_routines_in_module(self): |
| 1526 |
doc = pydoc.HTMLDoc() |
| 1527 |
result = doc.docmodule(pydocfodder) |
| 1528 |
result = html2text(result) |
| 1529 |
lines = self.getsection(result, ' Functions', None) |
| 1530 |
|
| 1531 |
self.assertIn(' global_func_alias = global_func(x, y)', lines) |
| 1532 |
self.assertIn(' A_staticmethod(x, y)', lines) |
| 1533 |
self.assertIn(' A_staticmethod_alias = A_staticmethod(x, y)', lines) |
| 1534 |
|
| 1535 |
self.assertIn('A_classmethod(x) class method of A', lines) |
| 1536 |
self.assertIn(' A_classmethod2 = A_classmethod(x) class method of A', lines) |
| 1537 |
self.assertIn(' A_classmethod3 = A_classmethod(x) class method of B', lines) |
| 1538 |
|
| 1539 |
self.assertIn(' A_method() method of A instance', lines) |
| 1540 |
self.assertIn(' A_method2 = A_method() method of A instance', lines) |
| 1541 |
self.assertIn(' A_method3 = A_method() method of B instance', lines) |
| 1542 |
self.assertIn(' A_staticmethod_ref = A_staticmethod(x, y)', lines) |
| 1543 |
self.assertIn(' A_staticmethod_ref2 = A_staticmethod(y) method of B instance', lines) |
| 1544 |
self.assertIn(' get(key, default=None, /) method of builtins.dict instance', lines) |
| 1545 |
self.assertIn(' dict_get = get(key, default=None, /) method of builtins.dict instance', lines) |
| 1546 |
|
| 1547 |
self.assertIn(' B_method(self)', lines) |
| 1548 |
self.assertIn(' B_method2 = B_method(self)', lines) |
| 1549 |
|
| 1550 |
|
| 1551 |
@unittest.skipIf( |
| 1552 |
is_emscripten or is_wasi, |
| 1553 |
"Socket server not available on Emscripten/WASI." |
| 1554 |
) |
| 1555 |
class PydocServerTest(unittest.TestCase): |
| 1556 |
"""Tests for pydoc._start_server""" |
| 1557 |
|
| 1558 |
def test_server(self): |
| 1559 |
|
| 1560 |
|
| 1561 |
def my_url_handler(url, content_type): |
| 1562 |
text = 'the URL sent was: (%s, %s)' % (url, content_type) |
| 1563 |
return text |
| 1564 |
|
| 1565 |
serverthread = pydoc._start_server( |
| 1566 |
my_url_handler, |
| 1567 |
hostname='localhost', |
| 1568 |
port=0, |
| 1569 |
) |
| 1570 |
self.assertEqual(serverthread.error, None) |
| 1571 |
self.assertTrue(serverthread.serving) |
| 1572 |
self.addCleanup( |
| 1573 |
lambda: serverthread.stop() if serverthread.serving else None |
| 1574 |
) |
| 1575 |
self.assertIn('localhost', serverthread.url) |
| 1576 |
|
| 1577 |
self.addCleanup(urlcleanup) |
| 1578 |
self.assertEqual( |
| 1579 |
b'the URL sent was: (/test, text/html)', |
| 1580 |
urlopen(urllib.parse.urljoin(serverthread.url, '/test')).read(), |
| 1581 |
) |
| 1582 |
self.assertEqual( |
| 1583 |
b'the URL sent was: (/test.css, text/css)', |
| 1584 |
urlopen(urllib.parse.urljoin(serverthread.url, '/test.css')).read(), |
| 1585 |
) |
| 1586 |
|
| 1587 |
serverthread.stop() |
| 1588 |
self.assertFalse(serverthread.serving) |
| 1589 |
self.assertIsNone(serverthread.docserver) |
| 1590 |
self.assertIsNone(serverthread.url) |
| 1591 |
|
| 1592 |
|
| 1593 |
class PydocUrlHandlerTest(PydocBaseTest): |
| 1594 |
"""Tests for pydoc._url_handler""" |
| 1595 |
|
| 1596 |
def test_content_type_err(self): |
| 1597 |
f = pydoc._url_handler |
| 1598 |
self.assertRaises(TypeError, f, 'A', '') |
| 1599 |
self.assertRaises(TypeError, f, 'B', 'foobar') |
| 1600 |
|
| 1601 |
def test_url_requests(self): |
| 1602 |
|
| 1603 |
|
| 1604 |
|
| 1605 |
requests = [ |
| 1606 |
("", "Pydoc: Index of Modules"), |
| 1607 |
("get?key=", "Pydoc: Index of Modules"), |
| 1608 |
("index", "Pydoc: Index of Modules"), |
| 1609 |
("topics", "Pydoc: Topics"), |
| 1610 |
("keywords", "Pydoc: Keywords"), |
| 1611 |
("pydoc", "Pydoc: module pydoc"), |
| 1612 |
("get?key=pydoc", "Pydoc: module pydoc"), |
| 1613 |
("search?key=pydoc", "Pydoc: Search Results"), |
| 1614 |
("topic?key=def", "Pydoc: KEYWORD def"), |
| 1615 |
("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"), |
| 1616 |
("foobar", "Pydoc: Error - foobar"), |
| 1617 |
] |
| 1618 |
|
| 1619 |
with self.restrict_walk_packages(): |
| 1620 |
for url, title in requests: |
| 1621 |
self.call_url_handler(url, title) |
| 1622 |
|
| 1623 |
|
| 1624 |
class TestHelper(unittest.TestCase): |
| 1625 |
def test_keywords(self): |
| 1626 |
self.assertEqual(sorted(pydoc.Helper.keywords), |
| 1627 |
sorted(keyword.kwlist)) |
| 1628 |
|
| 1629 |
|
| 1630 |
class PydocWithMetaClasses(unittest.TestCase): |
| 1631 |
@unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), |
| 1632 |
'trace function introduces __locals__ unexpectedly') |
| 1633 |
@requires_docstrings |
| 1634 |
def test_DynamicClassAttribute(self): |
| 1635 |
class Meta(type): |
| 1636 |
def __getattr__(self, name): |
| 1637 |
if name == 'ham': |
| 1638 |
return 'spam' |
| 1639 |
return super().__getattr__(name) |
| 1640 |
class DA(metaclass=Meta): |
| 1641 |
@types.DynamicClassAttribute |
| 1642 |
def ham(self): |
| 1643 |
return 'eggs' |
| 1644 |
expected_text_data_docstrings = tuple('\n | ' + s if s else '' |
| 1645 |
for s in expected_data_docstrings) |
| 1646 |
output = StringIO() |
| 1647 |
helper = pydoc.Helper(output=output) |
| 1648 |
helper(DA) |
| 1649 |
expected_text = expected_dynamicattribute_pattern % ( |
| 1650 |
(__name__,) + expected_text_data_docstrings[:2]) |
| 1651 |
result = output.getvalue().strip() |
| 1652 |
self.assertEqual(expected_text, result) |
| 1653 |
|
| 1654 |
@unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), |
| 1655 |
'trace function introduces __locals__ unexpectedly') |
| 1656 |
@requires_docstrings |
| 1657 |
def test_virtualClassAttributeWithOneMeta(self): |
| 1658 |
class Meta(type): |
| 1659 |
def __dir__(cls): |
| 1660 |
return ['__class__', '__module__', '__name__', 'LIFE'] |
| 1661 |
def __getattr__(self, name): |
| 1662 |
if name =='LIFE': |
| 1663 |
return 42 |
| 1664 |
return super().__getattr(name) |
| 1665 |
class Class(metaclass=Meta): |
| 1666 |
pass |
| 1667 |
output = StringIO() |
| 1668 |
helper = pydoc.Helper(output=output) |
| 1669 |
helper(Class) |
| 1670 |
expected_text = expected_virtualattribute_pattern1 % __name__ |
| 1671 |
result = output.getvalue().strip() |
| 1672 |
self.assertEqual(expected_text, result) |
| 1673 |
|
| 1674 |
@unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), |
| 1675 |
'trace function introduces __locals__ unexpectedly') |
| 1676 |
@requires_docstrings |
| 1677 |
def test_virtualClassAttributeWithTwoMeta(self): |
| 1678 |
class Meta1(type): |
| 1679 |
def __dir__(cls): |
| 1680 |
return ['__class__', '__module__', '__name__', 'one'] |
| 1681 |
def __getattr__(self, name): |
| 1682 |
if name =='one': |
| 1683 |
return 1 |
| 1684 |
return super().__getattr__(name) |
| 1685 |
class Meta2(type): |
| 1686 |
def __dir__(cls): |
| 1687 |
return ['__class__', '__module__', '__name__', 'two'] |
| 1688 |
def __getattr__(self, name): |
| 1689 |
if name =='two': |
| 1690 |
return 2 |
| 1691 |
return super().__getattr__(name) |
| 1692 |
class Meta3(Meta1, Meta2): |
| 1693 |
def __dir__(cls): |
| 1694 |
return list(sorted(set( |
| 1695 |
['__class__', '__module__', '__name__', 'three'] + |
| 1696 |
Meta1.__dir__(cls) + Meta2.__dir__(cls)))) |
| 1697 |
def __getattr__(self, name): |
| 1698 |
if name =='three': |
| 1699 |
return 3 |
| 1700 |
return super().__getattr__(name) |
| 1701 |
class Class1(metaclass=Meta1): |
| 1702 |
pass |
| 1703 |
class Class2(Class1, metaclass=Meta3): |
| 1704 |
pass |
| 1705 |
output = StringIO() |
| 1706 |
helper = pydoc.Helper(output=output) |
| 1707 |
helper(Class1) |
| 1708 |
expected_text1 = expected_virtualattribute_pattern2 % __name__ |
| 1709 |
result1 = output.getvalue().strip() |
| 1710 |
self.assertEqual(expected_text1, result1) |
| 1711 |
output = StringIO() |
| 1712 |
helper = pydoc.Helper(output=output) |
| 1713 |
helper(Class2) |
| 1714 |
expected_text2 = expected_virtualattribute_pattern3 % __name__ |
| 1715 |
result2 = output.getvalue().strip() |
| 1716 |
self.assertEqual(expected_text2, result2) |
| 1717 |
|
| 1718 |
@unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), |
| 1719 |
'trace function introduces __locals__ unexpectedly') |
| 1720 |
@requires_docstrings |
| 1721 |
def test_buggy_dir(self): |
| 1722 |
class M(type): |
| 1723 |
def __dir__(cls): |
| 1724 |
return ['__class__', '__name__', 'missing', 'here'] |
| 1725 |
class C(metaclass=M): |
| 1726 |
here = 'present!' |
| 1727 |
output = StringIO() |
| 1728 |
helper = pydoc.Helper(output=output) |
| 1729 |
helper(C) |
| 1730 |
expected_text = expected_missingattribute_pattern % __name__ |
| 1731 |
result = output.getvalue().strip() |
| 1732 |
self.assertEqual(expected_text, result) |
| 1733 |
|
| 1734 |
def test_resolve_false(self): |
| 1735 |
|
| 1736 |
|
| 1737 |
with captured_stdout() as help_io: |
| 1738 |
pydoc.help('enum.Enum') |
| 1739 |
helptext = help_io.getvalue() |
| 1740 |
self.assertIn('class Enum', helptext) |
| 1741 |
|
| 1742 |
|
| 1743 |
class TestInternalUtilities(unittest.TestCase): |
| 1744 |
|
| 1745 |
def setUp(self): |
| 1746 |
tmpdir = tempfile.TemporaryDirectory() |
| 1747 |
self.argv0dir = tmpdir.name |
| 1748 |
self.argv0 = os.path.join(tmpdir.name, "nonexistent") |
| 1749 |
self.addCleanup(tmpdir.cleanup) |
| 1750 |
self.abs_curdir = abs_curdir = os.getcwd() |
| 1751 |
self.curdir_spellings = ["", os.curdir, abs_curdir] |
| 1752 |
|
| 1753 |
def _get_revised_path(self, given_path, argv0=None): |
| 1754 |
|
| 1755 |
|
| 1756 |
if argv0 is None: |
| 1757 |
argv0 = self.argv0 |
| 1758 |
return pydoc._get_revised_path(given_path, argv0) |
| 1759 |
|
| 1760 |
def _get_starting_path(self): |
| 1761 |
|
| 1762 |
clean_path = sys.path.copy() |
| 1763 |
for spelling in self.curdir_spellings: |
| 1764 |
for __ in range(clean_path.count(spelling)): |
| 1765 |
clean_path.remove(spelling) |
| 1766 |
return clean_path |
| 1767 |
|
| 1768 |
def test_sys_path_adjustment_adds_missing_curdir(self): |
| 1769 |
clean_path = self._get_starting_path() |
| 1770 |
expected_path = [self.abs_curdir] + clean_path |
| 1771 |
self.assertEqual(self._get_revised_path(clean_path), expected_path) |
| 1772 |
|
| 1773 |
def test_sys_path_adjustment_removes_argv0_dir(self): |
| 1774 |
clean_path = self._get_starting_path() |
| 1775 |
expected_path = [self.abs_curdir] + clean_path |
| 1776 |
leading_argv0dir = [self.argv0dir] + clean_path |
| 1777 |
self.assertEqual(self._get_revised_path(leading_argv0dir), expected_path) |
| 1778 |
trailing_argv0dir = clean_path + [self.argv0dir] |
| 1779 |
self.assertEqual(self._get_revised_path(trailing_argv0dir), expected_path) |
| 1780 |
|
| 1781 |
def test_sys_path_adjustment_protects_pydoc_dir(self): |
| 1782 |
def _get_revised_path(given_path): |
| 1783 |
return self._get_revised_path(given_path, argv0=pydoc.__file__) |
| 1784 |
clean_path = self._get_starting_path() |
| 1785 |
leading_argv0dir = [self.argv0dir] + clean_path |
| 1786 |
expected_path = [self.abs_curdir] + leading_argv0dir |
| 1787 |
self.assertEqual(_get_revised_path(leading_argv0dir), expected_path) |
| 1788 |
trailing_argv0dir = clean_path + [self.argv0dir] |
| 1789 |
expected_path = [self.abs_curdir] + trailing_argv0dir |
| 1790 |
self.assertEqual(_get_revised_path(trailing_argv0dir), expected_path) |
| 1791 |
|
| 1792 |
def test_sys_path_adjustment_when_curdir_already_included(self): |
| 1793 |
clean_path = self._get_starting_path() |
| 1794 |
for spelling in self.curdir_spellings: |
| 1795 |
with self.subTest(curdir_spelling=spelling): |
| 1796 |
|
| 1797 |
leading_curdir = [spelling] + clean_path |
| 1798 |
self.assertIsNone(self._get_revised_path(leading_curdir)) |
| 1799 |
trailing_curdir = clean_path + [spelling] |
| 1800 |
self.assertIsNone(self._get_revised_path(trailing_curdir)) |
| 1801 |
leading_argv0dir = [self.argv0dir] + leading_curdir |
| 1802 |
self.assertIsNone(self._get_revised_path(leading_argv0dir)) |
| 1803 |
trailing_argv0dir = trailing_curdir + [self.argv0dir] |
| 1804 |
self.assertIsNone(self._get_revised_path(trailing_argv0dir)) |
| 1805 |
|
| 1806 |
|
| 1807 |
def setUpModule(): |
| 1808 |
thread_info = threading_helper.threading_setup() |
| 1809 |
unittest.addModuleCleanup(threading_helper.threading_cleanup, *thread_info) |
| 1810 |
unittest.addModuleCleanup(reap_children) |
| 1811 |
|
| 1812 |
|
| 1813 |
if __name__ == "__main__": |
| 1814 |
unittest.main() |