Debian Codegraph @

tests/unit/test_ticketed_features.py

raw
1 """A growing set of tests designed to ensure when isort implements a feature described in a ticket
2 it fully works as defined in the associated ticket.
3 """
4
5 import warnings
6 from functools import partial
7 from io import StringIO
8 from pathlib import Path
9
10 import pytest
11
12 import isort
13 from isort import Config, exceptions
14
15
16 def test_semicolon_ignored_for_dynamic_lines_after_import_issue_1178() -> None:
17 """Test to ensure even if a semicolon is in the decorator in the line following an import
18 the correct line spacing determination will be made.
19 See: https://github.com/pycqa/isort/issues/1178.
20 """
21 assert isort.check_code(
22 """
23 import pytest
24
25
26 @pytest.mark.skip(';')
27 def test_thing(): pass
28 """,
29 show_diff=True,
30 )
31
32
33 def test_isort_automatically_removes_duplicate_aliases_issue_1193() -> None:
34 """Test to ensure isort can automatically remove duplicate aliases.
35 See: https://github.com/pycqa/isort/issues/1281
36 """
37 assert isort.check_code("from urllib import parse as parse\n", show_diff=True)
38 assert (
39 isort.code("from urllib import parse as parse", remove_redundant_aliases=True)
40 == "from urllib import parse\n"
41 )
42 assert isort.check_code("import os as os\n", show_diff=True)
43 assert isort.code("import os as os", remove_redundant_aliases=True) == "import os\n"
44
45
46 def test_isort_enables_floating_imports_to_top_of_module_issue_1228() -> None:
47 """Test to ensure isort will allow floating all non-indented imports to the top of a file.
48 See: https://github.com/pycqa/isort/issues/1228.
49 """
50 assert (
51 isort.code(
52 """
53 import os
54
55
56 def my_function_1():
57 pass
58
59 import sys
60
61 def my_function_2():
62 pass
63 """,
64 float_to_top=True,
65 )
66 == """
67 import os
68 import sys
69
70
71 def my_function_1():
72 pass
73
74
75 def my_function_2():
76 pass
77 """
78 )
79
80 assert (
81 isort.code(
82 """
83 import os
84
85
86 def my_function_1():
87 pass
88
89 # isort: split
90 import sys
91
92 def my_function_2():
93 pass
94 """,
95 float_to_top=True,
96 )
97 == """
98 import os
99
100
101 def my_function_1():
102 pass
103
104 # isort: split
105 import sys
106
107
108 def my_function_2():
109 pass
110 """
111 )
112
113 assert (
114 isort.code(
115 """
116 import os
117
118
119 def my_function_1():
120 pass
121
122 # isort: off
123 import b
124 import a
125 def y():
126 pass
127
128 # isort: on
129 import b
130
131 def my_function_2():
132 pass
133
134 import a
135 """,
136 float_to_top=True,
137 )
138 == """
139 import os
140
141
142 def my_function_1():
143 pass
144
145 # isort: off
146 import b
147 import a
148 def y():
149 pass
150
151 # isort: on
152 import a
153 import b
154
155
156 def my_function_2():
157 pass
158 """
159 )
160
161
162 def test_isort_provides_official_api_for_diff_output_issue_1335() -> None:
163 """Test to ensure isort API for diff capturing allows capturing diff without sys.stdout.
164 See: https://github.com/pycqa/isort/issues/1335.
165 """
166 diff_output = StringIO()
167 isort.code("import b\nimport a\n", show_diff=diff_output)
168 diff_output.seek(0)
169 assert "+import a" in diff_output.read()
170
171
172 def test_isort_warns_when_known_sections_dont_match_issue_1331() -> None:
173 """Test to ensure that isort warns if there is a mismatch between sections and known_sections.
174 See: https://github.com/pycqa/isort/issues/1331.
175 """
176 assert (
177 isort.place_module(
178 "bot_core",
179 config=Config(
180 known_robotlocomotion_upstream=["bot_core"],
181 sections=["ROBOTLOCOMOTION_UPSTREAM", "THIRDPARTY"],
182 ),
183 )
184 == "ROBOTLOCOMOTION_UPSTREAM"
185 )
186 with pytest.warns(UserWarning):
187 assert (
188 isort.place_module(
189 "bot_core",
190 config=Config(
191 known_robotlocomotion_upstream=["bot_core"],
192 sections=["ROBOTLOOMOTION_UPSTREAM", "THIRDPARTY"],
193 ),
194 )
195 == "THIRDPARTY"
196 )
197 with pytest.warns(UserWarning):
198 assert (
199 isort.place_module(
200 "bot_core", config=Config(known_robotlocomotion_upstream=["bot_core"])
201 )
202 == "THIRDPARTY"
203 )
204
205
206 def test_isort_supports_append_only_imports_issue_727() -> None:
207 """Test to ensure isort provides a way to only add imports as an append.
208 See: https://github.com/pycqa/isort/issues/727.
209 """
210 assert isort.code("", add_imports=["from __future__ import absolute_imports"]) == ""
211 assert (
212 isort.code("import os", add_imports=["from __future__ import absolute_imports"])
213 == """from __future__ import absolute_imports
214
215 import os
216 """
217 )
218
219 # issue 1838: don't append in middle of class
220 assert isort.check_code(
221 '''class C:
222 """a
223
224 """
225 # comment
226 ''',
227 append_only=True,
228 add_imports=["from __future__ import annotations"],
229 show_diff=True,
230 )
231
232
233 def test_isort_supports_shared_profiles_issue_970() -> None:
234 """Test to ensure isort provides a way to use shared profiles.
235 See: https://github.com/pycqa/isort/issues/970.
236 """
237 assert isort.code("import a", profile="example") == "import a\n" # shared profile
238 assert isort.code("import a", profile="black") == "import a\n" # bundled profile
239 with pytest.raises(exceptions.ProfileDoesNotExist):
240 assert isort.code("import a", profile="madeupfake") == "import a\n" # non-existent profile
241
242
243 def test_treating_comments_as_code_issue_1357() -> None:
244 """Test to ensure isort provides a way to treat comments as code.
245 See: https://github.com/pycqa/isort/issues/1357
246 """
247 assert (
248 isort.code(
249 """# %%
250 import numpy as np
251 np.array([1,2,3])
252
253 # %%
254 import pandas as pd
255 pd.Series([1,2,3])
256
257 # %%
258 # This is a comment on the second import
259 import pandas as pd
260 pd.Series([4,5,6])""",
261 treat_comments_as_code=["# comment1", "# %%"],
262 )
263 == """# %%
264 import numpy as np
265
266 np.array([1,2,3])
267
268 # %%
269 import pandas as pd
270
271 pd.Series([1,2,3])
272
273 # %%
274 # This is a comment on the second import
275 import pandas as pd
276
277 pd.Series([4,5,6])
278 """
279 )
280 assert (
281 isort.code(
282 """# %%
283 import numpy as np
284 np.array([1,2,3])
285
286 # %%
287 import pandas as pd
288 pd.Series([1,2,3])
289
290 # %%
291 # This is a comment on the second import
292 import pandas as pd
293 pd.Series([4,5,6])""",
294 treat_comments_as_code=["# comment1", "# %%"],
295 float_to_top=True,
296 )
297 == """# %%
298 import numpy as np
299 # This is a comment on the second import
300 import pandas as pd
301
302 np.array([1,2,3])
303
304 # %%
305 pd.Series([1,2,3])
306
307 # %%
308 pd.Series([4,5,6])
309 """
310 )
311 assert (
312 isort.code(
313 """# %%
314 import numpy as np
315 np.array([1,2,3])
316
317 # %%
318 import pandas as pd
319 pd.Series([1,2,3])
320
321 # %%
322 # This is a comment on the second import
323 import pandas as pd
324 pd.Series([4,5,6])""",
325 treat_all_comments_as_code=True,
326 )
327 == """# %%
328 import numpy as np
329
330 np.array([1,2,3])
331
332 # %%
333 import pandas as pd
334
335 pd.Series([1,2,3])
336
337 # %%
338 # This is a comment on the second import
339 import pandas as pd
340
341 pd.Series([4,5,6])
342 """
343 )
344 assert (
345 isort.code(
346 """import b
347
348 # these are special imports that have to do with installing X plugin
349 import c
350 import a
351 """,
352 treat_all_comments_as_code=True,
353 )
354 == """import b
355
356 # these are special imports that have to do with installing X plugin
357 import a
358 import c
359 """
360 )
361
362
363 def test_isort_allows_setting_import_types_issue_1181() -> None:
364 """Test to ensure isort provides a way to set the type of imports.
365 See: https://github.com/pycqa/isort/issues/1181
366 """
367 assert isort.code("from x import AA, Big, variable") == "from x import AA, Big, variable\n"
368 assert (
369 isort.code("from x import AA, Big, variable", constants=["variable"])
370 == "from x import AA, variable, Big\n"
371 )
372 assert (
373 isort.code("from x import AA, Big, variable", variables=["AA"])
374 == "from x import Big, AA, variable\n"
375 )
376 assert (
377 isort.code(
378 "from x import AA, Big, variable",
379 constants=["Big"],
380 variables=["AA"],
381 classes=["variable"],
382 )
383 == "from x import Big, variable, AA\n"
384 )
385
386
387 def test_isort_enables_deduping_section_headers_issue_953() -> None:
388 """isort should provide a way to only have identical import headings show up once.
389 See: https://github.com/pycqa/isort/issues/953
390 """
391 isort_code = partial(
392 isort.code,
393 config=Config(
394 import_heading_firstparty="Local imports.",
395 import_heading_localfolder="Local imports.",
396 dedup_headings=True,
397 known_first_party=["isort"],
398 ),
399 )
400
401 assert (
402 isort_code("from . import something")
403 == """# Local imports.
404 from . import something
405 """
406 )
407 assert (
408 isort_code(
409 """from isort import y
410
411 from . import something"""
412 )
413 == """# Local imports.
414 from isort import y
415
416 from . import something
417 """
418 )
419 assert isort_code("import os") == "import os\n"
420
421
422 def test_isort_doesnt_remove_as_imports_when_combine_star_issue_1380() -> None:
423 """Test to ensure isort will not remove as imports along side other imports
424 when requested to combine star imports together.
425 See: https://github.com/PyCQA/isort/issues/1380
426 """
427 test_input = """
428 from a import a
429 from a import *
430 from a import b
431 from a import b as y
432 from a import c
433 """
434 assert (
435 isort.code(
436 test_input,
437 combine_star=True,
438 )
439 == isort.code(test_input, combine_star=True, force_single_line=True)
440 == isort.code(
441 test_input,
442 combine_star=True,
443 force_single_line=True,
444 combine_as_imports=True,
445 )
446 == """
447 from a import *
448 from a import b as y
449 """
450 )
451
452
453 def test_isort_support_custom_groups_above_stdlib_that_contain_stdlib_modules_issue_1407() -> None:
454 """Test to ensure it is possible to declare custom groups above standard library that include
455 modules from the standard library.
456 See: https://github.com/PyCQA/isort/issues/1407
457 """
458 assert isort.check_code(
459 """
460 from __future__ import annotations
461 from typing import *
462
463 from pathlib import Path
464 """,
465 known_typing=["typing"],
466 sections=["FUTURE", "TYPING", "STDLIB", "THIRDPARTY", "FIRSTPARTY", "LOCALFOLDER"],
467 no_lines_before=["TYPING"],
468 show_diff=True,
469 )
470
471
472 def test_isort_intelligently_places_noqa_comments_issue_1456() -> None:
473 assert isort.check_code(
474 """
475 from my.horribly.long.import.line.that.just.keeps.on.going.and.going.and.going import ( # noqa
476 my_symbol,
477 )
478 """,
479 force_single_line=True,
480 show_diff=True,
481 multi_line_output=3,
482 include_trailing_comma=True,
483 force_grid_wrap=0,
484 use_parentheses=True,
485 line_length=79,
486 )
487
488 assert isort.check_code(
489 """
490 from my.horribly.long.import.line.that.just.keeps.on.going.and.going.and.going import (
491 my_symbol,
492 )
493 """,
494 force_single_line=True,
495 show_diff=True,
496 multi_line_output=3,
497 include_trailing_comma=True,
498 force_grid_wrap=0,
499 use_parentheses=True,
500 line_length=79,
501 )
502
503 assert isort.check_code(
504 """
505 from my.horribly.long.import.line.that.just.keeps.on.going.and.going.and.going import ( # noqa
506 my_symbol
507 )
508 """,
509 force_single_line=True,
510 use_parentheses=True,
511 multi_line_output=3,
512 line_length=79,
513 show_diff=True,
514 )
515
516 assert isort.check_code(
517 """
518 from my.horribly.long.import.line.that.just.keeps.on.going.and.going.and.going import (
519 my_symbol
520 )
521 """,
522 force_single_line=True,
523 use_parentheses=True,
524 multi_line_output=3,
525 line_length=79,
526 show_diff=True,
527 )
528
529 # see: https://github.com/PyCQA/isort/issues/1415
530 assert isort.check_code(
531 "from dials.test.algorithms.spot_prediction."
532 "test_scan_static_reflection_predictor import ( # noqa: F401\n"
533 " data as static_test,\n)\n",
534 profile="black",
535 show_diff=True,
536 )
537
538
539 def test_isort_respects_quiet_from_sort_file_api_see_1461(
540 capsys: pytest.CaptureFixture[str], tmp_path: Path
541 ) -> None:
542 """Test to ensure isort respects the quiet API parameter when passed in via the API.
543 See: https://github.com/PyCQA/isort/issues/1461.
544 """
545 settings_file = tmp_path / ".isort.cfg"
546 custom_settings_file = tmp_path / ".custom.isort.cfg"
547 tmp_file = tmp_path / "file.py"
548 tmp_file.write_text("import b\nimport a\n")
549 isort.file(tmp_file)
550
551 out, error = capsys.readouterr()
552 assert not error
553 assert "Fixing" in out
554
555 # When passed in directly as a setting override
556 tmp_file.write_text("import b\nimport a\n")
557 isort.file(tmp_file, quiet=True)
558 out, error = capsys.readouterr()
559 assert not error
560 assert not out
561
562 # Present in an automatically loaded configuration file
563 settings_file.write_text(
564 """
565 [isort]
566 quiet = true
567 """
568 )
569 tmp_file.write_text("import b\nimport a\n")
570 isort.file(tmp_file)
571 out, error = capsys.readouterr()
572 assert not error
573 assert not out
574
575 # In a custom configuration file
576 settings_file.write_text(
577 """
578 [isort]
579 quiet = false
580 """
581 )
582 custom_settings_file.write_text(
583 """
584 [isort]
585 quiet = true
586 """
587 )
588 tmp_file.write_text("import b\nimport a\n")
589 isort.file(tmp_file, settings_file=str(custom_settings_file))
590 out, error = capsys.readouterr()
591 assert not error
592 assert not out
593
594 # Reused configuration object
595 custom_config = Config(settings_file=str(custom_settings_file))
596 isort.file(tmp_file, config=custom_config)
597 out, error = capsys.readouterr()
598 assert not error
599 assert not out
600
601
602 def test_isort_should_warn_on_empty_custom_config_issue_1433(tmp_path: Path) -> None:
603 """Feedback should be provided when a user provides a custom settings file that has no
604 discoverable configuration.
605 See: https://github.com/PyCQA/isort/issues/1433
606 """
607 settings_file = tmp_path / ".custom.cfg"
608 settings_file.write_text(
609 """
610 [settings]
611 quiet = true
612 """
613 )
614 with pytest.warns(UserWarning):
615 assert not Config(settings_file=str(settings_file)).quiet
616
617 settings_file.write_text(
618 """
619 [isort]
620 quiet = true
621 """
622 )
623 with warnings.catch_warnings():
624 warnings.simplefilter("error")
625 assert Config(settings_file=str(settings_file)).quiet
626
627
628 def test_float_to_top_should_respect_existing_newlines_between_imports_issue_1502() -> None:
629 """When a file has an existing top of file import block before code but after comments
630 isort's float to top feature should respect the existing spacing between the top file comment
631 and the import statements.
632 See: https://github.com/PyCQA/isort/issues/1502
633 """
634 assert isort.check_code(
635 """#!/usr/bin/env bash
636 '''My comment'''
637
638 import a
639
640 x = 1
641 """,
642 float_to_top=True,
643 show_diff=True,
644 )
645 assert isort.check_code(
646 """#!/usr/bin/env bash
647 '''My comment'''
648
649
650 import a
651
652 x = 1
653 """,
654 float_to_top=True,
655 show_diff=True,
656 )
657 assert (
658 isort.code(
659 """#!/usr/bin/env bash
660 '''My comment'''
661
662
663 import a
664
665 x = 1
666 """,
667 float_to_top=True,
668 add_imports=["import b"],
669 )
670 == """#!/usr/bin/env bash
671 '''My comment'''
672
673
674 import a
675 import b
676
677 x = 1
678 """
679 )
680
681 assert (
682 isort.code(
683 """#!/usr/bin/env bash
684 '''My comment'''
685
686
687 def my_function():
688 pass
689
690
691 import a
692 """,
693 float_to_top=True,
694 )
695 == """#!/usr/bin/env bash
696 '''My comment'''
697 import a
698
699
700 def my_function():
701 pass
702 """
703 )
704
705 assert (
706 isort.code(
707 """#!/usr/bin/env bash
708 '''My comment'''
709
710
711 def my_function():
712 pass
713 """,
714 add_imports=["import os"],
715 float_to_top=True,
716 )
717 == """#!/usr/bin/env bash
718 '''My comment'''
719 import os
720
721
722 def my_function():
723 pass
724 """
725 )
726
727
728 def test_api_to_allow_custom_diff_and_output_stream_1583(
729 capsys: pytest.CaptureFixture[str], tmp_path: Path
730 ) -> None:
731 """isort should provide a way from the Python API to process an existing
732 file and output to a stream the new version of that file, as well as a diff
733 to a different stream.
734 See: https://github.com/PyCQA/isort/issues/1583
735 """
736 tmp_file = tmp_path / "file.py"
737 tmp_file.write_text("import b\nimport a\n")
738
739 isort_diff = StringIO()
740 isort_output = StringIO()
741
742 isort.file(str(tmp_file), show_diff=isort_diff, output=isort_output)
743
744 _, error = capsys.readouterr()
745 assert not error
746
747 isort_diff.seek(0)
748 isort_diff_content = isort_diff.read()
749 assert "+import a" in isort_diff_content
750 assert " import b" in isort_diff_content
751 assert "-import a" in isort_diff_content
752
753 isort_output.seek(0)
754 assert isort_output.read().splitlines() == ["import a", "import b"]
755
756 # should still work with no diff produced
757 tmp_file2 = tmp_path / "file2.py"
758 tmp_file2.write_text("import a\nimport b\n")
759
760 isort_diff2 = StringIO()
761 isort_output2 = StringIO()
762
763 isort.file(str(tmp_file2), show_diff=isort_diff2, output=isort_output2)
764
765 _, error = capsys.readouterr()
766 assert not error
767
768 isort_diff2.seek(0)
769 assert not isort_diff2.read()
770
771
772 def test_autofix_mixed_indent_imports_1575() -> None:
773 """isort should automatically fix import statements that are sent in
774 with incorrect mixed indentation.
775 See: https://github.com/PyCQA/isort/issues/1575
776 """
777 assert (
778 isort.code(
779 """
780 import os
781 import os
782 """
783 )
784 == """
785 import os
786 """
787 )
788 assert (
789 isort.code(
790 """
791 def one():
792 import os
793 import os
794 """
795 )
796 == """
797 def one():
798 import os
799
800 import os
801 """
802 )
803 assert (
804 isort.code(
805 """
806 import os
807 import os
808 import os
809 import os
810 import os
811 """
812 )
813 == """
814 import os
815 """
816 )
817
818
819 def test_indented_import_headings_issue_1604() -> None:
820 """Test to ensure it is possible to toggle import headings on indented import sections
821 See: https://github.com/PyCQA/isort/issues/1604
822 """
823 assert (
824 isort.code(
825 """
826 import numpy as np
827
828
829 def function():
830 import numpy as np
831 """,
832 import_heading_thirdparty="External imports",
833 )
834 == """
835 # External imports
836 import numpy as np
837
838
839 def function():
840 # External imports
841 import numpy as np
842 """
843 )
844 assert (
845 isort.code(
846 """
847 import numpy as np
848
849
850 def function():
851 import numpy as np
852 """,
853 import_heading_thirdparty="External imports",
854 indented_import_headings=False,
855 )
856 == """
857 # External imports
858 import numpy as np
859
860
861 def function():
862 import numpy as np
863 """
864 )
865
866
867 def test_isort_auto_detects_and_ignores_invalid_from_imports_issue_1688() -> None:
868 """isort should automatically detect and ignore incorrectly written from import statements
869 see: https://github.com/PyCQA/isort/issues/1688
870 """
871 assert (
872 isort.code(
873 """
874 from package1 import alright
875 from package2 imprt and_its_gone
876 from package3 import also_ok
877 """
878 )
879 == """
880 from package1 import alright
881
882 from package2 imprt and_its_gone
883 from package3 import also_ok
884 """
885 )
886
887
888 def test_isort_allows_reversing_sort_order_issue_1645() -> None:
889 """isort allows reversing the sort order for those who prefer Z or longer imports first.
890 see: https://github.com/PyCQA/isort/issues/1688
891 """
892 assert (
893 isort.code(
894 """
895 from xxx import (
896 g,
897 hi,
898 def,
899 abcd,
900 )
901 """,
902 profile="black",
903 reverse_sort=True,
904 length_sort=True,
905 line_length=20,
906 )
907 == """
908 from xxx import (
909 abcd,
910 def,
911 hi,
912 g,
913 )
914 """
915 )
916
917
918 def test_isort_can_push_star_imports_above_others_issue_1504() -> None:
919 """isort should provide a way to push star imports above other imports to avoid explicit
920 imports from being overwritten.
921 see: https://github.com/PyCQA/isort/issues/1504
922 """
923 assert (
924 (
925 isort.code(
926 """
927 from ._bar import Any, All, Not
928 from ._foo import a, *
929 """,
930 star_first=True,
931 )
932 )
933 == """
934 from ._foo import *
935 from ._foo import a
936 from ._bar import All, Any, Not
937 """
938 )
939
940
941 def test_isort_can_combine_reverse_sort_with_force_sort_within_sections_issue_1726() -> None:
942 """isort should support reversing import order even with force sort within sections turned on.
943 See: https://github.com/PyCQA/isort/issues/1726
944 """
945 assert (
946 isort.code(
947 """
948 import blaaa
949 from bl4aaaaaaaaaaaaaaaa import r
950 import blaaaaaaaaaaaa
951 import bla
952 import blaaaaaaa
953 from bl1aaaaaaaaaaaaaa import this_is_1
954 from bl2aaaaaaa import THIIIIIIIIIIIISS_is_2
955 from bl3aaaaaa import less
956 """,
957 length_sort=True,
958 reverse_sort=True,
959 force_sort_within_sections=True,
960 )
961 == """
962 from bl2aaaaaaa import THIIIIIIIIIIIISS_is_2
963 from bl1aaaaaaaaaaaaaa import this_is_1
964 from bl4aaaaaaaaaaaaaaaa import r
965 from bl3aaaaaa import less
966 import blaaaaaaaaaaaa
967 import blaaaaaaa
968 import blaaa
969 import bla
970 """
971 )
972
973
974 def test_isort_can_turn_off_import_adds_with_action_comment_issue_1737() -> None:
975 assert (
976 isort.code(
977 """
978 import os
979 """,
980 add_imports=[
981 "from __future__ import absolute_imports",
982 "from __future__ import annotations",
983 ],
984 )
985 == """
986 from __future__ import absolute_imports, annotations
987
988 import os
989 """
990 )
991
992 assert isort.check_code(
993 """
994 # isort: dont-add-imports
995 import os
996 """,
997 show_diff=True,
998 add_imports=[
999 "from __future__ import absolute_imports",
1000 "from __future__ import annotations",
1001 ],
1002 )
1003
1004 assert (
1005 isort.code(
1006 """
1007 # isort: dont-add-import: from __future__ import annotations
1008 import os
1009 """,
1010 add_imports=[
1011 "from __future__ import absolute_imports",
1012 "from __future__ import annotations",
1013 ],
1014 )
1015 == """
1016 # isort: dont-add-import: from __future__ import annotations
1017 from __future__ import absolute_imports
1018
1019 import os
1020 """
1021 )
1022
1023
1024 def test_sort_configurable_sort_issue_1732() -> None:
1025 """Test support for pluggable isort sort functions."""
1026 test_input = (
1027 "from bob2.apples2 import aardvark as aardvark2\n"
1028 "from bob.apples import aardvark \n"
1029 "import module9\n"
1030 "import module10\n"
1031 "import module200\n"
1032 )
1033 assert isort.code(test_input, sort_order="native") == (
1034 "import module10\n"
1035 "import module200\n"
1036 "import module9\n"
1037 "from bob.apples import aardvark\n"
1038 "from bob2.apples2 import aardvark as aardvark2\n"
1039 )
1040 assert (
1041 isort.code(test_input, sort_order="natural")
1042 == isort.code(test_input)
1043 == (
1044 "import module9\n"
1045 "import module10\n"
1046 "import module200\n"
1047 "from bob2.apples2 import aardvark as aardvark2\n"
1048 "from bob.apples import aardvark\n"
1049 )
1050 )
1051 assert (
1052 isort.code(test_input, sort_order="natural_plus")
1053 == isort.code(test_input)
1054 == (
1055 "import module9\n"
1056 "import module10\n"
1057 "import module200\n"
1058 "from bob2.apples2 import aardvark as aardvark2\n"
1059 "from bob.apples import aardvark\n"
1060 )
1061 )
1062 with pytest.raises(exceptions.SortingFunctionDoesNotExist):
1063 isort.code(test_input, sort_order="round")
1064
1065
1066 def test_cython_pure_python_imports_2062() -> None:
1067 """Test to ensure an import form a cython.cimports remains import, not cimport.
1068 See: https://github.com/pycqa/isort/issues/2062.
1069 """
1070 assert isort.check_code(
1071 """
1072 import cython
1073 from cython.cimports.libc import math
1074
1075
1076 def use_libc_math():
1077 return math.ceil(5.5)
1078 """,
1079 show_diff=True,
1080 )
1081
1082
1083 def test_unindented_comment_in_indented_block_issue_1899() -> None:
1084 """Test that unindented comments before indented imports are not corrupted.
1085
1086 See: https://github.com/PyCQA/isort/issues/1899
1087 """
1088 test_input = """import sys
1089
1090 if True:
1091 # this will get cut off
1092 import os
1093 """
1094 assert isort.code(test_input) == test_input
1095
1096
1097 def test_sort_separate_packages_issue_2104() -> None:
1098 """
1099 Test to ensure that packages within a section can be separated by blank lines.
1100 See: https://github.com/PyCQA/isort/issues/2104
1101 """
1102
1103 # Base case as described in issue
1104 assert (
1105 isort.code(
1106 """
1107 import os
1108 import sys
1109
1110 from django.db.models.signals import m2m_changed
1111 from django.utils import functional
1112 from django_filters import BooleanFilter
1113 from junitparser import JUnitXml
1114 from junitparser import TestSuite
1115 from loguru import logger
1116 """,
1117 force_single_line=True,
1118 separate_packages=["THIRDPARTY"],
1119 )
1120 == """
1121 import os
1122 import sys
1123
1124 from django.db.models.signals import m2m_changed
1125 from django.utils import functional
1126
1127 from django_filters import BooleanFilter
1128
1129 from junitparser import JUnitXml
1130 from junitparser import TestSuite
1131
1132 from loguru import logger
1133 """
1134 )
1135
1136 # Check that multiline comments aren't broken up
1137 assert (
1138 isort.code(
1139 """
1140 from junitparser import TestSuite
1141 # Some multiline
1142 # comment
1143 from loguru import logger
1144 """,
1145 force_single_line=True,
1146 separate_packages=["THIRDPARTY"],
1147 )
1148 == """
1149 from junitparser import TestSuite
1150
1151 # Some multiline
1152 # comment
1153 from loguru import logger
1154 """
1155 )
1156
1157 # Check it works for custom sections
1158 assert (
1159 isort.code(
1160 """
1161 import os
1162 from package2 import bar
1163 from package1 import foo
1164 """,
1165 force_single_line=True,
1166 known_MYPACKAGES=["package1", "package2"],
1167 sections=["STDLIB", "MYPACKAGES"],
1168 separate_packages=["MYPACKAGES"],
1169 )
1170 == """
1171 import os
1172
1173 from package1 import foo
1174
1175 from package2 import bar
1176 """
1177 )
1178
1179 # Check it works for packages with deeper nesting
1180 assert (
1181 isort.code(
1182 """
1183 import os
1184 from package2 import bar
1185 from package1.a.b import foo
1186 from package1.a.c import baz
1187 """,
1188 force_single_line=True,
1189 known_MYPACKAGES=["package1.a", "package2"],
1190 sections=["STDLIB", "MYPACKAGES"],
1191 separate_packages=["MYPACKAGES"],
1192 )
1193 == """
1194 import os
1195
1196 from package1.a.b import foo
1197
1198 from package1.a.c import baz
1199
1200 from package2 import bar
1201 """
1202 )
1203
1204
1205 def test_combine_as_with_comments_and_vertical_hang_2316() -> None:
1206 """Comments should still produce correct parentheses with multi_line_output=3.
1207 See: https://github.com/PyCQA/isort/issues/2316
1208 """
1209 assert (
1210 isort.code(
1211 "from pythonosc.udp_client import SimpleUDPClient # type: ignore[import-untyped]",
1212 combine_as_imports=True,
1213 multi_line_output=3,
1214 )
1215 == """\
1216 from pythonosc.udp_client import ( # type: ignore[import-untyped]
1217 SimpleUDPClient
1218 )
1219 """
1220 )
1221 assert (
1222 isort.code(
1223 "from pythonosc.udp_client import SimpleUDPClient # type: ignore[import-untyped]",
1224 combine_as_imports=True,
1225 multi_line_output=3,
1226 include_trailing_comma=True,
1227 )
1228 == """\
1229 from pythonosc.udp_client import ( # type: ignore[import-untyped]
1230 SimpleUDPClient,
1231 )
1232 """
1233 )
1234
1235
1236 def test_isort_preserves_empty_inline_comments() -> None:
1237 """isort should not strip empty inline comments (bare `#`).
1238 See: https://github.com/PyCQA/isort/issues/1913
1239 """
1240 # Straight imports
1241 assert isort.code("import a #\n") == "import a #\n"
1242
1243 # From imports
1244 assert isort.code("from foo import bar #\n") == "from foo import bar #\n"
1245
1246 # Should be idempotent
1247 assert isort.code(isort.code("import a #\n")) == "import a #\n"
1248 assert isort.code(isort.code("from foo import bar #\n")) == "from foo import bar #\n"
1249
1250 # Regular (non-empty) comments should still work
1251 assert isort.code("import a # comment\n") == "import a # comment\n"
1252 assert isort.code("from foo import bar # comment\n") == "from foo import bar # comment\n"
1253
1254
1255 def test_comment_not_duplicated_across_from_imports_2282() -> None:
1256 """isort should not copy a comment from one 'from X import' line to other lines.
1257
1258 See: https://github.com/PyCQA/isort/issues/2282
1259 """
1260 # Comment should stay only on the line with a, b - not copied to e
1261 code = """\
1262 from foo import a, b # comment
1263 from foo import c as d
1264 from foo import e
1265 """
1266 assert isort.code(code) == code