This repository was archived by the owner on Nov 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 187
/
Copy pathtest_integration.py
1596 lines (1239 loc) · 45.1 KB
/
test_integration.py
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
"""Use tox or pytest to run the test-suite."""
from collections import namedtuple
import os
import shlex
import shutil
import pytest
import pathlib
import tempfile
import textwrap
import subprocess
import sys
from unittest import mock
from pydocstyle import checker, violations
__all__ = ()
class SandboxEnv:
"""An isolated environment where pydocstyle can be run.
Since running pydocstyle as a script is affected by local config files,
it's important that tests will run in an isolated environment. This class
should be used as a context manager and offers utility methods for adding
files to the environment and changing the environment's configuration.
"""
Result = namedtuple('Result', ('out', 'err', 'code'))
def __init__(
self,
script_name='pydocstyle',
section_name='pydocstyle',
config_name='tox.ini',
):
"""Initialize the object."""
self.tempdir = None
self.script_name = script_name
self.section_name = section_name
self.config_name = config_name
def write_config(self, prefix='', name=None, **kwargs):
"""Change an environment config file.
Applies changes to `tox.ini` relative to `tempdir/prefix`.
If the given path prefix does not exist it is created.
"""
base = os.path.join(self.tempdir, prefix) if prefix else self.tempdir
if not os.path.isdir(base):
self.makedirs(base)
name = self.config_name if name is None else name
if name.endswith('.toml'):
def convert_value(val):
return (
repr(val).lower()
if isinstance(val, bool)
else repr(val)
)
else:
def convert_value(val):
return val
with open(os.path.join(base, name), 'wt') as conf:
conf.write(f"[{self.section_name}]\n")
for k, v in kwargs.items():
conf.write("{} = {}\n".format(
k.replace('_', '-'), convert_value(v)
))
def open(self, path, *args, **kwargs):
"""Open a file in the environment.
The file path should be relative to the base of the environment.
"""
return open(os.path.join(self.tempdir, path), *args, **kwargs)
def get_path(self, name, prefix=''):
return os.path.join(self.tempdir, prefix, name)
def makedirs(self, path, *args, **kwargs):
"""Create a directory in a path relative to the environment base."""
os.makedirs(os.path.join(self.tempdir, path), *args, **kwargs)
def invoke(self, args="", target=None):
"""Run pydocstyle on the environment base folder with the given args.
If `target` is not None, will run pydocstyle on `target` instead of
the environment base folder.
"""
run_target = self.tempdir if target is None else \
os.path.join(self.tempdir, target)
cmd = shlex.split("{} {} {}"
.format(self.script_name, run_target, args),
posix=False)
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = p.communicate()
return self.Result(out=out.decode('utf-8'),
err=err.decode('utf-8'),
code=p.returncode)
def __enter__(self):
self.tempdir = tempfile.mkdtemp()
# Make sure we won't be affected by other config files
self.write_config()
return self
def __exit__(self, *args, **kwargs):
shutil.rmtree(self.tempdir)
pass
@pytest.fixture(scope="module")
def install_package(request):
"""Install the package in development mode for the tests.
This is so we can run the integration tests on the installed console
script.
"""
cwd = os.path.join(os.path.dirname(__file__), '..', '..')
subprocess.check_call(
[sys.executable, "-m", "pip", "install", "-e", "."], cwd=cwd
)
yield
subprocess.check_call(
[sys.executable, "-m", "pip", "uninstall", "-y", "pydocstyle"], cwd=cwd
)
@pytest.fixture(scope="function", params=['ini', 'toml'])
def env(request):
"""Add a testing environment to a test method."""
sandbox_settings = {
'ini': {
'section_name': 'pydocstyle',
'config_name': 'tox.ini',
},
'toml': {
'section_name': 'tool.pydocstyle',
'config_name': 'pyproject.toml',
},
}[request.param]
with SandboxEnv(**sandbox_settings) as test_env:
yield test_env
pytestmark = pytest.mark.usefixtures("install_package")
def parse_errors(err):
"""Parse `err` to a dictionary of {filename: error_codes}.
This is for test purposes only. All file names should be different.
"""
result = {}
py_ext = '.py'
lines = err.split('\n')
while lines:
curr_line = lines.pop(0)
filename = curr_line[:curr_line.find(py_ext) + len(py_ext)]
if lines:
err_line = lines.pop(0).strip()
err_code = err_line.split(':')[0]
basename = os.path.basename(filename)
result.setdefault(basename, set()).add(err_code)
return result
def test_pep257_conformance():
"""Test that we conform to PEP 257."""
base_dir = (pathlib.Path(__file__).parent / '..').resolve()
excluded = base_dir / 'tests' / 'test_cases'
src_files = (str(path) for path in base_dir.glob('**/*.py')
if excluded not in path.parents)
ignored = {'D104', 'D105'}
select = violations.conventions.pep257 - ignored
errors = list(checker.check(src_files, select=select))
assert errors == [], errors
def test_ignore_list():
"""Test that `ignore`d errors are not reported in the API."""
function_to_check = textwrap.dedent('''
def function_with_bad_docstring(foo):
""" does spacinwithout a period in the end
no blank line after one-liner is bad. Also this - """
return foo
''')
expected_error_codes = {'D100', 'D400', 'D401', 'D205', 'D209', 'D210',
'D403', 'D415', 'D213'}
mock_open = mock.mock_open(read_data=function_to_check)
from pydocstyle import checker
with mock.patch.object(
checker.tk, 'open', mock_open, create=True):
# Passing a blank ignore here explicitly otherwise
# checkers takes the pep257 ignores by default.
errors = tuple(checker.check(['filepath'], ignore={}))
error_codes = {error.code for error in errors}
assert error_codes == expected_error_codes
# We need to recreate the mock, otherwise the read file is empty
mock_open = mock.mock_open(read_data=function_to_check)
with mock.patch.object(
checker.tk, 'open', mock_open, create=True):
ignored = {'D100', 'D202', 'D213'}
errors = tuple(checker.check(['filepath'], ignore=ignored))
error_codes = {error.code for error in errors}
assert error_codes == expected_error_codes - ignored
def test_skip_errors():
"""Test that `ignore`d errors are not reported in the API."""
function_to_check = textwrap.dedent('''
def function_with_bad_docstring(foo): # noqa: D400, D401, D403, D415
""" does spacinwithout a period in the end
no blank line after one-liner is bad. Also this - """
return foo
''')
expected_error_codes = {'D100', 'D205', 'D209', 'D210', 'D213'}
mock_open = mock.mock_open(read_data=function_to_check)
from pydocstyle import checker
with mock.patch.object(
checker.tk, 'open', mock_open, create=True):
# Passing a blank ignore here explicitly otherwise
# checkers takes the pep257 ignores by default.
errors = tuple(checker.check(['filepath'], ignore={}))
error_codes = {error.code for error in errors}
assert error_codes == expected_error_codes
skipped_error_codes = {'D400', 'D401', 'D403', 'D415'}
# We need to recreate the mock, otherwise the read file is empty
mock_open = mock.mock_open(read_data=function_to_check)
with mock.patch.object(
checker.tk, 'open', mock_open, create=True):
errors = tuple(checker.check(['filepath'], ignore={},
ignore_inline_noqa=True))
error_codes = {error.code for error in errors}
assert error_codes == expected_error_codes | skipped_error_codes
def test_run_as_named_module():
"""Test that pydocstyle can be run as a "named module".
This means that the following should run pydocstyle:
python -m pydocstyle
"""
# Add --match='' so that no files are actually checked (to make sure that
# the return code is 0 and to reduce execution time).
cmd = [sys.executable, "-m", "pydocstyle", "--match=''"]
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = p.communicate()
assert p.returncode == 0, out.decode('utf-8') + err.decode('utf-8')
def test_config_file(env):
"""Test that options are correctly loaded from a config file.
This test create a temporary directory and creates two files in it: a
Python file that has two violations (D100 and D103) and a config
file (tox.ini). This test alternates settings in the config file and checks
that we give the correct output.
"""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent("""\
def foo():
pass
"""))
env.write_config(ignore='D100')
out, err, code = env.invoke()
assert code == 1
assert 'D100' not in out
assert 'D103' in out
env.write_config(ignore='')
out, err, code = env.invoke()
assert code == 1
assert 'D100' in out
assert 'D103' in out
env.write_config(ignore='D100,D103')
out, err, code = env.invoke()
assert code == 0
assert 'D100' not in out
assert 'D103' not in out
env.write_config(ignore='D10')
_, err, code = env.invoke()
assert code == 0
assert 'D100' not in err
assert 'D103' not in err
def test_sectionless_config_file(env):
"""Test that config files without a valid section name issue a warning."""
with env.open('config.ini', 'wt') as conf:
conf.write('[pdcstl]')
config_path = conf.name
_, err, code = env.invoke(f'--config={config_path}')
assert code == 0
assert 'Configuration file does not contain a pydocstyle section' in err
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent("""\
def foo():
pass
"""))
with env.open('tox.ini', 'wt') as conf:
conf.write('[pdcstl]\n')
conf.write('ignore = D100')
out, err, code = env.invoke()
assert code == 1
assert 'D100' in out
assert 'file does not contain a pydocstyle section' not in err
@pytest.mark.parametrize(
# Don't parametrize over 'pyproject.toml'
# since this test applies only to '.ini' files
'env', ['ini'], indirect=True
)
def test_multiple_lined_config_file(env):
"""Test that .ini files with multi-lined entries are parsed correctly."""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent("""\
class Foo(object):
"Doc string"
def foo():
pass
"""))
select_string = ('D100,\n'
' #D103,\n'
' D204, D300 # Just remember - don\'t check D103!')
env.write_config(select=select_string)
out, err, code = env.invoke()
assert code == 1
assert 'D100' in out
assert 'D204' in out
assert 'D300' in out
assert 'D103' not in out
@pytest.mark.parametrize(
# Don't parametrize over 'tox.ini' since
# this test applies only to '.toml' files
'env', ['toml'], indirect=True
)
def test_accepts_select_error_code_list(env):
"""Test that .ini files with multi-lined entries are parsed correctly."""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent("""\
class Foo(object):
"Doc string"
def foo():
pass
"""))
env.write_config(select=['D100', 'D204', 'D300'])
out, err, code = env.invoke()
assert code == 1
assert 'D100' in out
assert 'D204' in out
assert 'D300' in out
assert 'D103' not in out
def test_config_path(env):
"""Test that options are correctly loaded from a specific config file.
Make sure that a config file passed via --config is actually used and that
normal config file discovery is disabled.
"""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent("""\
def foo():
pass
"""))
# either my_config.ini or my_config.toml
config_ext = env.config_name.split('.')[-1]
config_name = 'my_config.' + config_ext
env.write_config(ignore='D100')
env.write_config(name=config_name, ignore='D103')
out, err, code = env.invoke()
assert code == 1
assert 'D100' not in out
assert 'D103' in out
out, err, code = env.invoke('--config={} -d'
.format(env.get_path(config_name)))
assert code == 1, out + err
assert 'D100' in out
assert 'D103' not in out
def test_non_existent_config(env):
out, err, code = env.invoke('--config=does_not_exist')
assert code == 2
def test_verbose(env):
"""Test that passing --verbose prints more information."""
with env.open('example.py', 'wt') as example:
example.write('"""Module docstring."""\n')
out, _, code = env.invoke()
assert code == 0
assert 'example.py' not in out
out, _, code = env.invoke(args="--verbose")
assert code == 0
assert 'example.py' in out
def test_count(env):
"""Test that passing --count correctly prints the error num."""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent("""\
def foo():
pass
"""))
out, err, code = env.invoke(args='--count')
assert code == 1
assert '2' in out
# The error count should be in the last line of the output.
# -2 since there is a newline at the end of the output.
assert '2' == out.split('\n')[-2].strip()
def test_select_cli(env):
"""Test choosing error codes with `--select` in the CLI."""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent("""\
def foo():
pass
"""))
out, err, code = env.invoke(args="--select=D100")
assert code == 1
assert 'D100' in out
assert 'D103' not in out
def test_select_config(env):
"""Test choosing error codes with `select` in the config file."""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent("""\
class Foo(object):
"Doc string"
def foo():
pass
"""))
env.write_config(select="D100,D3")
out, err, code = env.invoke()
assert code == 1
assert 'D100' in out
assert 'D300' in out
assert 'D103' not in out
def test_add_select_cli(env):
"""Test choosing error codes with --add-select in the CLI."""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent("""\
class Foo(object):
"Doc string"
def foo():
pass
"""))
env.write_config(select="D100")
out, err, code = env.invoke(args="--add-select=D204,D3")
assert code == 1
assert 'D100' in out
assert 'D204' in out
assert 'D300' in out
assert 'D103' not in out
def test_add_ignore_cli(env):
"""Test choosing error codes with --add-ignore in the CLI."""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent("""\
class Foo(object):
def foo():
pass
"""))
env.write_config(select="D100,D101")
out, err, code = env.invoke(args="--add-ignore=D101")
assert code == 1
assert 'D100' in out
assert 'D101' not in out
assert 'D103' not in out
def test_wildcard_add_ignore_cli(env):
"""Test choosing error codes with --add-ignore in the CLI."""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent("""\
class Foo(object):
"Doc string"
def foo():
pass
"""))
env.write_config(select="D203,D300")
out, err, code = env.invoke(args="--add-ignore=D30")
assert code == 1
assert 'D203' in out
assert 'D300' not in out
@pytest.mark.parametrize(
# Don't parametrize over 'pyproject.toml'
# since this test applies only to '.ini' files
'env', ['ini'], indirect=True
)
def test_ignores_whitespace_in_fixed_option_set(env):
with env.open('example.py', 'wt') as example:
example.write("class Foo(object):\n 'Doc string'")
env.write_config(ignore="D100,\n # comment\n D300")
out, err, code = env.invoke()
assert code == 1
assert 'D300' not in out
assert err == ''
@pytest.mark.parametrize(
# Don't parametrize over 'tox.ini' since
# this test applies only to '.toml' files
'env', ['toml'], indirect=True
)
def test_accepts_ignore_error_code_list(env):
with env.open('example.py', 'wt') as example:
example.write("class Foo(object):\n 'Doc string'")
env.write_config(ignore=['D100', 'D300'])
out, err, code = env.invoke()
assert code == 1
assert 'D300' not in out
assert err == ''
def test_bad_wildcard_add_ignore_cli(env):
"""Test adding a non-existent error codes with --add-ignore."""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent("""\
class Foo(object):
"Doc string"
def foo():
pass
"""))
env.write_config(select="D203,D300")
out, err, code = env.invoke(args="--add-ignore=D3004")
assert code == 1
assert 'D203' in out
assert 'D300' in out
assert 'D3004' not in out
assert ('Error code passed is not a prefix of any known errors: D3004'
in err)
def test_overload_function(env):
"""Functions decorated with @overload trigger D418 error."""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent('''\
from typing import overload
@overload
def overloaded_func(a: int) -> str:
...
@overload
def overloaded_func(a: str) -> str:
"""Foo bar documentation."""
...
def overloaded_func(a):
"""Foo bar documentation."""
return str(a)
'''))
env.write_config(ignore="D100")
out, err, code = env.invoke()
assert code == 1
assert 'D418' in out
assert 'D103' not in out
def test_overload_async_function(env):
"""Async functions decorated with @overload trigger D418 error."""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent('''\
from typing import overload
@overload
async def overloaded_func(a: int) -> str:
...
@overload
async def overloaded_func(a: str) -> str:
"""Foo bar documentation."""
...
async def overloaded_func(a):
"""Foo bar documentation."""
return str(a)
'''))
env.write_config(ignore="D100")
out, err, code = env.invoke()
assert code == 1
assert 'D418' in out
assert 'D103' not in out
def test_overload_method(env):
"""Methods decorated with @overload trigger D418 error."""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent('''\
from typing import overload
class ClassWithMethods:
@overload
def overloaded_method(a: int) -> str:
...
@overload
def overloaded_method(a: str) -> str:
"""Foo bar documentation."""
...
def overloaded_method(a):
"""Foo bar documentation."""
return str(a)
'''))
env.write_config(ignore="D100")
out, err, code = env.invoke()
assert code == 1
assert 'D418' in out
assert 'D102' not in out
assert 'D103' not in out
def test_overload_method_valid(env):
"""Valid case for overload decorated Methods.
This shouldn't throw any errors.
"""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent('''\
from typing import overload
class ClassWithMethods:
"""Valid docstring in public Class."""
@overload
def overloaded_method(a: int) -> str:
...
@overload
def overloaded_method(a: str) -> str:
...
def overloaded_method(a):
"""Foo bar documentation."""
return str(a)
'''))
env.write_config(ignore="D100, D203")
out, err, code = env.invoke()
assert code == 0
def test_overload_function_valid(env):
"""Valid case for overload decorated functions.
This shouldn't throw any errors.
"""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent('''\
from typing import overload
@overload
def overloaded_func(a: int) -> str:
...
@overload
def overloaded_func(a: str) -> str:
...
def overloaded_func(a):
"""Foo bar documentation."""
return str(a)
'''))
env.write_config(ignore="D100")
out, err, code = env.invoke()
assert code == 0
def test_overload_async_function_valid(env):
"""Valid case for overload decorated async functions.
This shouldn't throw any errors.
"""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent('''\
from typing import overload
@overload
async def overloaded_func(a: int) -> str:
...
@overload
async def overloaded_func(a: str) -> str:
...
async def overloaded_func(a):
"""Foo bar documentation."""
return str(a)
'''))
env.write_config(ignore="D100")
out, err, code = env.invoke()
assert code == 0
def test_overload_nested_function(env):
"""Nested functions decorated with @overload trigger D418 error."""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent('''\
from typing import overload
def function_with_nesting():
"""Valid docstring in public function."""
@overload
def overloaded_func(a: int) -> str:
...
@overload
def overloaded_func(a: str) -> str:
"""Foo bar documentation."""
...
def overloaded_func(a):
"""Foo bar documentation."""
return str(a)
'''))
env.write_config(ignore="D100")
out, err, code = env.invoke()
assert code == 1
assert 'D418' in out
assert 'D103' not in out
def test_overload_nested_function_valid(env):
"""Valid case for overload decorated nested functions.
This shouldn't throw any errors.
"""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent('''\
from typing import overload
def function_with_nesting():
"""Adding a docstring to a function."""
@overload
def overloaded_func(a: int) -> str:
...
@overload
def overloaded_func(a: str) -> str:
...
def overloaded_func(a):
"""Foo bar documentation."""
return str(a)
'''))
env.write_config(ignore="D100")
out, err, code = env.invoke()
assert code == 0
def test_conflicting_select_ignore_config(env):
"""Test that select and ignore are mutually exclusive."""
env.write_config(select="D100", ignore="D101")
_, err, code = env.invoke()
assert code == 2
assert 'mutually exclusive' in err
def test_conflicting_select_convention_config(env):
"""Test that select and convention are mutually exclusive."""
env.write_config(select="D100", convention="pep257")
_, err, code = env.invoke()
assert code == 2
assert 'mutually exclusive' in err
def test_conflicting_ignore_convention_config(env):
"""Test that select and convention are mutually exclusive."""
env.write_config(ignore="D100", convention="pep257")
_, err, code = env.invoke()
assert code == 2
assert 'mutually exclusive' in err
def test_missing_docstring_in_package(env):
"""Make sure __init__.py files are treated as packages."""
with env.open('__init__.py', 'wt') as init:
pass # an empty package file
out, err, code = env.invoke()
assert code == 1
assert 'D100' not in out # shouldn't be treated as a module
assert 'D104' in out # missing docstring in package
def test_illegal_convention(env):
"""Test that illegal convention names are dealt with properly."""
_, err, code = env.invoke('--convention=illegal_conv')
assert code == 2, err
assert "Illegal convention 'illegal_conv'." in err
assert 'Possible conventions' in err
assert 'pep257' in err
assert 'numpy' in err
def test_empty_select_cli(env):
"""Test excluding all error codes with `--select=` in the CLI."""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent("""\
def foo():
pass
"""))
_, _, code = env.invoke(args="--select=")
assert code == 0
def test_empty_select_config(env):
"""Test excluding all error codes with `select=` in the config file."""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent("""\
def foo():
pass
"""))
env.write_config(select="")
_, _, code = env.invoke()
assert code == 0
def test_empty_select_with_added_error(env):
"""Test excluding all errors but one."""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent("""\
def foo():
pass
"""))
env.write_config(select="")
out, err, code = env.invoke(args="--add-select=D100")
assert code == 1
assert 'D100' in out
assert 'D101' not in out
assert 'D103' not in out
def test_pep257_convention(env):
"""Test that the 'pep257' convention options has the correct errors."""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent('''
class Foo(object):
"""Docstring for this class"""
def foo():
pass
# Original PEP-257 example from -
# https://www.python.org/dev/peps/pep-0257/
def complex(real=0.0, imag=0.0):
"""Form a complex number.
Keyword arguments:
real -- the real part (default 0.0)
imag -- the imaginary part (default 0.0)
"""
if imag == 0.0 and real == 0.0:
return complex_zero
'''))
env.write_config(convention="pep257")
out, err, code = env.invoke()
assert code == 1
assert 'D100' in out
assert 'D211' in out
assert 'D203' not in out
assert 'D212' not in out
assert 'D213' not in out
assert 'D413' not in out
def test_numpy_convention(env):
"""Test that the 'numpy' convention options has the correct errors."""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent('''
class Foo(object):
"""Docstring for this class.
returns
------
"""
def __init__(self):
pass
'''))
env.write_config(convention="numpy")
out, err, code = env.invoke()
assert code == 1
assert 'D107' not in out
assert 'D213' not in out
assert 'D215' in out
assert 'D405' in out
assert 'D409' in out
assert 'D414' in out
assert 'D410' not in out
assert 'D413' not in out
def test_google_convention(env):
"""Test that the 'google' convention options has the correct errors."""
with env.open('example.py', 'wt') as example:
example.write(textwrap.dedent('''
def func(num1, num2, num_three=0):
"""Docstring for this function.
Args:
num1 (int): Number 1.
num2: Number 2.
"""
class Foo(object):
"""Docstring for this class.