-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
reorder_python_imports_test.py
1218 lines (961 loc) · 35.3 KB
/
reorder_python_imports_test.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
from __future__ import annotations
import ast
import io
import os
import subprocess
import sys
from unittest import mock
import pytest
from reorder_python_imports import _mod_startswith
from reorder_python_imports import apply_import_sorting
from reorder_python_imports import CodePartition
from reorder_python_imports import CodeType
from reorder_python_imports import fix_file_contents
from reorder_python_imports import get_line_offsets_by_line_no
from reorder_python_imports import main
from reorder_python_imports import partition_source
from reorder_python_imports import remove_duplicated_imports
from reorder_python_imports import separate_comma_imports
from reorder_python_imports import TopLevelImportVisitor
@pytest.fixture
def in_tmpdir(tmpdir):
with tmpdir.as_cwd():
yield tmpdir
def test_partition_source_trivial():
assert partition_source('') == []
def test_partition_source_errors_with_bytes():
with pytest.raises((AttributeError, TypeError)):
partition_source(b'') # type: ignore
def test_partition_source_shebang():
assert partition_source('#!/usr/bin/env python\n') == [
CodePartition(CodeType.PRE_IMPORT_CODE, '#!/usr/bin/env python\n'),
]
def test_partition_source_shebang_no_nl():
assert partition_source('#!/usr/bin/env python') == [
CodePartition(CodeType.PRE_IMPORT_CODE, '#!/usr/bin/env python'),
]
def test_partition_source_encoding():
assert partition_source('# -*- coding: UTF-8 -*-\n') == [
CodePartition(CodeType.PRE_IMPORT_CODE, '# -*- coding: UTF-8 -*-\n'),
]
def test_partition_source_encoding_no_nl():
assert partition_source('# -*- coding: UTF-8 -*-') == [
CodePartition(CodeType.PRE_IMPORT_CODE, '# -*- coding: UTF-8 -*-'),
]
def test_partition_source_indented_encoding():
assert partition_source(' # -*- coding: UTF-8 -*-\n') == [
CodePartition(
CodeType.PRE_IMPORT_CODE,
' # -*- coding: UTF-8 -*-\n',
),
]
def test_partition_source_encoding_and_shebang():
assert partition_source(
'#!/usr/bin/env python\n'
'# -*- coding: UTF-8 -*-\n',
) == [
CodePartition(CodeType.PRE_IMPORT_CODE, '#!/usr/bin/env python\n'),
CodePartition(CodeType.PRE_IMPORT_CODE, '# -*- coding: UTF-8 -*-\n'),
]
def test_partition_source_import():
assert partition_source('import os\n') == [
CodePartition(CodeType.IMPORT, 'import os\n'),
]
def test_partion_source_import_no_nl():
assert partition_source('import os') == [
CodePartition(CodeType.IMPORT, 'import os'),
]
def test_partition_source_import_contains_comment():
# We want to maintain comments with imports
assert partition_source('from foo import * # noqa\n') == [
CodePartition(CodeType.IMPORT, 'from foo import * # noqa\n'),
]
def test_partition_source_import_inside_code_not_an_import():
assert partition_source('x = 1\nimport os\n') == [
CodePartition(CodeType.CODE, 'x = 1\nimport os\n'),
]
def test_partition_source_docstring():
assert partition_source('"""foo"""\n') == [
CodePartition(CodeType.PRE_IMPORT_CODE, '"""foo"""\n'),
]
def test_partition_source_docstring_no_nl():
assert partition_source('"""foo"""') == [
CodePartition(CodeType.PRE_IMPORT_CODE, '"""foo"""'),
]
def test_partition_source_multiple_docstrings():
assert partition_source(
'"""foo"""\n'
'"""bar"""\n',
) == [
# only the first docstring should count as a docstring
CodePartition(CodeType.PRE_IMPORT_CODE, '"""foo"""\n'),
CodePartition(CodeType.PRE_IMPORT_CODE, '"""bar"""\n'),
]
def test_partition_source_unicode_docstring():
assert partition_source(
'# -*- coding: UTF-8 -*-\n'
'u"""☃☃☃"""\n',
) == [
CodePartition(CodeType.PRE_IMPORT_CODE, '# -*- coding: UTF-8 -*-\n'),
CodePartition(CodeType.PRE_IMPORT_CODE, 'u"""☃☃☃"""\n'),
]
def test_partition_source_blank_lines_with_whitespace():
assert partition_source(
'import os\n'
'\n'
' \n'
'import sys\n',
) == [
CodePartition(CodeType.IMPORT, 'import os\n'),
CodePartition(CodeType.NON_CODE, '\n'),
CodePartition(CodeType.NON_CODE, ' \n'),
CodePartition(CodeType.IMPORT, 'import sys\n'),
]
def test_partition_source_code():
assert partition_source('x = 1\n') == [
CodePartition(CodeType.CODE, 'x = 1\n'),
]
def test_partition_source_code_no_nl():
assert partition_source('x = 1') == [
CodePartition(CodeType.CODE, 'x = 1'),
]
def test_partition_source_comment_lines():
assert partition_source(
'# hello world\n'
'import os\n',
) == [
CodePartition(CodeType.PRE_IMPORT_CODE, '# hello world\n'),
CodePartition(CodeType.IMPORT, 'import os\n'),
]
def _src_to_import_lines(src):
ast_obj = ast.parse(src)
visitor = TopLevelImportVisitor()
visitor.visit(ast_obj)
return visitor.top_level_import_line_numbers
def test_import_visitor_trivial():
assert _src_to_import_lines(b'') == []
def test_import_visitor_simple_import():
ret = _src_to_import_lines(
b'import foo\n'
b'#something else\n',
)
assert ret == [1]
def test_import_visitor_simple_import_2():
ret = _src_to_import_lines(
b'# -*- coding: utf-8 -*-\n'
b'import os\n',
)
assert ret == [2]
def test_import_visitor_multiple_imports():
ret = _src_to_import_lines(
b'import os\n'
b'import sys\n',
)
assert ret == [1, 2]
def test_import_visitor_ignores_indented_imports():
ret = _src_to_import_lines(
b'if True:\n'
b' import os\n',
)
assert ret == []
def test_line_offsets_trivial():
assert get_line_offsets_by_line_no('') == [0, 0]
def test_line_offsets_no_eof_newline():
assert get_line_offsets_by_line_no('hello') == [0, 0, 5]
def test_line_offsets_eof_newline():
assert get_line_offsets_by_line_no('hello\n') == [0, 0, 6]
def test_line_offsets_multiple_lines():
src = 'hello\nworld\n'
ret = get_line_offsets_by_line_no(src)
assert ret == [0, 0, 6, 12]
# To demonstrate how it is used: acquire everything from line 2 onwards
assert src[ret[2]:] == 'world\n'
def test_separate_comma_imports_trivial():
assert separate_comma_imports([]) == []
def test_separate_comma_imports_none_to_separate():
input_partitions = [
CodePartition(CodeType.IMPORT, 'import os\n'),
CodePartition(CodeType.NON_CODE, '\n'),
CodePartition(CodeType.IMPORT, 'import six\n'),
]
assert separate_comma_imports(input_partitions) == input_partitions
def test_separate_comma_imports_separates_some():
assert separate_comma_imports([
CodePartition(CodeType.IMPORT, 'import os, sys\n'),
]) == [
CodePartition(CodeType.IMPORT, 'import os\n'),
CodePartition(CodeType.IMPORT, 'import sys\n'),
]
def test_separate_comma_imports_removes_comments():
# Since it's not really possible to know what the comma points to, we just
# remove it
assert separate_comma_imports([
CodePartition(CodeType.IMPORT, 'import os, sys # derp\n'),
]) == [
CodePartition(CodeType.IMPORT, 'import os\n'),
CodePartition(CodeType.IMPORT, 'import sys\n'),
]
def test_separate_comma_imports_does_not_remove_comments_when_not_splitting():
input_partitions = [CodePartition(CodeType.IMPORT, 'import sys # noqa\n')]
assert separate_comma_imports(input_partitions) == input_partitions
def test_remove_duplicated_imports_trivial():
assert remove_duplicated_imports([]) == []
def test_remove_duplicated_imports_no_dupes_no_removals():
input_partitions = [
CodePartition(CodeType.IMPORT, 'import sys\n'),
CodePartition(CodeType.NON_CODE, '\n'),
CodePartition(CodeType.IMPORT, 'from six import text_type\n'),
]
assert remove_duplicated_imports(input_partitions) == input_partitions
def test_remove_duplicated_imports_removes_duplicated():
assert remove_duplicated_imports([
CodePartition(CodeType.IMPORT, 'import sys\n'),
CodePartition(CodeType.IMPORT, 'import sys\n'),
]) == [
CodePartition(CodeType.IMPORT, 'import sys\n'),
]
def test_remove_duplicate_redundant_import_imports():
assert remove_duplicated_imports([
CodePartition(CodeType.IMPORT, 'import os\n'),
CodePartition(CodeType.IMPORT, 'import os.path\n'),
]) == [
CodePartition(CodeType.IMPORT, 'import os.path\n'),
]
assert remove_duplicated_imports([
CodePartition(CodeType.IMPORT, 'import os.path\n'),
CodePartition(CodeType.IMPORT, 'import os\n'),
]) == [
CodePartition(CodeType.IMPORT, 'import os.path\n'),
]
def test_aliased_imports_not_considered_redundant():
partitions = [
CodePartition(CodeType.IMPORT, 'import os\n'),
CodePartition(CodeType.IMPORT, 'import os.path as os_path\n'),
]
assert remove_duplicated_imports(partitions) == partitions
def test_aliased_imports_not_considered_redundant_v2():
partitions = [
CodePartition(CodeType.IMPORT, 'import os as osmod\n'),
CodePartition(CodeType.IMPORT, 'import os.path\n'),
]
assert remove_duplicated_imports(partitions) == partitions
def test_apply_import_sorting_trivial():
assert apply_import_sorting([]) == []
def test_apply_import_sorting_all_types():
input_partitions = [
CodePartition(CodeType.PRE_IMPORT_CODE, '#!/usr/bin/env python\n'),
CodePartition(CodeType.PRE_IMPORT_CODE, '# -*- coding: UTF-8 -*-\n'),
CodePartition(CodeType.PRE_IMPORT_CODE, '"""foo"""\n'),
CodePartition(CodeType.IMPORT, 'import os\n'),
CodePartition(CodeType.CODE, '\n\nx = 5\n'),
]
assert apply_import_sorting(input_partitions) == input_partitions
def test_apply_import_sorting_sorts_imports():
assert apply_import_sorting([
# local imports
CodePartition(
CodeType.IMPORT, 'from reorder_python_imports import main\n',
),
CodePartition(CodeType.IMPORT, 'import reorder_python_imports\n'),
# site-package imports
CodePartition(CodeType.IMPORT, 'from six import text_type\n'),
CodePartition(CodeType.IMPORT, 'import aspy\n'),
# System imports (out of order)
CodePartition(CodeType.IMPORT, 'from os import path\n'),
CodePartition(CodeType.IMPORT, 'import os\n'),
]) == [
CodePartition(CodeType.IMPORT, 'import os\n'),
CodePartition(CodeType.IMPORT, 'from os import path\n'),
CodePartition(CodeType.NON_CODE, '\n'),
CodePartition(CodeType.IMPORT, 'import aspy\n'),
CodePartition(CodeType.IMPORT, 'from six import text_type\n'),
CodePartition(CodeType.NON_CODE, '\n'),
CodePartition(CodeType.IMPORT, 'import reorder_python_imports\n'),
CodePartition(
CodeType.IMPORT, 'from reorder_python_imports import main\n',
),
]
def test_apply_import_sorting_sorts_imports_with_separate_relative():
assert apply_import_sorting(
[
# relative imports
CodePartition(CodeType.IMPORT, 'from .main import main\n'),
# local imports
CodePartition(
CodeType.IMPORT, 'from reorder_python_imports import main\n',
),
CodePartition(CodeType.IMPORT, 'import reorder_python_imports\n'),
# site-package imports
CodePartition(CodeType.IMPORT, 'from six import text_type\n'),
CodePartition(CodeType.IMPORT, 'import aspy\n'),
# System imports (out of order)
CodePartition(CodeType.IMPORT, 'from os import path\n'),
CodePartition(CodeType.IMPORT, 'import os\n'),
],
separate_relative=True,
) == [
CodePartition(CodeType.IMPORT, 'import os\n'),
CodePartition(CodeType.IMPORT, 'from os import path\n'),
CodePartition(CodeType.NON_CODE, '\n'),
CodePartition(CodeType.IMPORT, 'import aspy\n'),
CodePartition(CodeType.IMPORT, 'from six import text_type\n'),
CodePartition(CodeType.NON_CODE, '\n'),
CodePartition(CodeType.IMPORT, 'import reorder_python_imports\n'),
CodePartition(
CodeType.IMPORT, 'from reorder_python_imports import main\n',
),
CodePartition(CodeType.NON_CODE, '\n'),
CodePartition(CodeType.IMPORT, 'from .main import main\n'),
]
def test_apply_import_sorting_sorts_imports_with_separate_from_import():
assert apply_import_sorting(
[
# local imports
CodePartition(
CodeType.IMPORT, 'from reorder_python_imports import main\n',
),
CodePartition(CodeType.IMPORT, 'import reorder_python_imports\n'),
# site-package imports
CodePartition(CodeType.IMPORT, 'from six import text_type\n'),
CodePartition(CodeType.IMPORT, 'import aspy\n'),
# System imports (out of order)
CodePartition(CodeType.IMPORT, 'from os import path\n'),
CodePartition(CodeType.IMPORT, 'import os\n'),
],
separate_from_import=True,
) == [
CodePartition(CodeType.IMPORT, 'import os\n'),
CodePartition(CodeType.NON_CODE, '\n'),
CodePartition(CodeType.IMPORT, 'from os import path\n'),
CodePartition(CodeType.NON_CODE, '\n'),
CodePartition(CodeType.IMPORT, 'import aspy\n'),
CodePartition(CodeType.NON_CODE, '\n'),
CodePartition(CodeType.IMPORT, 'from six import text_type\n'),
CodePartition(CodeType.NON_CODE, '\n'),
CodePartition(CodeType.IMPORT, 'import reorder_python_imports\n'),
CodePartition(CodeType.NON_CODE, '\n'),
CodePartition(
CodeType.IMPORT, 'from reorder_python_imports import main\n',
),
]
def test_apply_import_sorting_sorts_imports_with_application_module():
assert apply_import_sorting(
[
CodePartition(CodeType.IMPORT, 'import _c_module\n'),
CodePartition(CodeType.IMPORT, 'import reorder_python_imports\n'),
CodePartition(CodeType.IMPORT, 'import third_party\n'),
],
unclassifiable_application_modules=['_c_module'],
) == [
CodePartition(CodeType.IMPORT, 'import third_party\n'),
CodePartition(CodeType.NON_CODE, '\n'),
CodePartition(CodeType.IMPORT, 'import _c_module\n'),
CodePartition(CodeType.IMPORT, 'import reorder_python_imports\n'),
]
def test_apply_import_sorting_maintains_comments():
input_partitions = [
CodePartition(CodeType.IMPORT, 'import foo # noqa\n'),
]
assert apply_import_sorting(input_partitions) == input_partitions
def test_apply_import_sorting_removes_padding_if_only_imports():
assert apply_import_sorting([
CodePartition(CodeType.IMPORT, 'import foo\n'),
CodePartition(CodeType.NON_CODE, '\n\n'),
]) == [
CodePartition(CodeType.IMPORT, 'import foo\n'),
]
def test_add_import_trivial():
assert fix_file_contents(
'',
imports_to_add=('from __future__ import absolute_import',),
) == ''
def test_add_import_import_already_there():
assert fix_file_contents(
'from __future__ import absolute_import\n',
imports_to_add=('from __future__ import absolute_import',),
) == 'from __future__ import absolute_import\n'
def test_add_import_not_there():
assert fix_file_contents(
'import os',
imports_to_add=('from __future__ import absolute_import',),
) == (
'from __future__ import absolute_import\n'
'\n'
'import os\n'
)
def test_does_not_put_before_leading_comment():
assert fix_file_contents(
'# -*- coding: UTF-8 -*-',
imports_to_add=('from __future__ import absolute_import',),
) == (
'# -*- coding: UTF-8 -*-\n'
'from __future__ import absolute_import\n'
)
def test_remove_import_trivial():
assert fix_file_contents(
'',
imports_to_remove=('from __future__ import with_statement',),
) == ''
def test_remove_import_import_not_there():
assert fix_file_contents(
'import os\n',
imports_to_remove=('from __future__ import with_statement',),
) == 'import os\n'
def test_remove_imports_actually_removes():
assert fix_file_contents(
'from __future__ import with_statement\n\n'
'import os\n',
imports_to_remove=('from __future__ import with_statement',),
) == 'import os\n'
@pytest.mark.parametrize(
('s', 'prefix', 'expected'),
(
(['foo'], ['bar'], False),
(['foo'], ['foo'], True),
(['foo', 'bar'], ['foo'], True),
(['foo_mod'], ['foo'], False),
),
)
def test_mod_startswith(s, prefix, expected):
assert _mod_startswith(s, prefix) is expected
def test_replace_imports_noop():
ret = fix_file_contents(
'import os\n'
'import sys\n',
# import imports are not rewritten
imports_to_replace=[(['os'], ['fail'], '')],
)
assert ret == 'import os\nimport sys\n'
def test_replace_imports_basic_from():
ret = fix_file_contents(
'from foo import bar\n',
imports_to_replace=[(['foo'], ['baz'], '')],
)
assert ret == 'from baz import bar\n'
def test_replace_imports_from_does_not_replace_name():
ret = fix_file_contents(
'from foo import bar\n',
imports_to_replace=[(['foo', 'bar'], ['baz', 'hi'], '')],
)
assert ret == 'from foo import bar\n'
def test_replace_imports_from_asname():
ret = fix_file_contents(
'from foo import bar as baz\n',
imports_to_replace=[(['foo'], ['baz'], '')],
)
assert ret == 'from baz import bar as baz\n'
def test_replace_imports_specific_attribute_name():
ret = fix_file_contents(
'from foo import bar\n'
'from foo import baz\n',
imports_to_replace=[(['foo'], ['aaa'], 'bar')],
)
assert ret == (
'from aaa import bar\n'
'from foo import baz\n'
)
def test_replace_module_imported():
ret = fix_file_contents(
'from six.moves import queue\n',
imports_to_replace=[(['six', 'moves', 'queue'], ['queue'], '')],
)
assert ret == 'import queue\n'
def test_replace_module_imported_asname():
ret = fix_file_contents(
'from six.moves import queue as Queue\n',
imports_to_replace=[(['six', 'moves', 'queue'], ['queue'], '')],
)
assert ret == 'import queue as Queue\n'
cases = pytest.mark.parametrize(
('s', 'expected'),
(
pytest.param('', '', id='trivial'),
pytest.param(
'import os\n'
"# I'm right after imports\n"
'x = os.path\n',
'import os\n'
"# I'm right after imports\n"
'x = os.path\n',
id='code right after imports',
),
pytest.param(
'# Mostly to demonstrate the (potentially non-ideal) behaviour\n'
'import os\n\n'
'# Hello from nomansland\n'
'import six\n',
'# Mostly to demonstrate the (potentially non-ideal) behaviour\n'
'import os\n\n'
'import six\n'
'# Hello from nomansland\n',
id='comment in imports',
),
pytest.param(
"# I'm a license comment\n"
'import os\n',
"# I'm a license comment\n"
'import os\n',
id='license comment',
),
pytest.param(
'import reorder_python_imports\n'
'import os\n'
'import six\n',
'import os\n\n'
'import six\n\n'
'import reorder_python_imports\n',
id='needs reordering',
),
pytest.param(
'import sys\n'
'import os',
'import os\n'
'import sys\n',
id='no eol',
),
pytest.param(
'# noreorder\n'
'import reorder_python_imports\n'
'import os\n'
'import six\n',
'# noreorder\n'
'import reorder_python_imports\n'
'import os\n'
'import six\n',
id='noreorder all',
),
pytest.param(
'import sys\n'
'import reorder_python_imports\n\n'
'import matplotlib # noreorder\n'
"matplotlib.use('Agg')\n",
'import sys\n\n'
'import reorder_python_imports\n\n'
'import matplotlib # noreorder\n'
"matplotlib.use('Agg')\n",
id='noreorder inline',
),
pytest.param(
'import sys\n'
'import reorder_python_imports\n\n'
'# noreorder\n'
'import matplotlib\n'
"matplotlib.use('Agg')\n",
'import sys\n\n'
'import reorder_python_imports\n\n'
'# noreorder\n'
'import matplotlib\n'
"matplotlib.use('Agg')\n",
id='noreorder not at beginning',
),
),
)
@cases
def test_fix_file_contents(s, expected):
assert fix_file_contents(s) == expected
@cases
def test_integration_main(s, expected, tmpdir):
test_file = tmpdir.join('test.py')
test_file.write(s)
# Check return value with --diff-only
retv_diff = main((str(test_file), '--diff-only'))
assert retv_diff == int(s != expected)
retv = main((str(test_file),))
# Check return value
assert retv == int(s != expected)
# Check the contents rewritten
assert test_file.read() == expected
def test_integration_main_stdout(tmpdir, capsys):
f = tmpdir.join('f.py')
f.write(
'import reorder_python_imports\n'
'import os\n'
'import six\n',
)
ret = main(('--print-only', f.strpath))
assert ret == 1
out, err = capsys.readouterr()
assert out == (
'import os\n\n'
'import six\n\n'
'import reorder_python_imports\n'
)
assert err == (
'warning: --print-only is deprecated and will be removed\n'
f'==> {f} <==\n'
)
def _apply_patch(patch, origfile=None):
args = ('patch', origfile) if origfile else ('patch',)
patch_proc = subprocess.Popen(args, stdin=subprocess.PIPE)
patch_proc.communicate(patch.encode())
assert patch_proc.returncode == 0
def test_does_not_reorder_with_diff_only(in_tmpdir, capsys):
test_file = in_tmpdir.join('test.py')
test_file.write('import sys\nimport os\n')
retv = main((str(test_file), '--diff-only'))
assert retv == 1
assert test_file.read() == 'import sys\nimport os\n'
patch, _ = capsys.readouterr()
_apply_patch(patch)
assert test_file.read() == 'import os\nimport sys\n'
def test_patch_multiple_files_no_eol(in_tmpdir, capsys):
test1file = in_tmpdir.join('test1.py')
test2file = in_tmpdir.join('test2.py')
# Intentionally no EOL
test1file.write('import sys\nimport os')
test2file.write('import sys\nimport os\n')
ret = main((str(test1file), str(test2file), '--diff-only'))
assert ret == 1
patch, _ = capsys.readouterr()
_apply_patch(patch)
assert test1file.read() == 'import os\nimport sys\n'
assert test2file.read() == 'import os\nimport sys\n'
@pytest.fixture
def restore_sys_path():
before = sys.path[:]
yield
sys.path[:] = before
@pytest.mark.usefixtures('restore_sys_path')
def test_additional_directories_integration(in_tmpdir):
if '' in sys.path: # pragma: no cover (depends on run environment)
sys.path.remove('')
# Intentionally avoiding 'tests' and 'testing' because those would clash
# with the names of this project
in_tmpdir.join('nottests/nottesting/__init__.py').ensure()
in_tmpdir.join('foo.py').write(
'import thirdparty\n'
'import nottests\n'
'import nottesting\n',
)
# Without the new option
main(('foo.py',))
assert in_tmpdir.join('foo.py').read() == (
'import nottesting\n'
'import thirdparty\n'
'\n'
'import nottests\n'
)
# With the new option
main(('foo.py', '--application-directories', '.:nottests'))
assert in_tmpdir.join('foo.py').read() == (
'import thirdparty\n'
'\n'
'import nottesting\n'
'import nottests\n'
)
def test_separate_relative_integration(in_tmpdir):
in_tmpdir.join('foo/__init__.py').ensure()
in_tmpdir.join('foo/bar/__init__.py').ensure()
in_tmpdir.join('foo/foo.py').write(
'import thirdparty\n'
'from foo import bar\n'
'from . import bar\n',
)
main(('foo/foo.py',))
assert in_tmpdir.join('foo/foo.py').read() == (
'import thirdparty\n'
'\n'
'from . import bar\n'
'from foo import bar\n'
)
main(('foo/foo.py', '--separate-relative'))
assert in_tmpdir.join('foo/foo.py').read() == (
'import thirdparty\n'
'\n'
'from foo import bar\n'
'\n'
'from . import bar\n'
)
def test_separate_from_import_integration(in_tmpdir):
in_tmpdir.join('foo/__init__.py').ensure()
in_tmpdir.join('foo/bar/__init__.py').ensure()
in_tmpdir.join('foo/foo.py').write(
'import thirdparty\n'
'import foo.bar\n'
'from foo import bar\n'
'from . import bar\n',
)
main(('foo/foo.py',))
assert in_tmpdir.join('foo/foo.py').read() == (
'import thirdparty\n'
'\n'
'import foo.bar\n'
'from . import bar\n'
'from foo import bar\n'
)
main(('foo/foo.py', '--separate-from-import'))
assert in_tmpdir.join('foo/foo.py').read() == (
'import thirdparty\n'
'\n'
'import foo.bar\n'
'\n'
'from . import bar\n'
'from foo import bar\n'
)
def test_separate_relative_and_separate_from_next_to_from_import():
ret = fix_file_contents(
'from reorder_python_imports import y\n'
'from . import z\n',
separate_from_import=True,
separate_relative=True,
)
assert ret == (
'from reorder_python_imports import y\n'
'\n'
'from . import z\n'
)
def test_separate_relative_and_separate_from_next_to_import_import():
ret = fix_file_contents(
'import thirdparty\n'
'from . import bar\n',
separate_from_import=True,
separate_relative=True,
)
assert ret == (
'import thirdparty\n'
'\n'
'from . import bar\n'
)
def test_separate_relative_when_only_relative_imports_are_present():
src = (
'from . import bar\n'
'from . import foo\n'
)
assert fix_file_contents(src, separate_relative=True) == src
def test_fix_crlf():
s = (
'"""foo"""\r\n'
'import os\r\n'
'import sys\r\n'
'x = 1\r\n'
)
assert fix_file_contents(s) == s
def test_fix_cr():
s = (
'"""foo"""\r'
'import os\r'
'import sys\r'
'x = 1\r'
)
assert fix_file_contents(s) == s
@pytest.mark.parametrize(
('opt', 'expected'),
(
(
'--py22-plus',
'from __future__ import unicode_literals\n'
'from __future__ import with_statement\n\n'
'from io import open\n',
),
(
'--py26-plus',
'from __future__ import unicode_literals\n\n'
'from io import open\n',
),
(
'--py3-plus',
'',
),
),
)
def test_py_options(tmpdir, opt, expected):
f = tmpdir.join('f.py')
f.write(
'from __future__ import unicode_literals\n'
'from __future__ import with_statement\n\n'
'from io import open\n',
)
main((str(f), opt))
assert f.read() == expected
def test_py3_plus_unsixes_imports_rename_module(tmpdir):
f = tmpdir.join('f.py')
f.write('from six.moves.urllib.parse import quote_plus\n')
assert main((str(f), '--py3-plus'))
assert f.read() == 'from urllib.parse import quote_plus\n'
def test_py3_plus_unsixes_imports_removes_builtins(tmpdir):
f = tmpdir.join('f.py')
f.write('from six.moves import range\n')
assert main((str(f), '--py3-plus'))
assert f.read() == ''
def test_py3_plus_unsixes_moved_attributes(tmpdir):
f = tmpdir.join('f.py')
f.write('from six.moves import reduce\n')
assert main((str(f), '--py3-plus'))
assert f.read() == 'from functools import reduce\n'
def test_py3_plus_unsixes_wraps(tmpdir):
f = tmpdir.join('f.py')
f.write('from six import wraps\n')
assert main((str(f), '--py3-plus'))
assert f.read() == 'from functools import wraps\n'
def test_py3_plus_rewrites_mock(tmpdir):
f = tmpdir.join('f.py')
f.write('from mock import ANY\n')
assert main((str(f), '--py3-plus'))