Debian Codegraph @

tests/unit/test_regressions.py

raw
1 """A growing set of tests designed to ensure isort doesn't have regressions in new versions"""
2
3 import ast
4 from io import BytesIO, StringIO, TextIOWrapper
5 from pathlib import Path
6
7 import pytest
8
9 import isort
10 import isort.sections
11 from isort.core import STRING_PREFIXES, _float_to_top
12 from isort.main import main
13 from isort.wrap_modes import WrapModes
14
15
16 def test_isort_duplicating_comments_issue_1264() -> None:
17 """Ensure isort doesn't duplicate comments when force_sort_within_sections is set to `True`
18 as was the case in issue #1264: https://github.com/pycqa/isort/issues/1264
19 """
20 assert (
21 isort.code(
22 """
23 from homeassistant.util.logging import catch_log_exception
24
25 # Loading the config flow...
26 from . import config_flow
27 """,
28 force_sort_within_sections=True,
29 ).count("# Loading the config flow...")
30 == 1
31 )
32
33
34 def test_moving_comments_issue_726() -> None:
35 test_input = (
36 "from Blue import models as BlueModels\n"
37 "# comment for PlaidModel\n"
38 "from Plaid.models import PlaidModel\n"
39 )
40 assert isort.code(test_input, force_sort_within_sections=True) == test_input
41
42 test_input = (
43 "# comment for BlueModels\n"
44 "from Blue import models as BlueModels\n"
45 "# comment for PlaidModel\n"
46 "# another comment for PlaidModel\n"
47 "from Plaid.models import PlaidModel\n"
48 )
49 assert isort.code(test_input, force_sort_within_sections=True) == test_input
50
51
52 def test_pylint_disable_next_stays_with_first_import_issue_2054() -> None:
53 test_input = (
54 "# pylint: disable-next=import-error\n"
55 "from C import D\n"
56 "# pylint: disable-next=no-name-in-module\n"
57 "from A import B\n"
58 )
59 expected_output = (
60 "# pylint: disable-next=no-name-in-module\n"
61 "from A import B\n"
62 "# pylint: disable-next=import-error\n"
63 "from C import D\n"
64 )
65
66 assert isort.code(test_input) == expected_output
67
68
69 def test_blank_lines_before_comments_issue_2156() -> None:
70 test_input = """
71 def my_function():
72 def inner_function():
73 return 1
74
75 # A comment
76 return inner_function()
77 """
78 assert isort.code(test_input, lines_before_imports=1) == test_input
79
80
81 def test_force_sort_within_sections_uses_logical_import_lines_issue_1985() -> None:
82 source = """from package import aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa88
83 from package import bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb89
84 from package import cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc88
85 """
86 expected = """from package import aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa88
87 from package import (
88 bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb89,
89 )
90 from package import cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc88
91 """
92 assert (
93 isort.code(source, profile="black", force_single_line=True, force_sort_within_sections=True)
94 == expected
95 )
96
97 source = """from package import aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa88
98 from package import ( # noqa
99 zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz89,
100 )
101 """
102 assert (
103 isort.code(source, profile="black", force_single_line=True, force_sort_within_sections=True)
104 == source
105 )
106
107
108 def test_blank_lined_removed_issue_1275() -> None:
109 """Ensure isort doesn't accidentally remove blank lines after doc strings and before imports.
110 See: https://github.com/pycqa/isort/issues/1275
111 """
112 assert (
113 isort.code(
114 '''"""
115 My docstring
116 """
117
118 from b import thing
119 from a import other_thing
120 '''
121 )
122 == '''"""
123 My docstring
124 """
125
126 from a import other_thing
127 from b import thing
128 '''
129 )
130
131 assert (
132 isort.code(
133 '''"""
134 My docstring
135 """
136
137 from b import thing
138 from a import other_thing
139 ''',
140 add_imports=["from b import thing"],
141 )
142 == '''"""
143 My docstring
144 """
145
146 from a import other_thing
147 from b import thing
148 '''
149 )
150
151
152 def test_blank_lined_removed_issue_1283() -> None:
153 """Ensure isort doesn't accidentally remove blank lines after __version__ identifiers.
154 See: https://github.com/pycqa/isort/issues/1283
155 """
156 test_input = """__version__ = "0.58.1"
157
158 from starlette import status
159 """
160 assert isort.code(test_input) == test_input
161
162
163 def test_extra_blank_line_added_nested_imports_issue_1290() -> None:
164 """Ensure isort doesn't add unnecessary blank lines above nested imports.
165 See: https://github.com/pycqa/isort/issues/1290
166 """
167 test_input = '''from typing import TYPE_CHECKING
168
169 # Special imports
170 from special import thing
171
172 if TYPE_CHECKING:
173 # Special imports
174 from special import another_thing
175
176
177 def func():
178 """Docstring"""
179
180 # Special imports
181 from special import something_else
182 return
183 '''
184 assert (
185 isort.code(
186 test_input,
187 import_heading_special="Special imports",
188 known_special=["special"],
189 sections=["FUTURE", "STDLIB", "THIRDPARTY", "SPECIAL", "FIRSTPARTY", "LOCALFOLDER"],
190 )
191 == test_input
192 )
193
194
195 def test_add_imports_shouldnt_make_isort_unusable_issue_1297() -> None:
196 """Test to ensure add imports doesn't cause any unexpected behaviour when combined with check
197 See: https://github.com/pycqa/isort/issues/1297
198 """
199 assert isort.check_code(
200 """from __future__ import unicode_literals
201
202 from os import path
203 """,
204 add_imports={"from __future__ import unicode_literals"},
205 )
206
207
208 def test_no_extra_lines_for_imports_in_functions_issue_1277() -> None:
209 """Test to ensure isort doesn't introduce extra blank lines for imports within function.
210 See: https://github.com/pycqa/isort/issues/1277
211 """
212 test_input = """
213 def main():
214 import time
215
216 import sys
217 """
218 expected_output = """
219 def main():
220 import sys
221 import time
222 """
223 assert isort.code(isort.code(isort.code(test_input))) == expected_output
224
225
226 def test_no_extra_blank_lines_in_methods_issue_1293() -> None:
227 """Test to ensure isort isn't introducing extra lines in methods that contain imports
228 See: https://github.com/pycqa/isort/issues/1293
229 """
230 test_input = """
231
232 class Something(object):
233 def on_email_deleted(self, email):
234 from hyperkitty.tasks import rebuild_thread_cache_new_email
235
236 # update or cleanup thread # noqa: E303 (isort issue)
237 if self.emails.count() == 0:
238 ...
239 """
240 assert isort.code(test_input) == test_input
241 assert isort.code(test_input, lines_after_imports=2) == test_input
242
243
244 def test_form_feed_blank_line_not_removed_issue_2562() -> None:
245 """Ensure isort preserves form feed as a valid blank line."""
246 test_input = 'import sys\n\n\f\nprint("!")\n'
247 assert isort.code(test_input) == 'import sys\n\n\fprint("!")\n'
248 assert isort.code(test_input, lines_after_imports=2) == test_input
249
250 test_input = 'import sys\n\n\n\fprint("!")\n'
251 assert isort.code(test_input) == 'import sys\n\n\fprint("!")\n'
252 assert isort.code(test_input, lines_after_imports=2) == test_input
253
254
255 def test_force_single_line_shouldnt_remove_preceding_comment_lines_issue_1296() -> None:
256 """Tests to ensure force_single_line setting doesn't result in lost comments.
257 See: https://github.com/pycqa/isort/issues/1296
258 """
259 test_input = """
260 # A comment
261 # A comment
262
263 # Oh no, I'm gone
264 from moo import foo
265 """
266 # assert isort.code(test_input) == test_input
267 assert isort.code(test_input, force_single_line=True) == test_input
268
269
270 def test_ensure_new_line_before_comments_mixed_with_ensure_newline_before_comments_1295() -> None:
271 """Tests to ensure that the black profile can be used in conjunction with
272 force_sort_within_sections.
273
274 See: https://github.com/pycqa/isort/issues/1295
275 """
276 test_input = """
277 from openzwave.group import ZWaveGroup
278 from openzwave.network import ZWaveNetwork
279
280 # pylint: disable=import-error
281 from openzwave.option import ZWaveOption
282 """
283 assert isort.code(test_input, profile="black") == test_input
284 assert isort.code(test_input, profile="black", force_sort_within_sections=True) == test_input
285
286
287 def test_trailing_comma_doesnt_introduce_broken_code_with_comment_and_wrap_issue_1302() -> None:
288 """Tests to assert the combination of include_trailing_comma and a wrapped line doesn't break.
289 See: https://github.com/pycqa/isort/issues/1302.
290 """
291 assert (
292 isort.code(
293 """
294 from somewhere import very_very_very_very_very_very_long_symbol # some comment
295 """,
296 line_length=50,
297 include_trailing_comma=True,
298 )
299 == """
300 from somewhere import \\
301 very_very_very_very_very_very_long_symbol # some comment
302 """
303 )
304
305
306 def test_ensure_sre_parse_is_identified_as_stdlib_issue_1304() -> None:
307 """Ensure sre_parse is identified as STDLIB.
308 See: https://github.com/pycqa/isort/issues/1304.
309 """
310 assert isort.place_module("sre_parse") == isort.place_module("sre") == isort.sections.STDLIB
311
312
313 def test_add_imports_shouldnt_move_lower_comments_issue_1300() -> None:
314 """Ensure add_imports doesn't move comments immediately below imports.
315 See:: https://github.com/pycqa/isort/issues/1300.
316 """
317 test_input = """from __future__ import unicode_literals
318
319 from os import path
320
321 # A comment for a constant
322 ANSWER = 42
323 """
324 assert isort.code(test_input, add_imports=["from os import path"]) == test_input
325
326
327 def test_windows_newline_issue_1277() -> None:
328 """Test to ensure windows new lines are correctly handled within indented scopes.
329 See: https://github.com/pycqa/isort/issues/1277
330 """
331 assert (
332 isort.code("\ndef main():\r\n import time\r\n\n import sys\r\n")
333 == "\ndef main():\r\n import sys\r\n import time\r\n"
334 )
335
336
337 def test_windows_newline_issue_1278() -> None:
338 """Test to ensure windows new lines are correctly handled within indented scopes.
339 See: https://github.com/pycqa/isort/issues/1278
340 """
341 assert isort.check_code(
342 "\ntry:\r\n import datadog_agent\r\n\r\n "
343 "from ..log import CheckLoggingAdapter, init_logging\r\n\r\n init_logging()\r\n"
344 "except ImportError:\r\n pass\r\n"
345 )
346
347
348 def test_check_never_passes_with_indented_headings_issue_1301() -> None:
349 """Test to ensure that test can pass even when there are indented headings.
350 See: https://github.com/pycqa/isort/issues/1301
351 """
352 assert isort.check_code(
353 """
354 try:
355 # stdlib
356 import logging
357 from os import abc, path
358 except ImportError:
359 pass
360 """,
361 import_heading_stdlib="stdlib",
362 )
363
364
365 def test_isort_shouldnt_fail_on_long_from_with_dot_issue_1190() -> None:
366 """Test to ensure that isort will correctly handle formatting a long from import that contains
367 a dot.
368 See: https://github.com/pycqa/isort/issues/1190
369 """
370 assert (
371 isort.code(
372 """
373 from this_is_a_very_long_import_statement.that_will_occur_across_two_lines\\
374 .when_the_line_length.is_only_seventynine_chars import (
375 function1,
376 function2,
377 )
378 """,
379 line_length=79,
380 multi_line_output=3,
381 )
382 == """
383 from this_is_a_very_long_import_statement.that_will_occur_across_two_lines"""
384 """.when_the_line_length.is_only_seventynine_chars import (
385 function1,
386 function2
387 )
388 """
389 )
390
391
392 def test_isort_shouldnt_add_extra_new_line_when_fass_and_n_issue_1315() -> None:
393 """Test to ensure isort doesn't add a second extra new line when combining --fss and -n options.
394 See: https://github.com/pycqa/isort/issues/1315
395 """
396 assert isort.check_code(
397 """import sys
398
399 # Comment canary
400 from . import foo
401 """,
402 ensure_newline_before_comments=True, # -n
403 force_sort_within_sections=True, # -fss
404 show_diff=True, # for better debugging in the case the test case fails.
405 )
406
407 assert (
408 isort.code(
409 """
410 from . import foo
411 # Comment canary
412 from .. import foo
413 """,
414 ensure_newline_before_comments=True,
415 force_sort_within_sections=True,
416 )
417 == """
418 from . import foo
419
420 # Comment canary
421 from .. import foo
422 """
423 )
424
425
426 def test_isort_doesnt_rewrite_import_with_dot_to_from_import_issue_1280() -> None:
427 """Test to ensure isort doesn't rewrite imports in the from of import y.x into from y import x.
428 This is because they are not technically fully equivalent to each other and can introduce broken
429 behaviour.
430 See: https://github.com/pycqa/isort/issues/1280
431 """
432 assert isort.check_code(
433 """
434 import test.module
435 import test.module as m
436 from test import module
437 from test import module as m
438 """,
439 show_diff=True,
440 )
441
442
443 def test_isort_shouldnt_introduce_extra_lines_with_fass_issue_1322() -> None:
444 """Tests to ensure isort doesn't introduce extra lines when used with fass option.
445 See: https://github.com/pycqa/isort/issues/1322
446 """
447 assert (
448 isort.code(
449 """
450 import logging
451
452 # Comment canary
453 from foo import bar
454 import quux
455 """,
456 force_sort_within_sections=True,
457 ensure_newline_before_comments=True,
458 )
459 == """
460 import logging
461
462 # Comment canary
463 from foo import bar
464 import quux
465 """
466 )
467
468
469 def test_comments_should_cause_wrapping_on_long_lines_black_mode_issue_1219() -> None:
470 """Tests to ensure if isort encounters a single import line which is made too long with a comment
471 it is wrapped when using black profile.
472 See: https://github.com/pycqa/isort/issues/1219
473 """
474 assert isort.check_code(
475 """
476 from many_stop_words import (
477 get_stop_words as get_base_stopwords, # extended list of stop words, also for en
478 )
479 """,
480 show_diff=True,
481 profile="black",
482 )
483
484
485 def test_comment_blocks_should_stay_associated_without_extra_lines_issue_1156() -> None:
486 """Tests to ensure isort doesn't add an extra line when there are large import blocks
487 or otherwise warp the intent.
488 See: https://github.com/pycqa/isort/issues/1156
489 """
490 assert (
491 isort.code(
492 """from top_level_ignored import config # isort:skip
493 ####################################
494 # COMMENT BLOCK SEPARATING THESE #
495 ####################################
496 from ast import excepthandler
497 import logging
498 """
499 )
500 == """from top_level_ignored import config # isort:skip
501 import logging
502 ####################################
503 # COMMENT BLOCK SEPARATING THESE #
504 ####################################
505 from ast import excepthandler
506 """
507 )
508
509
510 def test_comment_shouldnt_be_duplicated_with_fass_enabled_issue_1329() -> None:
511 """Tests to ensure isort doesn't duplicate comments when imports occur with comment on top,
512 immediately after large comment blocks.
513 See: https://github.com/pycqa/isort/pull/1329/files.
514 """
515 assert isort.check_code(
516 """'''
517 Multi-line docstring
518 '''
519 # Comment for A.
520 import a
521 # Comment for B - not A!
522 import b
523 """,
524 force_sort_within_sections=True,
525 show_diff=True,
526 )
527
528
529 def test_wrap_mode_equal_to_line_length_with_indendet_imports_issue_1333() -> None:
530 assert isort.check_code(
531 """
532 import a
533 import b
534
535
536 def function():
537 import a as b
538 import c as d
539 """,
540 line_length=17,
541 wrap_length=17,
542 show_diff=True,
543 )
544
545
546 def test_isort_skipped_nested_imports_issue_1339() -> None:
547 """Ensure `isort:skip are honored in nested imports.
548 See: https://github.com/pycqa/isort/issues/1339.
549 """
550 assert isort.check_code(
551 """
552 def import_test():
553 from os ( # isort:skip
554 import path
555 )
556 """,
557 show_diff=True,
558 )
559
560
561 def test_windows_diff_too_large_misrepresentative_issue_1348(test_path: Path) -> None:
562 """Ensure isort handles windows files correctly when it come to producing a diff with --diff.
563 See: https://github.com/pycqa/isort/issues/1348
564 """
565 diff_output = StringIO()
566 isort.file(test_path / "example_crlf_file.py", show_diff=diff_output)
567 diff_output.seek(0)
568 assert diff_output.read().endswith(
569 "-1,5 +1,5 @@\n+import a\r\n import b\r\n-import a\r\n \r\n \r\n def func():\r\n"
570 )
571
572
573 def test_combine_as_does_not_lose_comments_issue_1321() -> None:
574 """Test to ensure isort doesn't lose comments when --combine-as is used.
575 See: https://github.com/pycqa/isort/issues/1321
576 """
577 test_input = """
578 from foo import * # noqa
579 from foo import bar as quux # other
580 from foo import x as a # noqa
581
582 import operator as op # op comment
583 import datetime as dtime # dtime comment
584
585 from datetime import date as d # dcomm
586 from datetime import datetime as dt # dtcomm
587 """
588
589 expected_output = """
590 import datetime as dtime # dtime comment
591 import operator as op # op comment
592 from datetime import date as d, datetime as dt # dcomm; dtcomm
593
594 from foo import * # noqa
595 from foo import bar as quux, x as a # other; noqa
596 """
597
598 assert isort.code(test_input, combine_as_imports=True) == expected_output
599
600
601 def test_combine_as_does_not_lose_comments_issue_1381() -> None:
602 """Test to ensure isort doesn't lose comments when --combine-as is used.
603 See: https://github.com/pycqa/isort/issues/1381
604 """
605 test_input = """
606 from smtplib import SMTPConnectError, SMTPNotSupportedError # important comment
607 """
608 assert "# important comment" in isort.code(test_input, combine_as_imports=True)
609
610 test_input = """
611 from appsettings import AppSettings, ObjectSetting, StringSetting # type: ignore
612 """
613 assert "# type: ignore" in isort.code(test_input, combine_as_imports=True)
614
615
616 def test_incorrect_grouping_when_comments_issue_1396() -> None:
617 """Test to ensure isort groups import correct independent of the comments present.
618 See: https://github.com/pycqa/isort/issues/1396
619 """
620 assert (
621 isort.code(
622 """from django.shortcuts import render
623 from apps.profiler.models import Project
624 from django.contrib.auth.decorators import login_required
625 from django.views.generic import (
626 # ListView,
627 # DetailView,
628 TemplateView,
629 # CreateView,
630 # View
631 )
632 """,
633 line_length=88,
634 known_first_party=["apps"],
635 known_django=["django"],
636 sections=["FUTURE", "STDLIB", "DJANGO", "THIRDPARTY", "FIRSTPARTY", "LOCALFOLDER"],
637 )
638 == """from django.contrib.auth.decorators import login_required
639 from django.shortcuts import render
640 from django.views.generic import \\
641 TemplateView # ListView,; DetailView,; CreateView,; View
642
643 from apps.profiler.models import Project
644 """
645 )
646 assert (
647 isort.code(
648 """from django.contrib.auth.decorators import login_required
649 from django.shortcuts import render
650
651 from apps.profiler.models import Project
652
653 from django.views.generic import ( # ListView,; DetailView,; CreateView,; View
654 TemplateView,
655 )
656 """,
657 line_length=88,
658 known_first_party=["apps"],
659 known_django=["django"],
660 sections=["FUTURE", "STDLIB", "DJANGO", "THIRDPARTY", "FIRSTPARTY", "LOCALFOLDER"],
661 include_trailing_comma=True,
662 multi_line_output=3,
663 force_grid_wrap=0,
664 use_parentheses=True,
665 ensure_newline_before_comments=True,
666 )
667 == """from django.contrib.auth.decorators import login_required
668 from django.shortcuts import render
669 from django.views.generic import ( # ListView,; DetailView,; CreateView,; View
670 TemplateView,
671 )
672
673 from apps.profiler.models import Project
674 """
675 )
676
677
678 def test_reverse_relative_combined_with_force_sort_within_sections_issue_1395() -> None:
679 """Test to ensure reverse relative combines well with other common isort settings.
680 See: https://github.com/pycqa/isort/issues/1395.
681 """
682 assert isort.check_code(
683 """from .fileA import a_var
684 from ..fileB import b_var
685 """,
686 show_diff=True,
687 reverse_relative=True,
688 force_sort_within_sections=True,
689 order_by_type=False,
690 case_sensitive=False,
691 multi_line_output=5,
692 sections=["FUTURE", "STDLIB", "THIRDPARTY", "FIRSTPARTY", "APPLICATION", "LOCALFOLDER"],
693 lines_after_imports=2,
694 no_lines_before="LOCALFOLDER",
695 )
696
697
698 def test_isort_should_be_able_to_add_independent_of_doc_string_placement_issue_1420() -> None:
699 """isort should be able to know when an import requested to be added is successfully added,
700 independent of where the top doc string is located.
701 See: https://github.com/PyCQA/isort/issues/1420
702 """
703 assert isort.check_code(
704 '''"""module docstring"""
705
706 import os
707 ''',
708 show_diff=True,
709 add_imports=["os"],
710 )
711
712
713 def test_force_single_line_should_not_influence_order_of_star_import() -> None:
714 """isort should never move comments to different import statement.
715
716 Originally reported as an issue with moving comments across import statements,
717 see: https://github.com/PyCQA/isort/issues/1427
718 """
719 expected = """from package import * # noqa
720 from package import CONSTANT
721 """
722 assert isort.check_code(
723 expected,
724 force_single_line=False,
725 show_diff=True,
726 )
727 assert isort.check_code(
728 expected,
729 force_single_line=True,
730 show_diff=True,
731 )
732 assert (
733 isort.code(
734 """from package import CONSTANT
735 from package import * # noqa
736 """,
737 force_single_line=False,
738 )
739 == expected
740 )
741 assert (
742 isort.code(
743 """from package import CONSTANT
744 from package import * # noqa
745 """,
746 force_single_line=True,
747 )
748 == expected
749 )
750
751
752 def test_isort_doesnt_misplace_comments_issue_1431() -> None:
753 """Test to ensure isort won't misplace comments.
754 See: https://github.com/PyCQA/isort/issues/1431
755 """
756 input_text = """from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import (
757 MyLovelyCompanyTeamProjectComponent, # NOT DRY
758 )
759 from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import (
760 MyLovelyCompanyTeamProjectComponent as component, # DRY
761 )
762 """
763 assert isort.code(input_text, profile="black") == input_text
764
765
766 def test_isort_doesnt_misplace_add_import_issue_1445() -> None:
767 """Test to ensure isort won't misplace an added import depending on docstring position
768 See: https://github.com/PyCQA/isort/issues/1445
769 """
770 assert (
771 isort.code(
772 '''#!/usr/bin/env python
773
774 """module docstring"""
775 ''',
776 add_imports=["import os"],
777 )
778 == '''#!/usr/bin/env python
779
780 """module docstring"""
781
782 import os
783 '''
784 )
785
786 assert isort.check_code(
787 '''#!/usr/bin/env python
788
789 """module docstring"""
790
791 import os
792 ''',
793 add_imports=["import os"],
794 show_diff=True,
795 )
796
797
798 def test_isort_doesnt_mangle_code_when_adding_imports_issue_1444() -> None:
799 """isort should NEVER mangle code. This particularly nasty and easy to reproduce bug,
800 caused isort to produce invalid code just by adding a single import statement depending
801 on comment placement.
802 See: https://github.com/PyCQA/isort/issues/1444
803 """
804 assert (
805 isort.code(
806 '''
807
808 """module docstring"""
809 ''',
810 add_imports=["import os"],
811 )
812 == '''
813
814 """module docstring"""
815
816 import os
817 '''
818 )
819
820
821 def test_isort_float_to_top_with_sort_on_off_tests() -> None:
822 """Characterization test for current behaviour of float-to-top on isort: on/off sections.
823 - imports in isort:off sections stay where they are
824 - imports in isort:on sections float up, but to the top of the isort:on section (not the
825 top of the file)"""
826 assert (
827 isort.code(
828 """
829 def foo():
830 pass
831
832 import a
833
834 # isort: off
835 import stays_in_section
836
837 x = 1
838
839 import stays_in_place
840
841 # isort: on
842
843 def bar():
844 pass
845
846 import floats_to_top_of_section
847
848 def baz():
849 pass
850 """,
851 float_to_top=True,
852 )
853 == """import a
854
855
856 def foo():
857 pass
858
859 # isort: off
860 import stays_in_section
861
862 x = 1
863
864 import stays_in_place
865
866 # isort: on
867 import floats_to_top_of_section
868
869
870 def bar():
871 pass
872
873
874 def baz():
875 pass
876 """
877 )
878
879 to_sort = """# isort: off
880
881 def foo():
882 pass
883
884 import stays_in_place
885 import no_float_to_to_top
886 import no_ordering
887
888 def bar():
889 pass
890 """
891
892 # No changes if isort is off
893 assert isort.code(to_sort, float_to_top=True) == to_sort
894
895
896 def test_isort_float_to_top_respects_isort_off_with_crlf_issue_2528() -> None:
897 to_sort = """
898 import b
899 import a
900
901 # isort: off
902 pytest.importorskip('cattrs')
903
904 import z
905 import y
906 """
907
908 assert (
909 isort.code(to_sort, float_to_top=True)
910 == """
911 import a
912 import b
913
914 # isort: off
915 pytest.importorskip('cattrs')
916
917 import z
918 import y
919 """
920 )
921
922
923 def test_isort_doesnt_float_to_top_correctly_when_imports_not_at_top_issue_1382() -> None:
924 """isort should float existing imports to the top, if they are currently below the top.
925 See: https://github.com/PyCQA/isort/issues/1382
926 """
927 assert (
928 isort.code(
929 """
930 def foo():
931 pass
932
933 import a
934
935 def bar():
936 pass
937 """,
938 float_to_top=True,
939 )
940 == """import a
941
942
943 def foo():
944 pass
945
946
947 def bar():
948 pass
949 """
950 )
951
952 assert (
953 isort.code(
954 """
955
956
957
958
959
960
961 def foo():
962 pass
963
964 import a
965
966 def bar():
967 pass
968 """,
969 float_to_top=True,
970 )
971 == """import a
972
973
974 def foo():
975 pass
976
977
978 def bar():
979 pass
980 """
981 )
982
983 assert (
984 isort.code(
985 '''"""My comment
986
987
988 """
989 def foo():
990 pass
991
992 import a
993
994 def bar():
995 pass
996 ''',
997 float_to_top=True,
998 )
999 == '''"""My comment
1000
1001
1002 """
1003 import a
1004
1005
1006 def foo():
1007 pass
1008
1009
1010 def bar():
1011 pass
1012 '''
1013 )
1014
1015 assert (
1016 isort.code(
1017 '''
1018 """My comment
1019
1020
1021 """
1022 def foo():
1023 pass
1024
1025 import a
1026
1027 def bar():
1028 pass
1029 ''',
1030 float_to_top=True,
1031 )
1032 == '''
1033 """My comment
1034
1035
1036 """
1037 import a
1038
1039
1040 def foo():
1041 pass
1042
1043
1044 def bar():
1045 pass
1046 '''
1047 )
1048
1049 assert (
1050 isort.code(
1051 '''#!/usr/bin/env bash
1052 """My comment
1053
1054
1055 """
1056 def foo():
1057 pass
1058
1059 import a
1060
1061 def bar():
1062 pass
1063 ''',
1064 float_to_top=True,
1065 )
1066 == '''#!/usr/bin/env bash
1067 """My comment
1068
1069
1070 """
1071 import a
1072
1073
1074 def foo():
1075 pass
1076
1077
1078 def bar():
1079 pass
1080 '''
1081 )
1082
1083 assert (
1084 isort.code(
1085 '''#!/usr/bin/env bash
1086
1087 """My comment
1088
1089
1090 """
1091 def foo():
1092 pass
1093
1094 import a
1095
1096 def bar():
1097 pass
1098 ''',
1099 float_to_top=True,
1100 )
1101 == '''#!/usr/bin/env bash
1102
1103 """My comment
1104
1105
1106 """
1107 import a
1108
1109
1110 def foo():
1111 pass
1112
1113
1114 def bar():
1115 pass
1116 '''
1117 )
1118
1119
1120 def test_empty_float_to_top_shouldnt_error_issue_1453() -> None:
1121 """isort shouldn't error when float to top is set with a mostly empty file"""
1122 assert isort.check_code(
1123 """
1124 """,
1125 show_diff=True,
1126 float_to_top=True,
1127 )
1128 assert isort.check_code(
1129 """
1130 """,
1131 show_diff=True,
1132 )
1133
1134
1135 def test_import_sorting_shouldnt_be_endless_with_headers_issue_1454() -> None:
1136 """isort should never enter an endless sorting loop.
1137 See: https://github.com/PyCQA/isort/issues/1454
1138 """
1139 assert isort.check_code(
1140 """
1141
1142 # standard library imports
1143 import sys
1144
1145 try:
1146 # Comment about local lib
1147 # related third party imports
1148 from local_lib import stuff
1149 except ImportError as e:
1150 pass
1151 """,
1152 known_third_party=["local_lib"],
1153 import_heading_thirdparty="related third party imports",
1154 show_diff=True,
1155 )
1156
1157
1158 def test_isort_should_leave_non_import_from_lines_alone_issue_1488() -> None:
1159 """isort should never mangle non-import from statements.
1160 See: https://github.com/PyCQA/isort/issues/1488
1161 """
1162 raise_from_should_be_ignored = """
1163 raise SomeException("Blah") \\
1164 from exceptionsInfo.popitem()[1]
1165 """
1166 assert isort.check_code(raise_from_should_be_ignored, show_diff=True)
1167
1168 yield_from_should_be_ignored = """
1169 def generator_function():
1170 yield \\
1171 from other_function()[1]
1172 """
1173 assert isort.check_code(yield_from_should_be_ignored, show_diff=True)
1174
1175 wont_ignore_comment_contiuation = """
1176 # one
1177
1178 # two
1179
1180
1181 def function():
1182 # three \\
1183 import b
1184 import a
1185 """
1186 assert (
1187 isort.code(wont_ignore_comment_contiuation)
1188 == """
1189 # one
1190
1191 # two
1192
1193
1194 def function():
1195 # three \\
1196 import a
1197 import b
1198 """
1199 )
1200
1201 will_ignore_if_non_comment_continuation = """
1202 # one
1203
1204 # two
1205
1206
1207 def function():
1208 raise \\
1209 import b
1210 import a
1211 """
1212 assert isort.check_code(will_ignore_if_non_comment_continuation, show_diff=True)
1213
1214 yield_from_parens_should_be_ignored = """
1215 def generator_function():
1216 (
1217 yield
1218 from other_function()[1]
1219 )
1220 """
1221 assert isort.check_code(yield_from_parens_should_be_ignored, show_diff=True)
1222
1223 yield_from_lots_of_parens_and_space_should_be_ignored = """
1224 def generator_function():
1225 (
1226 (
1227 ((((
1228 (((((
1229 ((
1230 (((
1231 yield
1232
1233
1234
1235 from other_function()[1]
1236 )))))))))))))
1237 )))
1238 """
1239 assert isort.check_code(yield_from_lots_of_parens_and_space_should_be_ignored, show_diff=True)
1240
1241 yield_from_should_be_ignored_when_following_import_statement = """
1242 def generator_function():
1243 import os
1244
1245 yield \\
1246 from other_function()[1]
1247 """
1248 assert isort.check_code(
1249 yield_from_should_be_ignored_when_following_import_statement, show_diff=True
1250 )
1251
1252 yield_at_file_end_ignored = """
1253 def generator_function():
1254 (
1255 (
1256 ((((
1257 (((((
1258 ((
1259 (((
1260 yield
1261 """
1262 assert isort.check_code(yield_at_file_end_ignored, show_diff=True)
1263
1264 raise_at_file_end_ignored = """
1265 def generator_function():
1266 (
1267 (
1268 ((((
1269 (((((
1270 ((
1271 (((
1272 raise (
1273 """
1274 assert isort.check_code(raise_at_file_end_ignored, show_diff=True)
1275
1276 raise_from_at_file_end_ignored = """
1277 def generator_function():
1278 (
1279 (
1280 ((((
1281 (((((
1282 ((
1283 (((
1284 raise \\
1285 from \\
1286 """
1287 assert isort.check_code(raise_from_at_file_end_ignored, show_diff=True)
1288
1289
1290 def test_isort_float_to_top_correctly_identifies_single_line_comments_1499() -> None:
1291 """Test to ensure isort correctly handles the case where float to top is used
1292 to push imports to the top and the top comment is a multiline type but only
1293 one line.
1294 See: https://github.com/PyCQA/isort/issues/1499
1295 """
1296 assert isort.code(
1297 '''#!/usr/bin/env bash
1298 """My comment"""
1299 def foo():
1300 pass
1301
1302 import a
1303
1304 def bar():
1305 pass
1306 ''',
1307 float_to_top=True,
1308 ) == (
1309 '''#!/usr/bin/env bash
1310 """My comment"""
1311 import a
1312
1313
1314 def foo():
1315 pass
1316
1317
1318 def bar():
1319 pass
1320 '''
1321 )
1322 assert isort.code(
1323 """#!/usr/bin/env bash
1324 '''My comment'''
1325 def foo():
1326 pass
1327
1328 import a
1329
1330 def bar():
1331 pass
1332 """,
1333 float_to_top=True,
1334 ) == (
1335 """#!/usr/bin/env bash
1336 '''My comment'''
1337 import a
1338
1339
1340 def foo():
1341 pass
1342
1343
1344 def bar():
1345 pass
1346 """
1347 )
1348
1349 assert isort.check_code(
1350 """#!/usr/bin/env bash
1351 '''My comment'''
1352 import a
1353
1354 x = 1
1355 """,
1356 float_to_top=True,
1357 show_diff=True,
1358 )
1359
1360
1361 def test_isort_shouldnt_mangle_from_multi_line_string_issue_1507() -> None:
1362 """isort was seen mangling lines that happened to contain the word from after
1363 a yield happened to be in a file. Clearly this shouldn't happen.
1364 See: https://github.com/PyCQA/isort/issues/1507.
1365 """
1366 assert isort.check_code(
1367 '''
1368 def a():
1369 yield f(
1370 """
1371 select %s from (values %%s) as t(%s)
1372 """
1373 )
1374
1375 def b():
1376 return (
1377 """
1378 select name
1379 from foo
1380 """
1381 % main_table
1382 )
1383
1384 def c():
1385 query = (
1386 """
1387 select {keys}
1388 from (values %s) as t(id)
1389 """
1390 )
1391
1392 def d():
1393 query = f"""select t.id
1394 from {table} t
1395 {extra}"""
1396 ''',
1397 show_diff=True,
1398 )
1399
1400
1401 def test_isort_should_keep_all_as_and_non_as_imports_issue_1523() -> None:
1402 """isort should keep as and non-as imports of the same path that happen to exist within the
1403 same statement.
1404 See: https://github.com/PyCQA/isort/issues/1523.
1405 """
1406 assert isort.check_code(
1407 """
1408 from selenium.webdriver import Remote, Remote as Driver
1409 """,
1410 show_diff=True,
1411 combine_as_imports=True,
1412 )
1413
1414
1415 def test_isort_shouldnt_introduce_syntax_error_issue_1539() -> None:
1416 """isort should NEVER introduce syntax errors.
1417 In 5.5.4 some strings that contained a line starting with from could lead to no empty paren.
1418 See: https://github.com/PyCQA/isort/issues/1539.
1419 """
1420 assert isort.check_code(
1421 '''"""Foobar
1422 from {}""".format(
1423 "bar",
1424 )
1425 ''',
1426 show_diff=True,
1427 )
1428 assert isort.check_code(
1429 '''"""Foobar
1430 import {}""".format(
1431 "bar",
1432 )
1433 ''',
1434 show_diff=True,
1435 )
1436 assert (
1437 isort.code(
1438 '''"""Foobar
1439 from {}"""
1440 from a import b, a
1441 ''',
1442 )
1443 == '''"""Foobar
1444 from {}"""
1445 from a import a, b
1446 '''
1447 )
1448 assert (
1449 isort.code(
1450 '''"""Foobar
1451 from {}"""
1452 import b
1453 import a
1454 ''',
1455 )
1456 == '''"""Foobar
1457 from {}"""
1458 import a
1459 import b
1460 '''
1461 )
1462
1463
1464 def test_isort_shouldnt_split_skip_issue_1548() -> None:
1465 """Ensure isort doesn't add a spurious new line if isort: skip is combined with float to top.
1466 See: https://github.com/PyCQA/isort/issues/1548.
1467 """
1468 assert isort.check_code(
1469 """from tools.dependency_pruning.prune_dependencies import ( # isort:skip
1470 prune_dependencies,
1471 )
1472 """,
1473 show_diff=True,
1474 profile="black",
1475 float_to_top=True,
1476 )
1477 assert isort.check_code(
1478 """from tools.dependency_pruning.prune_dependencies import ( # isort:skip
1479 prune_dependencies,
1480 )
1481 import a
1482 import b
1483 """,
1484 show_diff=True,
1485 profile="black",
1486 float_to_top=True,
1487 )
1488 assert isort.check_code(
1489 """from tools.dependency_pruning.prune_dependencies import # isort:skip
1490 import a
1491 import b
1492 """,
1493 show_diff=True,
1494 float_to_top=True,
1495 )
1496 assert isort.check_code(
1497 """from tools.dependency_pruning.prune_dependencies import ( # isort:skip
1498 a
1499 )
1500 import b
1501 """,
1502 show_diff=True,
1503 profile="black",
1504 float_to_top=True,
1505 )
1506 assert isort.check_code(
1507 """from tools.dependency_pruning.prune_dependencies import ( # isort:skip
1508 )
1509 """,
1510 show_diff=True,
1511 profile="black",
1512 float_to_top=True,
1513 )
1514 assert isort.check_code(
1515 """from tools.dependency_pruning.prune_dependencies import ( # isort:skip
1516 )""",
1517 show_diff=True,
1518 profile="black",
1519 float_to_top=True,
1520 )
1521 assert (
1522 isort.code(
1523 """from tools.dependency_pruning.prune_dependencies import ( # isort:skip
1524 )
1525 """,
1526 profile="black",
1527 float_to_top=True,
1528 add_imports=["import os"],
1529 )
1530 == """from tools.dependency_pruning.prune_dependencies import ( # isort:skip
1531 )
1532 import os
1533 """
1534 )
1535 assert (
1536 isort.code(
1537 """from tools.dependency_pruning.prune_dependencies import ( # isort:skip
1538 )""",
1539 profile="black",
1540 float_to_top=True,
1541 add_imports=["import os"],
1542 )
1543 == """from tools.dependency_pruning.prune_dependencies import ( # isort:skip
1544 )
1545 import os
1546 """
1547 )
1548
1549
1550 def test_isort_shouldnt_split_skip_issue_1556() -> None:
1551 assert isort.check_code(
1552 """
1553 from tools.dependency_pruning.prune_dependencies import ( # isort:skip
1554 prune_dependencies,
1555 )
1556 from tools.developer_pruning.prune_developers import ( # isort:skip
1557 prune_developers,
1558 )
1559 """,
1560 show_diff=True,
1561 profile="black",
1562 float_to_top=True,
1563 )
1564 assert isort.check_code(
1565 """
1566 from tools.dependency_pruning.prune_dependencies import ( # isort:skip
1567 prune_dependencies,
1568 )
1569 from tools.developer_pruning.prune_developers import x # isort:skip
1570 """,
1571 show_diff=True,
1572 profile="black",
1573 float_to_top=True,
1574 )
1575
1576
1577 def test_isort_losing_imports_vertical_prefix_from_module_import_wrap_mode_issue_1542() -> None:
1578 """Ensure isort doesn't lose imports when a comment is combined with an import and
1579 wrap mode VERTICAL_PREFIX_FROM_MODULE_IMPORT is used.
1580 See: https://github.com/PyCQA/isort/issues/1542.
1581 """
1582 assert (
1583 isort.code(
1584 """
1585 from xxxxxxxxxxxxxxxx import AAAAAAAAAA, BBBBBBBBBB
1586 from xxxxxxxxxxxxxxxx import CCCCCCCCC, DDDDDDDDD # xxxxxxxxxxxxxxxxxx
1587
1588 print(CCCCCCCCC)
1589 """,
1590 multi_line_output=9,
1591 )
1592 == """
1593 from xxxxxxxxxxxxxxxx import AAAAAAAAAA, BBBBBBBBBB # xxxxxxxxxxxxxxxxxx
1594 from xxxxxxxxxxxxxxxx import CCCCCCCCC, DDDDDDDDD
1595
1596 print(CCCCCCCCC)
1597 """
1598 )
1599
1600 assert isort.check_code(
1601 """
1602 from xxxxxxxxxxxxxxxx import AAAAAAAAAA, BBBBBBBBBB
1603
1604 from xxxxxxxxxxxxxxxx import CCCCCCCCC, DDDDDDDDD # xxxxxxxxxxxxxxxxxx isort: skip
1605
1606 print(CCCCCCCCC)
1607 """,
1608 show_diff=True,
1609 multi_line_output=9,
1610 )
1611
1612
1613 def test_isort_adding_second_comma_issue_1621() -> None:
1614 """Ensure isort doesn't add a second comma when very long comment is present
1615 See: https://github.com/PyCQA/isort/issues/1621.
1616 """
1617 assert isort.check_code(
1618 """from .test import (
1619 TestTestTestTestTestTest2 as TestTestTestTestTestTest1, """
1620 """# Some really long comment bla bla bla bla bla
1621 )
1622 """,
1623 profile="black",
1624 show_diff=True,
1625 )
1626 assert (
1627 isort.code(
1628 """from .test import (
1629 TestTestTestTestTestTest2 as TestTestTestTestTestTest1 """
1630 """# Some really long comment bla bla bla bla bla
1631 )
1632 """,
1633 profile="black",
1634 )
1635 == """from .test import (
1636 TestTestTestTestTestTest2 as TestTestTestTestTestTest1, """
1637 """# Some really long comment bla bla bla bla bla
1638 )
1639 """
1640 )
1641
1642
1643 def test_isort_shouldnt_duplicate_comments_issue_1631() -> None:
1644 assert isort.check_code(
1645 """
1646 import a # a comment
1647 import a as b # b comment
1648 """,
1649 show_diff=True,
1650 )
1651 assert (
1652 isort.code(
1653 """
1654 import a # a comment
1655 import a as a # b comment
1656 """,
1657 remove_redundant_aliases=True,
1658 )
1659 == """
1660 import a # a comment; b comment
1661 """
1662 )
1663
1664
1665 def test_isort_shouldnt_add_extra_new_lines_with_import_heading_issue_1670() -> None:
1666 snippet = """#!/usr/bin/python3 -ttu
1667 # Standard Library
1668 import argparse
1669 import datetime
1670
1671 import attr
1672 import requests
1673
1674
1675 def foo() -> int:
1676 print("Hello world")
1677 return 0
1678
1679
1680 def spam():
1681
1682
1683 # Standard Library
1684 import collections
1685 import logging
1686 """
1687 assert (
1688 isort.code(
1689 snippet,
1690 import_heading_stdlib="Standard Library",
1691 )
1692 == snippet
1693 )
1694
1695
1696 def test_isort_shouldnt_add_extra_line_float_to_top_issue_1667() -> None:
1697 assert isort.check_code(
1698 """
1699 import sys
1700
1701 sys.path.insert(1, 'path/containing/something_else/..')
1702
1703 import something_else # isort:skip
1704
1705 # Some constant
1706 SOME_CONSTANT = 4
1707 """,
1708 show_diff=True,
1709 float_to_top=True,
1710 )
1711
1712
1713 def test_isort_shouldnt_move_noqa_comment_issue_1594() -> None:
1714 assert (
1715 isort.code(
1716 """
1717 from .test import TestTestTestTestTestTest1 # noqa: F401
1718 from .test import TestTestTestTestTestTest2, TestTestTestTestTestTest3, """
1719 """TestTestTestTestTestTest4, TestTestTestTestTestTest5 # noqa: F401
1720 """,
1721 profile="black",
1722 )
1723 == """
1724 from .test import TestTestTestTestTestTest1 # noqa: F401
1725 from .test import ( # noqa: F401
1726 TestTestTestTestTestTest2,
1727 TestTestTestTestTestTest3,
1728 TestTestTestTestTestTest4,
1729 TestTestTestTestTestTest5,
1730 )
1731 """
1732 )
1733
1734
1735 def test_isort_correctly_handles_unix_vs_linux_newlines_issue_1566() -> None:
1736 import_statement = (
1737 "from impacket.smb3structs import (\n"
1738 "SMB2_CREATE, SMB2_FLAGS_DFS_OPERATIONS, SMB2_IL_IMPERSONATION, "
1739 "SMB2_OPLOCK_LEVEL_NONE, SMB2Create,"
1740 "\nSMB2Create_Response, SMB2Packet)\n"
1741 )
1742 assert isort.code(import_statement, line_length=120) == isort.code(
1743 import_statement.replace("\n", "\r\n"), line_length=120
1744 ).replace("\r\n", "\n")
1745
1746
1747 def test_isort_treats_src_paths_same_as_from_config_as_cli_issue_1711(tmp_path: Path) -> None:
1748 assert isort.check_code(
1749 """
1750 import mymodule
1751 import sqlalchemy
1752 """,
1753 show_diff=True,
1754 )
1755
1756 config_file = tmp_path / ".isort.cfg"
1757 config_file.write_text(
1758 """
1759 [settings]
1760 src_paths=
1761 api
1762 """
1763 )
1764 api_dir = tmp_path / "api"
1765 api_dir.mkdir()
1766 (api_dir / "mymodule.py").write_text("# comment")
1767
1768 config = isort.settings.Config(str(config_file))
1769 assert isort.check_code(
1770 """
1771 import sqlalchemy
1772
1773 import mymodule
1774 """,
1775 show_diff=True,
1776 config=config,
1777 )
1778
1779
1780 def test_isort_should_never_quietly_remove_imports_in_hanging_line_mode_issue_1741() -> None:
1781 assert (
1782 isort.code(
1783 """
1784 from src import abcd, qwerty, efg, xyz # some comment
1785 """,
1786 line_length=50,
1787 multi_line_output=2,
1788 )
1789 == """
1790 from src import abcd, efg, qwerty, xyz \\
1791 # some comment
1792 """
1793 )
1794 assert (
1795 isort.code(
1796 """
1797 from src import abcd, qwerty, efg, xyz # some comment
1798 """,
1799 line_length=54,
1800 multi_line_output=2,
1801 )
1802 == """
1803 from src import abcd, efg, qwerty, xyz # some comment
1804 """
1805 )
1806 assert (
1807 isort.code(
1808 """
1809 from src import abcd, qwerty, efg, xyz # some comment
1810 """,
1811 line_length=53,
1812 multi_line_output=2,
1813 )
1814 == """
1815 from src import abcd, efg, qwerty, xyz \\
1816 # some comment
1817 """
1818 )
1819 assert (
1820 isort.code(
1821 """
1822 from src import abcd, qwerty, efg, xyz # some comment
1823 """,
1824 line_length=30,
1825 multi_line_output=2,
1826 )
1827 == """
1828 from src import abcd, efg, \\
1829 qwerty, xyz \\
1830 # some comment
1831 """
1832 )
1833
1834
1835 @pytest.mark.parametrize("multi_line_output", range(12))
1836 def test_isort_should_never_quietly_remove_imports_in_any_hangin_mode_issue_1741(
1837 multi_line_output: int,
1838 ) -> None:
1839 sorted_code = isort.code(
1840 """
1841 from src import abcd, qwerty, efg, xyz # some comment
1842 """,
1843 line_length=30,
1844 multi_line_output=multi_line_output,
1845 )
1846 assert "abcd" in sorted_code
1847 assert "qwerty" in sorted_code
1848 assert "efg" in sorted_code
1849 assert "xyz" in sorted_code
1850
1851
1852 def test_isort_should_keep_multi_noqa_with_star_issue_1744() -> None:
1853 assert isort.check_code(
1854 """
1855 from typing import * # noqa
1856 from typing import IO, BinaryIO, Union # noqa
1857 """,
1858 show_diff=True,
1859 )
1860 assert isort.check_code(
1861 """
1862 from typing import * # noqa 1
1863 from typing import IO, BinaryIO, Union # noqa 2
1864 """,
1865 show_diff=True,
1866 )
1867 assert isort.check_code(
1868 """
1869 from typing import * # noqa
1870 from typing import IO, BinaryIO, Union
1871 """,
1872 show_diff=True,
1873 )
1874 assert isort.check_code(
1875 """
1876 from typing import *
1877 from typing import IO, BinaryIO, Union # noqa
1878 """,
1879 show_diff=True,
1880 )
1881 assert (
1882 isort.code(
1883 """
1884 from typing import * # hi
1885 from typing import IO, BinaryIO, Union # noqa
1886 """,
1887 combine_star=True,
1888 )
1889 == """
1890 from typing import * # noqa; hi
1891 """
1892 )
1893 assert (
1894 isort.code(
1895 """
1896 from typing import * # noqa
1897 from typing import IO, BinaryIO, Union # noqa
1898 """,
1899 combine_star=True,
1900 )
1901 == """
1902 from typing import * # noqa
1903 """
1904 )
1905
1906
1907 def test_isort_should_keep_multiple_noqa_comments_force_single_line_mode_issue_1721() -> None:
1908 assert isort.check_code(
1909 """
1910 from some_very_long_filename_to_import_from_that_causes_a_too_long_import_row import ( # noqa: E501
1911 CONSTANT_1,
1912 )
1913 from some_very_long_filename_to_import_from_that_causes_a_too_long_import_row import ( # noqa: E501
1914 CONSTANT_2,
1915 )
1916 """,
1917 show_diff=True,
1918 profile="black",
1919 force_single_line=True,
1920 )
1921
1922
1923 def test_isort_should_only_add_imports_to_valid_location_issue_1769() -> None:
1924 assert (
1925 isort.code(
1926 '''v = """
1927 """.split(
1928 "\n"
1929 )
1930 ''',
1931 add_imports=["from __future__ import annotations"],
1932 )
1933 == '''from __future__ import annotations
1934
1935 v = """
1936 """.split(
1937 "\n"
1938 )
1939 '''
1940 )
1941 assert (
1942 isort.code(
1943 '''v=""""""''',
1944 add_imports=["from __future__ import annotations"],
1945 )
1946 == '''from __future__ import annotations
1947
1948 v=""""""
1949 '''
1950 )
1951
1952
1953 def test_literal_sort_at_top_of_file_issue_1792() -> None:
1954 assert (
1955 isort.code(
1956 '''"""I'm a docstring! Look at me!"""
1957
1958 # isort: unique-list
1959 __all__ = ["Foo", "Foo", "Bar"]
1960
1961 from typing import final # arbitrary
1962
1963
1964 @final
1965 class Foo:
1966 ...
1967
1968
1969 @final
1970 class Bar:
1971 ...
1972 '''
1973 )
1974 == '''"""I'm a docstring! Look at me!"""
1975
1976 # isort: unique-list
1977 __all__ = ["Bar", "Foo"]
1978
1979 from typing import final # arbitrary
1980
1981
1982 @final
1983 class Foo:
1984 ...
1985
1986
1987 @final
1988 class Bar:
1989 ...
1990 '''
1991 )
1992
1993
1994 def test_isort_should_produce_the_same_code_on_subsequent_runs_issue_1799(
1995 tmp_path: Path,
1996 ) -> None:
1997 code = """import sys
1998
1999 from importlib.metadata import PackageNotFoundError, version
2000 """
2001 config_file = tmp_path / ".isort.cfg"
2002 config_file.write_text(
2003 """[isort]
2004 profile=black
2005 src_paths=isort,test
2006 line_length=100
2007 skip=.tox,.venv,build,dist,docs,tests
2008 extra_standard_library=pkg_resources,setuptools,typing
2009 known_test=pytest
2010 known_first_party=ibpt
2011 sections=FUTURE,STDLIB,TEST,THIRDPARTY,FIRSTPARTY,LOCALFOLDER
2012 import_heading_firstparty=internal
2013 import_heading_thirdparty=external
2014 """
2015 )
2016 settings = isort.settings.Config(str(config_file))
2017 assert isort.code(code, config=settings) == isort.code(
2018 isort.code(code, config=settings), config=settings
2019 )
2020
2021
2022 def test_check_code_should_not_false_positive_with_float_to_top_and_add_imports() -> None:
2023 """isort check_code should not report incorrectly sorted imports when
2024 float_to_top and add_imports are used together and the import is already present.
2025 See: https://github.com/PyCQA/isort/issues/1971
2026 """
2027 assert isort.check_code(
2028 isort.code("1\n", float_to_top=True, add_imports=["import os"]),
2029 float_to_top=True,
2030 add_imports=["import os"],
2031 )
2032
2033
2034 @pytest.mark.parametrize("line_ending", ["\n", "\r\n"])
2035 @pytest.mark.parametrize(
2036 "boundary",
2037 [
2038 "# isort: split\n",
2039 "import z # isort: split\n",
2040 "# isort: off\nimport z\nimport a\n# isort: on\n",
2041 ],
2042 )
2043 def test_float_to_top_check_accepts_unchanged_sections_issue_2681(
2044 line_ending: str, boundary: str
2045 ) -> None:
2046 source = ("import os\n\n" + boundary + "\nimport sys\n").replace("\n", line_ending)
2047
2048 assert isort.code(source, float_to_top=True) == source
2049 assert isort.check_code(source, float_to_top=True, show_diff=True)
2050
2051
2052 @pytest.mark.parametrize("line_ending", ["\n", "\r\n"])
2053 @pytest.mark.parametrize("blank_lines", [0, 1, 3])
2054 def test_float_to_top_preserves_boundary_spacing_issue_2681(
2055 line_ending: str, blank_lines: int
2056 ) -> None:
2057 source = ("import os\n" + "\n" * blank_lines + "# isort: split\n").replace("\n", line_ending)
2058 result = _float_to_top(StringIO(source), [], isort.Config(float_to_top=True), "py")
2059
2060 assert result.input_stream.read() == source
2061 assert not result.made_changes
2062
2063
2064 @pytest.mark.parametrize("line_ending", ["\n", "\r\n"])
2065 def test_float_to_top_check_detects_unsorted_sections_issue_2681(line_ending: str) -> None:
2066 source = "import sys\nimport os\n\n# isort: split\n\nimport a\n".replace("\n", line_ending)
2067 expected = "import os\nimport sys\n\n# isort: split\n\nimport a\n".replace("\n", line_ending)
2068
2069 assert not isort.check_code(source, float_to_top=True)
2070 assert isort.code(source, float_to_top=True) == expected
2071 assert isort.check_code(expected, float_to_top=True)
2072
2073
2074 @pytest.mark.parametrize("configured_ending", ["\n", "\r\n"])
2075 def test_float_to_top_configured_line_ending_issue_2681(configured_ending: str) -> None:
2076 source = "import os\r\n\r\n# isort: split\r\n\r\nimport sys\r\n"
2077 expected = source.replace("\r\n", configured_ending)
2078 result = isort.code(source, float_to_top=True, line_ending=configured_ending)
2079
2080 assert result == expected
2081 assert isort.check_code(result, float_to_top=True, line_ending=configured_ending)
2082
2083
2084 def test_float_to_top_cli_check_accepts_crlf_issue_2681(tmp_path: Path) -> None:
2085 path = tmp_path / "example.py"
2086 source = b"import os\r\n\r\n# isort: split\r\n\r\nimport sys\r\n"
2087 path.write_bytes(source)
2088
2089 main(["--float-to-top", "--check-only", str(path)])
2090 assert path.read_bytes() == source
2091
2092
2093 def test_unrecoverable_exception_on_valid_input_ending_with_backslash_issue_1893() -> None:
2094 """Ensure isort doesn't raise an IndexError on valid input ending with a backslash
2095 without a trailing newline, as was the case in issue #1893:
2096 https://github.com/PyCQA/isort/issues/1893
2097 """
2098 assert isort.code("import os #\\") == "import os # \\\n"
2099
2100
2101 def test_comment_on_opening_line_of_aliased_import_does_not_move() -> None:
2102 """Ensure isort doesn't move comments from the opening "from ... import (" line
2103 to the alias attribute line when using import aliases that wrap across multiple lines.
2104 See: https://github.com/PyCQA/isort/issues/2392
2105 """
2106 # Opening-line comment (e.g. "# type: ignore") must stay on the "import (" line,
2107 # not drift down to the alias attribute line.
2108 test_input = """\
2109 from a_long_name_to_enforce.splitting_across.two_lines import ( # type: ignore[attr-defined]
2110 a_random_attribute as renamed_random_attribute,
2111 )
2112 """
2113 assert isort.code(test_input, profile="black") == test_input
2114
2115 # An inline comment on the *attribute* line must stay on the attribute line, not move up to
2116 # the opening line.
2117 attr_comment_input = """\
2118 from com.my_lovely_company.my_lovely_team.my_lovely_project.my_lovely_component import (
2119 MyLovelyCompanyTeamProjectComponent as component, # DRY alias
2120 )
2121 """
2122 assert isort.code(attr_comment_input, profile="black") == attr_comment_input
2123
2124 # When both an opening-line comment and an attribute-line comment are present,
2125 # each must remain on its original line.
2126 both_comments_input = """\
2127 from a_long_name_to_enforce.splitting_across.two_lines import ( # opening comment
2128 a_random_attribute as renamed_random_attribute, # attr comment
2129 )
2130 """
2131 assert isort.code(both_comments_input, profile="black") == both_comments_input
2132
2133 # Non-alias imports with an opening-line comment should also keep the comment in place.
2134 non_alias_input = """\
2135 from a_long_name_to_enforce.splitting_across.two_lines import ( # type: ignore
2136 a_random_attribute,
2137 )
2138 """
2139 assert isort.code(non_alias_input, profile="black") == non_alias_input
2140
2141 # When the import is short enough to fit on one line the opening-line comment is
2142 # preserved at the end of that single line (both alias and non-alias).
2143 short_alias = "from mod import attr as alias # type: ignore[attr-defined]\n"
2144 assert isort.code(short_alias, profile="black") == short_alias
2145
2146 # The fix must also work when use_parentheses=True with other wrap modes
2147 # (not just the Black profile's VERTICAL_HANGING_INDENT mode).
2148 test_input_no_trailing_comma = """\
2149 from a_long_name_to_enforce.splitting_across.two_lines import ( # type: ignore[attr-defined]
2150 a_random_attribute as renamed_random_attribute
2151 )
2152 """
2153 assert (
2154 isort.code(
2155 test_input_no_trailing_comma,
2156 use_parentheses=True,
2157 multi_line_output=3,
2158 line_length=88,
2159 )
2160 == test_input_no_trailing_comma
2161 )
2162
2163 # When the import is short enough to fit on one line both the opening-line comment and the
2164 # attribute-line comment are preserved at the end of the single line (both alias and non-alias).
2165 short_line = """\
2166 from mod import ( # My comment
2167 attr as alias # type: ignore[attr-defined]
2168 )
2169 """
2170 assert (
2171 isort.code(short_line, profile="black")
2172 == "from mod import attr as alias # type: ignore[attr-defined] # My comment\n"
2173 )
2174
2175
2176 def test_sort_reexports_with_stdin_raises_error_issue_2393() -> None:
2177 """Ensure --sort-reexports raises a clear error when used with stdin."""
2178 fake_stdin = TextIOWrapper(BytesIO(b"from test import B, A\n"))
2179 with pytest.raises(SystemExit) as exc_info:
2180 main(argv=["--sort-reexports", "-"], stdin=fake_stdin)
2181 assert exc_info.value.code != 0
2182
2183
2184 def test_split_on_trailing_comma_idempotent_with_non_default_wrap_mode() -> None:
2185 """Ensure isort output is idempotent when ``split_on_trailing_comma`` and
2186 ``include_trailing_comma`` are combined with a non-default ``multi_line_output`` mode.
2187
2188 With both options enabled, isort always appends a trailing comma when it wraps an
2189 import across multiple lines. ``split_on_trailing_comma`` then explodes any import
2190 that ends with a trailing comma onto individual lines on the *next* run. Previously
2191 the explode was only applied when the *input* already carried a trailing comma, so the
2192 first pass wrapped using the requested ``multi_line_output`` mode (e.g. VERTICAL or
2193 GRID) and only the second pass collapsed the result to VERTICAL_HANGING_INDENT, making
2194 the output unstable.
2195 """
2196 to_sort = "from a.b.c import (d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s)\n"
2197
2198 # Every multi-line wrap mode must reach a fixpoint after a single pass.
2199 for multi_line_output in (0, 1, 2, 3, 4, 5):
2200 first_pass = isort.code(
2201 to_sort,
2202 include_trailing_comma=True,
2203 split_on_trailing_comma=True,
2204 multi_line_output=multi_line_output,
2205 line_length=40,
2206 )
2207 second_pass = isort.code(
2208 first_pass,
2209 include_trailing_comma=True,
2210 split_on_trailing_comma=True,
2211 multi_line_output=multi_line_output,
2212 line_length=40,
2213 )
2214 assert first_pass == second_pass, (
2215 f"not idempotent for multi_line_output={multi_line_output}"
2216 )
2217
2218 # The Black profile sets include_trailing_comma + split_on_trailing_comma; combining it
2219 # with an explicit wrap-mode override must remain stable too.
2220 black_override = isort.code(to_sort, profile="black", multi_line_output=1, line_length=40)
2221 assert black_override == isort.code(
2222 black_override, profile="black", multi_line_output=1, line_length=40
2223 )
2224
2225
2226 def test_noqa_wrap_mode_idempotent_with_existing_comment() -> None:
2227 """Ensure ``multi_line_output=NOQA`` does not keep prepending ``NOQA`` to an import
2228 that already carries its own comment.
2229
2230 In NOQA mode isort appends ``# NOQA`` to imports it cannot fit on one line. When the
2231 import also has its own comment (e.g. ``# leading``) the first pass correctly produces
2232 ``# NOQA leading``. Re-parsing that line gives a single combined comment
2233 ``"NOQA leading"``, so the old "already has NOQA" guard - which compared against the
2234 list of comments - no longer matched and isort prepended yet another ``NOQA`` on every
2235 subsequent run (``# NOQA NOQA leading``, ``# NOQA NOQA NOQA leading`` ...), never
2236 reaching a fixpoint.
2237 """
2238 to_sort = (
2239 "from a import ( # leading\n"
2240 " b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z\n"
2241 ")\n"
2242 )
2243
2244 first_pass = isort.code(to_sort, multi_line_output=7)
2245 assert first_pass == (
2246 "from a import b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, "
2247 "v, w, x, y, z # NOQA leading\n"
2248 )
2249
2250 # A single NOQA must be present, and re-running must not add more of them.
2251 assert first_pass.count("NOQA") == 1
2252 second_pass = isort.code(first_pass, multi_line_output=7)
2253 assert second_pass == first_pass
2254 assert second_pass.count("NOQA") == 1
2255
2256
2257 def test_noqa_wrap_mode_does_not_accumulate_spaces_with_as_import() -> None:
2258 """A long ``as`` import in NOQA mode must not grow extra spaces before ``# NOQA``.
2259
2260 With ``force_single_line`` an aliased import that overflows the line length is emitted
2261 on its own line and gets a ``# NOQA`` appended. The auto-added comment is re-parsed on
2262 the next run and put back through ``add_to_line``, which used to keep the whitespace that
2263 had preceded the stripped ``#`` and then add the comment prefix on top of it - so every
2264 pass inserted two more spaces (``import x # NOQA`` -> ``import x # NOQA`` -> ...),
2265 never reaching a fixpoint. See issue #2394.
2266 """
2267 to_sort = "from my_package.my_module import super_long_file_name as super_long_alias\n"
2268
2269 first_pass = isort.code(to_sort, multi_line_output=7, force_single_line=True, line_length=40)
2270 assert first_pass == (
2271 "from my_package.my_module import super_long_file_name as super_long_alias # NOQA\n"
2272 )
2273
2274 second_pass = isort.code(
2275 first_pass, multi_line_output=7, force_single_line=True, line_length=40
2276 )
2277 assert second_pass == first_pass
2278
2279
2280 def test_sort_reexports_respects_black_profile_issue_2280() -> None:
2281 """``--sort-reexports`` must honor the active formatting config, not stdlib ``pprint``.
2282
2283 ``isort.literal`` used to format the sorted ``__all__`` with stdlib ``pprint``, which
2284 only reads ``config.line_length`` and ignores ``include_trailing_comma`` and the quote
2285 style entirely. So a long ``__all__`` under ``--profile=black`` came back
2286 single-quoted, wrapped in ``pprint`` style (a bare continuation line prefixed with one
2287 space) and without a trailing comma - output that black immediately reformats. See
2288 issue #2280: https://github.com/pycqa/isort/issues/2280
2289
2290 The sorted list must instead match what black itself produces: one element per line,
2291 double quotes, a trailing comma and a hanging-indented closing bracket.
2292 """
2293 test_input = """__all__ = [
2294 "AliasAddress",
2295 "Address",
2296 "BankAccountConnection",
2297 "Certificate",
2298 "ConcessionFee",
2299 "ContactDetails",
2300 "Determination",
2301 ]
2302 """
2303 expected_output = """__all__ = [
2304 "Address",
2305 "AliasAddress",
2306 "BankAccountConnection",
2307 "Certificate",
2308 "ConcessionFee",
2309 "ContactDetails",
2310 "Determination",
2311 ]
2312 """
2313 assert isort.code(test_input, profile="black", sort_reexports=True) == expected_output
2314
2315
2316 def test_literal_dict_sort_respects_black_profile_issue_2280() -> None:
2317 """The ``# isort: dict`` literal sort shares the same formatter as ``--sort-reexports``
2318 and must likewise honor the black profile rather than stdlib ``pprint`` (which produced
2319 single quotes, pprint-style wrapping and no trailing comma). Same root cause as #2280.
2320 """
2321 test_input = (
2322 "# isort: dict\n"
2323 + "d = {"
2324 + ", ".join(f"'key_{i:02d}': 'value_{i:02d}'" for i in (3, 1, 2, 0))
2325 + "}\n"
2326 )
2327 expected_output = (
2328 "# isort: dict\nd = {\n"
2329 + "".join(f' "key_{i:02d}": "value_{i:02d}",\n' for i in range(4))
2330 + "}\n"
2331 )
2332 assert isort.code(test_input, profile="black") == expected_output
2333
2334
2335 def test_sort_reexports_output_is_black_stable_issue_2280() -> None:
2336 """isort's sorted __all__ under the black profile must be a fixpoint for both isort
2337 and black (running either again changes nothing). See issue #2280."""
2338 import black # noqa: PLC0415
2339 from black.report import NothingChanged # noqa: PLC0415
2340
2341 source = (
2342 "__all__ = [\n"
2343 + "".join(f' "Name{i:02d}",\n' for i in (5, 3, 9, 1, 7, 2, 8, 4, 6, 0))
2344 + "]\n"
2345 )
2346
2347 first = isort.code(source, profile="black", sort_reexports=True)
2348 # isort is idempotent
2349 assert isort.code(first, profile="black", sort_reexports=True) == first
2350 # black leaves isort's output unchanged
2351 try:
2352 black_out = black.format_file_contents(first, fast=True, mode=black.FileMode())
2353 except NothingChanged:
2354 black_out = first
2355 assert black_out == first
2356
2357
2358 def test_sort_reexports_check_mode_multiline_all_issue_2280() -> None:
2359 """``--check`` on a multi-line ``__all__`` with ``--sort-reexports`` must not crash.
2360
2361 Check mode routes output to a null stream whose ``tell()`` is always 0. The reexport
2362 handling used ``output_stream.seek(output_stream.tell() - len(first_line))`` to roll
2363 back over the opening line, which went negative and raised ``ValueError: Negative seek
2364 position``. Our black-compatible formatter emits multi-line ``__all__``, so ``isort
2365 --check`` began crashing on isort's own output. See issue #2280.
2366 """
2367 # already-sorted, black-formatted multi-line __all__ (what isort itself now produces)
2368 sorted_all = "__all__ = [\n" + "".join(f' "Name{i:02d}",\n' for i in range(9)) + "]\n"
2369 # check must report "no changes" without raising, in both string and stream forms
2370 assert isort.check_code(sorted_all, show_diff=False, profile="black", sort_reexports=True)
2371
2372 # and with imports before it (the realistic module case)
2373 with_imports = "from .core import A\n\n" + sorted_all
2374 checked = isort.code(with_imports, profile="black", sort_reexports=True)
2375 assert isort.check_code(checked, show_diff=False, profile="black", sort_reexports=True)
2376
2377
2378 def test_sort_reexports_preserves_short_multiline_trailing_comma_issue_2578() -> None:
2379 """A short __all__ with a trailing comma should keep its explicit multiline style."""
2380 test_input = """__all__ = (
2381 "FirstClass",
2382 "SecondClass",
2383 )
2384 """
2385 assert isort.code(test_input, profile="black", sort_reexports=True) == test_input
2386
2387
2388 def test_sort_reexports_preserves_short_multiline_list_trailing_comma_issue_2578() -> None:
2389 """The same trailing-comma preservation applies to list-style __all__ exports."""
2390 test_input = """__all__ = [
2391 "FirstClass",
2392 "SecondClass",
2393 ]
2394 """
2395 assert isort.code(test_input, profile="black", sort_reexports=True) == test_input
2396
2397
2398 def test_sort_reexports_preserves_crlf_line_endings_issue_2668() -> None:
2399 """``--sort-reexports`` must keep CRLF endings instead of injecting bare LFs."""
2400 test_input = (
2401 "from .somewhere import FirstClass, SecondClass\r\n"
2402 "\r\n"
2403 "__all__ = (\r\n"
2404 ' "SecondClass",\r\n'
2405 ' "FirstClass",\r\n'
2406 ")\r\n"
2407 )
2408 expected = (
2409 "from .somewhere import FirstClass, SecondClass\r\n"
2410 "\r\n"
2411 "__all__ = (\r\n"
2412 ' "FirstClass",\r\n'
2413 ' "SecondClass",\r\n'
2414 ")\r\n"
2415 )
2416 assert isort.code(test_input, profile="black", sort_reexports=True) == expected
2417
2418
2419 def test_sort_reexports_preserves_crlf_list_style_issue_2668() -> None:
2420 """List-style ``__all__`` reexports should preserve CRLF the same way."""
2421 test_input = (
2422 "from .somewhere import FirstClass, SecondClass\r\n"
2423 "\r\n"
2424 "__all__ = [\r\n"
2425 ' "SecondClass",\r\n'
2426 ' "FirstClass",\r\n'
2427 "]\r\n"
2428 )
2429 expected = (
2430 "from .somewhere import FirstClass, SecondClass\r\n"
2431 "\r\n"
2432 "__all__ = [\r\n"
2433 ' "FirstClass",\r\n'
2434 ' "SecondClass",\r\n'
2435 "]\r\n"
2436 )
2437 assert isort.code(test_input, profile="black", sort_reexports=True) == expected
2438
2439
2440 def test_literal_sort_action_comment_preserves_crlf_issue_2668() -> None:
2441 """``# isort: list`` shares the literal formatter and must keep CRLF too."""
2442 test_input = '# isort: list\r\n__all__ = [\r\n "SecondClass",\r\n "FirstClass",\r\n]\r\n'
2443 expected = '# isort: list\r\n__all__ = [\r\n "FirstClass",\r\n "SecondClass",\r\n]\r\n'
2444 assert isort.code(test_input, profile="black") == expected
2445
2446
2447 def test_noqa_added_to_long_force_single_line_as_import_with_comment_issue_2093() -> None:
2448 """A long ``as`` import with inline comment must get ``# NOQA`` in NOQA mode.
2449
2450 With ``force_single_line`` an aliased import that carries an inline comment
2451 and overflows the line length must still receive ``# NOQA``. Previously
2452 ``with_comments()`` wrapped ``wrap.line()``, so the length check ran on the
2453 import without the comment and ``# NOQA`` was never added.
2454 """
2455 to_sort = (
2456 "from my_package.my_module import super_long_file_name as super_long_alias"
2457 " # type: ignore\n"
2458 )
2459
2460 first_pass = isort.code(to_sort, multi_line_output=7, force_single_line=True, line_length=40)
2461 assert first_pass == (
2462 "from my_package.my_module import super_long_file_name as super_long_alias"
2463 " # type: ignore # NOQA\n"
2464 )
2465
2466 second_pass = isort.code(
2467 first_pass, multi_line_output=7, force_single_line=True, line_length=40
2468 )
2469 assert second_pass == first_pass
2470
2471
2472 def test_noqa_added_to_long_as_import_with_opening_comment_issue_2093() -> None:
2473 """A long ``as`` import with opening-line comment must get ``# NOQA`` in NOQA mode.
2474
2475 When ``use_parentheses`` is enabled, opening-line comments are kept on the
2476 ``from X import (`` line. The ``wrap.line()`` call ran before the comment was
2477 attached, so it saw a short import and never added ``# NOQA``. The fix re-runs
2478 ``wrap.line()`` in NOQA mode after the comment is attached.
2479 """
2480 to_sort = (
2481 "from my_package.my_module import (\n"
2482 " super_long_file_name as super_long_alias # type: ignore\n"
2483 ")\n"
2484 )
2485
2486 first_pass = isort.code(to_sort, multi_line_output=7, line_length=40)
2487 assert first_pass == (
2488 "from my_package.my_module import super_long_file_name as super_long_alias"
2489 " # type: ignore # NOQA\n"
2490 )
2491
2492 second_pass = isort.code(first_pass, multi_line_output=7, line_length=40)
2493 assert second_pass == first_pass
2494
2495
2496 def test_noqa_added_to_long_combined_straight_imports_issue_2093() -> None:
2497 """Long combined straight imports must get ``# NOQA`` in NOQA mode.
2498
2499 With ``combine_straight_imports`` enabled, multiple ``import`` statements
2500 are merged into a single ``import a, b, c, ...`` line. Previously this line
2501 was appended directly without going through ``wrap.line()``, so ``# NOQA``
2502 was never added even when it exceeded the line length.
2503 """
2504 to_sort = "import a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p\n"
2505
2506 first_pass = isort.code(
2507 to_sort, multi_line_output=7, combine_straight_imports=True, line_length=40
2508 )
2509 assert first_pass == ("import a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p # NOQA\n")
2510
2511 second_pass = isort.code(
2512 first_pass, multi_line_output=7, combine_straight_imports=True, line_length=40
2513 )
2514 assert second_pass == first_pass
2515
2516
2517 def test_noqa_added_to_long_straight_import_issue_2093() -> None:
2518 """Long straight imports must get ``# NOQA`` in NOQA mode.
2519
2520 Straight imports (``import x`` or ``import x as y``) that exceed the line
2521 length were emitted directly without going through ``wrap.line()``, so
2522 ``# NOQA`` was never added. The fix wraps each import through ``wrap.line()``.
2523 """
2524 to_sort = "import aaaa_long_module_name as bbbb_long_alias_name\n"
2525
2526 first_pass = isort.code(to_sort, multi_line_output=7, line_length=40)
2527 assert first_pass == "import aaaa_long_module_name as bbbb_long_alias_name # NOQA\n"
2528
2529 second_pass = isort.code(first_pass, multi_line_output=7, line_length=40)
2530 assert second_pass == first_pass
2531
2532
2533 def test_noqa_added_to_long_as_import_with_opening_line_comment_issue_2093() -> None:
2534 """A long ``as`` import with an opening-line comment and ``use_parentheses``.
2535
2536 When ``use_parentheses`` is enabled and the import carries an opening-line
2537 comment, the comment is attached to the first line after wrapping. In NOQA
2538 mode ``wrap.line()`` is re-run on that line so ``# NOQA`` is added when it
2539 still exceeds the line length. In non-NOQA modes the comment is preserved on
2540 the ``from X import (`` line without ``# NOQA``.
2541 """
2542 to_sort = (
2543 "from my_package.my_module import super_long_file_name as super_long_alias"
2544 " # type: ignore\n"
2545 )
2546
2547 # NOQA mode: # NOQA is appended after the opening-line comment.
2548 first_pass = isort.code(to_sort, multi_line_output=7, use_parentheses=True, line_length=40)
2549 assert first_pass == (
2550 "from my_package.my_module import super_long_file_name as super_long_alias"
2551 " # NOQA # type: ignore\n"
2552 )
2553
2554 # Non-NOQA mode (grid): the comment stays on the opening parenthesis line.
2555 grid_pass = isort.code(to_sort, multi_line_output=0, use_parentheses=True, line_length=40)
2556 assert grid_pass == (
2557 "from my_package.my_module import ( # type: ignore\n"
2558 " super_long_file_name as super_long_alias)\n"
2559 )
2560
2561 # With ignore_comments the opening-line comment is stripped, leaving # NOQA.
2562 ignored_pass = isort.code(
2563 to_sort,
2564 multi_line_output=7,
2565 use_parentheses=True,
2566 ignore_comments=True,
2567 line_length=40,
2568 )
2569 assert ignored_pass == (
2570 "from my_package.my_module import super_long_file_name as super_long_alias # NOQA\n"
2571 )
2572
2573
2574 def test_noqa_added_to_long_combined_straight_imports_with_bare_comment_issue_2093() -> None:
2575 """A bare ``#`` comment with ``combine_straight_imports`` gets ``# NOQA``.
2576
2577 A bare ``#`` with no text parses to an empty comment string. When such a
2578 comment is present on a combined straight import that exceeds the line
2579 length, the empty comment branch must still pass through ``wrap.line()`` so
2580 that ``# NOQA`` is added in NOQA mode.
2581 """
2582 to_sort = "import a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p #\n"
2583
2584 first_pass = isort.code(
2585 to_sort, multi_line_output=7, combine_straight_imports=True, line_length=40
2586 )
2587 assert first_pass == ("import a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p # # NOQA\n")
2588
2589
2590 def test_isort_skip_is_honored_with_future_import_issue_2092() -> None:
2591 """A per-line ``isort: skip`` must be honored even when a ``__future__`` import is present.
2592
2593 ``__future__`` imports are always floated to the very top, which used to make isort splice
2594 the sorted import block ahead of a following ``# isort: skip`` line and relocate the skipped
2595 import below the block - silently violating the skip directive. The skipped import must stay
2596 exactly where it is, and the result must be stable across re-runs. See issue #2092.
2597 """
2598 to_sort = (
2599 "from __future__ import annotations\n"
2600 "\n"
2601 "from foo import bar # isort: skip\n"
2602 "from bar import baz\n"
2603 )
2604
2605 first_pass = isort.code(to_sort)
2606 assert first_pass == to_sort
2607 assert isort.check_code(to_sort, show_diff=True)
2608
2609 # An interleaved skip (between two regular imports) must keep its position rather than
2610 # being sorted to the bottom of the block, and must be idempotent.
2611 interleaved = "import aaa\nfrom foo import bar # isort: skip\nimport ccc\n"
2612 sorted_interleaved = isort.code(interleaved)
2613 lines = sorted_interleaved.splitlines()
2614 skip_index = next(i for i, line in enumerate(lines) if "# isort: skip" in line)
2615 assert lines.index("import ccc") > skip_index # skip not relocated below the block
2616 assert isort.code(sorted_interleaved) == sorted_interleaved
2617
2618
2619 def test_isort_does_not_drop_aliased_import_when_plain_name_has_a_comment() -> None:
2620 """A name imported both plainly (with a trailing comment) and aliased must keep its
2621 alias when a sibling sorts ahead of it.
2622
2623 ``from x import m # c`` and ``from x import m as z`` combine into one group, and the
2624 alias is only emitted while ``m`` leads that group. When ``aaa`` sorts before ``m`` the
2625 comment pass used to consume ``m`` and drop ``m as z``, which only surfaced on a second
2626 run once the group was re-sorted.
2627 """
2628 to_sort = "from x import aaa\nfrom x import m # c\nfrom x import m as z\n"
2629 assert isort.code(to_sort) == to_sort
2630
2631 # The same holds for a relative (local-folder) import.
2632 relative = "from . import bar, one\nfrom . import one as zzz # NOQA\n"
2633 relative_sorted = isort.code(relative)
2634 expected = "from . import bar\nfrom . import one # NOQA\nfrom . import one as zzz\n"
2635 assert relative_sorted == expected
2636 assert isort.code(relative_sorted) == relative_sorted
2637
2638
2639 def test_add_import_keeps_a_prefixed_module_docstring_first_issue_1893() -> None:
2640 """``add_imports`` must not move an import above a module docstring that carries a
2641 string prefix (``r``, ``b``, ``f``, ``u`` or a legal combination of them), as reported
2642 in issue #1893: https://github.com/pycqa/isort/issues/1893
2643 """
2644 # The exact input from the report: the added import was emitted a second time, above
2645 # the docstring.
2646 reported = 'r"""module docstring\n"""\nfrom __future__ import annotations\n'
2647 assert isort.code(reported, add_imports=["from __future__ import annotations"]) == reported
2648
2649 # The import still has to be added, below the docstring -- where an unprefixed
2650 # docstring already puts it.
2651 with_code = 'r"""module docstring\n"""\n\nx = 1\n'
2652 assert (
2653 isort.code(with_code, add_imports=["import a"])
2654 == 'r"""module docstring\n"""\n\nimport a\n\nx = 1\n'
2655 )
2656
2657 # Every prefix isort itself recognises, in both quote flavours and in lower,
2658 # upper and mixed case.
2659 for prefix in sorted(STRING_PREFIXES):
2660 for cased in sorted({prefix, prefix.upper(), prefix.capitalize()}):
2661 for quote in ('"""', "'''"):
2662 docstring = f"{cased}{quote}module docstring\n{quote}\n"
2663 source = docstring + "import a\n"
2664 assert isort.code(source, add_imports=["import a"]) == source, cased + quote
2665
2666
2667 def test_hanging_indent_with_parentheses_keeps_syntax_out_of_trailing_comments() -> None:
2668 """``multi_line_output=10`` must not append a comma or the closing parenthesis after a
2669 trailing comment, which silently rewrote valid code into code that no longer parses.
2670
2671 The mode keeps the comment on the import line (its siblings hoist it to the ``(`` line),
2672 then appended punctuation to that line unconditionally. The closing ``)`` landed inside
2673 the comment, and a wrapping comma was consumed by the comment re-splice in
2674 ``comments.add_to_line`` -- so the output lost a separator it never got back.
2675 """
2676 # Closing parenthesis captured by the comment: "'(' was never closed".
2677 captured_paren = isort.code(
2678 "from a import b, c # trailing\nfrom a import d\n",
2679 multi_line_output=10,
2680 line_length=40,
2681 force_grid_wrap=2,
2682 )
2683 assert ast.parse(captured_paren)
2684 assert captured_paren == "from a import (b, c, d) # trailing\n"
2685
2686 # Comma eaten at a wrap point: the names either side of it merged into "eta gamma".
2687 lost_comma = isort.code(
2688 "from mypkg.submodule import alpha, beta, gamma, delta, epsilon, zeta, eta # noqa: F401\n",
2689 multi_line_output=10,
2690 line_length=79,
2691 )
2692 assert ast.parse(lost_comma)
2693 assert "eta," in lost_comma
2694
2695 # No wrap mode may turn parsing code into non-parsing code.
2696 for mode in WrapModes:
2697 for line_length in (40, 79, 88):
2698 for source in (
2699 "from a import b, c # trailing\nfrom a import d\n",
2700 "from mypkg.submodule import alpha, beta, gamma, delta, epsilon, zeta # noqa: F401\n",
2701 "from mypkg.sub import alpha, beta, gamma, delta, epsilon # type: ignore\n",
2702 ):
2703 for trailing_comma in (False, True):
2704 output = isort.code(
2705 source,
2706 multi_line_output=mode.value,
2707 line_length=line_length,
2708 include_trailing_comma=trailing_comma,
2709 )
2710 ast.parse(output) # must never raise
2711
2712
2713 def test_float_to_top_keeps_indented_semicolon_imports_in_place() -> None:
2714 """float_to_top must not hoist semicolon separated imports out of an indented block."""
2715 assert (
2716 isort.code("import os\n\nif True:\n import b; import a\n", float_to_top=True)
2717 == "import os\n\nif True:\n import a\n import b\n"
2718 )
2719 assert (
2720 isort.code("def f():\n import b; import a # comment\n", float_to_top=True)
2721 == "def f():\n import a # comment\n import b\n"
2722 )