/
test_main.py
721 lines (596 loc) · 16 KB
/
test_main.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
import json
import subprocess
from datetime import datetime
from io import BytesIO, TextIOWrapper
import pytest
from hypothesis import given
from hypothesis import strategies as st
from isort import main
from isort._version import __version__
from isort.exceptions import InvalidSettingsPath
from isort.settings import DEFAULT_CONFIG, Config
from isort.wrap_modes import WrapModes
@given(
file_name=st.text(),
config=st.builds(Config),
check=st.booleans(),
ask_to_apply=st.booleans(),
write_to_stdout=st.booleans(),
)
def test_fuzz_sort_imports(file_name, config, check, ask_to_apply, write_to_stdout):
main.sort_imports(
file_name=file_name,
config=config,
check=check,
ask_to_apply=ask_to_apply,
write_to_stdout=write_to_stdout,
)
def test_iter_source_code(tmpdir):
tmp_file = tmpdir.join("file.py")
tmp_file.write("import os, sys\n")
assert tuple(main.iter_source_code((tmp_file,), DEFAULT_CONFIG, [], [])) == (tmp_file,)
def test_sort_imports(tmpdir):
tmp_file = tmpdir.join("file.py")
tmp_file.write("import os, sys\n")
assert main.sort_imports(str(tmp_file), DEFAULT_CONFIG, check=True).incorrectly_sorted
main.sort_imports(str(tmp_file), DEFAULT_CONFIG)
assert not main.sort_imports(str(tmp_file), DEFAULT_CONFIG, check=True).incorrectly_sorted
skip_config = Config(skip=["file.py"])
assert main.sort_imports(
str(tmp_file), config=skip_config, check=True, disregard_skip=False
).skipped
assert main.sort_imports(str(tmp_file), config=skip_config, disregard_skip=False).skipped
def test_sort_imports_error_handling(tmpdir, mocker, capsys):
tmp_file = tmpdir.join("file.py")
tmp_file.write("import os, sys\n")
mocker.patch("isort.core.process").side_effect = IndexError("Example unhandled exception")
with pytest.raises(IndexError):
main.sort_imports(str(tmp_file), DEFAULT_CONFIG, check=True).incorrectly_sorted
out, error = capsys.readouterr()
assert "Unrecoverable exception thrown when parsing" in error
def test_parse_args():
assert main.parse_args([]) == {}
assert main.parse_args(["--multi-line", "1"]) == {"multi_line_output": WrapModes.VERTICAL}
assert main.parse_args(["--multi-line", "GRID"]) == {"multi_line_output": WrapModes.GRID}
assert main.parse_args(["--dont-order-by-type"]) == {"order_by_type": False}
assert main.parse_args(["--dt"]) == {"order_by_type": False}
assert main.parse_args(["--only-sections"]) == {"only_sections": True}
assert main.parse_args(["--os"]) == {"only_sections": True}
def test_ascii_art(capsys):
main.main(["--version"])
out, error = capsys.readouterr()
assert (
out
== f"""
_ _
(_) ___ ___ _ __| |_
| |/ _/ / _ \\/ '__ _/
| |\\__ \\/\\_\\/| | | |_
|_|\\___/\\___/\\_/ \\_/
isort your imports, so you don't have to.
VERSION {__version__}
"""
)
assert error == ""
def test_preconvert():
assert main._preconvert(frozenset([1, 1, 2])) == [1, 2]
assert main._preconvert(WrapModes.GRID) == "GRID"
assert main._preconvert(main._preconvert) == "_preconvert"
with pytest.raises(TypeError):
main._preconvert(datetime.now())
def test_show_files(capsys, tmpdir):
tmpdir.join("a.py").write("import a")
tmpdir.join("b.py").write("import b")
# show files should list the files isort would sort
main.main([str(tmpdir), "--show-files"])
out, error = capsys.readouterr()
assert "a.py" in out
assert "b.py" in out
assert not error
# can not be used for stream
with pytest.raises(SystemExit):
main.main(["-", "--show-files"])
# can not be used with show-config
with pytest.raises(SystemExit):
main.main([str(tmpdir), "--show-files", "--show-config"])
def test_main(capsys, tmpdir):
base_args = [
"-sp",
str(tmpdir),
"--virtual-env",
str(tmpdir),
"--src-path",
str(tmpdir),
]
tmpdir.mkdir(".git")
# If nothing is passed in the quick guide is returned without erroring
main.main([])
out, error = capsys.readouterr()
assert main.QUICK_GUIDE in out
assert not error
# If no files are passed in but arguments are the quick guide is returned, alongside an error.
with pytest.raises(SystemExit):
main.main(base_args)
out, error = capsys.readouterr()
assert main.QUICK_GUIDE in out
# Unless the config is requested, in which case it will be returned alone as JSON
main.main(base_args + ["--show-config"])
out, error = capsys.readouterr()
returned_config = json.loads(out)
assert returned_config
assert returned_config["virtual_env"] == str(tmpdir)
# This should work even if settings path is not provided
main.main(base_args[2:] + ["--show-config"])
out, error = capsys.readouterr()
assert json.loads(out)["virtual_env"] == str(tmpdir)
# This should raise an error if an invalid settings path is provided
with pytest.raises(InvalidSettingsPath):
main.main(
base_args[2:]
+ ["--show-config"]
+ ["--settings-path", "/random-root-folder-that-cant-exist-right?"]
)
# Should be able to set settings path to a file
config_file = tmpdir.join(".isort.cfg")
config_file.write(
"""
[settings]
profile=hug
verbose=true
"""
)
config_args = ["--settings-path", str(config_file)]
main.main(
config_args
+ ["--virtual-env", "/random-root-folder-that-cant-exist-right?"]
+ ["--show-config"]
)
out, error = capsys.readouterr()
assert json.loads(out)["profile"] == "hug"
# Should be able to stream in content to sort
input_content = TextIOWrapper(
BytesIO(
b"""
import b
import a
"""
)
)
main.main(config_args + ["-"], stdin=input_content)
out, error = capsys.readouterr()
assert (
out
== f"""
else-type place_module for b returned {DEFAULT_CONFIG.default_section}
else-type place_module for a returned {DEFAULT_CONFIG.default_section}
import a
import b
"""
)
# Should be able to stream diff
input_content = TextIOWrapper(
BytesIO(
b"""
import b
import a
"""
)
)
main.main(config_args + ["-", "--diff"], stdin=input_content)
out, error = capsys.readouterr()
assert not error
assert "+" in out
assert "-" in out
assert "import a" in out
assert "import b" in out
# check should work with stdin
input_content_check = TextIOWrapper(
BytesIO(
b"""
import b
import a
"""
)
)
with pytest.raises(SystemExit):
main.main(config_args + ["-", "--check-only"], stdin=input_content_check)
out, error = capsys.readouterr()
assert error == "ERROR: Imports are incorrectly sorted and/or formatted.\n"
# Should be able to run with just a file
python_file = tmpdir.join("has_imports.py")
python_file.write(
"""
import b
import a
"""
)
main.main([str(python_file), "--filter-files", "--verbose"])
assert python_file.read().lstrip() == "import a\nimport b\n"
# Add a file to skip
should_skip = tmpdir.join("should_skip.py")
should_skip.write("import nothing")
main.main(
[
str(python_file),
str(should_skip),
"--filter-files",
"--verbose",
"--skip",
str(should_skip),
]
)
# Should raise a system exit if check only, with broken file
python_file.write(
"""
import b
import a
"""
)
with pytest.raises(SystemExit):
main.main(
[
str(python_file),
str(should_skip),
"--filter-files",
"--verbose",
"--check-only",
"--skip",
str(should_skip),
]
)
# Should have same behavior if full directory is skipped
with pytest.raises(SystemExit):
main.main(
[str(tmpdir), "--filter-files", "--verbose", "--check-only", "--skip", str(should_skip)]
)
# Nested files should be skipped without needing --filter-files
nested_file = tmpdir.mkdir("nested_dir").join("skip.py")
nested_file.write("import b;import a")
python_file.write(
"""
import a
import b
"""
)
main.main([str(tmpdir), "--skip", "skip.py", "--check"])
# without filter options passed in should successfully sort files
main.main([str(python_file), str(should_skip), "--verbose", "--atomic"])
# Should raise a system exit if all passed path is broken
with pytest.raises(SystemExit):
main.main(["not-exist", "--check-only"])
# Should not raise system exit if any of passed path is not broken
main.main([str(python_file), "not-exist", "--verbose", "--check-only"])
out, error = capsys.readouterr()
assert "Broken" in out
# should respect gitignore if requested.
out, error = capsys.readouterr() # clear sysoutput before tests
subprocess.run(["git", "init", str(tmpdir)])
main.main([str(python_file), "--skip-gitignore", "--filter-files"])
out, error = capsys.readouterr()
assert "Skipped" not in out
tmpdir.join(".gitignore").write("has_imports.py")
main.main([str(python_file)])
out, error = capsys.readouterr()
assert "Skipped" not in out
main.main([str(python_file), "--skip-gitignore", "--filter-files"])
out, error = capsys.readouterr()
assert "Skipped" in out
# warnings should be displayed if old flags are used
with pytest.warns(UserWarning):
main.main([str(python_file), "--recursive", "-fss"])
# warnings should be displayed when streaming input is provided with old flags as well
with pytest.warns(UserWarning):
main.main(["-sp", str(config_file), "-"], stdin=input_content)
def test_isort_command():
"""Ensure ISortCommand got registered, otherwise setuptools error must have occurred"""
assert main.ISortCommand
def test_isort_with_stdin(capsys):
# ensures that isort sorts stdin without any flags
input_content = TextIOWrapper(
BytesIO(
b"""
import b
import a
"""
)
)
main.main(["-"], stdin=input_content)
out, error = capsys.readouterr()
assert out == (
"""
import a
import b
"""
)
input_content_from = TextIOWrapper(
BytesIO(
b"""
import c
import b
from a import z, y, x
"""
)
)
main.main(["-"], stdin=input_content_from)
out, error = capsys.readouterr()
assert out == (
"""
import b
import c
from a import x, y, z
"""
)
# ensures that isort correctly sorts stdin with --fas flag
input_content = TextIOWrapper(
BytesIO(
b"""
import sys
import pandas
from z import abc
from a import xyz
"""
)
)
main.main(["-", "--fas"], stdin=input_content)
out, error = capsys.readouterr()
assert out == (
"""
from a import xyz
from z import abc
import pandas
import sys
"""
)
# ensures that isort correctly sorts stdin with --fass flag
input_content = TextIOWrapper(
BytesIO(
b"""
from a import Path, abc
"""
)
)
main.main(["-", "--fass"], stdin=input_content)
out, error = capsys.readouterr()
assert out == (
"""
from a import abc, Path
"""
)
# ensures that isort correctly sorts stdin with --ff flag
input_content = TextIOWrapper(
BytesIO(
b"""
import b
from c import x
from a import y
"""
)
)
main.main(["-", "--ff", "FROM_FIRST"], stdin=input_content)
out, error = capsys.readouterr()
assert out == (
"""
from a import y
from c import x
import b
"""
)
# ensures that isort correctly sorts stdin with -fss flag
input_content = TextIOWrapper(
BytesIO(
b"""
import b
from a import a
"""
)
)
main.main(["-", "--fss"], stdin=input_content)
out, error = capsys.readouterr()
assert out == (
"""
from a import a
import b
"""
)
input_content = TextIOWrapper(
BytesIO(
b"""
import a
from b import c
"""
)
)
main.main(["-", "--fss"], stdin=input_content)
out, error = capsys.readouterr()
assert out == (
"""
import a
from b import c
"""
)
# ensures that isort correctly sorts stdin with --ds flag
input_content = TextIOWrapper(
BytesIO(
b"""
import sys
import pandas
import a
"""
)
)
main.main(["-", "--ds"], stdin=input_content)
out, error = capsys.readouterr()
assert out == (
"""
import a
import pandas
import sys
"""
)
# ensures that isort correctly sorts stdin with --cs flag
input_content = TextIOWrapper(
BytesIO(
b"""
from a import b
from a import *
"""
)
)
main.main(["-", "--cs"], stdin=input_content)
out, error = capsys.readouterr()
assert out == (
"""
from a import *
"""
)
# ensures that isort correctly sorts stdin with --ca flag
input_content = TextIOWrapper(
BytesIO(
b"""
from a import x as X
from a import y as Y
"""
)
)
main.main(["-", "--ca"], stdin=input_content)
out, error = capsys.readouterr()
assert out == (
"""
from a import x as X, y as Y
"""
)
# ensures that isort works consistently with check and ws flags
input_content = TextIOWrapper(
BytesIO(
b"""
import os
import a
import b
"""
)
)
main.main(["-", "--check-only", "--ws"], stdin=input_content)
out, error = capsys.readouterr()
assert not error
# ensures that isort correctly sorts stdin with --ls flag
input_content = TextIOWrapper(
BytesIO(
b"""
import abcdef
import x
"""
)
)
main.main(["-", "--ls"], stdin=input_content)
out, error = capsys.readouterr()
assert out == (
"""
import x
import abcdef
"""
)
# ensures that isort correctly sorts stdin with --nis flag
input_content = TextIOWrapper(
BytesIO(
b"""
from z import b, c, a
"""
)
)
main.main(["-", "--nis"], stdin=input_content)
out, error = capsys.readouterr()
assert out == (
"""
from z import b, c, a
"""
)
# ensures that isort correctly sorts stdin with --sl flag
input_content = TextIOWrapper(
BytesIO(
b"""
from z import b, c, a
"""
)
)
main.main(["-", "--sl"], stdin=input_content)
out, error = capsys.readouterr()
assert out == (
"""
from z import a
from z import b
from z import c
"""
)
# ensures that isort correctly sorts stdin with --top flag
input_content = TextIOWrapper(
BytesIO(
b"""
import os
import sys
"""
)
)
main.main(["-", "--top", "sys"], stdin=input_content)
out, error = capsys.readouterr()
assert out == (
"""
import sys
import os
"""
)
# ensure that isort correctly sorts stdin with --os flag
input_content = TextIOWrapper(
BytesIO(
b"""
import sys
import os
import z
from a import b, e, c
"""
)
)
main.main(["-", "--os"], stdin=input_content)
out, error = capsys.readouterr()
assert out == (
"""
import sys
import os
import z
from a import b, e, c
"""
)
# ensures that isort warns with deprecated flags with stdin
input_content = TextIOWrapper(
BytesIO(
b"""
import sys
import os
"""
)
)
with pytest.warns(UserWarning):
main.main(["-", "-ns"], stdin=input_content)
out, error = capsys.readouterr()
assert out == (
"""
import os
import sys
"""
)
input_content = TextIOWrapper(
BytesIO(
b"""
import sys
import os
"""
)
)
with pytest.warns(UserWarning):
main.main(["-", "-k"], stdin=input_content)
out, error = capsys.readouterr()
assert out == (
"""
import os
import sys
"""
)