-
-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy path__init__.py
More file actions
1800 lines (1544 loc) · 64.2 KB
/
__init__.py
File metadata and controls
1800 lines (1544 loc) · 64.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Unit tests for pdoc package.
"""
import doctest
import enum
import importlib
import inspect
import os
import shutil
import signal
import subprocess
import sys
import typing
import threading
import unittest
import warnings
from contextlib import contextmanager, redirect_stderr, redirect_stdout
from functools import wraps
from glob import glob
from io import StringIO
from itertools import chain
from random import randint
from tempfile import TemporaryDirectory
from time import sleep
from types import ModuleType
from unittest.mock import patch
from urllib.error import HTTPError
from urllib.request import Request, urlopen
import pdoc
from pdoc import cli
from pdoc.html_helpers import (
minify_css, minify_html, glimpse, to_html,
ReferenceWarning, extract_toc, format_git_link,
)
TESTS_BASEDIR = os.path.abspath(os.path.dirname(__file__) or '.')
sys.path.insert(0, TESTS_BASEDIR)
EXAMPLE_MODULE = 'example_pkg'
EXAMPLE_PDOC_MODULE = pdoc.Module(EXAMPLE_MODULE, context=pdoc.Context())
PDOC_PDOC_MODULE = pdoc.Module(pdoc, context=pdoc.Context())
EMPTY_MODULE = ModuleType('empty')
EMPTY_MODULE.__pdoc__ = {} # type: ignore
with warnings.catch_warnings(record=True):
DUMMY_PDOC_MODULE = pdoc.Module(EMPTY_MODULE, context=pdoc.Context())
T = typing.TypeVar("T")
@contextmanager
def temp_dir():
with TemporaryDirectory(prefix='pdoc-test-') as path:
yield path
@contextmanager
def chdir(path):
old = os.getcwd()
try:
os.chdir(path)
yield
finally:
os.chdir(old)
def run(*args, **kwargs) -> int:
params = (('--' + key.replace('_', '-'), value)
for key, value in kwargs.items())
params = list(filter(None, chain.from_iterable(params))) # type: ignore
_args = cli.parser.parse_args([*params, *args]) # type: ignore
try:
returncode = cli.main(_args)
return returncode or 0
except SystemExit as e:
return e.code
@contextmanager
def run_html(*args, **kwargs):
with temp_dir() as path, \
redirect_streams():
run(*args, html=None, output_dir=path, **kwargs)
with chdir(path):
yield
@contextmanager
def redirect_streams():
stdout, stderr = StringIO(), StringIO()
with redirect_stderr(stderr), redirect_stdout(stdout):
yield stdout, stderr
def ignore_warnings(func):
@wraps(func)
def wrapper(*args, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter('ignore')
func(*args, **kwargs)
return wrapper
class CliTest(unittest.TestCase):
"""
Command-line interface unit tests.
"""
ALL_FILES = [
'example_pkg',
os.path.join('example_pkg', 'index.html'),
os.path.join('example_pkg', 'index.m.html'),
os.path.join('example_pkg', 'module.html'),
os.path.join('example_pkg', '_private'),
os.path.join('example_pkg', '_private', 'index.html'),
os.path.join('example_pkg', '_private', 'module.html'),
os.path.join('example_pkg', 'subpkg'),
os.path.join('example_pkg', 'subpkg', '_private.html'),
os.path.join('example_pkg', 'subpkg', 'index.html'),
os.path.join('example_pkg', 'subpkg2'),
os.path.join('example_pkg', 'subpkg2', '_private.html'),
os.path.join('example_pkg', 'subpkg2', 'module.html'),
os.path.join('example_pkg', 'subpkg2', 'index.html'),
]
PUBLIC_FILES = [f for f in ALL_FILES if (os.path.sep + '_') not in f]
def setUp(self):
pdoc.reset()
@unittest.skipIf(sys.version_info < (3, 7), 'pdoc._formatannotation fails on Py3.6')
def test_project_doctests(self):
doctests = doctest.testmod(pdoc)
assert not doctests.failed and doctests.attempted, doctests
def _basic_html_assertions(self, expected_files=PUBLIC_FILES):
# Output directory tree layout is as expected
files = glob('**', recursive=True)
self.assertEqual(sorted(files), sorted(expected_files))
def _check_files(self, include_patterns=(), exclude_patterns=(), file_pattern='**/*.html'):
files = glob(file_pattern, recursive=True)
assert files
for file in files:
with open(file) as f:
contents = f.read()
for pattern in include_patterns:
self.assertIn(pattern, contents)
for pattern in exclude_patterns:
self.assertNotIn(pattern, contents)
def test_html(self):
include_patterns = [
'a=<object',
'CONST docstring',
'var docstring',
'foreign_var',
'foreign var docstring',
'A',
'A.overridden docstring',
'A.overridden_same_docstring docstring',
'A.inherited',
'B docstring',
'B.overridden docstring',
'builtins.int',
'External refs: ',
'>sys.version<',
'B.CONST docstring',
'B.var docstring',
'b=1',
'*args',
'**kwargs',
'x, y, z, w',
'instance_var',
'instance var docstring',
'B.f docstring',
'B.static docstring',
'B.cls docstring',
'B.p docstring',
'B.C docstring',
'B.overridden docstring',
'<code>__init__</code> docstring',
' class="ident">static',
]
exclude_patterns = [
'<object ',
' class="ident">_private',
' class="ident">_Private',
'non_callable_routine',
]
package_files = {
'': self.PUBLIC_FILES,
'.subpkg2': [f for f in self.PUBLIC_FILES
if 'subpkg2' in f or f == EXAMPLE_MODULE],
'._private': [f for f in self.ALL_FILES
if EXAMPLE_MODULE + os.path.sep + '_private' in f or f == EXAMPLE_MODULE],
}
for package, expected_files in package_files.items():
with self.subTest(package=package):
with run_html(EXAMPLE_MODULE + package,
'--config', 'show_type_annotations=False',
config='show_source_code=False'):
self._basic_html_assertions(expected_files)
self._check_files(include_patterns, exclude_patterns)
filenames_files = {
('module.py',): ['module.html'],
('module.py', 'subpkg2'): ['module.html', 'subpkg2',
os.path.join('subpkg2', 'index.html'),
os.path.join('subpkg2', 'module.html')],
}
with chdir(TESTS_BASEDIR):
for filenames, expected_files in filenames_files.items():
with self.subTest(filename=','.join(filenames)):
with run_html(*(os.path.join(EXAMPLE_MODULE, f) for f in filenames),
'--config', 'show_type_annotations=False',
config='show_source_code=False'):
self._basic_html_assertions(expected_files)
self._check_files(include_patterns, exclude_patterns)
def test_html_multiple_files(self):
with chdir(TESTS_BASEDIR):
with run_html(os.path.join(EXAMPLE_MODULE, 'module.py'),
os.path.join(EXAMPLE_MODULE, 'subpkg2')):
self._basic_html_assertions(['module.html', 'subpkg2',
os.path.join('subpkg2', 'index.html'),
os.path.join('subpkg2', 'module.html')])
def test_html_identifier(self):
for package in ('', '._private'):
with self.subTest(package=package), \
self.assertWarns(UserWarning) as cm:
with run_html(EXAMPLE_MODULE + package, filter='A',
config='show_source_code=False'):
self._check_files(['A'], ['CONST', 'B docstring'])
self.assertIn('Code reference `example_pkg.B`', cm.warning.args[0])
def test_html_ref_links(self):
with run_html(EXAMPLE_MODULE, config='show_source_code=False'):
self._check_files(
file_pattern=os.path.join(EXAMPLE_MODULE, 'index.html'),
include_patterns=[
'href="#example_pkg.B">',
'href="#example_pkg.A">',
],
)
def test_docformat(self):
with self.assertWarns(UserWarning) as cm,\
run_html(EXAMPLE_MODULE, config='docformat="restructuredtext"'):
self._basic_html_assertions()
self.assertIn('numpy', cm.warning.args[0])
def test_html_no_source(self):
with self.assertWarns(DeprecationWarning),\
run_html(EXAMPLE_MODULE, html_no_source=None):
self._basic_html_assertions()
self._check_files(exclude_patterns=['class="source"', 'Hidden'])
def test_google_search_query(self):
with run_html(EXAMPLE_MODULE, config='google_search_query="anything"'):
self._basic_html_assertions()
self._check_files(include_patterns=['class="gcse-search"'])
def test_lunr_search(self):
with run_html(EXAMPLE_MODULE, config='lunr_search={"fuzziness": 1}'):
files = self.PUBLIC_FILES + ["doc-search.html", "index.js"]
self._basic_html_assertions(expected_files=files)
self._check_files(exclude_patterns=['class="gcse-search"'])
self._check_files(include_patterns=['URLS=[\n"example_pkg/index.html",\n"example_pkg/'],
file_pattern='index.js')
self._check_files(include_patterns=["'../doc-search.html#'"],
file_pattern='example_pkg/index.html')
self._check_files(include_patterns=["'../doc-search.html#'"],
file_pattern='example_pkg/module.html')
self._check_files(include_patterns=["'../../doc-search.html#'"],
file_pattern='example_pkg/subpkg/index.html')
# Only build lunr search when --html
with redirect_streams() as (_, stderr):
run(EXAMPLE_MODULE, config='lunr_search={"fuzziness": 1}')
self.assertFalse(stderr.read())
def test_force(self):
with run_html(EXAMPLE_MODULE):
with redirect_streams() as (stdout, stderr):
returncode = run(EXAMPLE_MODULE, html=None, output_dir=os.getcwd())
self.assertNotEqual(returncode, 0)
self.assertNotEqual(stderr.getvalue(), '')
with redirect_streams() as (stdout, stderr):
returncode = run(EXAMPLE_MODULE, html=None, force=None, output_dir=os.getcwd())
self.assertEqual(returncode, 0)
self.assertEqual(stderr.getvalue(), '')
def test_external_links(self):
with run_html(EXAMPLE_MODULE):
self._basic_html_assertions()
self._check_files(exclude_patterns=['<a href="/sys.version.ext"'])
with self.assertWarns(DeprecationWarning),\
run_html(EXAMPLE_MODULE, external_links=None):
self._basic_html_assertions()
self._check_files(['<a title="sys.version" href="/sys.version.ext"'])
def test_template_dir(self):
old_tpl_dirs = pdoc.tpl_lookup.directories.copy()
# Prevent loading incorrect template cached from prev runs
pdoc.tpl_lookup._collection.clear()
try:
with run_html(EXAMPLE_MODULE, template_dir=TESTS_BASEDIR):
self._basic_html_assertions()
self._check_files(['FOOBAR', '/* Empty CSS */'], ['coding: utf-8'])
finally:
pdoc.tpl_lookup.directories = old_tpl_dirs
pdoc.tpl_lookup._collection.clear()
def test_link_prefix(self):
with self.assertWarns(DeprecationWarning),\
run_html(EXAMPLE_MODULE, link_prefix='/foobar/'):
self._basic_html_assertions()
self._check_files(['/foobar/' + EXAMPLE_MODULE])
def test_text(self):
include_patterns = [
'object_as_arg_default(*args, a=<object ',
'CONST docstring',
'var docstring',
'foreign_var',
'foreign var docstring',
'A',
'A.overridden docstring',
'A.overridden_same_docstring docstring',
'A.inherited',
'B docstring',
'B.overridden docstring',
'builtins.int',
'External refs: ',
'sys.version',
'B.CONST docstring',
'B.var docstring',
'x, y, z, w',
'`__init__` docstring',
'instance_var',
'instance var docstring',
'b=1',
'*args',
'**kwargs',
'B.f docstring',
'B.static docstring',
'B.cls docstring',
'B.p docstring',
'C',
'B.overridden docstring',
]
exclude_patterns = [
'_private',
'_Private',
'subprocess',
'Hidden',
'non_callable_routine',
]
with self.subTest(package=EXAMPLE_MODULE):
with redirect_streams() as (stdout, _):
run(EXAMPLE_MODULE, config='show_type_annotations=False')
out = stdout.getvalue()
header = f"Module {EXAMPLE_MODULE}\n{'':=<{len('Module ') + len(EXAMPLE_MODULE)}}"
self.assertIn(header, out)
for pattern in include_patterns:
self.assertIn(pattern, out)
for pattern in exclude_patterns:
self.assertNotIn(pattern, out)
with chdir(TESTS_BASEDIR):
for files in (('module.py',),
('module.py', 'subpkg2')):
with self.subTest(filename=','.join(files)):
with redirect_streams() as (stdout, _):
run(*(os.path.join(EXAMPLE_MODULE, f) for f in files))
out = stdout.getvalue()
for f in files:
header = f'Module {os.path.splitext(f)[0]}\n'
self.assertIn(header, out)
def test_text_identifier(self):
with redirect_streams() as (stdout, _):
run(EXAMPLE_MODULE, filter='A')
out = stdout.getvalue()
self.assertIn('A', out)
self.assertIn('### Descendants\n\n * example_pkg.B', out)
self.assertNotIn('CONST', out)
self.assertNotIn('B docstring', out)
def test_pdf(self):
with redirect_streams() as (stdout, stderr):
run('pdoc', pdf=None)
out = stdout.getvalue()
err = stderr.getvalue()
self.assertIn('pdoc3.github.io', out)
self.assertIn('pandoc', err)
self.assertIn('Doc(name', out.replace('>', '').replace('\n', '').replace(' ', ''))
@unittest.skipUnless('PDOC_TEST_PANDOC' in os.environ, 'PDOC_TEST_PANDOC not set/requested')
def test_pdf_pandoc(self):
with temp_dir() as path, \
chdir(path), \
redirect_streams() as (stdout, _), \
open('pdf.md', 'w') as f:
run('pdoc', pdf=None)
f.write(stdout.getvalue())
subprocess.run(pdoc.cli._PANDOC_COMMAND, shell=True, check=True)
self.assertTrue(os.path.exists('pdf.pdf'))
def test_config(self):
with run_html(EXAMPLE_MODULE, config='link_prefix="/foobar/"'):
self._basic_html_assertions()
self._check_files(['/foobar/' + EXAMPLE_MODULE])
def test_output_text(self):
with temp_dir() as path, \
redirect_streams():
run(EXAMPLE_MODULE, output_dir=path)
with chdir(path):
self._basic_html_assertions([file.replace('.html', '.md')
for file in self.PUBLIC_FILES])
def test_google_analytics(self):
expected = ['google-analytics.com']
with run_html(EXAMPLE_MODULE):
self._check_files((), exclude_patterns=expected)
with run_html(EXAMPLE_MODULE, config='google_analytics="UA-xxxxxx-y"'):
self._check_files(expected)
def test_relative_dir_path(self):
with chdir(os.path.join(TESTS_BASEDIR, EXAMPLE_MODULE)):
with run_html('.'):
self._check_files(())
def test_skip_errors(self):
with chdir(os.path.join(TESTS_BASEDIR, EXAMPLE_MODULE, '_skip_errors')),\
redirect_streams(),\
self.assertWarns(pdoc.Module.ImportWarning) as cm:
run('.', skip_errors=None)
self.assertIn('ZeroDivision', cm.warning.args[0])
@unittest.skipIf(sys.version_info < (3, 7), '__future__.annotations unsupported in <Py3.7')
def test_resolve_typing_forwardrefs(self):
# GH-245
with chdir(os.path.join(TESTS_BASEDIR, EXAMPLE_MODULE, '_resolve_typing_forwardrefs')):
with redirect_streams() as (out, _err):
run('postponed')
out = out.getvalue()
self.assertIn('bar', out)
self.assertIn('baz', out)
self.assertIn('dt', out)
self.assertIn('datetime', out)
with redirect_streams() as (out, _err):
run('evaluated')
out = out.getvalue()
self.assertIn('Set[Bar]', out)
class ApiTest(unittest.TestCase):
"""
Programmatic/API unit tests.
"""
def setUp(self):
pdoc.reset()
def test_module(self):
modules = {
EXAMPLE_MODULE: ('', ('index', 'module', 'subpkg', 'subpkg2')),
EXAMPLE_MODULE + '.subpkg2': ('.subpkg2', ('subpkg2.module',)),
}
with chdir(TESTS_BASEDIR):
for module, (name_suffix, submodules) in modules.items():
with self.subTest(module=module):
m = pdoc.Module(module)
self.assertEqual(repr(m), f"<Module '{m.obj.__name__}'>")
self.assertEqual(m.name, EXAMPLE_MODULE + name_suffix)
self.assertEqual(sorted(m.name for m in m.submodules()),
[EXAMPLE_MODULE + '.' + m for m in submodules])
def test_Module_find_class(self):
class A:
pass
mod = PDOC_PDOC_MODULE
self.assertIsInstance(mod.find_class(pdoc.Doc), pdoc.Class)
self.assertIsInstance(mod.find_class(A), pdoc.External)
def test_import_filename(self):
with patch.object(sys, 'path', ['']), \
chdir(os.path.join(TESTS_BASEDIR, EXAMPLE_MODULE)):
pdoc.import_module('index')
def test_imported_once(self):
with chdir(os.path.join(TESTS_BASEDIR, EXAMPLE_MODULE)):
pdoc.import_module('_imported_once.py')
def test_namespace(self):
# Test the three namespace types
# https://packaging.python.org/guides/packaging-namespace-packages/#creating-a-namespace-package
for i in range(1, 4):
path = os.path.join(TESTS_BASEDIR, EXAMPLE_MODULE, '_namespace', str(i))
with patch.object(sys, 'path', [os.path.join(path, 'a'),
os.path.join(path, 'b')]):
mod = pdoc.Module('a.main')
self.assertIn('D', mod.doc)
def test_module_allsubmodules(self):
m = pdoc.Module(EXAMPLE_MODULE + '._private')
self.assertEqual(sorted(m.name for m in m.submodules()),
[EXAMPLE_MODULE + '._private.module'])
def test_instance_var(self):
mod = EXAMPLE_PDOC_MODULE
var = mod.doc['B'].doc['instance_var']
self.assertTrue(var.instance_var)
def test_readonly_value_descriptors(self):
pdoc.reset()
mod = pdoc.Module(pdoc.import_module(EXAMPLE_MODULE))
var = mod.doc['B'].doc['ro_value_descriptor']
self.assertIsInstance(var, pdoc.Variable)
self.assertTrue(var.instance_var)
self.assertEqual(var.docstring, """ro_value_descriptor docstring""")
self.assertTrue(var.source)
var = mod.doc['B'].doc['ro_value_descriptor_no_doc']
self.assertIsInstance(var, pdoc.Variable)
self.assertTrue(var.instance_var)
self.assertEqual(var.docstring, """Read-only value descriptor""")
self.assertTrue(var.source)
def test_class_variables_docstring_not_from_obj(self):
class C:
vars_dont = 0
but_clss_have_doc = int
doc = pdoc.Class('C', DUMMY_PDOC_MODULE, C)
self.assertEqual(doc.doc['vars_dont'].docstring, '')
self.assertIn('integer', doc.doc['but_clss_have_doc'].docstring)
def test_builtin_methoddescriptors(self):
import parser
with self.assertWarns(UserWarning):
c = pdoc.Class('STType', pdoc.Module(parser), parser.STType)
self.assertIsInstance(c.doc['compile'], pdoc.Function)
def test_refname(self):
mod = EXAMPLE_MODULE + '.' + 'subpkg'
module = pdoc.Module(mod)
var = module.doc['var']
cls = module.doc['B']
nested_cls = cls.doc['C']
cls_var = cls.doc['var']
method = cls.doc['f']
self.assertEqual(pdoc.External('foo').refname, 'foo')
self.assertEqual(module.refname, mod)
self.assertEqual(var.refname, mod + '.var')
self.assertEqual(cls.refname, mod + '.B')
self.assertEqual(nested_cls.refname, mod + '.B.C')
self.assertEqual(cls_var.refname, mod + '.B.var')
self.assertEqual(method.refname, mod + '.B.f')
# Inherited method's refname points to class' implicit copy
pdoc.link_inheritance()
self.assertEqual(cls.doc['inherited'].refname, mod + '.B.inherited')
def test_qualname(self):
module = EXAMPLE_PDOC_MODULE
var = module.doc['var']
cls = module.doc['B']
nested_cls = cls.doc['C']
cls_var = cls.doc['var']
method = cls.doc['f']
self.assertEqual(pdoc.External('foo').qualname, 'foo')
self.assertEqual(module.qualname, EXAMPLE_MODULE)
self.assertEqual(var.qualname, 'var')
self.assertEqual(cls.qualname, 'B')
self.assertEqual(nested_cls.qualname, 'B.C')
self.assertEqual(cls_var.qualname, 'B.var')
self.assertEqual(method.qualname, 'B.f')
def test__pdoc__dict(self):
module = pdoc.import_module(EXAMPLE_MODULE)
with patch.object(module, '__pdoc__', {'B': False}):
pdoc.reset()
mod = pdoc.Module(module)
pdoc.link_inheritance()
self.assertIn('A', mod.doc)
self.assertNotIn('B', mod.doc)
with patch.object(module, '__pdoc__', {'B.f': False}):
pdoc.reset()
mod = pdoc.Module(module)
pdoc.link_inheritance()
self.assertIn('B', mod.doc)
self.assertNotIn('f', mod.doc['B'].doc)
self.assertIsInstance(mod.find_ident('B.f'), pdoc.External)
# GH-125: https://github.com/pdoc3/pdoc/issues/125
with patch.object(module, '__pdoc__', {'B.inherited': False}):
pdoc.reset()
mod = pdoc.Module(module)
pdoc.link_inheritance()
self.assertNotIn('inherited', mod.doc['B'].doc)
# Ensure "overridden key doesn't exist" warning is raised
with patch.object(module, '__pdoc__', {'xxx': False}):
pdoc.reset()
mod = pdoc.Module(module)
with self.assertWarns(UserWarning) as cm:
pdoc.link_inheritance()
self.assertIn("'xxx' does not exist", cm.warning.args[0])
# GH-99: https://github.com/pdoc3/pdoc/issues/99
module = pdoc.import_module(EXAMPLE_MODULE + '._exclude_dir')
with patch.object(module, '__pdoc__', {'downloaded_modules': False}, create=True):
pdoc.reset()
mod = pdoc.Module(module)
# GH-206: https://github.com/pdoc3/pdoc/issues/206
with warnings.catch_warnings(record=True) as cm:
pdoc.link_inheritance()
self.assertEqual(cm, [])
self.assertNotIn('downloaded_modules', mod.doc)
@ignore_warnings
def test_dont_touch__pdoc__blacklisted(self):
class Bomb:
def __getattribute__(self, item):
raise RuntimeError
class D:
x = Bomb()
"""doc"""
__qualname__ = 'D'
module = EMPTY_MODULE
D.__module__ = module.__name__ # Need to match is_from_this_module check
with patch.object(module, 'x', Bomb(), create=True), \
patch.object(module, '__pdoc__', {'x': False}):
mod = pdoc.Module(module)
pdoc.link_inheritance()
self.assertNotIn('x', mod.doc)
with patch.object(module, 'D', D, create=True), \
patch.object(module, '__pdoc__', {'D.x': False}):
mod = pdoc.Module(module)
pdoc.link_inheritance()
self.assertNotIn('x', mod.doc['D'].doc)
def test__pdoc__invalid_value(self):
module = pdoc.import_module(EXAMPLE_MODULE)
with patch.object(module, '__pdoc__', {'B': 1}), \
self.assertRaises(ValueError):
pdoc.Module(module)
pdoc.link_inheritance()
def test__pdoc__whitelist(self):
module = pdoc.import_module(EXAMPLE_MODULE)
mod = pdoc.Module(module)
pdoc.link_inheritance()
self.assertNotIn('__call__', mod.doc['A'].doc)
self.assertNotIn('_private_function', mod.doc)
# Override docstring string
docstring = "Overwrite private function doc"
with patch.object(module, '__pdoc__', {'A.__call__': docstring}):
mod = pdoc.Module(module)
pdoc.link_inheritance()
self.assertEqual(mod.doc['A'].doc['__call__'].docstring, docstring)
# Module-relative
with patch.object(module, '__pdoc__', {'_private_function': True}):
mod = pdoc.Module(module)
pdoc.link_inheritance()
self.assertIn('Private function', mod.doc['_private_function'].docstring)
self.assertNotIn('_private_function', mod.doc["subpkg"].doc)
# Defined in example_pkg, referring to a member of its submodule
with patch.object(module, '__pdoc__', {'subpkg.A.__call__': True}):
mod = pdoc.Module(module)
pdoc.link_inheritance()
self.assertIn('A.__call__', mod.doc['subpkg'].doc['A'].doc['__call__'].docstring)
# Using full refname
with patch.object(module, '__pdoc__', {'example_pkg.subpkg.A.__call__': True}):
mod = pdoc.Module(module)
pdoc.link_inheritance()
self.assertIn('A.__call__', mod.doc['subpkg'].doc['A'].doc['__call__'].docstring)
# Entire module, absolute refname
with patch.object(module, '__pdoc__', {'example_pkg._private': True}):
mod = pdoc.Module(module)
pdoc.link_inheritance()
self.assertIn('module', mod.doc['_private'].doc)
self.assertNotIn('_private', mod.doc['_private'].doc)
self.assertNotIn('__call__', mod.doc['_private'].doc['module'].doc)
# Entire module, relative
with patch.object(module, '__pdoc__', {'_private': True}):
mod = pdoc.Module(module)
pdoc.link_inheritance()
self.assertIn('_private', mod.doc)
self.assertNotIn('_private', mod.doc['_private'].doc)
self.assertNotIn('__call__', mod.doc['_private'].doc['module'].doc)
# Private instance variables
with patch.object(module, '__pdoc__', {'B._private_instance_var': True}):
mod = pdoc.Module(module)
pdoc.link_inheritance()
self.assertIn('should be private', mod.doc['B'].doc['_private_instance_var'].docstring)
def test__all__(self):
module = pdoc.import_module(EXAMPLE_MODULE + '.index')
with patch.object(module, '__all__', ['B'], create=True):
mod = pdoc.Module(module)
with self.assertWarns(UserWarning): # Only B is used but __pdoc__ contains others
pdoc.link_inheritance()
self.assertEqual(list(mod.doc.keys()), ['B', 'B.C'])
def test_find_ident(self):
mod = pdoc.Module(EXAMPLE_MODULE)
self.assertIsInstance(mod.find_ident('subpkg'), pdoc.Module)
mod = pdoc.Module(pdoc)
self.assertIsInstance(mod.find_ident('subpkg'), pdoc.External)
self.assertIsInstance(mod.find_ident(EXAMPLE_MODULE + '.subpkg'), pdoc.Module)
nonexistent = 'foo()'
result = mod.find_ident(nonexistent)
self.assertIsInstance(result, pdoc.External)
self.assertEqual(result.name, nonexistent)
# Ref by class __init__
self.assertIs(mod.find_ident('pdoc.Doc.__init__').obj, pdoc.Doc)
def test_inherits(self):
module = pdoc.Module(EXAMPLE_MODULE)
pdoc.link_inheritance()
a = module.doc['A']
b = module.doc['B']
self.assertEqual(b.doc['inherited'].inherits,
a.doc['inherited'])
self.assertEqual(b.doc['overridden_same_docstring'].inherits,
a.doc['overridden_same_docstring'])
self.assertEqual(b.doc['overridden'].inherits,
None)
c = module.doc['C']
d = module.doc['D']
self.assertEqual(d.doc['overridden'].inherits, c.doc['overridden'])
self.assertEqual(c.doc['overridden'].inherits, b.doc['overridden'])
def test_inherited_members(self):
mod = pdoc.Module(EXAMPLE_MODULE)
pdoc.link_inheritance()
a = mod.doc['A']
b = mod.doc['B']
self.assertEqual(b.inherited_members(), [(a, [a.doc['inherited'],
a.doc['overridden_same_docstring']])])
self.assertEqual(a.inherited_members(), [])
@ignore_warnings
def test_subclasses(self):
class A:
pass
class B(type):
pass
class C(A):
pass
class D(B):
pass
class G(C):
pass
class F(C):
pass
class E(C):
pass
mod = DUMMY_PDOC_MODULE
self.assertEqual([x.refname for x in pdoc.Class('A', mod, A).subclasses()],
[mod.find_class(C).refname])
self.assertEqual([x.refname for x in pdoc.Class('B', mod, B).subclasses()],
[mod.find_class(D).refname])
self.assertEqual([x.refname for x in pdoc.Class('C', mod, C).subclasses()],
[mod.find_class(x).refname for x in (E, F, G)])
def test_link_inheritance(self):
mod = pdoc.Module(EXAMPLE_MODULE)
with warnings.catch_warnings(record=True) as w:
pdoc.link_inheritance()
pdoc.link_inheritance()
self.assertFalse(w)
# Test inheritance across modules
pdoc.reset()
mod = pdoc.Module(EXAMPLE_MODULE + '._test_linking')
pdoc.link_inheritance()
a = mod.doc['a'].doc['A']
b = mod.doc['b'].doc['B']
c = mod.doc['b'].doc['c'].doc['C']
self.assertEqual(b.doc['a'].inherits, a.doc['a'])
self.assertEqual(b.doc['c'].inherits, c.doc['c'])
# While classes do inherit from superclasses, they just shouldn't always
# say so, because public classes do want to be exposed and linked to
self.assertNotEqual(b.inherits, a)
def test_context(self):
context = pdoc.Context()
pdoc.Module(pdoc, context=context)
self.assertIn('pdoc', context)
self.assertIn('pdoc.cli', context)
self.assertIn('pdoc.cli.main', context)
self.assertIn('pdoc.Module', context)
self.assertIsInstance(context['pdoc'], pdoc.Module)
self.assertIsInstance(context['pdoc.cli'], pdoc.Module)
self.assertIsInstance(context['pdoc.cli.main'], pdoc.Function)
self.assertIsInstance(context['pdoc.Module'], pdoc.Class)
module = pdoc.Module(pdoc)
self.assertIsInstance(module.find_ident('pdoc.Module'), pdoc.Class)
pdoc.reset()
self.assertIsInstance(module.find_ident('pdoc.Module'), pdoc.External)
def test_Function_params(self):
mod = PDOC_PDOC_MODULE
func = pdoc.Function('f', mod,
lambda a, _a, _b=None: None)
self.assertEqual(func.params(), ['a', '_a'])
func = pdoc.Function('f', mod,
lambda _ok, a, _a, *args, _b=None, c=None, _d=None: None)
self.assertEqual(func.params(), ['_ok', 'a', '_a', '*args', 'c=None'])
func = pdoc.Function('f', mod,
lambda a, b, *, _c=1: None)
self.assertEqual(func.params(), ['a', 'b'])
func = pdoc.Function('f', mod,
lambda a, *, b, c: None)
self.assertEqual(func.params(), ['a', '*', 'b', 'c'])
func = pdoc.Function('f', mod,
lambda a=os.environ, b=sys.stdout: None)
self.assertEqual(func.params(), ['a=os.environ', 'b=sys.stdout'])
class Foo(enum.Enum):
a, b = 1, 2
func = pdoc.Function('f', mod, lambda a=Foo.a: None)
self.assertEqual(func.params(), ['a=Foo.a'])
func = pdoc.Function('f', mod, lambda a=object(): None)
self.assertEqual(func.params(), ['a=<object object>'])
func = pdoc.Function('f', mod, lambda a=object(): None)
self.assertEqual(func.params(link=lambda x: ''), ['a=<object object>'])
# typed
def f(a: int, *b, c: typing.List[pdoc.Doc] = []): pass
func = pdoc.Function('f', mod, f)
self.assertEqual(func.params(), ['a', '*b', "c=[]"])
self.assertEqual(func.params(annotate=True),
['a:\N{NBSP}int', '*b', "c:\N{NBSP}List[pdoc.Doc]\N{NBSP}=\N{NBSP}[]"])
# typed, linked
def link(dobj):
return f'<a href="{dobj.url(relative_to=mod)}">{dobj.qualname}</a>'
self.assertEqual(func.params(annotate=True, link=link),
['a:\N{NBSP}int', '*b',
"c:\N{NBSP}List[<a href=\"#pdoc.Doc\">Doc</a>]\N{NBSP}=\N{NBSP}[]"])
# typed, linked, GH-311
def f(a: typing.Dict[str, pdoc.Doc]): pass
func = pdoc.Function('f', mod, f)
self.assertEqual(func.params(annotate=True, link=link),
["a:\N{NBSP}Dict[str,\N{NBSP}<a href=\"#pdoc.Doc\">Doc</a>]"])
# shadowed name
def f(pdoc: int): pass
func = pdoc.Function('f', mod, f)
self.assertEqual(func.params(annotate=True, link=link), ['pdoc:\N{NBSP}int'])
def bug130_str_annotation(a: "str"):
return
self.assertEqual(pdoc.Function('bug130', mod, bug130_str_annotation).params(annotate=True),
['a:\N{NBSP}str'])
# typed, NewType
CustomType = typing.NewType('CustomType', bool)
def bug253_newtype_annotation(a: CustomType):
return
self.assertEqual(
pdoc.Function('bug253', mod, bug253_newtype_annotation).params(annotate=True),
['a:\N{NBSP}CustomType'])
# typing.Callable bug
def f(a: typing.Callable):
return
self.assertEqual(
pdoc.Function('f', mod, f).params(annotate=True),
['a:\N{NBSP}Callable'])
# builtin callables with signatures in docstrings
from itertools import repeat
self.assertEqual(pdoc.Function('repeat', mod, repeat).params(), ['object', 'times'])
self.assertEqual(pdoc.Function('slice', mod, slice).params(), ['start', 'stop', 'step'])
class get_sample(repeat):
""" get_sample(self: int, pos: int) -> Tuple[int, float] """
self.assertEqual(pdoc.Function('get_sample', mod, get_sample).params(annotate=True),
['self:\xa0int', 'pos:\xa0int'])
self.assertEqual(pdoc.Function('get_sample', mod, get_sample).return_annotation(),
'Tuple[int,\xa0float]')
@unittest.skipIf(sys.version_info < (3, 8), "positional-only arguments unsupported in < py3.8")
def test_test_Function_params_python38_specific(self):
mod = DUMMY_PDOC_MODULE
func = pdoc.Function('f', mod, eval("lambda a, /, b: None"))
self.assertEqual(func.params(), ['a', '/', 'b'])
func = pdoc.Function('f', mod, eval("lambda a, /: None"))
self.assertEqual(func.params(), ['a', '/'])
def test_Function_return_annotation(self):
def f() -> typing.List[typing.Union[str, pdoc.Doc]]: pass
func = pdoc.Function('f', DUMMY_PDOC_MODULE, f)
self.assertEqual(func.return_annotation(), 'List[Union[str,\N{NBSP}pdoc.Doc]]')
@ignore_warnings
def test_Variable_type_annotation(self):
class Foobar:
@property
def prop(self) -> typing.Optional[int]:
pass
mod = DUMMY_PDOC_MODULE
cls = pdoc.Class('Foobar', mod, Foobar)
self.assertEqual(cls.doc['prop'].type_annotation(), 'Optional[int]')
@ignore_warnings
def test_Variable_type_annotation_py36plus(self):
with temp_dir() as path:
filename = os.path.join(path, 'module36syntax.py')
with open(filename, 'w') as f:
f.write('''
from typing import overload
var: str = 'x'
"""dummy"""
class Foo:
var: int = 3
"""dummy"""
@overload
def __init__(self, var2: float):
pass
def __init__(self, var2):
self.var2: float = float(var2)
"""dummy2"""
''')
mod = pdoc.Module(pdoc.import_module(filename))
self.assertEqual(mod.doc['var'].type_annotation(), 'str')
self.assertEqual(mod.doc['Foo'].doc['var'].type_annotation(), 'int')
self.assertIsInstance(mod.doc['Foo'].doc['var2'], pdoc.Variable)
self.assertEqual(mod.doc['Foo'].doc['var2'].type_annotation(), '') # Won't fix
self.assertEqual(mod.doc['Foo'].doc['var2'].docstring, 'dummy2')
self.assertIn('var: str', mod.text())
self.assertIn('var: int', mod.text())
@ignore_warnings
def test_Class_docstring(self):
class A:
"""foo"""
class B:
def __init__(self):
"""foo"""