forked from lyz-code/autoimport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_services.py
1093 lines (817 loc) · 22.1 KB
/
test_services.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
"""Tests the service layer."""
from textwrap import dedent
import pytest
from autoimport.model import common_statements
from autoimport.services import fix_code
def test_fix_code_adds_missing_import() -> None:
"""Understands that os is a package and add it to the top of the file."""
source = "os.getcwd()"
fixed_source = dedent(
"""\
import os
os.getcwd()"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_doesnt_change_source_if_package_doesnt_exist() -> None:
"""As foo is not found, nothing is changed."""
source = "foo"
result = fix_code(source)
assert result == source
def test_fix_imports_packages_below_docstring() -> None:
"""Imports are located below the module docstrings."""
source = dedent(
'''\
"""Module docstring.
"""
import pytest
os.getcwd()'''
)
fixed_source = dedent(
'''\
"""Module docstring.
"""
import os
os.getcwd()'''
)
result = fix_code(source)
assert result == fixed_source
def test_fix_imports_packages_below_single_line_docstring() -> None:
"""Imports are located below the module docstrings when they only take one line."""
source = dedent(
'''\
"""Module docstring."""
import pytest
os.getcwd()'''
)
fixed_source = dedent(
'''\
"""Module docstring."""
import os
os.getcwd()'''
)
result = fix_code(source)
assert result == fixed_source
def test_fix_imports_type_hints() -> None:
"""Typing objects are initialized with their required header."""
source = dedent(
"""\
def function(dictionary: Dict) -> None:
pass"""
)
fixed_source = dedent(
"""\
from typing import Dict
def function(dictionary: Dict) -> None:
pass"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_removes_unneeded_imports() -> None:
"""If there is an import statement of an unused package it should be removed."""
source = dedent(
"""\
import requests
foo = 1"""
)
fixed_source = "foo = 1"
result = fix_code(source)
assert result == fixed_source
def test_fix_removes_multiple_unneeded_imports() -> None:
"""
Given: A source code with multiple unused import statements.
When: fix_code is run.
Then: The unused import statements are deleted.
"""
source = dedent(
"""\
import requests
from textwrap import dedent
from yaml import YAMLError
foo = 1"""
)
fixed_source = "foo = 1"
result = fix_code(source)
assert result == fixed_source
def test_fix_removes_unneeded_imports_in_from_statements() -> None:
"""Remove `from package import` statement of an unused packages."""
source = dedent(
"""\
from os import path
foo = 1"""
)
fixed_source = "foo = 1"
result = fix_code(source)
assert result == fixed_source
def test_fix_removes_unused_imports_in_multiline_from_statements() -> None:
"""
Given: A source code with multiline import from statements.
When: fix_code is run
Then: Unused import statements are deleted
"""
source = dedent(
"""\
from os import (
getcwd,
path,
)
getcwd()"""
)
fixed_source = dedent(
"""\
from os import (
getcwd,
)
getcwd()"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_removes_unneeded_imports_in_beginning_of_from_statements() -> None:
"""Remove unused `object_name` in `from package import object_name, other_object`
statements.
"""
source = dedent(
"""\
from os import path, getcwd
getcwd()"""
)
fixed_source = dedent(
"""\
from os import getcwd
getcwd()"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_removes_unneeded_imports_in_middle_of_from_statements() -> None:
"""Remove unused `object_name` in
`from package import other_object, object_name, other_used_object` statements.
"""
source = dedent(
"""\
from os import getcwd, path, mkdir
getcwd()
mkdir()"""
)
fixed_source = dedent(
"""\
from os import getcwd, mkdir
getcwd()
mkdir()"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_removes_unneeded_imports_in_end_of_from_statements() -> None:
"""Remove unused `object_name` in `from package import other_object, object_name`
statements.
"""
source = dedent(
"""\
from os import getcwd, path
getcwd()"""
)
fixed_source = dedent(
"""\
from os import getcwd
getcwd()"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_respects_multiple_from_import_lines() -> None:
"""
Given: Multiple from X import Y lines.
When: Fix code is run
Then: The import statements aren't broken
"""
source = dedent(
"""\
from os import getcwd
from re import match
getcwd()
match(r'a', 'a')"""
)
result = fix_code(source)
assert result == source
def test_fix_respects_multiple_from_import_lines_in_multiple_lines() -> None:
"""
Given: Multiple from X import Y lines, some with multiline format.
When: Fix code is run
Then: The import statements aren't broken
"""
source = dedent(
"""\
from os import (
getcwd,
)
from re import match
getcwd()
match(r'a', 'a')"""
)
result = fix_code(source)
assert result == source
def test_fix_respects_import_lines_in_multiple_line_strings() -> None:
"""
Given: Import lines in several multiline strings.
When: Fix code is run.
Then: The import statements inside the string are not moved to the top.
"""
source = dedent(
"""\
from textwrap import dedent
source = dedent(
\"\"\"\\
from re import match
match(r'a', 'a')\"\"\"
)
source = dedent(
\"\"\"\\
from os import (
getcwd,
)
getcwd()\"\"\"
)"""
)
fixed_source = dedent(
"""\
from textwrap import dedent
source = dedent(
\"\"\"\\
from re import match
match(r'a', 'a')\"\"\"
)
source = dedent(
\"\"\"\\
from os import (
getcwd,
)
getcwd()\"\"\"
)"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_moves_import_statements_to_the_top() -> None:
"""Move import statements present in the source code to the top of the file"""
source = dedent(
"""\
a = 3
import os
os.getcwd()"""
)
fixed_source = dedent(
"""\
import os
a = 3
os.getcwd()"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_moves_import_statements_in_indented_code_to_the_top() -> None:
"""Move import statements present indented in the source code
to the top of the file
"""
source = dedent(
"""\
import requests
requests.get('hi')
def test():
import os
os.getcwd()"""
)
fixed_source = dedent(
"""\
import requests
import os
requests.get('hi')
def test():
os.getcwd()"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_moves_from_import_statements_to_the_top() -> None:
"""Move from import statements present in the source code to the top of the file"""
source = dedent(
"""\
a = 3
from os import getcwd
getcwd()"""
)
fixed_source = dedent(
"""\
from os import getcwd
a = 3
getcwd()"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_moves_multiline_import_statements_to_the_top() -> None:
"""
Given: Multiple from X import Y lines.
When: Fix code is run.
Then: The import statements are moved to the top.
"""
source = dedent(
"""\
from os import getcwd
getcwd()
from re import (
match,
)
match(r'a', 'a')"""
)
fixed_source = dedent(
"""\
from os import getcwd
from re import (
match,
)
getcwd()
match(r'a', 'a')"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_doesnt_break_objects_with_import_in_their_names() -> None:
"""Objects that have the import name in their name should not be changed."""
source = dedent(
"""\
def import_code():
pass
def code_import():
pass
def import():
pass
import_string = 'a'"""
)
result = fix_code(source)
assert result == source
def test_fix_doesnt_move_import_statements_with_noqa_to_the_top() -> None:
"""Ignore lines that have # noqa: autoimport."""
source = dedent(
"""\
a = 3
from os import getcwd # noqa: autoimport
getcwd()"""
)
result = fix_code(source)
assert result == source
def test_fix_doesnt_fail_on_noqa_lines_on_unused_import() -> None:
"""Ignore lines that have # noqa: autoimport."""
source = dedent(
"""\
from os import getcwd # noqa: autoimport"""
)
result = fix_code(source)
assert result == source
def test_fix_respects_noqa_in_from_import_lines_in_multiple_lines() -> None:
"""
Given: Multiple from X import Y lines, some with multiline format with noqa
statement.
When: Fix code is run.
Then: The import statements aren't broken.
"""
source = dedent(
"""\
from os import getcwd
getcwd()
from re import ( # noqa: autoimport
match,
)
match(r'a', 'a')"""
)
result = fix_code(source)
assert result == source
def test_fix_respects_strings_with_import_statements() -> None:
"""
Given: Code with a string that has import statements structure.
When: Fix code is run.
Then: The string is respected
"""
source = dedent(
"""\
import_string = 'import requests'
from_import_string = "from re import match"
multiline string = dedent(
\"\"\"\\
import requests
from re import match
\"\"\"
)
multiline single_quote_string = dedent(
\'\'\'\\
import requests
from re import match
\'\'\'
)
import os"""
)
fixed_source = dedent(
"""\
import os
import_string = 'import requests'
from_import_string = "from re import match"
multiline string = dedent(
\"\"\"\\
import requests
from re import match
\"\"\"
)
multiline single_quote_string = dedent(
\'\'\'\\
import requests
from re import match
\'\'\'
)"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_doesnt_mistake_docstrings_with_multiline_string() -> None:
"""
Given: A function with a docstring.
When: Fix code is run.
Then: The rest of the file is not mistaken for a long multiline string
"""
source = dedent(
"""\
def function_1():
\"\"\"Function docstring\"\"\"
import os
os.getcwd()"""
)
fixed_source = dedent(
"""\
import os
def function_1():
\"\"\"Function docstring\"\"\"
os.getcwd()"""
)
result = fix_code(source)
assert result == fixed_source
@pytest.mark.parametrize(
("import_key", "import_statement"),
((key, value) for key, value in common_statements.items()),
ids=list(common_statements.keys()),
)
def test_fix_autoimports_common_imports(import_key: str, import_statement: str) -> None:
"""
Given: Code with missing import statements that match the common list.
When: Fix code is run.
Then: The imports are done
"""
source = dedent(
f"""\
import os
os.getcwd
variable = {import_key}"""
)
fixed_source = dedent(
f"""\
import os
{import_statement}
os.getcwd
variable = {import_key}"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_autoimports_objects_defined_in_the_root_of_the_package() -> None:
"""
Given:
The fix code is run from a directory that belongs to a python project package.
And a source code with an object that needs an import statement.
And that object belongs to the root of the python package.
When: Fix code is run.
Then: The import is done
"""
source = dedent(
"""\
fix_code()"""
)
fixed_source = dedent(
"""\
from autoimport import fix_code
fix_code()"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_autoimports_objects_defined_in___all__special_variable() -> None:
"""
Given: Some missing packages in the __all__ variable
When: Fix code is run.
Then: The import is done
"""
source = dedent(
"""\
__all__ = ['fix_code']"""
)
fixed_source = dedent(
"""\
from autoimport import fix_code
__all__ = ['fix_code']"""
)
result = fix_code(source)
assert result == fixed_source
def test_fix_respects_type_checking_import_statements() -> None:
"""
Given: Code with if TYPE_CHECKING imports
When: Fix code is run.
Then: The imports are not moved above the if statement.
"""
source = dedent(
"""\
import os
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .model import Book
os.getcwd()
def read_book(book: Book):
pass"""
)
result = fix_code(source)
assert result == source
def test_fix_respects_multiparagraph_type_checking_import_statements() -> None:
"""
Given: Code with two paragraphs of imports inside an if TYPE_CHECKING block
When: Fix code is run.
Then: The imports are not moved above the if statement.
"""
source = dedent(
"""\
import os
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .model import Book
from other import Other
os.getcwd()
def read_book(book: Book, other: Other):
pass"""
)
result = fix_code(source)
assert result == source
def test_fix_respects_try_except_in_import_statements() -> None:
"""
Given: Code with try except statements in the imports.
When: Fix code is run
Then: The try except statements are respected
"""
source = dedent(
"""\
import os
try:
from typing import TypedDict # noqa
except ImportError:
from mypy_extensions import TypedDict # <=3.7
os.getcwd()
Movie = TypedDict('Movie', {'name': str, 'year': int})"""
)
result = fix_code(source)
assert result == source
def test_fix_respects_leading_comments() -> None:
"""
Given: Code with initial comments like shebang and editor configuration.
When: Fix code is run
Then: The comment statements are respected
"""
source = dedent(
'''\
#!/usr/bin/env python3
# -*- coding: latin-1 -*-
"""docstring"""
print(os.path.exists("."))'''
)
desired_source = dedent(
'''\
#!/usr/bin/env python3
# -*- coding: latin-1 -*-
"""docstring"""
import os
print(os.path.exists("."))'''
)
result = fix_code(source)
assert result == desired_source
def test_fix_respects_leading_comments_with_new_lines() -> None:
"""
Given: Code with initial comments with new lines and a trailing newline.
When: Fix code is run.
Then: The comment statements and trailing newline are respected.
"""
source = dedent(
'''\
#!/usr/bin/env python3
# -*- coding: latin-1 -*-
# pylint: disable=foobar
"""
This is the docstring.
"""
import sys
print(os.path.exists(sys.argv[1]))
'''
)
desired_source = dedent(
'''\
#!/usr/bin/env python3
# -*- coding: latin-1 -*-
# pylint: disable=foobar
"""
This is the docstring.
"""
import sys
import os
print(os.path.exists(sys.argv[1]))
'''
)
result = fix_code(source)
assert result == desired_source
def test_fix_imports_dependency_only_once() -> None:
"""
Given: Code with a line that uses a package three times.
When: Fix code is run.
Then: The dependency is imported only once
"""
source = dedent(
"""\
def f(x):
return os.getcwd() + os.getcwd() + os.getcwd()
"""
)
desired_source = dedent(
"""\
import os
def f(x):
return os.getcwd() + os.getcwd() + os.getcwd()
"""
)
result = fix_code(source)
assert result == desired_source
def test_fix_doesnt_fail_on_empty_file() -> None:
"""
Given: An empty file
When: Fix code is run.
Then: The output doesn't change
"""
source = ""
result = fix_code(source)
assert result == source
def test_file_that_only_has_unused_imports() -> None:
"""
Given: A file that only has unused imports.
When: Fix code is run.
Then: The output should be a single empty line.
"""
source = dedent(
"""\
import os
import sys
"""
)
result = fix_code(source)
assert result == "\n"
def test_file_with_common_statement() -> None:
"""
Given: Code with a commonly-used object.
When: Fix code is run.
Then: The appropriate import statement from the common_statements dict is added.
"""
source = dedent(
"""\
BeautifulSoup
"""
)
desired_source = dedent(
"""\
from bs4 import BeautifulSoup
BeautifulSoup
"""
)
result = fix_code(source)
assert result == desired_source
def test_file_with_custom_common_statement() -> None:
"""
Given: Code that uses an undefined object called `FooBar`.
When:
Fix code is run and a `config` dict is passed specifying `FooBar` as a common
statement.
Then:
The appropriate import statement from the common_statements dict is added.
"""
source = dedent(
"""\
FooBar
"""
)
custom_config = {"common_statements": {"FooBar": "from baz_qux import FooBar"}}
desired_source = dedent(
"""\
from baz_qux import FooBar
FooBar
"""
)
result = fix_code(source, config=custom_config)
assert result == desired_source
def test_file_with_comment_in_import() -> None:
"""
Given: Code with a comment on two import statements
When: Fix code is run.
Then: The unused import line is removed with it's comment
"""
source = dedent(
"""\
import os # comment 1
import sys # comment 2
os.getcwd()
"""
)
desired_source = dedent(
"""\
import os # comment 1
os.getcwd()
"""
)
result = fix_code(source)
assert result == desired_source
def test_file_with_comment_in_from_import() -> None:
"""
Given: Code with a comment on two import statements
When: Fix code is run.
Then: The unused import line is removed with it's comment
"""
source = dedent(
"""\
import os # comment 1
from textwrap import dedent # comment 2
os.getcwd()
"""
)
desired_source = dedent(
"""\
import os # comment 1
os.getcwd()