Debian Codegraph @

tests/unit/test_isort.py

raw
1 """Tests all major functionality of the isort library
2
3 Should be ran using py.test by simply running py.test in the isort project directory
4 """
5
6 import os
7 import os.path
8 import subprocess
9 import sys
10 from io import StringIO
11 from pathlib import Path
12 from tempfile import NamedTemporaryFile
13 from typing import TYPE_CHECKING, Any
14 from collections.abc import Iterator
15
16 import pytest
17
18 import isort
19 from isort import api, files, sections
20 from isort.exceptions import ExistingSyntaxErrors, FileSkipped, MissingSection
21 from isort.settings import Config
22 from isort.utils import exists_case_sensitive
23 from isort.main import parse_args
24 from isort.main import main
25
26 from .utils import UnreadableStream, as_stream
27
28 if TYPE_CHECKING:
29 WrapModes: Any
30 else:
31 from isort.wrap_modes import WrapModes
32
33 TEST_DEFAULT_CONFIG = """
34 [*.{py,pyi}]
35 max_line_length = 120
36 indent_style = space
37 indent_size = 4
38 known_first_party = isort
39 known_third_party = kate
40 known_something_else = something_entirely_different
41 sections = FUTURE, STDLIB, THIRDPARTY, FIRSTPARTY, LOCALFOLDER, SOMETHING_ELSE
42 ignore_frosted_errors = E103
43 skip = build,.tox,venv
44 balanced_wrapping = true
45 """
46 SHORT_IMPORT = "from third_party import lib1, lib2, lib3, lib4"
47 SINGLE_FROM_IMPORT = "from third_party import lib1"
48 SINGLE_LINE_LONG_IMPORT = "from third_party import lib1, lib2, lib3, lib4, lib5, lib5ab"
49 REALLY_LONG_IMPORT = (
50 "from third_party import lib1, lib2, lib3, lib4, lib5, lib6, lib7, lib8, lib9, lib10, lib11,"
51 "lib12, lib13, lib14, lib15, lib16, lib17, lib18, lib20, lib21, lib22"
52 )
53 REALLY_LONG_IMPORT_WITH_COMMENT = (
54 "from third_party import lib1, lib2, lib3, lib4, lib5, lib6, lib7, lib8, lib9, "
55 "lib10, lib11, lib12, lib13, lib14, lib15, lib16, lib17, lib18, lib20, lib21, lib22"
56 " # comment"
57 )
58
59
60 @pytest.fixture(scope="session", autouse=True)
61 def default_settings_path(tmp_path_factory: pytest.TempPathFactory) -> Iterator[str]:
62 config_dir = tmp_path_factory.mktemp("config")
63 config_file = config_dir / ".editorconfig"
64 config_file.write_text(TEST_DEFAULT_CONFIG)
65
66 assert Config(str(config_file)).known_other
67
68 original_cwd = os.getcwd()
69 os.chdir(config_dir)
70 try:
71 yield str(config_dir)
72 finally:
73 os.chdir(original_cwd)
74
75
76 def test_happy_path() -> None:
77 """Test the most basic use case, straight imports no code, simply not organized by category."""
78 test_input = "import sys\nimport os\nimport myproject.test\nimport django.settings"
79 test_output = isort.code(test_input, known_first_party=["myproject"])
80 assert test_output == (
81 "import os\nimport sys\n\nimport django.settings\n\nimport myproject.test\n"
82 )
83
84
85 def test_code_intermixed() -> None:
86 """Defines what should happen when isort encounters imports intermixed with
87 code.
88
89 (it should pull them all to the top)
90
91 """
92 test_input = (
93 "import sys\n"
94 "print('yo')\n"
95 "print('I like to put code between imports cause I want stuff to break')\n"
96 "import myproject.test\n"
97 )
98 test_output = isort.code(test_input)
99 assert test_output == (
100 "import sys\n"
101 "\n"
102 "print('yo')\n"
103 "print('I like to put code between imports cause I want stuff to break')\n"
104 "import myproject.test\n"
105 )
106
107
108 def test_correct_space_between_imports() -> None:
109 """Ensure after imports a correct amount of space (in newlines) is
110 enforced.
111
112 (2 for method, class, or decorator definitions 1 for anything else)
113
114 """
115 test_input_method = "import sys\ndef my_method():\n print('hello world')\n"
116 test_output_method = isort.code(test_input_method)
117 assert test_output_method == ("import sys\n\n\ndef my_method():\n print('hello world')\n")
118
119 test_input_decorator = "import sys\n@my_decorator\ndef my_method():\n print('hello world')\n"
120 test_output_decorator = isort.code(test_input_decorator)
121 assert test_output_decorator == (
122 "import sys\n\n\n@my_decorator\ndef my_method():\n print('hello world')\n"
123 )
124
125 test_input_class = "import sys\nclass MyClass(object):\n pass\n"
126 test_output_class = isort.code(test_input_class)
127 assert test_output_class == "import sys\n\n\nclass MyClass(object):\n pass\n"
128
129 test_input_other = "import sys\nprint('yo')\n"
130 test_output_other = isort.code(test_input_other)
131 assert test_output_other == "import sys\n\nprint('yo')\n"
132
133 test_input_inquotes = (
134 "import sys\n"
135 "@my_decorator('''hello\nworld''')\n"
136 "def my_method():\n"
137 " print('hello world')\n"
138 )
139 test_output_inquotes = api.sort_code_string(test_input_inquotes)
140 assert (
141 test_output_inquotes == "import sys\n"
142 "\n\n"
143 "@my_decorator('''hello\nworld''')\n"
144 "def my_method():\n"
145 " print('hello world')\n"
146 )
147 test_input_assign = "import sys\nVAR = 1\n"
148 test_output_assign = api.sort_code_string(test_input_assign)
149 assert test_output_assign == "import sys\n\nVAR = 1\n"
150
151 test_input_assign = "import sys\nVAR = 1\ndef y():\n"
152 test_output_assign = api.sort_code_string(test_input_assign)
153 assert test_output_assign == "import sys\n\nVAR = 1\ndef y():\n"
154
155 test_input = """
156 import os
157
158 x = "hi"
159 def x():
160 pass
161 """
162 assert isort.code(test_input) == test_input
163
164
165 def test_sort_on_number() -> None:
166 """Ensure numbers get sorted logically (10 > 9 not the other way around)"""
167 test_input = "import lib10\nimport lib9\n"
168 test_output = isort.code(test_input)
169 assert test_output == "import lib9\nimport lib10\n"
170
171
172 def test_line_length() -> None:
173 """Ensure isort enforces the set line_length."""
174 assert len(isort.code(REALLY_LONG_IMPORT, line_length=80).split("\n")[0]) <= 80
175 assert len(isort.code(REALLY_LONG_IMPORT, line_length=120).split("\n")[0]) <= 120
176
177 test_output = isort.code(REALLY_LONG_IMPORT, line_length=42)
178 assert test_output == (
179 "from third_party import (lib1, lib2, lib3,\n"
180 " lib4, lib5, lib6,\n"
181 " lib7, lib8, lib9,\n"
182 " lib10, lib11,\n"
183 " lib12, lib13,\n"
184 " lib14, lib15,\n"
185 " lib16, lib17,\n"
186 " lib18, lib20,\n"
187 " lib21, lib22)\n"
188 )
189
190 test_input = (
191 "from django.contrib.gis.gdal.field import (\n"
192 " OFTDate, OFTDateTime, OFTInteger, OFTInteger64, OFTReal, OFTString,\n"
193 " OFTTime,\n"
194 ")\n"
195 ) # Test case described in issue #654
196 assert (
197 isort.code(
198 code=test_input,
199 include_trailing_comma=True,
200 line_length=79,
201 multi_line_output=WrapModes.VERTICAL_GRID_GROUPED,
202 balanced_wrapping=False,
203 )
204 == test_input
205 )
206
207 test_output = isort.code(code=REALLY_LONG_IMPORT, line_length=42, wrap_length=32)
208 assert test_output == (
209 "from third_party import (lib1,\n"
210 " lib2,\n"
211 " lib3,\n"
212 " lib4,\n"
213 " lib5,\n"
214 " lib6,\n"
215 " lib7,\n"
216 " lib8,\n"
217 " lib9,\n"
218 " lib10,\n"
219 " lib11,\n"
220 " lib12,\n"
221 " lib13,\n"
222 " lib14,\n"
223 " lib15,\n"
224 " lib16,\n"
225 " lib17,\n"
226 " lib18,\n"
227 " lib20,\n"
228 " lib21,\n"
229 " lib22)\n"
230 )
231
232 test_input = (
233 "from .test import a_very_long_function_name_that_exceeds_the_normal_pep8_line_length\n"
234 )
235 with pytest.raises(ValueError, match="wrap_length must be set lower than or equal to line_le"):
236 test_output = isort.code(code=REALLY_LONG_IMPORT, line_length=80, wrap_length=99)
237 assert (
238 isort.code(REALLY_LONG_IMPORT, line_length=100, wrap_length=99)
239 == """
240 from third_party import (lib1, lib2, lib3, lib4, lib5, lib6, lib7, lib8, lib9, lib10, lib11, lib12,
241 lib13, lib14, lib15, lib16, lib17, lib18, lib20, lib21, lib22)
242 """.lstrip()
243 )
244
245 # Test Case described in issue #1015
246 test_output = isort.code(
247 REALLY_LONG_IMPORT, line_length=25, multi_line_output=WrapModes.HANGING_INDENT
248 )
249 assert test_output == (
250 "from third_party import \\\n"
251 " lib1, lib2, lib3, \\\n"
252 " lib4, lib5, lib6, \\\n"
253 " lib7, lib8, lib9, \\\n"
254 " lib10, lib11, \\\n"
255 " lib12, lib13, \\\n"
256 " lib14, lib15, \\\n"
257 " lib16, lib17, \\\n"
258 " lib18, lib20, \\\n"
259 " lib21, lib22\n"
260 )
261
262
263 def test_output_modes() -> None:
264 """Test setting isort to use various output modes works as expected"""
265 test_output_grid = isort.code(
266 code=REALLY_LONG_IMPORT, multi_line_output=WrapModes.GRID, line_length=40
267 )
268 assert test_output_grid == (
269 "from third_party import (lib1, lib2,\n"
270 " lib3, lib4,\n"
271 " lib5, lib6,\n"
272 " lib7, lib8,\n"
273 " lib9, lib10,\n"
274 " lib11, lib12,\n"
275 " lib13, lib14,\n"
276 " lib15, lib16,\n"
277 " lib17, lib18,\n"
278 " lib20, lib21,\n"
279 " lib22)\n"
280 )
281
282 test_output_vertical = isort.code(
283 code=REALLY_LONG_IMPORT, multi_line_output=WrapModes.VERTICAL, line_length=40
284 )
285 assert test_output_vertical == (
286 "from third_party import (lib1,\n"
287 " lib2,\n"
288 " lib3,\n"
289 " lib4,\n"
290 " lib5,\n"
291 " lib6,\n"
292 " lib7,\n"
293 " lib8,\n"
294 " lib9,\n"
295 " lib10,\n"
296 " lib11,\n"
297 " lib12,\n"
298 " lib13,\n"
299 " lib14,\n"
300 " lib15,\n"
301 " lib16,\n"
302 " lib17,\n"
303 " lib18,\n"
304 " lib20,\n"
305 " lib21,\n"
306 " lib22)\n"
307 )
308
309 comment_output_vertical = isort.code(
310 code=REALLY_LONG_IMPORT_WITH_COMMENT, multi_line_output=WrapModes.VERTICAL, line_length=40
311 )
312 assert comment_output_vertical == (
313 "from third_party import (lib1, # comment\n"
314 " lib2,\n"
315 " lib3,\n"
316 " lib4,\n"
317 " lib5,\n"
318 " lib6,\n"
319 " lib7,\n"
320 " lib8,\n"
321 " lib9,\n"
322 " lib10,\n"
323 " lib11,\n"
324 " lib12,\n"
325 " lib13,\n"
326 " lib14,\n"
327 " lib15,\n"
328 " lib16,\n"
329 " lib17,\n"
330 " lib18,\n"
331 " lib20,\n"
332 " lib21,\n"
333 " lib22)\n"
334 )
335
336 test_output_hanging_indent = isort.code(
337 code=REALLY_LONG_IMPORT,
338 multi_line_output=WrapModes.HANGING_INDENT,
339 line_length=40,
340 indent=" ",
341 )
342 assert test_output_hanging_indent == (
343 "from third_party import lib1, lib2, \\\n"
344 " lib3, lib4, lib5, lib6, lib7, \\\n"
345 " lib8, lib9, lib10, lib11, lib12, \\\n"
346 " lib13, lib14, lib15, lib16, lib17, \\\n"
347 " lib18, lib20, lib21, lib22\n"
348 )
349
350 comment_output_hanging_indent = isort.code(
351 code=REALLY_LONG_IMPORT_WITH_COMMENT,
352 multi_line_output=WrapModes.HANGING_INDENT,
353 line_length=40,
354 indent=" ",
355 )
356 assert comment_output_hanging_indent == (
357 "from third_party import lib1, lib2, \\\n"
358 " lib3, lib4, lib5, lib6, lib7, \\\n"
359 " lib8, lib9, lib10, lib11, lib12, \\\n"
360 " lib13, lib14, lib15, lib16, lib17, \\\n"
361 " lib18, lib20, lib21, lib22 \\\n"
362 " # comment\n"
363 )
364
365 test_output_vertical_indent = isort.code(
366 code=REALLY_LONG_IMPORT,
367 multi_line_output=WrapModes.VERTICAL_HANGING_INDENT,
368 line_length=40,
369 indent=" ",
370 )
371 assert test_output_vertical_indent == (
372 "from third_party import (\n"
373 " lib1,\n"
374 " lib2,\n"
375 " lib3,\n"
376 " lib4,\n"
377 " lib5,\n"
378 " lib6,\n"
379 " lib7,\n"
380 " lib8,\n"
381 " lib9,\n"
382 " lib10,\n"
383 " lib11,\n"
384 " lib12,\n"
385 " lib13,\n"
386 " lib14,\n"
387 " lib15,\n"
388 " lib16,\n"
389 " lib17,\n"
390 " lib18,\n"
391 " lib20,\n"
392 " lib21,\n"
393 " lib22\n"
394 ")\n"
395 )
396
397 comment_output_vertical_indent = isort.code(
398 code=REALLY_LONG_IMPORT_WITH_COMMENT,
399 multi_line_output=WrapModes.VERTICAL_HANGING_INDENT,
400 line_length=40,
401 indent=" ",
402 )
403 assert comment_output_vertical_indent == (
404 "from third_party import ( # comment\n"
405 " lib1,\n"
406 " lib2,\n"
407 " lib3,\n"
408 " lib4,\n"
409 " lib5,\n"
410 " lib6,\n"
411 " lib7,\n"
412 " lib8,\n"
413 " lib9,\n"
414 " lib10,\n"
415 " lib11,\n"
416 " lib12,\n"
417 " lib13,\n"
418 " lib14,\n"
419 " lib15,\n"
420 " lib16,\n"
421 " lib17,\n"
422 " lib18,\n"
423 " lib20,\n"
424 " lib21,\n"
425 " lib22\n"
426 ")\n"
427 )
428
429 test_output_vertical_grid = isort.code(
430 code=REALLY_LONG_IMPORT,
431 multi_line_output=WrapModes.VERTICAL_GRID,
432 line_length=40,
433 indent=" ",
434 )
435 assert test_output_vertical_grid == (
436 "from third_party import (\n"
437 " lib1, lib2, lib3, lib4, lib5, lib6,\n"
438 " lib7, lib8, lib9, lib10, lib11,\n"
439 " lib12, lib13, lib14, lib15, lib16,\n"
440 " lib17, lib18, lib20, lib21, lib22)\n"
441 )
442
443 comment_output_vertical_grid = isort.code(
444 code=REALLY_LONG_IMPORT_WITH_COMMENT,
445 multi_line_output=WrapModes.VERTICAL_GRID,
446 line_length=40,
447 indent=" ",
448 )
449 assert comment_output_vertical_grid == (
450 "from third_party import ( # comment\n"
451 " lib1, lib2, lib3, lib4, lib5, lib6,\n"
452 " lib7, lib8, lib9, lib10, lib11,\n"
453 " lib12, lib13, lib14, lib15, lib16,\n"
454 " lib17, lib18, lib20, lib21, lib22)\n"
455 )
456
457 test_output_vertical_grid_grouped = isort.code(
458 code=REALLY_LONG_IMPORT,
459 multi_line_output=WrapModes.VERTICAL_GRID_GROUPED,
460 line_length=40,
461 indent=" ",
462 )
463 assert test_output_vertical_grid_grouped == (
464 "from third_party import (\n"
465 " lib1, lib2, lib3, lib4, lib5, lib6,\n"
466 " lib7, lib8, lib9, lib10, lib11,\n"
467 " lib12, lib13, lib14, lib15, lib16,\n"
468 " lib17, lib18, lib20, lib21, lib22\n"
469 ")\n"
470 )
471
472 comment_output_vertical_grid_grouped = isort.code(
473 code=REALLY_LONG_IMPORT_WITH_COMMENT,
474 multi_line_output=WrapModes.VERTICAL_GRID_GROUPED,
475 line_length=40,
476 indent=" ",
477 )
478 assert comment_output_vertical_grid_grouped == (
479 "from third_party import ( # comment\n"
480 " lib1, lib2, lib3, lib4, lib5, lib6,\n"
481 " lib7, lib8, lib9, lib10, lib11,\n"
482 " lib12, lib13, lib14, lib15, lib16,\n"
483 " lib17, lib18, lib20, lib21, lib22\n"
484 ")\n"
485 )
486
487 output_noqa = isort.code(code=REALLY_LONG_IMPORT_WITH_COMMENT, multi_line_output=WrapModes.NOQA)
488 assert output_noqa == (
489 "from third_party import lib1, lib2, lib3, lib4, lib5, lib6, lib7,"
490 " lib8, lib9, lib10, lib11,"
491 " lib12, lib13, lib14, lib15, lib16, lib17, lib18, lib20, lib21, lib22 "
492 "# NOQA comment\n"
493 )
494
495 test_case = isort.code(
496 code=SINGLE_LINE_LONG_IMPORT,
497 multi_line_output=WrapModes.VERTICAL_GRID_GROUPED,
498 line_length=40,
499 indent=" ",
500 )
501 test_output_vertical_grid_grouped_doesnt_wrap_early = test_case
502 assert test_output_vertical_grid_grouped_doesnt_wrap_early == (
503 "from third_party import (\n lib1, lib2, lib3, lib4, lib5, lib5ab\n)\n"
504 )
505
506 test_output_prefix_from_module = isort.code(
507 code=REALLY_LONG_IMPORT,
508 multi_line_output=WrapModes.VERTICAL_PREFIX_FROM_MODULE_IMPORT,
509 line_length=40,
510 )
511 assert test_output_prefix_from_module == (
512 "from third_party import lib1, lib2\n"
513 "from third_party import lib3, lib4\n"
514 "from third_party import lib5, lib6\n"
515 "from third_party import lib7, lib8\n"
516 "from third_party import lib9, lib10\n"
517 "from third_party import lib11, lib12\n"
518 "from third_party import lib13, lib14\n"
519 "from third_party import lib15, lib16\n"
520 "from third_party import lib17, lib18\n"
521 "from third_party import lib20, lib21\n"
522 "from third_party import lib22\n"
523 )
524
525 test_output_prefix_from_module_with_comment = isort.code(
526 code=REALLY_LONG_IMPORT_WITH_COMMENT,
527 multi_line_output=WrapModes.VERTICAL_PREFIX_FROM_MODULE_IMPORT,
528 line_length=40,
529 indent=" ",
530 )
531 assert test_output_prefix_from_module_with_comment == (
532 "from third_party import lib1 # comment\n"
533 "from third_party import lib2, lib3\n"
534 "from third_party import lib4, lib5\n"
535 "from third_party import lib6, lib7\n"
536 "from third_party import lib8, lib9\n"
537 "from third_party import lib10, lib11\n"
538 "from third_party import lib12, lib13\n"
539 "from third_party import lib14, lib15\n"
540 "from third_party import lib16, lib17\n"
541 "from third_party import lib18, lib20\n"
542 "from third_party import lib21, lib22\n"
543 )
544
545 test_output_hanging_indent_with_parentheses = isort.code(
546 code=REALLY_LONG_IMPORT,
547 multi_line_output=WrapModes.HANGING_INDENT_WITH_PARENTHESES,
548 line_length=40,
549 indent=" ",
550 )
551 assert test_output_hanging_indent_with_parentheses == (
552 "from third_party import (lib1, lib2,\n"
553 " lib3, lib4, lib5, lib6, lib7, lib8,\n"
554 " lib9, lib10, lib11, lib12, lib13,\n"
555 " lib14, lib15, lib16, lib17, lib18,\n"
556 " lib20, lib21, lib22)\n"
557 )
558
559 comment_output_hanging_indent_with_parentheses = isort.code(
560 code=REALLY_LONG_IMPORT_WITH_COMMENT,
561 multi_line_output=WrapModes.HANGING_INDENT_WITH_PARENTHESES,
562 line_length=40,
563 indent=" ",
564 )
565 assert comment_output_hanging_indent_with_parentheses == (
566 "from third_party import (lib1, # comment\n"
567 " lib2, lib3, lib4, lib5, lib6, lib7,\n"
568 " lib8, lib9, lib10, lib11, lib12,\n"
569 " lib13, lib14, lib15, lib16, lib17,\n"
570 " lib18, lib20, lib21, lib22)\n"
571 )
572
573 test_input = (
574 "def a():\n"
575 " from allennlp.modules.text_field_embedders.basic_text_field_embedder"
576 " import BasicTextFieldEmbedder"
577 )
578 test_output = isort.code(test_input, line_length=100)
579 assert test_output == (
580 "def a():\n"
581 " from allennlp.modules.text_field_embedders.basic_text_field_embedder import \\\n"
582 " BasicTextFieldEmbedder"
583 )
584
585 test_input = (
586 "class A:\n"
587 " def a():\n"
588 " from allennlp.common.registrable import Registrable"
589 " # import here to avoid circular imports\n"
590 "\n\n"
591 "class B:\n"
592 " def b():\n"
593 " from allennlp.common.registrable import Registrable"
594 " # import here to avoid circular imports\n"
595 )
596 test_output = isort.code(test_input, line_length=100)
597 assert test_output == test_input
598
599
600 def test_qa_comment_case() -> None:
601 test_input = "from veryveryveryveryveryveryveryveryveryveryvery import X # NOQA"
602 test_output = isort.code(code=test_input, line_length=40, multi_line_output=WrapModes.NOQA)
603 assert test_output == "from veryveryveryveryveryveryveryveryveryveryvery import X # NOQA\n"
604
605 test_input = "import veryveryveryveryveryveryveryveryveryveryvery # NOQA"
606 test_output = isort.code(code=test_input, line_length=40, multi_line_output=WrapModes.NOQA)
607 assert test_output == "import veryveryveryveryveryveryveryveryveryveryvery # NOQA\n"
608
609
610 def test_length_sort() -> None:
611 """Test setting isort to sort on length instead of alphabetically."""
612 test_input = (
613 "import medium_sizeeeeeeeeeeeeee\n"
614 "import shortie\n"
615 "import looooooooooooooooooooooooooooooooooooooong\n"
616 "import medium_sizeeeeeeeeeeeeea\n"
617 )
618 test_output = isort.code(test_input, length_sort=True)
619 assert test_output == (
620 "import shortie\n"
621 "import medium_sizeeeeeeeeeeeeea\n"
622 "import medium_sizeeeeeeeeeeeeee\n"
623 "import looooooooooooooooooooooooooooooooooooooong\n"
624 )
625
626
627 def test_length_sort_straight() -> None:
628 """Test setting isort to sort straight imports on length instead of alphabetically."""
629 test_input = (
630 "import medium_sizeeeeeeeeeeeeee\n"
631 "import shortie\n"
632 "import looooooooooooooooooooooooooooooooooooooong\n"
633 "from medium_sizeeeeeeeeeeeeee import b\n"
634 "from shortie import c\n"
635 "from looooooooooooooooooooooooooooooooooooooong import a\n"
636 )
637 test_output = isort.code(test_input, length_sort_straight=True)
638 assert test_output == (
639 "import shortie\n"
640 "import medium_sizeeeeeeeeeeeeee\n"
641 "import looooooooooooooooooooooooooooooooooooooong\n"
642 "from looooooooooooooooooooooooooooooooooooooong import a\n"
643 "from medium_sizeeeeeeeeeeeeee import b\n"
644 "from shortie import c\n"
645 )
646
647
648 def test_length_sort_section() -> None:
649 """Test setting isort to sort on length instead of alphabetically for a specific section."""
650 test_input = (
651 "import medium_sizeeeeeeeeeeeeee\n"
652 "import shortie\n"
653 "import datetime\n"
654 "import sys\n"
655 "import os\n"
656 "import looooooooooooooooooooooooooooooooooooooong\n"
657 "import medium_sizeeeeeeeeeeeeea\n"
658 )
659 test_output = isort.code(test_input, length_sort_sections=("stdlib",))
660 assert test_output == (
661 "import os\n"
662 "import sys\n"
663 "import datetime\n"
664 "\n"
665 "import looooooooooooooooooooooooooooooooooooooong\n"
666 "import medium_sizeeeeeeeeeeeeea\n"
667 "import medium_sizeeeeeeeeeeeeee\n"
668 "import shortie\n"
669 )
670
671
672 def test_convert_hanging() -> None:
673 """Ensure that isort will convert hanging indents to correct indent
674 method."""
675 test_input = (
676 "from third_party import lib1, lib2, \\\n"
677 " lib3, lib4, lib5, lib6, lib7, \\\n"
678 " lib8, lib9, lib10, lib11, lib12, \\\n"
679 " lib13, lib14, lib15, lib16, lib17, \\\n"
680 " lib18, lib20, lib21, lib22\n"
681 )
682 test_output = isort.code(code=test_input, multi_line_output=WrapModes.GRID, line_length=40)
683 assert test_output == (
684 "from third_party import (lib1, lib2,\n"
685 " lib3, lib4,\n"
686 " lib5, lib6,\n"
687 " lib7, lib8,\n"
688 " lib9, lib10,\n"
689 " lib11, lib12,\n"
690 " lib13, lib14,\n"
691 " lib15, lib16,\n"
692 " lib17, lib18,\n"
693 " lib20, lib21,\n"
694 " lib22)\n"
695 )
696
697
698 def test_custom_indent() -> None:
699 """Ensure setting a custom indent will work as expected."""
700 test_output = isort.code(
701 code=REALLY_LONG_IMPORT,
702 multi_line_output=WrapModes.HANGING_INDENT,
703 line_length=40,
704 indent=" ",
705 balanced_wrapping=False,
706 )
707 assert test_output == (
708 "from third_party import lib1, lib2, \\\n"
709 " lib3, lib4, lib5, lib6, lib7, lib8, \\\n"
710 " lib9, lib10, lib11, lib12, lib13, \\\n"
711 " lib14, lib15, lib16, lib17, lib18, \\\n"
712 " lib20, lib21, lib22\n"
713 )
714
715 test_output = isort.code(
716 code=REALLY_LONG_IMPORT,
717 multi_line_output=WrapModes.HANGING_INDENT,
718 line_length=40,
719 indent="' '",
720 balanced_wrapping=False,
721 )
722 assert test_output == (
723 "from third_party import lib1, lib2, \\\n"
724 " lib3, lib4, lib5, lib6, lib7, lib8, \\\n"
725 " lib9, lib10, lib11, lib12, lib13, \\\n"
726 " lib14, lib15, lib16, lib17, lib18, \\\n"
727 " lib20, lib21, lib22\n"
728 )
729
730 test_output = isort.code(
731 code=REALLY_LONG_IMPORT,
732 multi_line_output=WrapModes.HANGING_INDENT,
733 line_length=40,
734 indent="tab",
735 balanced_wrapping=False,
736 )
737 assert test_output == (
738 "from third_party import lib1, lib2, \\\n"
739 "\tlib3, lib4, lib5, lib6, lib7, lib8, \\\n"
740 "\tlib9, lib10, lib11, lib12, lib13, \\\n"
741 "\tlib14, lib15, lib16, lib17, lib18, \\\n"
742 "\tlib20, lib21, lib22\n"
743 )
744
745 test_output = isort.code(
746 code=REALLY_LONG_IMPORT,
747 multi_line_output=WrapModes.HANGING_INDENT,
748 line_length=40,
749 indent=2,
750 balanced_wrapping=False,
751 )
752 assert test_output == (
753 "from third_party import lib1, lib2, \\\n"
754 " lib3, lib4, lib5, lib6, lib7, lib8, \\\n"
755 " lib9, lib10, lib11, lib12, lib13, \\\n"
756 " lib14, lib15, lib16, lib17, lib18, \\\n"
757 " lib20, lib21, lib22\n"
758 )
759
760
761 def test_use_parentheses() -> None:
762 test_input = (
763 "from fooooooooooooooooooooooooo.baaaaaaaaaaaaaaaaaaarrrrrrr import "
764 " my_custom_function as my_special_function"
765 )
766 test_output = isort.code(test_input, line_length=79, use_parentheses=True)
767
768 assert test_output == (
769 "from fooooooooooooooooooooooooo.baaaaaaaaaaaaaaaaaaarrrrrrr import (\n"
770 " my_custom_function as my_special_function)\n"
771 )
772
773 test_output = isort.code(
774 code=test_input, line_length=79, use_parentheses=True, include_trailing_comma=True
775 )
776
777 assert test_output == (
778 "from fooooooooooooooooooooooooo.baaaaaaaaaaaaaaaaaaarrrrrrr import (\n"
779 " my_custom_function as my_special_function,)\n"
780 )
781
782 test_output = isort.code(
783 code=test_input,
784 line_length=79,
785 use_parentheses=True,
786 multi_line_output=WrapModes.VERTICAL_HANGING_INDENT,
787 )
788
789 assert test_output == (
790 "from fooooooooooooooooooooooooo.baaaaaaaaaaaaaaaaaaarrrrrrr import (\n"
791 " my_custom_function as my_special_function\n)\n"
792 )
793
794 test_output = isort.code(
795 code=test_input,
796 line_length=79,
797 use_parentheses=True,
798 multi_line_output=WrapModes.VERTICAL_GRID_GROUPED,
799 include_trailing_comma=True,
800 )
801
802 assert test_output == (
803 "from fooooooooooooooooooooooooo.baaaaaaaaaaaaaaaaaaarrrrrrr import (\n"
804 " my_custom_function as my_special_function,\n)\n"
805 )
806
807
808 def test_skip() -> None:
809 """Ensure skipping a single import will work as expected."""
810 test_input = (
811 "import myproject\n"
812 "import django\n"
813 "print('hey')\n"
814 "import sys # isort: skip this import needs to be placed here\n\n\n\n\n\n\n"
815 )
816
817 test_output = isort.code(test_input, known_first_party=["myproject"])
818 assert test_output == (
819 "import django\n"
820 "\n"
821 "import myproject\n"
822 "\n"
823 "print('hey')\n"
824 "import sys # isort: skip this import needs to be placed here\n"
825 )
826
827
828 def test_skip_with_file_name() -> None:
829 """Ensure skipping a file works even when file_contents is provided."""
830 test_input = "import django\nimport myproject\n"
831 with pytest.raises(FileSkipped):
832 isort.code(
833 file_path=Path("/baz.py"), code=test_input, settings_path=os.getcwd(), skip=["baz.py"]
834 )
835
836
837 def test_skip_within_file() -> None:
838 """Ensure skipping a whole file works."""
839 test_input = "# isort: skip_file\nimport django\nimport myproject\n"
840 with pytest.raises(FileSkipped):
841 isort.code(test_input, known_third_party=["django"])
842
843
844 def test_force_to_top() -> None:
845 """Ensure forcing a single import to the top of its category works as expected."""
846 test_input = "import lib6\nimport lib2\nimport lib5\nimport lib1\n"
847 test_output = isort.code(test_input, force_to_top=["lib5"])
848 assert test_output == "import lib5\nimport lib1\nimport lib2\nimport lib6\n"
849
850
851 def test_add_imports() -> None:
852 """Ensures adding imports works as expected."""
853 test_input = "import lib6\nimport lib2\nimport lib5\nimport lib1\n\n"
854 test_output = isort.code(code=test_input, add_imports=["import lib4", "import lib7"])
855 assert test_output == (
856 "import lib1\nimport lib2\nimport lib4\nimport lib5\nimport lib6\nimport lib7\n"
857 )
858
859 # Using simplified syntax
860 test_input = "import lib6\nimport lib2\nimport lib5\nimport lib1\n\n"
861 test_output = isort.code(code=test_input, add_imports=["lib4", "lib7", "lib8.a"])
862 assert test_output == (
863 "import lib1\n"
864 "import lib2\n"
865 "import lib4\n"
866 "import lib5\n"
867 "import lib6\n"
868 "import lib7\n"
869 "from lib8 import a\n"
870 )
871
872 # On a file that has no pre-existing imports
873 test_input = '"""Module docstring"""\nclass MyClass(object):\n pass\n'
874 test_output = isort.code(code=test_input, add_imports=["from __future__ import print_function"])
875 assert test_output == (
876 '"""Module docstring"""\n'
877 "from __future__ import print_function\n"
878 "\n"
879 "\n"
880 "class MyClass(object):\n"
881 " pass\n"
882 )
883
884 # On a file that has no pre-existing imports and a multiline docstring
885 test_input = (
886 '"""Module docstring\n\nWith a second line\n"""\nclass MyClass(object):\n pass\n'
887 )
888 test_output = isort.code(code=test_input, add_imports=["from __future__ import print_function"])
889 assert test_output == (
890 '"""Module docstring\n'
891 "\n"
892 "With a second line\n"
893 '"""\n'
894 "from __future__ import print_function\n"
895 "\n"
896 "\n"
897 "class MyClass(object):\n"
898 " pass\n"
899 )
900
901 # On a file that has no pre-existing imports and a multiline docstring.
902 # In this example, the closing quotes for the docstring are on the final
903 # line rather than a separate one.
904 test_input = '"""Module docstring\n\nWith a second line"""\nclass MyClass(object):\n pass\n'
905 test_output = isort.code(code=test_input, add_imports=["from __future__ import print_function"])
906 assert test_output == (
907 '"""Module docstring\n'
908 "\n"
909 'With a second line"""\n'
910 "from __future__ import print_function\n"
911 "\n"
912 "\n"
913 "class MyClass(object):\n"
914 " pass\n"
915 )
916
917 # On a file that has no pre-existing imports, and no doc-string
918 test_input = "class MyClass(object):\n pass\n"
919 test_output = isort.code(code=test_input, add_imports=["from __future__ import print_function"])
920 assert test_output == (
921 "from __future__ import print_function\n\n\nclass MyClass(object):\n pass\n"
922 )
923
924 # On a file with no content what so ever
925 test_input = ""
926 test_output = isort.code(test_input, add_imports=["lib4"])
927 assert test_output == ("")
928
929 # On a file with no content what so ever, after force_adds is set to True
930 test_input = ""
931 test_output = isort.code(code=test_input, add_imports=["lib4"], force_adds=True)
932 assert test_output == ("import lib4\n")
933
934
935 def test_remove_imports() -> None:
936 """Ensures removing imports works as expected."""
937 test_input = "import lib6\nimport lib2\nimport lib5\nimport lib1"
938 test_output = isort.code(test_input, remove_imports=["lib2", "lib6"])
939 assert test_output == "import lib1\nimport lib5\n"
940
941 # Using natural syntax
942 test_input = "import lib6\nimport lib2\nimport lib5\nimport lib1\nfrom lib8 import a"
943 test_output = isort.code(
944 code=test_input, remove_imports=["import lib2", "import lib6", "from lib8 import a"]
945 )
946 assert test_output == "import lib1\nimport lib5\n"
947
948 # From imports
949 test_input = "from x import y"
950 test_output = isort.code(test_input, remove_imports=["x"])
951 assert test_output == ""
952
953 test_input = "from x import y"
954 test_output = isort.code(test_input, remove_imports=["x.y"])
955 assert test_output == ""
956
957
958 def test_comments_above() -> None:
959 """Test to ensure comments above an import will stay in place"""
960 test_input = "import os\n\nfrom x import y\n\n# comment\nfrom z import __version__, api\n"
961 assert isort.code(test_input, ensure_newline_before_comments=True) == test_input
962
963
964 def test_explicitly_local_import() -> None:
965 """Ensure that explicitly local imports are separated."""
966 test_input = "import lib1\nimport lib2\nimport .lib6\nfrom . import lib7"
967 assert isort.code(test_input) == (
968 "import lib1\nimport lib2\n\nimport .lib6\nfrom . import lib7\n"
969 )
970
971
972 def test_quotes_in_file() -> None:
973 """Ensure imports within triple quotes don't get imported."""
974 test_input = 'import os\n\n"""\nLet us\nimport foo\nokay?\n"""\n'
975 assert isort.code(test_input) == test_input
976
977 test_input = 'import os\n\n\'"""\'\nimport foo\n'
978 assert isort.code(test_input) == test_input
979
980 test_input = 'import os\n\n"""Let us"""\nimport foo\n\n"""okay?"""\n'
981 assert isort.code(test_input) == test_input
982
983 test_input = 'import os\n\n#"""\nimport foo\n#"""'
984 assert isort.code(test_input) == ('import os\n\nimport foo\n\n#"""\n#"""\n')
985
986 test_input = "import os\n\n'\\\nimport foo'\n"
987 assert isort.code(test_input) == test_input
988
989 test_input = "import os\n\n'''\n\\'''\nimport junk\n'''\n"
990 assert isort.code(test_input) == test_input
991
992
993 def test_check_newline_in_imports(capsys: pytest.CaptureFixture[str]) -> None:
994 """Ensure tests works correctly when new lines are in imports."""
995 test_input = "from lib1 import (\n sub1,\n sub2,\n sub3\n)\n"
996
997 assert api.check_code_string(
998 code=test_input,
999 multi_line_output=WrapModes.VERTICAL_HANGING_INDENT,
1000 line_length=20,
1001 verbose=True,
1002 )
1003 out, _ = capsys.readouterr()
1004 assert "SUCCESS" in out
1005
1006 # if the verbose is only on modified outputs no output will be given
1007 assert api.check_code_string(
1008 code=test_input,
1009 multi_line_output=WrapModes.VERTICAL_HANGING_INDENT,
1010 line_length=20,
1011 verbose=True,
1012 only_modified=True,
1013 )
1014 out, _ = capsys.readouterr()
1015 assert not out
1016
1017 # we can make the input invalid to again see output
1018 test_input = "from lib1 import (\n sub2,\n sub1,\n sub3\n)\n"
1019 assert not api.check_code_string(
1020 code=test_input,
1021 multi_line_output=WrapModes.VERTICAL_HANGING_INDENT,
1022 line_length=20,
1023 verbose=True,
1024 only_modified=True,
1025 )
1026 out, _ = capsys.readouterr()
1027 assert out
1028
1029
1030 def test_forced_separate() -> None:
1031 """Ensure that forcing certain sub modules to show separately works as expected."""
1032 test_input = (
1033 "import sys\n"
1034 "import warnings\n"
1035 "from collections import OrderedDict\n"
1036 "\n"
1037 "from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation\n"
1038 "from django.core.paginator import InvalidPage\n"
1039 "from django.core.urlresolvers import reverse\n"
1040 "from django.db import models\n"
1041 "from django.db.models.fields import FieldDoesNotExist\n"
1042 "from django.utils import six\n"
1043 "\n"
1044 "from django.utils.deprecation import RenameMethodsBase\n"
1045 "from django.utils.encoding import force_str, force_text\n"
1046 "from django.utils.http import urlencode\n"
1047 "from django.utils.translation import ugettext, ugettext_lazy\n"
1048 "\n"
1049 "from django.contrib.admin import FieldListFilter\n"
1050 "from django.contrib.admin.exceptions import DisallowedModelAdminLookup\n"
1051 "from django.contrib.admin.options import IncorrectLookupParameters, IS_POPUP_VAR, "
1052 "TO_FIELD_VAR\n"
1053 )
1054 assert (
1055 isort.code(
1056 code=test_input,
1057 forced_separate=["django.utils.*", "django.contrib"],
1058 known_third_party=["django"],
1059 line_length=120,
1060 order_by_type=False,
1061 )
1062 == test_input
1063 )
1064 assert (
1065 isort.code(
1066 code=test_input,
1067 forced_separate=["django.utils.*", "django.contrib"],
1068 known_third_party=["django"],
1069 line_length=120,
1070 order_by_type=False,
1071 )
1072 == test_input
1073 )
1074
1075 test_input = "from .foo import bar\n\nfrom .y import ca\n"
1076 assert (
1077 isort.code(code=test_input, forced_separate=[".y"], line_length=120, order_by_type=False)
1078 == test_input
1079 )
1080
1081
1082 def test_default_section() -> None:
1083 """Test to ensure changing the default section works as expected."""
1084 test_input = "import sys\nimport os\nimport myproject.test\nimport django.settings"
1085 test_output = isort.code(
1086 code=test_input, known_third_party=["django"], default_section="FIRSTPARTY"
1087 )
1088 assert test_output == (
1089 "import os\nimport sys\n\nimport django.settings\n\nimport myproject.test\n"
1090 )
1091
1092 test_output_custom = isort.code(
1093 code=test_input, known_third_party=["django"], default_section="STDLIB"
1094 )
1095 assert test_output_custom == (
1096 "import myproject.test\nimport os\nimport sys\n\nimport django.settings\n"
1097 )
1098
1099
1100 def test_first_party_overrides_standard_section() -> None:
1101 """Test to ensure changing the default section works as expected."""
1102 test_input = (
1103 "from HTMLParser import HTMLParseError, HTMLParser\n"
1104 "import sys\n"
1105 "import os\n"
1106 "import profile.test\n"
1107 )
1108 test_output = isort.code(code=test_input, known_first_party=["profile"], py_version="27")
1109 assert test_output == (
1110 "import os\n"
1111 "import sys\n"
1112 "from HTMLParser import HTMLParseError, HTMLParser\n"
1113 "\n"
1114 "import profile.test\n"
1115 )
1116
1117
1118 def test_thirdy_party_overrides_standard_section() -> None:
1119 """Test to ensure changing the default section works as expected."""
1120 test_input = "import sys\nimport os\nimport profile.test\n"
1121 test_output = isort.code(test_input, known_third_party=["profile"])
1122 assert test_output == "import os\nimport sys\n\nimport profile.test\n"
1123
1124
1125 def test_known_pattern_path_expansion(tmp_path: Path) -> None:
1126 """Test to ensure patterns ending with path sep gets expanded
1127 and nested packages treated as known patterns.
1128 """
1129 src_dir = tmp_path / "src"
1130 src_dir.mkdir()
1131 (src_dir / "foo").mkdir()
1132 (src_dir / "bar").mkdir()
1133 test_input = (
1134 "from kate_plugin import isort_plugin\n"
1135 "import sys\n"
1136 "from foo import settings\n"
1137 "import bar\n"
1138 "import this\n"
1139 "import os\n"
1140 )
1141 test_output = isort.code(
1142 code=test_input,
1143 default_section="THIRDPARTY",
1144 known_first_party=["src/", "this", "kate_plugin"],
1145 directory=str(tmp_path),
1146 )
1147 assert test_output == (
1148 "import os\n"
1149 "import sys\n"
1150 "\n"
1151 "import bar\n"
1152 "import this\n"
1153 "from foo import settings\n"
1154 "from kate_plugin import isort_plugin\n"
1155 )
1156
1157
1158 def test_force_single_line_imports() -> None:
1159 """Test to ensure forcing imports to each have their own line works as expected."""
1160 test_input = (
1161 "from third_party import lib1, lib2, \\\n"
1162 " lib3, lib4, lib5, lib6, lib7, \\\n"
1163 " lib8, lib9, lib10, lib11, lib12, \\\n"
1164 " lib13, lib14, lib15, lib16, lib17, \\\n"
1165 " lib18, lib20, lib21, lib22\n"
1166 )
1167 test_output = isort.code(
1168 code=test_input, multi_line_output=WrapModes.GRID, line_length=40, force_single_line=True
1169 )
1170 assert test_output == (
1171 "from third_party import lib1\n"
1172 "from third_party import lib2\n"
1173 "from third_party import lib3\n"
1174 "from third_party import lib4\n"
1175 "from third_party import lib5\n"
1176 "from third_party import lib6\n"
1177 "from third_party import lib7\n"
1178 "from third_party import lib8\n"
1179 "from third_party import lib9\n"
1180 "from third_party import lib10\n"
1181 "from third_party import lib11\n"
1182 "from third_party import lib12\n"
1183 "from third_party import lib13\n"
1184 "from third_party import lib14\n"
1185 "from third_party import lib15\n"
1186 "from third_party import lib16\n"
1187 "from third_party import lib17\n"
1188 "from third_party import lib18\n"
1189 "from third_party import lib20\n"
1190 "from third_party import lib21\n"
1191 "from third_party import lib22\n"
1192 )
1193
1194 test_input = "from third_party import lib_a, lib_b, lib_d\nfrom third_party.lib_c import lib1\n"
1195 test_output = isort.code(
1196 code=test_input, multi_line_output=WrapModes.GRID, line_length=40, force_single_line=True
1197 )
1198 assert test_output == (
1199 "from third_party import lib_a\n"
1200 "from third_party import lib_b\n"
1201 "from third_party import lib_d\n"
1202 "from third_party.lib_c import lib1\n"
1203 )
1204
1205
1206 def test_force_single_line_long_imports() -> None:
1207 test_input = "from veryveryveryveryveryvery import small, big\n"
1208 test_output = isort.code(
1209 code=test_input, multi_line_output=WrapModes.NOQA, line_length=40, force_single_line=True
1210 )
1211 assert test_output == (
1212 "from veryveryveryveryveryvery import big\n"
1213 "from veryveryveryveryveryvery import small # NOQA\n"
1214 )
1215
1216
1217 def test_force_single_line_imports_and_sort_within_sections() -> None:
1218 test_input = "from third_party import lib_a, lib_b, lib_d\nfrom third_party.lib_c import lib1\n"
1219 test_output = isort.code(
1220 code=test_input,
1221 multi_line_output=WrapModes.GRID,
1222 line_length=40,
1223 force_single_line=True,
1224 force_sort_within_sections=True,
1225 )
1226 assert test_output == (
1227 "from third_party import lib_a\n"
1228 "from third_party import lib_b\n"
1229 "from third_party import lib_d\n"
1230 "from third_party.lib_c import lib1\n"
1231 )
1232 test_output = isort.code(
1233 code=test_input,
1234 multi_line_output=WrapModes.GRID,
1235 line_length=40,
1236 force_single_line=True,
1237 force_sort_within_sections=True,
1238 lexicographical=True,
1239 )
1240 assert test_output == (
1241 "from third_party import lib_a\n"
1242 "from third_party import lib_b\n"
1243 "from third_party.lib_c import lib1\n"
1244 "from third_party import lib_d\n"
1245 )
1246
1247 test_input = """import sympy
1248 import numpy as np
1249 import pandas as pd
1250 from matplotlib import pyplot as plt
1251 """
1252 assert (
1253 isort.code(code=test_input, force_sort_within_sections=True, length_sort=True) == test_input
1254 )
1255
1256
1257 def test_titled_imports() -> None:
1258 """Tests setting custom titled/commented import sections."""
1259 test_input = (
1260 "import sys\n"
1261 "import unicodedata\n"
1262 "import statistics\n"
1263 "import os\n"
1264 "import myproject.test\n"
1265 "import django.settings"
1266 )
1267 test_output = isort.code(
1268 code=test_input,
1269 known_first_party=["myproject"],
1270 import_heading_stdlib="Standard Library",
1271 import_heading_firstparty="My Stuff",
1272 )
1273 assert test_output == (
1274 "# Standard Library\n"
1275 "import os\n"
1276 "import statistics\n"
1277 "import sys\n"
1278 "import unicodedata\n"
1279 "\n"
1280 "import django.settings\n"
1281 "\n"
1282 "# My Stuff\n"
1283 "import myproject.test\n"
1284 )
1285 test_second_run = isort.code(
1286 code=test_output,
1287 known_first_party=["myproject"],
1288 import_heading_stdlib="Standard Library",
1289 import_heading_firstparty="My Stuff",
1290 )
1291 assert test_second_run == test_output
1292
1293 test_input_lines_down = (
1294 "# comment 1\n"
1295 "import django.settings\n"
1296 "\n"
1297 "# Standard Library\n"
1298 "import sys\n"
1299 "import unicodedata\n"
1300 "import statistics\n"
1301 "import os\n"
1302 "import myproject.test\n"
1303 )
1304 test_output_lines_down = isort.code(
1305 code=test_input_lines_down,
1306 known_first_party=["myproject"],
1307 import_heading_stdlib="Standard Library",
1308 import_heading_firstparty="My Stuff",
1309 )
1310 assert test_output_lines_down == (
1311 "# comment 1\n"
1312 "# Standard Library\n"
1313 "import os\n"
1314 "import statistics\n"
1315 "import sys\n"
1316 "import unicodedata\n"
1317 "\n"
1318 "import django.settings\n"
1319 "\n"
1320 "# My Stuff\n"
1321 "import myproject.test\n"
1322 )
1323
1324
1325 def test_footered_imports() -> None:
1326 """Tests setting both custom titles and footers to import sections."""
1327 test_input = (
1328 "import sys\n"
1329 "import unicodedata\n"
1330 "import statistics\n"
1331 "import os\n"
1332 "import myproject.test\n"
1333 "import django.settings"
1334 )
1335 test_output = isort.code(
1336 code=test_input,
1337 known_first_party=["myproject"],
1338 import_footer_stdlib="Standard Library End",
1339 import_footer_firstparty="My Stuff End",
1340 )
1341 assert test_output == (
1342 "import os\n"
1343 "import statistics\n"
1344 "import sys\n"
1345 "import unicodedata\n"
1346 "\n"
1347 "# Standard Library End\n"
1348 "\n"
1349 "import django.settings\n"
1350 "\n"
1351 "import myproject.test\n"
1352 "\n"
1353 "# My Stuff End\n"
1354 )
1355 test_second_run = isort.code(
1356 code=test_output,
1357 known_first_party=["myproject"],
1358 import_footer_stdlib="Standard Library End",
1359 import_footer_firstparty="My Stuff End",
1360 )
1361 assert test_second_run == test_output
1362
1363 test_input_lines_down = (
1364 "# comment 1\n"
1365 "import django.settings\n"
1366 "\n"
1367 "import sys\n"
1368 "import unicodedata\n"
1369 "import statistics\n"
1370 "import os\n"
1371 "import myproject.test\n"
1372 "\n"
1373 "# Standard Library End\n"
1374 )
1375 test_output_lines_down = isort.code(
1376 code=test_input_lines_down,
1377 known_first_party=["myproject"],
1378 import_footer_stdlib="Standard Library End",
1379 import_footer_firstparty="My Stuff End",
1380 )
1381 assert test_output_lines_down == (
1382 "# comment 1\n"
1383 "import os\n"
1384 "import statistics\n"
1385 "import sys\n"
1386 "import unicodedata\n"
1387 "\n"
1388 "# Standard Library End\n"
1389 "\n"
1390 "import django.settings\n"
1391 "\n"
1392 "import myproject.test\n"
1393 "\n"
1394 "# My Stuff End\n"
1395 )
1396
1397
1398 def test_titled_and_footered_imports() -> None:
1399 """Tests setting custom footers to import sections."""
1400 test_input = (
1401 "import sys\n"
1402 "import unicodedata\n"
1403 "import statistics\n"
1404 "import os\n"
1405 "import myproject.test\n"
1406 "import django.settings"
1407 )
1408 test_output = isort.code(
1409 code=test_input,
1410 known_first_party=["myproject"],
1411 import_heading_stdlib="Standard Library",
1412 import_heading_firstparty="My Stuff",
1413 import_footer_stdlib="Standard Library End",
1414 import_footer_firstparty="My Stuff End",
1415 )
1416 assert test_output == (
1417 "# Standard Library\n"
1418 "import os\n"
1419 "import statistics\n"
1420 "import sys\n"
1421 "import unicodedata\n"
1422 "\n"
1423 "# Standard Library End\n"
1424 "\n"
1425 "import django.settings\n"
1426 "\n"
1427 "# My Stuff\n"
1428 "import myproject.test\n"
1429 "\n"
1430 "# My Stuff End\n"
1431 )
1432 test_second_run = isort.code(
1433 code=test_output,
1434 known_first_party=["myproject"],
1435 import_heading_stdlib="Standard Library",
1436 import_heading_firstparty="My Stuff",
1437 import_footer_stdlib="Standard Library End",
1438 import_footer_firstparty="My Stuff End",
1439 )
1440 assert test_second_run == test_output
1441
1442 test_input_lines_down = (
1443 "# comment 1\n"
1444 "import django.settings\n"
1445 "\n"
1446 "# Standard Library\n"
1447 "import sys\n"
1448 "import unicodedata\n"
1449 "import statistics\n"
1450 "import os\n"
1451 "import myproject.test\n"
1452 "\n"
1453 "# Standard Library End\n"
1454 )
1455 test_output_lines_down = isort.code(
1456 code=test_input_lines_down,
1457 known_first_party=["myproject"],
1458 import_heading_stdlib="Standard Library",
1459 import_heading_firstparty="My Stuff",
1460 import_footer_stdlib="Standard Library End",
1461 import_footer_firstparty="My Stuff End",
1462 )
1463 assert test_output_lines_down == (
1464 "# comment 1\n"
1465 "# Standard Library\n"
1466 "import os\n"
1467 "import statistics\n"
1468 "import sys\n"
1469 "import unicodedata\n"
1470 "\n"
1471 "# Standard Library End\n"
1472 "\n"
1473 "import django.settings\n"
1474 "\n"
1475 "# My Stuff\n"
1476 "import myproject.test\n"
1477 "\n"
1478 "# My Stuff End\n"
1479 )
1480
1481 test_input_lines_down = (
1482 "# comment 1\n"
1483 "import django.settings\n"
1484 "\n"
1485 "# Standard Library\n"
1486 "import sys\n"
1487 "import unicodedata\n"
1488 "import statistics\n"
1489 "import os\n"
1490 "import myproject.test\n"
1491 "\n"
1492 "# Standard Library End\n"
1493 "# Standard Library End\n"
1494 )
1495 test_output_lines_down = isort.code(
1496 code=test_input_lines_down,
1497 known_first_party=["myproject"],
1498 import_heading_stdlib="Standard Library",
1499 import_heading_firstparty="My Stuff",
1500 import_footer_stdlib="Standard Library End",
1501 import_footer_firstparty="My Stuff End",
1502 dedup_headings=True,
1503 )
1504 assert test_output_lines_down == (
1505 "# comment 1\n"
1506 "# Standard Library\n"
1507 "import os\n"
1508 "import statistics\n"
1509 "import sys\n"
1510 "import unicodedata\n"
1511 "\n"
1512 "# Standard Library End\n"
1513 "\n"
1514 "import django.settings\n"
1515 "\n"
1516 "# My Stuff\n"
1517 "import myproject.test\n"
1518 "\n"
1519 "# My Stuff End\n"
1520 )
1521
1522 test_input_lines_down = (
1523 "# comment 1\n"
1524 "# Standard Library\n"
1525 "import os\n"
1526 "import statistics\n"
1527 "import sys\n"
1528 "import unicodedata\n"
1529 "\n"
1530 "# Standard Library End\n"
1531 "\n"
1532 "import django.settings\n"
1533 "\n"
1534 "# My Stuff\n"
1535 "import myproject.test\n"
1536 )
1537 test_output_lines_down = isort.code(
1538 code=test_input_lines_down,
1539 known_first_party=["myproject"],
1540 import_heading_stdlib="Standard Library",
1541 import_heading_firstparty="My Stuff",
1542 import_footer_stdlib="Standard Library End",
1543 import_footer_firstparty="My Stuff End",
1544 dedup_headings=True,
1545 )
1546 assert test_output_lines_down == (
1547 "# comment 1\n"
1548 "# Standard Library\n"
1549 "import os\n"
1550 "import statistics\n"
1551 "import sys\n"
1552 "import unicodedata\n"
1553 "\n"
1554 "# Standard Library End\n"
1555 "\n"
1556 "import django.settings\n"
1557 "\n"
1558 "# My Stuff\n"
1559 "import myproject.test\n"
1560 "\n"
1561 "# My Stuff End\n"
1562 )
1563
1564
1565 def test_balanced_wrapping() -> None:
1566 """Tests balanced wrapping mode, where the length of individual lines maintain width."""
1567 test_input = (
1568 "from __future__ import (absolute_import, division, print_function,\n"
1569 " unicode_literals)"
1570 )
1571 test_output = isort.code(code=test_input, line_length=70, balanced_wrapping=True)
1572 assert test_output == (
1573 "from __future__ import (absolute_import, division,\n"
1574 " print_function, unicode_literals)\n"
1575 )
1576
1577
1578 def test_relative_import_with_space() -> None:
1579 """Tests the case where the relation and the module that is being imported from is separated
1580 with a space.
1581 """
1582 test_input = "from ... fields.sproqet import SproqetCollection"
1583 assert isort.code(test_input) == ("from ...fields.sproqet import SproqetCollection\n")
1584 test_input = "from .import foo"
1585 test_output = "from . import foo\n"
1586 assert isort.code(test_input) == test_output
1587 test_input = "from.import foo"
1588 test_output = "from . import foo\n"
1589 assert isort.code(test_input) == test_output
1590
1591
1592 def test_multiline_import() -> None:
1593 """Test the case where import spawns multiple lines with inconsistent indentation."""
1594 test_input = "from pkg \\\n import stuff, other_suff \\\n more_stuff"
1595 assert isort.code(test_input) == ("from pkg import more_stuff, other_suff, stuff\n")
1596
1597 # test again with a custom configuration
1598 custom_configuration: dict[str, Any] = {
1599 "force_single_line": True,
1600 "line_length": 120,
1601 "known_first_party": ["asdf", "qwer"],
1602 "default_section": "THIRDPARTY",
1603 "forced_separate": "asdf",
1604 }
1605 expected_output = (
1606 "from pkg import more_stuff\nfrom pkg import other_suff\nfrom pkg import stuff\n"
1607 )
1608 assert isort.code(test_input, **custom_configuration) == expected_output
1609
1610
1611 def test_single_multiline() -> None:
1612 """Test the case where a single import spawns multiple lines."""
1613 test_input = "from os import\\\n getuid\n\nprint getuid()\n"
1614 output = isort.code(test_input)
1615 assert output == ("from os import getuid\n\nprint getuid()\n")
1616
1617
1618 def test_atomic_mode() -> None:
1619 """With atomic mode isort should be able to automatically detect and stop syntax errors"""
1620 # without syntax error, everything works OK
1621 test_input = "from b import d, c\nfrom a import f, e\n"
1622 assert isort.code(test_input, atomic=True) == ("from a import e, f\nfrom b import c, d\n")
1623
1624 # with syntax error content is not changed
1625 test_input += "while True print 'Hello world'" # blatant syntax error
1626 with pytest.raises(ExistingSyntaxErrors):
1627 isort.code(test_input, atomic=True)
1628
1629 # unless file is for Cython which doesn't yet provide a public AST parsing API
1630 assert (
1631 isort.code(test_input, extension="pyx", atomic=True, verbose=True)
1632 == isort.code(test_input, extension="pyx", atomic=True)
1633 == """from a import e, f
1634 from b import c, d
1635
1636 while True print 'Hello world'
1637 """
1638 )
1639
1640 # ensure atomic works with streams
1641 test_stream_input = as_stream("from b import d, c\nfrom a import f, e\n")
1642 test_output = UnreadableStream()
1643 isort.stream(test_stream_input, test_output, atomic=True)
1644 test_output.seek(0)
1645 assert test_output.read() == "from a import e, f\nfrom b import c, d\n"
1646
1647
1648 def test_order_by_type() -> None:
1649 test_input = "from module import Class, CONSTANT, function"
1650 assert isort.code(test_input, order_by_type=True) == (
1651 "from module import CONSTANT, Class, function\n"
1652 )
1653
1654 # More complex sample data
1655 test_input = "from module import Class, CONSTANT, function, BASIC, Apple"
1656 assert isort.code(test_input, order_by_type=True) == (
1657 "from module import BASIC, CONSTANT, Apple, Class, function\n"
1658 )
1659
1660 # Really complex sample data, to verify we don't mess with top level imports, only nested ones
1661 test_input = (
1662 "import StringIO\n"
1663 "import glob\n"
1664 "import os\n"
1665 "import shutil\n"
1666 "import tempfile\n"
1667 "import time\n"
1668 "from subprocess import PIPE, Popen, STDOUT\n"
1669 )
1670
1671 assert isort.code(test_input, order_by_type=True, py_version="27") == (
1672 "import glob\n"
1673 "import os\n"
1674 "import shutil\n"
1675 "import StringIO\n"
1676 "import tempfile\n"
1677 "import time\n"
1678 "from subprocess import PIPE, STDOUT, Popen\n"
1679 )
1680
1681
1682 @pytest.mark.parametrize("has_body", [True, False])
1683 def test_custom_lines_before_import_section(has_body: bool) -> None:
1684 """Test the case where the number of lines to output before imports has been explicitly set."""
1685 test_input = "from a import b\n"
1686 if has_body:
1687 test_input += "\nfoo = 'bar'\n"
1688
1689 ln = "\n"
1690
1691 # default case is no line added before the import
1692 assert isort.code(test_input) == (test_input)
1693
1694 # test again with a custom number of lines before the import section
1695 assert isort.code(test_input, lines_before_imports=2) == 2 * ln + test_input
1696
1697 comment = "# Comment\n"
1698
1699 # test with a comment above
1700 assert isort.code(comment + ln + test_input, lines_before_imports=0) == comment + test_input
1701
1702 # test with comments with empty lines
1703 assert (
1704 isort.code(comment + ln + comment + 3 * ln + test_input, lines_before_imports=1)
1705 == comment + ln + comment + 1 * ln + test_input
1706 )
1707
1708
1709 def test_check_code_detects_lines_before_import_changes() -> None:
1710 """check_code must return False when lines_before_imports requires adding or removing blank
1711 lines before the import section, even if the imports themselves are already sorted.
1712
1713 Regression test for https://github.com/PyCQA/isort/issues/2242
1714 """
1715 code = """from a import b, x
1716
1717 foo = 'bar'
1718 """
1719
1720 # Adding a blank line before imports (0 present, 1 required)
1721 assert isort.code(code, lines_before_imports=1) == "\n" + code
1722 assert not isort.check_code(code, lines_before_imports=1)
1723
1724 # Removing a blank line before imports (1 present, 0 required)
1725 assert isort.code("\n" + code, lines_before_imports=0) == code
1726 assert not isort.check_code("\n" + code, lines_before_imports=0)
1727
1728 # Already correct: no change needed
1729 assert isort.check_code(code, lines_before_imports=0)
1730 assert isort.check_code("\n" + code, lines_before_imports=1)
1731
1732
1733 def test_custom_lines_after_import_section() -> None:
1734 """Test the case where the number of lines to output after imports has been explicitly set."""
1735 test_input = "from a import b\nfoo = 'bar'\n"
1736
1737 # default case is one space if not method or class after imports
1738 assert isort.code(test_input) == ("from a import b\n\nfoo = 'bar'\n")
1739
1740 # test again with a custom number of lines after the import section
1741 assert isort.code(test_input, lines_after_imports=2) == ("from a import b\n\n\nfoo = 'bar'\n")
1742
1743
1744 def test_smart_lines_after_import_section() -> None:
1745 """Tests the default 'smart' behavior for dealing with lines after the import section"""
1746 # one space if not method or class after imports
1747 test_input = "from a import b\nfoo = 'bar'\n"
1748 assert isort.code(test_input) == ("from a import b\n\nfoo = 'bar'\n")
1749
1750 # two spaces if a method or class after imports
1751 test_input = "from a import b\ndef my_function():\n pass\n"
1752 assert isort.code(test_input) == ("from a import b\n\n\ndef my_function():\n pass\n")
1753
1754 # two spaces if an async method after imports
1755 test_input = "from a import b\nasync def my_function():\n pass\n"
1756 assert isort.code(test_input) == ("from a import b\n\n\nasync def my_function():\n pass\n")
1757
1758 # two spaces if a method or class after imports - even if comment before function
1759 test_input = "from a import b\n# comment should be ignored\ndef my_function():\n pass\n"
1760 assert isort.code(test_input) == (
1761 "from a import b\n\n\n# comment should be ignored\ndef my_function():\n pass\n"
1762 )
1763
1764 # the same logic does not apply to doc strings
1765 test_input = (
1766 'from a import b\n"""\n comment should be ignored\n"""\ndef my_function():\n pass\n'
1767 )
1768 assert isort.code(test_input) == (
1769 'from a import b\n\n"""\n comment should be ignored\n"""\ndef my_function():\n pass\n'
1770 )
1771
1772 # Ensure logic doesn't incorrectly skip over assignments to multi-line strings
1773 test_input = 'from a import b\nX = """test\n"""\ndef my_function():\n pass\n'
1774 assert isort.code(test_input) == (
1775 'from a import b\n\nX = """test\n"""\ndef my_function():\n pass\n'
1776 )
1777
1778
1779 def test_settings_overwrite() -> None:
1780 """Test to ensure settings overwrite instead of trying to combine."""
1781 assert Config(known_standard_library=["not_std_library"]).known_standard_library == frozenset(
1782 {"not_std_library"}
1783 )
1784 assert Config(known_first_party=["thread"]).known_first_party == frozenset({"thread"})
1785
1786
1787 def test_combined_from_and_as_imports() -> None:
1788 """Test to ensure it's possible to combine from and as imports."""
1789 test_input = (
1790 "from translate.misc.multistring import multistring\n"
1791 "from translate.storage import base, factory\n"
1792 "from translate.storage.placeables import general, parse as rich_parse\n"
1793 )
1794 assert isort.code(test_input, combine_as_imports=True) == test_input
1795 assert isort.code(test_input, combine_as_imports=True, only_sections=True) == test_input
1796 test_input = "import os \nimport os as _os"
1797 test_output = "import os\nimport os as _os\n"
1798 assert isort.code(test_input) == test_output
1799
1800
1801 def test_as_imports_with_line_length() -> None:
1802 """Test to ensure it's possible to combine from and as imports."""
1803 test_input = (
1804 "from translate.storage import base as storage_base\n"
1805 "from translate.storage.placeables import general, parse as rich_parse\n"
1806 )
1807 assert isort.code(code=test_input, combine_as_imports=False, line_length=40) == (
1808 "from translate.storage import \\\n base as storage_base\n"
1809 "from translate.storage.placeables import \\\n general\n"
1810 "from translate.storage.placeables import \\\n parse as rich_parse\n"
1811 )
1812
1813
1814 def test_keep_comments() -> None:
1815 """Test to ensure isort properly keeps comments in tact after sorting."""
1816 # Straight Import
1817 test_input = "import foo # bar\n"
1818 assert isort.code(test_input) == test_input
1819
1820 # Star import
1821 test_input_star = "from foo import * # bar\n"
1822 assert isort.code(test_input_star) == test_input_star
1823
1824 # Force Single Line From Import
1825 test_input = "from foo import bar # comment\n"
1826 assert isort.code(test_input, force_single_line=True) == test_input
1827
1828 # From import
1829 test_input = "from foo import bar # My Comment\n"
1830 assert isort.code(test_input) == test_input
1831
1832 # More complicated case
1833 test_input = "from a import b # My Comment1\nfrom a import c # My Comment2\n"
1834 assert isort.code(test_input) == (
1835 "from a import b # My Comment1\nfrom a import c # My Comment2\n"
1836 )
1837
1838 # Test case where imports comments make imports extend pass the line length
1839 test_input = "from a import b # My Comment1\nfrom a import c # My Comment2\nfrom a import d\n"
1840 assert isort.code(test_input, line_length=45) == (
1841 "from a import b # My Comment1\nfrom a import c # My Comment2\nfrom a import d\n"
1842 )
1843
1844 # Test case where imports with comments will be beyond line length limit
1845 test_input = (
1846 "from a import b, c # My Comment1\n"
1847 "from a import c, d # My Comment2 is really really really really long\n"
1848 )
1849 assert isort.code(test_input, line_length=45) == (
1850 "from a import ( # My Comment1; My Comment2 is really really really really long\n"
1851 " b, c, d)\n"
1852 )
1853
1854 # Test that comments are not stripped from 'import ... as ...' by default
1855 test_input = "from a import b as bb # b comment\nfrom a import c as cc # c comment\n"
1856 assert isort.code(test_input) == test_input
1857
1858 # Test that 'import ... as ...' comments are not collected inappropriately
1859 test_input = (
1860 "from a import b as bb # b comment\nfrom a import c as cc # c comment\nfrom a import d\n"
1861 )
1862 assert isort.code(test_input) == test_input
1863 assert isort.code(test_input, combine_as_imports=True) == (
1864 "from a import b as bb, c as cc, d # b comment; c comment\n"
1865 )
1866
1867
1868 def test_multiline_split_on_dot() -> None:
1869 """Test to ensure isort correctly handles multiline imports,
1870 even when split right after a '.'
1871 """
1872 test_input = (
1873 "from my_lib.my_package.test.level_1.level_2.level_3.level_4.level_5.\\\n"
1874 " my_module import my_function"
1875 )
1876 assert isort.code(test_input, line_length=70) == (
1877 "from my_lib.my_package.test.level_1.level_2.level_3.level_4.level_5.my_module import \\\n"
1878 " my_function\n"
1879 )
1880
1881
1882 def test_import_star() -> None:
1883 """Test to ensure isort handles star imports correctly"""
1884 test_input = "from blah import *\nfrom blah import _potato\n"
1885 assert isort.code(test_input) == ("from blah import *\nfrom blah import _potato\n")
1886 assert isort.code(test_input, combine_star=True) == ("from blah import *\n")
1887
1888
1889 def test_include_trailing_comma() -> None:
1890 """Test for the include_trailing_comma option"""
1891 test_output_grid = isort.code(
1892 code=SHORT_IMPORT,
1893 multi_line_output=WrapModes.GRID,
1894 line_length=40,
1895 include_trailing_comma=True,
1896 )
1897 assert test_output_grid == (
1898 "from third_party import (lib1, lib2,\n lib3, lib4,)\n"
1899 )
1900
1901 test_output_vertical = isort.code(
1902 code=SHORT_IMPORT,
1903 multi_line_output=WrapModes.VERTICAL,
1904 line_length=40,
1905 include_trailing_comma=True,
1906 )
1907 assert test_output_vertical == (
1908 "from third_party import (lib1,\n"
1909 " lib2,\n"
1910 " lib3,\n"
1911 " lib4,)\n"
1912 )
1913
1914 test_output_vertical_indent = isort.code(
1915 code=SHORT_IMPORT,
1916 multi_line_output=WrapModes.VERTICAL_HANGING_INDENT,
1917 line_length=40,
1918 include_trailing_comma=True,
1919 )
1920 assert test_output_vertical_indent == (
1921 "from third_party import (\n lib1,\n lib2,\n lib3,\n lib4,\n)\n"
1922 )
1923
1924 test_output_vertical_grid = isort.code(
1925 code=SHORT_IMPORT,
1926 multi_line_output=WrapModes.VERTICAL_GRID,
1927 line_length=40,
1928 include_trailing_comma=True,
1929 )
1930 assert test_output_vertical_grid == (
1931 "from third_party import (\n lib1, lib2, lib3, lib4,)\n"
1932 )
1933
1934 test_output_vertical_grid_grouped = isort.code(
1935 code=SHORT_IMPORT,
1936 multi_line_output=WrapModes.VERTICAL_GRID_GROUPED,
1937 line_length=40,
1938 include_trailing_comma=True,
1939 )
1940 assert test_output_vertical_grid_grouped == (
1941 "from third_party import (\n lib1, lib2, lib3, lib4,\n)\n"
1942 )
1943
1944 test_output_wrap_single_import_with_use_parentheses = isort.code(
1945 code=SINGLE_FROM_IMPORT, line_length=25, include_trailing_comma=True, use_parentheses=True
1946 )
1947 assert test_output_wrap_single_import_with_use_parentheses == (
1948 "from third_party import (\n lib1,)\n"
1949 )
1950
1951 test_output_wrap_single_import_vertical_indent = isort.code(
1952 code=SINGLE_FROM_IMPORT,
1953 line_length=25,
1954 multi_line_output=WrapModes.VERTICAL_HANGING_INDENT,
1955 include_trailing_comma=True,
1956 use_parentheses=True,
1957 )
1958 assert test_output_wrap_single_import_vertical_indent == (
1959 "from third_party import (\n lib1,\n)\n"
1960 )
1961
1962 trailing_comma_with_comment = (
1963 "from six.moves.urllib.parse import urlencode "
1964 "# pylint: disable=no-name-in-module,import-error"
1965 )
1966 expected_trailing_comma_with_comment = (
1967 "from six.moves.urllib.parse import (\n"
1968 " urlencode, # pylint: disable=no-n"
1969 "ame-in-module,import-error\n)\n"
1970 )
1971 trailing_comma_with_comment = isort.code(
1972 code=trailing_comma_with_comment,
1973 line_length=80,
1974 multi_line_output=WrapModes.VERTICAL_HANGING_INDENT,
1975 include_trailing_comma=True,
1976 use_parentheses=True,
1977 )
1978 assert trailing_comma_with_comment == expected_trailing_comma_with_comment
1979 # The next time around, it should be equal
1980 trailing_comma_with_comment = isort.code(
1981 code=trailing_comma_with_comment,
1982 line_length=80,
1983 multi_line_output=WrapModes.VERTICAL_HANGING_INDENT,
1984 include_trailing_comma=True,
1985 use_parentheses=True,
1986 )
1987 assert trailing_comma_with_comment == expected_trailing_comma_with_comment
1988
1989
1990 def test_similar_to_std_library() -> None:
1991 """Test to ensure modules that are named similarly to a standard library import
1992 don't end up clobbered
1993 """
1994 test_input = "import datetime\n\nimport requests\nimport times\n"
1995 assert isort.code(test_input, known_third_party=["requests", "times"]) == test_input
1996
1997
1998 def test_correctly_placed_imports() -> None:
1999 """Test to ensure comments stay on correct placement after being sorted"""
2000 test_input = "from a import b # comment for b\nfrom a import c # comment for c\n"
2001 assert isort.code(test_input, force_single_line=True) == (
2002 "from a import b # comment for b\nfrom a import c # comment for c\n"
2003 )
2004 assert isort.code(test_input) == (
2005 "from a import b # comment for b\nfrom a import c # comment for c\n"
2006 )
2007
2008 # Full example test from issue #143
2009 test_input = (
2010 "from itertools import chain\n"
2011 "\n"
2012 "from django.test import TestCase\n"
2013 "from model_mommy import mommy\n"
2014 "\n"
2015 "from apps.clientman.commands.download_usage_rights import "
2016 "associate_right_for_item_product\n"
2017 "from apps.clientman.commands.download_usage_rights import "
2018 "associate_right_for_item_product_d"
2019 "efinition\n"
2020 "from apps.clientman.commands.download_usage_rights import "
2021 "associate_right_for_item_product_d"
2022 "efinition_platform\n"
2023 "from apps.clientman.commands.download_usage_rights import "
2024 "associate_right_for_item_product_p"
2025 "latform\n"
2026 "from apps.clientman.commands.download_usage_rights import "
2027 "associate_right_for_territory_reta"
2028 "il_model\n"
2029 "from apps.clientman.commands.download_usage_rights import "
2030 "associate_right_for_territory_reta"
2031 "il_model_definition_platform_provider # noqa\n"
2032 "from apps.clientman.commands.download_usage_rights import "
2033 "clear_right_for_item_product\n"
2034 "from apps.clientman.commands.download_usage_rights import "
2035 "clear_right_for_item_product_defini"
2036 "tion\n"
2037 "from apps.clientman.commands.download_usage_rights import "
2038 "clear_right_for_item_product_defini"
2039 "tion_platform\n"
2040 "from apps.clientman.commands.download_usage_rights import "
2041 "clear_right_for_item_product_platfo"
2042 "rm\n"
2043 "from apps.clientman.commands.download_usage_rights import "
2044 "clear_right_for_territory_retail_mo"
2045 "del\n"
2046 "from apps.clientman.commands.download_usage_rights import "
2047 "clear_right_for_territory_retail_mo"
2048 "del_definition_platform_provider # noqa\n"
2049 "from apps.clientman.commands.download_usage_rights import "
2050 "create_download_usage_right\n"
2051 "from apps.clientman.commands.download_usage_rights import "
2052 "delete_download_usage_right\n"
2053 "from apps.clientman.commands.download_usage_rights import "
2054 "disable_download_for_item_product\n"
2055 "from apps.clientman.commands.download_usage_rights import "
2056 "disable_download_for_item_product_d"
2057 "efinition\n"
2058 "from apps.clientman.commands.download_usage_rights import "
2059 "disable_download_for_item_product_d"
2060 "efinition_platform\n"
2061 "from apps.clientman.commands.download_usage_rights import "
2062 "disable_download_for_item_product_p"
2063 "latform\n"
2064 "from apps.clientman.commands.download_usage_rights import "
2065 "disable_download_for_territory_reta"
2066 "il_model\n"
2067 "from apps.clientman.commands.download_usage_rights import "
2068 "disable_download_for_territory_reta"
2069 "il_model_definition_platform_provider # noqa\n"
2070 "from apps.clientman.commands.download_usage_rights import "
2071 "get_download_rights_for_item\n"
2072 "from apps.clientman.commands.download_usage_rights import "
2073 "get_right\n"
2074 )
2075 assert (
2076 isort.code(
2077 code=test_input,
2078 force_single_line=True,
2079 line_length=140,
2080 known_third_party=["django", "model_mommy"],
2081 default_section=sections.FIRSTPARTY,
2082 )
2083 == test_input
2084 )
2085
2086
2087 def test_auto_detection() -> None:
2088 """Initial test to ensure isort auto-detection works correctly -
2089 will grow over time as new issues are raised.
2090 """
2091
2092 # Issue 157
2093 test_input = "import binascii\nimport os\n\nimport cv2\nimport requests\n"
2094 assert isort.code(test_input, known_third_party=["cv2", "requests"]) == test_input
2095
2096 # alternative solution
2097 assert isort.code(test_input, default_section="THIRDPARTY") == test_input
2098
2099
2100 def test_same_line_statements() -> None:
2101 """Ensure isort correctly handles the case where a single line
2102 contains multiple statements including an import
2103 """
2104 test_input = "import pdb; import nose\n"
2105 assert isort.code(test_input) == ("import pdb\n\nimport nose\n")
2106
2107 test_input = "import pdb; pdb.set_trace()\nimport nose; nose.run()\n"
2108 assert isort.code(test_input) == test_input
2109
2110
2111 def test_long_line_comments() -> None:
2112 """Ensure isort correctly handles comments at the end of extremely long lines"""
2113 test_input = (
2114 "from foo.utils.fabric_stuff.live import check_clean_live, deploy_live, "
2115 "sync_live_envdir, "
2116 "update_live_app, update_live_cron # noqa\n"
2117 "from foo.utils.fabric_stuff.stage import check_clean_stage, deploy_stage, "
2118 "sync_stage_envdir, "
2119 "update_stage_app, update_stage_cron # noqa\n"
2120 )
2121 assert isort.code(code=test_input, line_length=100, balanced_wrapping=True) == (
2122 "from foo.utils.fabric_stuff.live import (check_clean_live, deploy_live, # noqa\n"
2123 " sync_live_envdir, update_live_app, "
2124 "update_live_cron)\n"
2125 "from foo.utils.fabric_stuff.stage import (check_clean_stage, deploy_stage, # noqa\n"
2126 " sync_stage_envdir, update_stage_app, "
2127 "update_stage_cron)\n"
2128 )
2129
2130
2131 def test_tab_character_in_import() -> None:
2132 """Ensure isort correctly handles import statements that contain a tab character"""
2133 test_input = "from __future__ import print_function\nfrom __future__ import\tprint_function\n"
2134 assert isort.code(test_input) == "from __future__ import print_function\n"
2135
2136
2137 def test_split_position() -> None:
2138 """Ensure isort splits on import instead of . when possible"""
2139 test_input = (
2140 "from p24.shared.exceptions.master.host_state_flag_unchanged "
2141 "import HostStateUnchangedException\n"
2142 )
2143 assert isort.code(test_input, line_length=80) == (
2144 "from p24.shared.exceptions.master.host_state_flag_unchanged import \\\n"
2145 " HostStateUnchangedException\n"
2146 )
2147
2148
2149 def test_place_comments() -> None:
2150 """Ensure manually placing imports works as expected"""
2151 test_input = (
2152 "import sys\n"
2153 "import os\n"
2154 "import myproject.test\n"
2155 "import django.settings\n"
2156 "\n"
2157 "# isort: imports-thirdparty\n"
2158 "# isort: imports-firstparty\n"
2159 "# isort:imports-stdlib\n"
2160 "\n"
2161 )
2162 expected_output = (
2163 "\n# isort: imports-thirdparty\n"
2164 "import django.settings\n"
2165 "\n"
2166 "# isort: imports-firstparty\n"
2167 "import myproject.test\n"
2168 "\n"
2169 "# isort:imports-stdlib\n"
2170 "import os\n"
2171 "import sys\n"
2172 )
2173 test_output = isort.code(test_input, known_first_party=["myproject"])
2174 assert test_output == expected_output
2175 test_output = isort.code(test_output, known_first_party=["myproject"])
2176 assert test_output == expected_output
2177
2178
2179 def test_placement_control() -> None:
2180 """Ensure that most specific placement control match wins"""
2181 test_input = (
2182 "import os\n"
2183 "import sys\n"
2184 "from bottle import Bottle, redirect, response, run\n"
2185 "import p24.imports._argparse as argparse\n"
2186 "import p24.imports._subprocess as subprocess\n"
2187 "import p24.imports._VERSION as VERSION\n"
2188 "import p24.shared.media_wiki_syntax as syntax\n"
2189 )
2190 test_output = isort.code(
2191 code=test_input,
2192 known_first_party=["p24", "p24.imports._VERSION"],
2193 known_standard_library=["p24.imports", "os", "sys"],
2194 known_third_party=["bottle"],
2195 default_section="THIRDPARTY",
2196 )
2197
2198 assert test_output == (
2199 "import os\n"
2200 "import p24.imports._argparse as argparse\n"
2201 "import p24.imports._subprocess as subprocess\n"
2202 "import sys\n"
2203 "\n"
2204 "from bottle import Bottle, redirect, response, run\n"
2205 "\n"
2206 "import p24.imports._VERSION as VERSION\n"
2207 "import p24.shared.media_wiki_syntax as syntax\n"
2208 )
2209
2210
2211 def test_custom_sections() -> None:
2212 """Ensure that most specific placement control match wins"""
2213 test_input = (
2214 "import os\n"
2215 "import sys\n"
2216 "from django.conf import settings\n"
2217 "from bottle import Bottle, redirect, response, run\n"
2218 "import p24.imports._argparse as argparse\n"
2219 "from django.db import models\n"
2220 "import p24.imports._subprocess as subprocess\n"
2221 "import pandas as pd\n"
2222 "import p24.imports._VERSION as VERSION\n"
2223 "import numpy as np\n"
2224 "import p24.shared.media_wiki_syntax as syntax\n"
2225 )
2226 test_output = isort.code(
2227 code=test_input,
2228 known_first_party=["p24", "p24.imports._VERSION"],
2229 import_heading_stdlib="Standard Library",
2230 import_heading_thirdparty="Third Party",
2231 import_heading_firstparty="First Party",
2232 import_heading_django="Django",
2233 import_heading_pandas="Pandas",
2234 known_standard_library=["p24.imports", "os", "sys"],
2235 known_third_party=["bottle"],
2236 known_django=["django"],
2237 known_pandas=["pandas", "numpy"],
2238 default_section="THIRDPARTY",
2239 sections=[
2240 "FUTURE",
2241 "STDLIB",
2242 "DJANGO",
2243 "THIRDPARTY",
2244 "PANDAS",
2245 "FIRSTPARTY",
2246 "LOCALFOLDER",
2247 ],
2248 )
2249 assert test_output == (
2250 "# Standard Library\n"
2251 "import os\n"
2252 "import p24.imports._argparse as argparse\n"
2253 "import p24.imports._subprocess as subprocess\n"
2254 "import sys\n"
2255 "\n"
2256 "# Django\n"
2257 "from django.conf import settings\n"
2258 "from django.db import models\n"
2259 "\n"
2260 "# Third Party\n"
2261 "from bottle import Bottle, redirect, response, run\n"
2262 "\n"
2263 "# Pandas\n"
2264 "import numpy as np\n"
2265 "import pandas as pd\n"
2266 "\n"
2267 "# First Party\n"
2268 "import p24.imports._VERSION as VERSION\n"
2269 "import p24.shared.media_wiki_syntax as syntax\n"
2270 )
2271
2272
2273 def test_custom_sections_exception_handling() -> None:
2274 """Ensure that appropriate exception is raised for missing sections"""
2275 test_input = "import requests\n"
2276
2277 with pytest.raises(MissingSection):
2278 isort.code(
2279 code=test_input,
2280 default_section="THIRDPARTY",
2281 sections=[
2282 "FUTURE",
2283 "STDLIB",
2284 "DJANGO",
2285 "PANDAS",
2286 "FIRSTPARTY",
2287 "LOCALFOLDER",
2288 ],
2289 )
2290
2291 test_input = "from requests import get, post\n"
2292
2293 with pytest.raises(MissingSection):
2294 isort.code(
2295 code=test_input,
2296 default_section="THIRDPARTY",
2297 sections=[
2298 "FUTURE",
2299 "STDLIB",
2300 "DJANGO",
2301 "PANDAS",
2302 "FIRSTPARTY",
2303 "LOCALFOLDER",
2304 ],
2305 )
2306
2307
2308 def test_glob_known() -> None:
2309 """Ensure that most specific placement control match wins"""
2310 test_input = (
2311 "import os\n"
2312 "from django_whatever import whatever\n"
2313 "import sys\n"
2314 "from django.conf import settings\n"
2315 "from . import another\n"
2316 )
2317 test_output = isort.code(
2318 code=test_input,
2319 import_heading_stdlib="Standard Library",
2320 import_heading_thirdparty="Third Party",
2321 import_heading_firstparty="First Party",
2322 import_heading_django="Django",
2323 import_heading_djangoplugins="Django Plugins",
2324 import_heading_localfolder="Local",
2325 known_django=["django"],
2326 known_djangoplugins=["django_*"],
2327 default_section="THIRDPARTY",
2328 sections=[
2329 "FUTURE",
2330 "STDLIB",
2331 "DJANGO",
2332 "DJANGOPLUGINS",
2333 "THIRDPARTY",
2334 "FIRSTPARTY",
2335 "LOCALFOLDER",
2336 ],
2337 )
2338 assert test_output == (
2339 "# Standard Library\n"
2340 "import os\n"
2341 "import sys\n"
2342 "\n"
2343 "# Django\n"
2344 "from django.conf import settings\n"
2345 "\n"
2346 "# Django Plugins\n"
2347 "from django_whatever import whatever\n"
2348 "\n"
2349 "# Local\n"
2350 "from . import another\n"
2351 )
2352
2353
2354 def test_sticky_comments() -> None:
2355 """Test to ensure it is possible to make comments 'stick' above imports"""
2356 test_input = (
2357 "import os\n"
2358 "\n"
2359 "# Used for type-hinting (ref: https://github.com/davidhalter/jedi/issues/414).\n"
2360 "from selenium.webdriver.remote.webdriver import WebDriver # noqa\n"
2361 )
2362 assert isort.code(test_input) == test_input
2363
2364 test_input = (
2365 "from django import forms\n"
2366 "# While this couples the geographic forms to the GEOS library,\n"
2367 "# it decouples from database (by not importing SpatialBackend).\n"
2368 "from django.contrib.gis.geos import GEOSException, GEOSGeometry\n"
2369 "from django.utils.translation import ugettext_lazy as _\n"
2370 )
2371 assert isort.code(test_input) == test_input
2372
2373
2374 def test_zipimport() -> None:
2375 """Imports ending in "import" shouldn't be clobbered"""
2376 test_input = "from zipimport import zipimport\n"
2377 assert isort.code(test_input) == test_input
2378
2379
2380 def test_from_ending() -> None:
2381 """Imports ending in "from" shouldn't be clobbered."""
2382 test_input = "from foo import get_foo_from, get_foo\n"
2383 expected_output = "from foo import get_foo, get_foo_from\n"
2384 assert isort.code(test_input) == expected_output
2385
2386
2387 def test_from_first() -> None:
2388 """Tests the setting from_first works correctly"""
2389 test_input = "from os import path\nimport os\n"
2390 assert isort.code(test_input, from_first=True) == test_input
2391
2392
2393 def test_top_comments() -> None:
2394 """Ensure correct behavior with top comments"""
2395 test_input = (
2396 "# -*- encoding: utf-8 -*-\n# Test comment\n#\nfrom __future__ import unicode_literals\n"
2397 )
2398 assert isort.code(test_input) == test_input
2399
2400 test_input = (
2401 "# -*- coding: utf-8 -*-\n"
2402 "from django.db import models\n"
2403 "from django.utils.encoding import python_2_unicode_compatible\n"
2404 )
2405 assert isort.code(test_input) == test_input
2406
2407 test_input = "# Comment\nimport sys\n"
2408 assert isort.code(test_input) == test_input
2409
2410 test_input = "# -*- coding\nimport sys\n"
2411 assert isort.code(test_input) == test_input
2412
2413
2414 def test_consistency() -> None:
2415 """Ensures consistency of handling even when dealing with non ordered-by-type imports"""
2416 test_input = "from sqlalchemy.dialects.postgresql import ARRAY, array\n"
2417 assert isort.code(test_input, order_by_type=True) == test_input
2418
2419
2420 def test_force_grid_wrap() -> None:
2421 """Ensures removing imports works as expected."""
2422 test_input = "from bar import lib2\nfrom foo import lib6, lib7\n"
2423 test_output = isort.code(
2424 code=test_input, force_grid_wrap=2, multi_line_output=WrapModes.VERTICAL_HANGING_INDENT
2425 )
2426 assert (
2427 test_output
2428 == """from bar import lib2
2429 from foo import (
2430 lib6,
2431 lib7
2432 )
2433 """
2434 )
2435 test_output = isort.code(
2436 code=test_input, force_grid_wrap=3, multi_line_output=WrapModes.VERTICAL_HANGING_INDENT
2437 )
2438 assert test_output == test_input
2439
2440
2441 def test_force_grid_wrap_long() -> None:
2442 """Ensure that force grid wrap still happens with long line length"""
2443 test_input = (
2444 "from foo import lib6, lib7\n"
2445 "from bar import lib2\n"
2446 "from babar import something_that_is_kind_of_long"
2447 )
2448 test_output = isort.code(
2449 code=test_input,
2450 force_grid_wrap=2,
2451 multi_line_output=WrapModes.VERTICAL_HANGING_INDENT,
2452 line_length=9999,
2453 )
2454 assert (
2455 test_output
2456 == """from babar import something_that_is_kind_of_long
2457 from bar import lib2
2458 from foo import (
2459 lib6,
2460 lib7
2461 )
2462 """
2463 )
2464
2465
2466 def test_uses_jinja_variables() -> None:
2467 """Test a basic set of imports that use jinja variables"""
2468 test_input = "import sys\nimport os\nimport myproject.{ test }\nimport django.{ settings }"
2469 test_output = isort.code(
2470 code=test_input, known_third_party=["django"], known_first_party=["myproject"]
2471 )
2472 assert test_output == (
2473 "import os\nimport sys\n\nimport django.{ settings }\n\nimport myproject.{ test }\n"
2474 )
2475
2476 test_input = "import {{ cookiecutter.repo_name }}\nfrom foo import {{ cookiecutter.bar }}\n"
2477 assert isort.code(test_input) == test_input
2478
2479
2480 def test_fcntl() -> None:
2481 """Test to ensure fcntl gets correctly recognized as stdlib import"""
2482 test_input = "import fcntl\nimport os\nimport sys\n"
2483 assert isort.code(test_input) == test_input
2484
2485
2486 def test_import_split_is_word_boundary_aware() -> None:
2487 """Test to ensure that isort splits words in a boundary aware manner"""
2488 test_input = (
2489 "from mycompany.model.size_value_array_import_func import \\\n"
2490 " get_size_value_array_import_func_jobs"
2491 )
2492 test_output = isort.code(
2493 code=test_input, multi_line_output=WrapModes.VERTICAL_HANGING_INDENT, line_length=79
2494 )
2495 assert test_output == (
2496 "from mycompany.model.size_value_array_import_func import (\n"
2497 " get_size_value_array_import_func_jobs\n"
2498 ")\n"
2499 )
2500
2501
2502 def test_other_file_encodings(tmp_path: Path) -> None:
2503 """Test to ensure file encoding is respected"""
2504 for encoding in ("latin1", "utf8"):
2505 tmp_fname = tmp_path / f"test_{encoding}.py"
2506 file_contents = f"# coding: {encoding}\n\ns = u'ã'\n"
2507 tmp_fname.write_bytes(file_contents.encode(encoding))
2508 api.sort_file(tmp_fname, file_path=tmp_fname, settings_path=os.getcwd())
2509 assert tmp_fname.read_text(encoding) == file_contents
2510
2511
2512 def test_other_file_encodings_in_place(tmp_path: Path) -> None:
2513 """Test to ensure file encoding is respected when overwritten in place."""
2514 for encoding in ("latin1", "utf8"):
2515 tmp_fname = tmp_path / f"test_{encoding}.py"
2516 file_contents = f"# coding: {encoding}\n\ns = u'ã'\n"
2517 tmp_fname.write_bytes(file_contents.encode(encoding))
2518 api.sort_file(
2519 tmp_fname,
2520 file_path=tmp_fname,
2521 settings_path=os.getcwd(),
2522 overwrite_in_place=True,
2523 )
2524 assert tmp_fname.read_text(encoding) == file_contents
2525
2526
2527 def test_encoding_not_in_comment(tmp_path: Path) -> None:
2528 """Test that 'encoding' not in a comment is ignored"""
2529 tmp_fname = tmp_path / "test_encoding.py"
2530 file_contents = "class Foo\n coding: latin1\n\ns = u'ã'\n"
2531 tmp_fname.write_bytes(file_contents.encode("utf8"))
2532 assert (
2533 isort.code(tmp_fname.read_text("utf8"), file_path=tmp_fname, settings_path=os.getcwd())
2534 == file_contents
2535 )
2536
2537
2538 def test_encoding_not_in_first_two_lines(tmp_path: Path) -> None:
2539 """Test that 'encoding' not in the first two lines is ignored"""
2540 tmp_fname = tmp_path / "test_encoding.py"
2541 file_contents = "\n\n# -*- coding: latin1\n\ns = u'ã'\n"
2542 tmp_fname.write_bytes(file_contents.encode("utf8"))
2543 assert (
2544 isort.code(tmp_fname.read_text("utf8"), file_path=tmp_fname, settings_path=os.getcwd())
2545 == file_contents
2546 )
2547
2548
2549 def test_comment_at_top_of_file() -> None:
2550 """Test to ensure isort correctly handles top of file comments"""
2551 test_input = (
2552 "# Comment one\n"
2553 "from django import forms\n"
2554 "# Comment two\n"
2555 "from django.contrib.gis.geos import GEOSException\n"
2556 )
2557 assert isort.code(test_input) == test_input
2558
2559 test_input = "# -*- coding: utf-8 -*-\nfrom django.db import models\n"
2560 assert isort.code(test_input) == test_input
2561
2562
2563 def test_alphabetic_sorting() -> None:
2564 """Test to ensure isort correctly handles single line imports"""
2565 test_input = (
2566 "import unittest\n"
2567 "\n"
2568 "import ABC\n"
2569 "import Zope\n"
2570 "from django.contrib.gis.geos import GEOSException\n"
2571 "from plone.app.testing import getRoles\n"
2572 "from plone.app.testing import ManageRoles\n"
2573 "from plone.app.testing import setRoles\n"
2574 "from Products.CMFPlone import utils\n"
2575 )
2576 options = {
2577 "force_single_line": True,
2578 "force_alphabetical_sort_within_sections": True,
2579 } # type: dict[str, Any]
2580
2581 output = isort.code(test_input, **options)
2582 assert output == test_input
2583
2584 test_input = "# -*- coding: utf-8 -*-\nfrom django.db import models\n"
2585 assert isort.code(test_input) == test_input
2586
2587
2588 def test_alphabetic_sorting_multi_line() -> None:
2589 """Test to ensure isort correctly handles multiline import see: issue 364"""
2590 test_input = (
2591 "from a import (CONSTANT_A, cONSTANT_B, CONSTANT_C, CONSTANT_D, CONSTANT_E,\n"
2592 " CONSTANT_F, CONSTANT_G, CONSTANT_H, CONSTANT_I, CONSTANT_J)\n"
2593 )
2594 options = {"force_alphabetical_sort_within_sections": True} # type: dict[str, Any]
2595 assert isort.code(test_input, **options) == test_input
2596
2597
2598 def test_comments_not_duplicated() -> None:
2599 """Test to ensure comments aren't duplicated: issue 303"""
2600 test_input = (
2601 "from flask import url_for\n"
2602 "# Whole line comment\n"
2603 "from service import demo # inline comment\n"
2604 "from service import settings\n"
2605 )
2606 output = isort.code(test_input)
2607 assert output.count("# Whole line comment\n") == 1
2608 assert output.count("# inline comment\n") == 1
2609
2610
2611 def test_top_of_line_comments() -> None:
2612 """Test to ensure top of line comments stay where they should: issue 260"""
2613 test_input = (
2614 "# -*- coding: utf-8 -*-\n"
2615 "from django.db import models\n"
2616 "#import json as simplejson\n"
2617 "from myproject.models import Servidor\n"
2618 "\n"
2619 "import reversion\n"
2620 "\n"
2621 "import logging\n"
2622 )
2623 output = isort.code(test_input)
2624 print(output)
2625 assert output.startswith("# -*- coding: utf-8 -*-\n")
2626
2627
2628 def test_basic_comment() -> None:
2629 """Test to ensure a basic comment won't crash isort"""
2630 test_input = "import logging\n# Foo\nimport os\n"
2631 assert isort.code(test_input) == test_input
2632
2633
2634 def test_shouldnt_add_lines() -> None:
2635 """Ensure that isort doesn't add a blank line when a top of import comment is present,
2636 See: issue #316
2637 """
2638 test_input = '"""Text"""\n# This is a comment\nimport pkg_resources\n'
2639 assert isort.code(test_input) == test_input
2640
2641
2642 def test_sections_parsed_correct(tmp_path: Path) -> None:
2643 """Ensure that modules for custom sections parsed as list from config file and
2644 isort result is correct
2645 """
2646 conf_file_data = (
2647 "[settings]\n"
2648 "sections=FUTURE,STDLIB,THIRDPARTY,FIRSTPARTY,LOCALFOLDER,COMMON\n"
2649 "known_common=nose\n"
2650 "import_heading_common=Common Library\n"
2651 "import_heading_stdlib=Standard Library\n"
2652 )
2653 test_input = "import os\nfrom nose import *\nimport nose\nfrom os import path"
2654 correct_output = (
2655 "# Standard Library\n"
2656 "import os\n"
2657 "from os import path\n"
2658 "\n"
2659 "# Common Library\n"
2660 "import nose\n"
2661 "from nose import *\n"
2662 )
2663 (tmp_path / ".isort.cfg").write_text(conf_file_data)
2664 assert isort.code(test_input, settings_path=str(tmp_path)) == correct_output
2665
2666
2667 def test_pyproject_conf_file(tmp_path: Path) -> None:
2668 """Ensure that modules for custom sections parsed as list from config file and
2669 isort result is correct
2670 """
2671 conf_file_data = (
2672 "[build-system]\n"
2673 'requires = ["setuptools", "wheel"]\n'
2674 "[project]\n"
2675 'name = "isort"\n'
2676 'version = "0.1.0"\n'
2677 'license = "MIT"\n'
2678 "[tool.isort]\n"
2679 "lines_between_types=1\n"
2680 'known_common="nose"\n'
2681 'known_first_party="foo"\n'
2682 'import_heading_common="Common Library"\n'
2683 'import_heading_stdlib="Standard Library"\n'
2684 'sections="FUTURE,STDLIB,THIRDPARTY,FIRSTPARTY,LOCALFOLDER,COMMON"\n'
2685 "include_trailing_comma = true\n"
2686 )
2687 test_input = "import os\nfrom nose import *\nimport nose\nfrom os import path\nimport foo"
2688 correct_output = (
2689 "# Standard Library\n"
2690 "import os\n"
2691 "\n"
2692 "from os import path\n"
2693 "\n"
2694 "import foo\n"
2695 "\n"
2696 "# Common Library\n"
2697 "import nose\n"
2698 "\n"
2699 "from nose import *\n"
2700 )
2701 (tmp_path / "pyproject.toml").write_text(conf_file_data)
2702 assert isort.code(test_input, settings_path=str(tmp_path)) == correct_output
2703
2704
2705 def test_alphabetic_sorting_no_newlines() -> None:
2706 """Test to ensure that alphabetical sort does not
2707 erroneously introduce new lines (issue #328)
2708 """
2709 test_input = "import os\n"
2710 test_output = isort.code(code=test_input, force_alphabetical_sort_within_sections=True)
2711 assert test_input == test_output
2712
2713 test_input = "import os\nimport unittest\n\nfrom a import b\n\n\nprint(1)\n"
2714 test_output = isort.code(
2715 code=test_input, force_alphabetical_sort_within_sections=True, lines_after_imports=2
2716 )
2717 assert test_input == test_output
2718
2719
2720 def test_sort_within_section() -> None:
2721 """Test to ensure its possible to force isort to sort within sections"""
2722 test_input = (
2723 "from Foob import ar\nimport foo\nfrom foo import bar\nfrom foo.bar import Quux, baz\n"
2724 )
2725 test_output = isort.code(test_input, force_sort_within_sections=True)
2726 assert test_output == test_input
2727
2728 test_input = (
2729 "import foo\n"
2730 "from foo import bar\n"
2731 "from foo.bar import baz\n"
2732 "from foo.bar import Quux\n"
2733 "from Foob import ar\n"
2734 )
2735 test_output = isort.code(
2736 code=test_input,
2737 force_sort_within_sections=True,
2738 order_by_type=False,
2739 force_single_line=True,
2740 )
2741 assert test_output == test_input
2742
2743 test_input = (
2744 "import foo\n"
2745 "from foo import bar\n"
2746 "from foo.bar import baz\n"
2747 "from foo.bar import Quux\n"
2748 "from Foob import ar\n"
2749 )
2750 test_output = isort.code(
2751 code=test_input,
2752 case_sensitive=True,
2753 force_sort_within_sections=True,
2754 order_by_type=False,
2755 force_single_line=True,
2756 )
2757 assert test_output == test_input
2758
2759 test_input = "from Foob import ar\nimport foo\nfrom foo import Quux\nfrom foo import baz\n"
2760 test_output = isort.code(
2761 code=test_input,
2762 case_sensitive=True,
2763 force_sort_within_sections=True,
2764 order_by_type=True,
2765 force_single_line=True,
2766 )
2767 assert test_output == test_input
2768
2769
2770 def test_sort_within_section_case_honored() -> None:
2771 """Ensure isort can do partial case-sensitive sorting in force-sorted sections"""
2772 test_input = (
2773 "import foo\nfrom foo import bar\nfrom foo.bar import Quux, baz\nfrom Foob import ar\n"
2774 )
2775 test_output = isort.code(
2776 test_input, force_sort_within_sections=True, honor_case_in_force_sorted_sections=True
2777 )
2778 assert test_output == test_input
2779
2780 test_input = (
2781 "import foo\n"
2782 "from foo import bar\n"
2783 "from foo.bar import baz\n"
2784 "from foo.bar import Quux\n"
2785 "from Foob import ar\n"
2786 )
2787 test_output = isort.code(
2788 code=test_input,
2789 force_sort_within_sections=True,
2790 honor_case_in_force_sorted_sections=True,
2791 order_by_type=False,
2792 force_single_line=True,
2793 )
2794 assert test_output == test_input
2795
2796 test_input = (
2797 "from Foob import ar\n"
2798 "import foo\n"
2799 "from foo import bar\n"
2800 "from foo.bar import baz\n"
2801 "from foo.bar import Quux\n"
2802 )
2803 test_output = isort.code(
2804 code=test_input,
2805 case_sensitive=True,
2806 force_sort_within_sections=True,
2807 honor_case_in_force_sorted_sections=True,
2808 order_by_type=False,
2809 force_single_line=True,
2810 )
2811 assert test_output == test_input
2812
2813 test_input = "from Foob import ar\nimport foo\nfrom foo import Quux\nfrom foo import baz\n"
2814 test_output = isort.code(
2815 code=test_input,
2816 case_sensitive=True,
2817 force_sort_within_sections=True,
2818 honor_case_in_force_sorted_sections=True,
2819 order_by_type=True,
2820 force_single_line=True,
2821 )
2822 assert test_output == test_input
2823
2824
2825 def test_sorting_with_two_top_comments() -> None:
2826 """Test to ensure isort will sort files that contain 2 top comments"""
2827 test_input = "#! comment1\n''' comment2\n'''\nimport b\nimport a\n"
2828 assert isort.code(test_input) == ("#! comment1\n''' comment2\n'''\nimport a\nimport b\n")
2829
2830
2831 def test_lines_between_sections() -> None:
2832 """Test to ensure lines_between_sections works"""
2833 test_input = "from bar import baz\nimport os\n"
2834 assert isort.code(test_input, lines_between_sections=0) == ("import os\nfrom bar import baz\n")
2835 assert isort.code(test_input, lines_between_sections=2) == (
2836 "import os\n\n\nfrom bar import baz\n"
2837 )
2838
2839
2840 def test_forced_sepatate_globs() -> None:
2841 """Test to ensure that forced_separate glob matches lines"""
2842 test_input = (
2843 "import os\n"
2844 "\n"
2845 "from myproject.foo.models import Foo\n"
2846 "\n"
2847 "from myproject.utils import util_method\n"
2848 "\n"
2849 "from myproject.bar.models import Bar\n"
2850 "\n"
2851 "import sys\n"
2852 )
2853 test_output = isort.code(code=test_input, forced_separate=["*.models"], line_length=120)
2854
2855 assert test_output == (
2856 "import os\n"
2857 "import sys\n"
2858 "\n"
2859 "from myproject.utils import util_method\n"
2860 "\n"
2861 "from myproject.bar.models import Bar\n"
2862 "from myproject.foo.models import Foo\n"
2863 )
2864
2865
2866 def test_no_additional_lines_issue_358() -> None:
2867 """Test to ensure issue 358 is resolved and running isort multiple times
2868 does not add extra newlines
2869 """
2870 test_input = (
2871 '"""This is a docstring"""\n'
2872 "# This is a comment\n"
2873 "from __future__ import (\n"
2874 " absolute_import,\n"
2875 " division,\n"
2876 " print_function,\n"
2877 " unicode_literals\n"
2878 ")\n"
2879 )
2880 expected_output = (
2881 '"""This is a docstring"""\n'
2882 "# This is a comment\n"
2883 "from __future__ import (\n"
2884 " absolute_import,\n"
2885 " division,\n"
2886 " print_function,\n"
2887 " unicode_literals\n"
2888 ")\n"
2889 )
2890 test_output = isort.code(
2891 code=test_input, multi_line_output=WrapModes.VERTICAL_HANGING_INDENT, line_length=20
2892 )
2893 assert test_output == expected_output
2894
2895 test_output = isort.code(
2896 code=test_output, multi_line_output=WrapModes.VERTICAL_HANGING_INDENT, line_length=20
2897 )
2898 assert test_output == expected_output
2899
2900 for _attempt in range(5):
2901 test_output = isort.code(
2902 code=test_output, multi_line_output=WrapModes.VERTICAL_HANGING_INDENT, line_length=20
2903 )
2904 assert test_output == expected_output
2905
2906 test_input = (
2907 '"""This is a docstring"""\n'
2908 "\n"
2909 "# This is a comment\n"
2910 "from __future__ import (\n"
2911 " absolute_import,\n"
2912 " division,\n"
2913 " print_function,\n"
2914 " unicode_literals\n"
2915 ")\n"
2916 )
2917 expected_output = (
2918 '"""This is a docstring"""\n'
2919 "\n"
2920 "# This is a comment\n"
2921 "from __future__ import (\n"
2922 " absolute_import,\n"
2923 " division,\n"
2924 " print_function,\n"
2925 " unicode_literals\n"
2926 ")\n"
2927 )
2928 test_output = isort.code(
2929 code=test_input, multi_line_output=WrapModes.VERTICAL_HANGING_INDENT, line_length=20
2930 )
2931 assert test_output == expected_output
2932
2933 test_output = isort.code(
2934 code=test_output, multi_line_output=WrapModes.VERTICAL_HANGING_INDENT, line_length=20
2935 )
2936 assert test_output == expected_output
2937
2938 for _attempt in range(5):
2939 test_output = isort.code(
2940 code=test_output, multi_line_output=WrapModes.VERTICAL_HANGING_INDENT, line_length=20
2941 )
2942 assert test_output == expected_output
2943
2944
2945 def test_import_by_paren_issue_375() -> None:
2946 """Test to ensure isort can correctly handle sorting imports where the
2947 paren is directly by the import body
2948 """
2949 test_input = "from .models import(\n Foo,\n Bar,\n)\n"
2950 assert isort.code(test_input) == "from .models import Bar, Foo\n"
2951
2952
2953 def test_import_by_paren_issue_460() -> None:
2954 """Test to ensure isort can doesn't move comments around"""
2955 test_input = """
2956 # First comment
2957 # Second comment
2958 # third comment
2959 import io
2960 import os
2961 """
2962 assert isort.code(test_input) == test_input
2963
2964
2965 def test_function_with_docstring() -> None:
2966 """Test to ensure isort can correctly sort imports when the first found content is a
2967 function with a docstring
2968 """
2969 add_imports = ["from __future__ import unicode_literals"]
2970 test_input = 'def foo():\n """ Single line triple quoted doctring """\n pass\n'
2971 expected_output = (
2972 "from __future__ import unicode_literals\n"
2973 "\n"
2974 "\n"
2975 "def foo():\n"
2976 ' """ Single line triple quoted doctring """\n'
2977 " pass\n"
2978 )
2979 assert isort.code(test_input, add_imports=add_imports) == expected_output
2980
2981
2982 def test_plone_style() -> None:
2983 """Test to ensure isort correctly plone style imports"""
2984 test_input = (
2985 "from django.contrib.gis.geos import GEOSException\n"
2986 "from plone.app.testing import getRoles\n"
2987 "from plone.app.testing import ManageRoles\n"
2988 "from plone.app.testing import setRoles\n"
2989 "from Products.CMFPlone import utils\n"
2990 "\n"
2991 "import ABC\n"
2992 "import unittest\n"
2993 "import Zope\n"
2994 )
2995 options = {"force_single_line": True, "force_alphabetical_sort": True} # type: dict[str, Any]
2996 assert isort.code(test_input, **options) == test_input
2997
2998
2999 def test_third_party_case_sensitive() -> None:
3000 """Modules which match builtins by name but not on case should not be picked up on Windows."""
3001 test_input = "import thirdparty\nimport os\nimport ABC\n"
3002
3003 expected_output = "import os\n\nimport ABC\nimport thirdparty\n"
3004 assert isort.code(test_input) == expected_output
3005
3006
3007 def test_exists_case_sensitive_file(tmp_path: Path) -> None:
3008 """Test exists_case_sensitive function for a file."""
3009 exists_case_sensitive.cache_clear()
3010 (tmp_path / "module.py").touch()
3011 assert exists_case_sensitive(str(tmp_path / "module.py"))
3012 assert not exists_case_sensitive(str(tmp_path / "MODULE.py"))
3013
3014
3015 def test_exists_case_sensitive_directory(tmp_path: Path) -> None:
3016 """Test exists_case_sensitive function for a directory."""
3017 exists_case_sensitive.cache_clear()
3018 (tmp_path / "pkg").mkdir()
3019 assert exists_case_sensitive(str(tmp_path / "pkg"))
3020 assert not exists_case_sensitive(str(tmp_path / "PKG"))
3021
3022
3023 def test_sys_path_mutation(tmp_path: Path) -> None:
3024 """Test to ensure sys.path is not modified"""
3025 (tmp_path / "src" / "a").mkdir(parents=True)
3026 test_input = "from myproject import test"
3027 expected_length = len(sys.path)
3028 isort.code(test_input, virtual_env=str(tmp_path))
3029 assert len(sys.path) == expected_length
3030
3031
3032 def test_long_single_line() -> None:
3033 """Test to ensure long single lines get handled correctly"""
3034 output = isort.code(
3035 code="from ..views import ("
3036 " _a,"
3037 "_xxxxxx_xxxxxxx_xxxxxxxx_xxx_xxxxxxx as xxxxxx_xxxxxxx_xxxxxxxx_xxx_xxxxxxx)",
3038 line_length=79,
3039 )
3040 for line in output.split("\n"):
3041 assert len(line) <= 79
3042
3043 output = isort.code(
3044 code="from ..views import ("
3045 " _a,"
3046 "_xxxxxx_xxxxxxx_xxxxxxxx_xxx_xxxxxxx as xxxxxx_xxxxxxx_xxxxxxxx_xxx_xxxxxxx)",
3047 line_length=79,
3048 combine_as_imports=True,
3049 )
3050 for line in output.split("\n"):
3051 assert len(line) <= 79
3052
3053
3054 def test_import_inside_class_issue_432() -> None:
3055 """Test to ensure issue 432 is resolved and isort
3056 doesn't insert imports in the middle of classes
3057 """
3058 test_input = "# coding=utf-8\nclass Foo:\n def bar(self):\n pass\n"
3059 expected_output = (
3060 "# coding=utf-8\nimport baz\n\n\nclass Foo:\n def bar(self):\n pass\n"
3061 )
3062 assert isort.code(test_input, add_imports=["import baz"]) == expected_output
3063
3064
3065 def test_wildcard_import_without_space_issue_496() -> None:
3066 """Test to ensure issue #496: wildcard without space, is resolved"""
3067 test_input = "from findorserver.coupon.models import*"
3068 expected_output = "from findorserver.coupon.models import *\n"
3069 assert isort.code(test_input) == expected_output
3070
3071
3072 def test_import_line_mangles_issues_491() -> None:
3073 """Test to ensure comment on import with parens doesn't cause issues"""
3074 test_input = 'import os # ([\n\nprint("hi")\n'
3075 assert isort.code(test_input) == test_input
3076
3077
3078 def test_import_line_mangles_issues_505() -> None:
3079 """Test to ensure comment on import with parens doesn't cause issues"""
3080 test_input = 'from sys import * # (\n\n\ndef test():\n print("Test print")\n'
3081 assert isort.code(test_input) == test_input
3082
3083
3084 def test_import_line_mangles_issues_439() -> None:
3085 """Test to ensure comment on import with parens doesn't cause issues"""
3086 test_input = "import a # () import\nfrom b import b\n"
3087 assert isort.code(test_input) == test_input
3088
3089
3090 def test_alias_using_paren_issue_466() -> None:
3091 """Test to ensure issue #466: Alias causes slash incorrectly is resolved"""
3092 test_input = (
3093 "from django.db.backends.mysql.base import DatabaseWrapper as MySQLDatabaseWrapper\n"
3094 )
3095 expected_output = (
3096 "from django.db.backends.mysql.base import (\n"
3097 " DatabaseWrapper as MySQLDatabaseWrapper)\n"
3098 )
3099 assert isort.code(test_input, line_length=50, use_parentheses=True) == expected_output
3100
3101 test_input = (
3102 "from django.db.backends.mysql.base import DatabaseWrapper as MySQLDatabaseWrapper\n"
3103 )
3104 expected_output = (
3105 "from django.db.backends.mysql.base import (\n"
3106 " DatabaseWrapper as MySQLDatabaseWrapper\n"
3107 ")\n"
3108 )
3109 assert (
3110 isort.code(
3111 code=test_input,
3112 line_length=50,
3113 multi_line_output=WrapModes.VERTICAL_GRID_GROUPED,
3114 use_parentheses=True,
3115 )
3116 == expected_output
3117 )
3118
3119
3120 def test_long_alias_using_paren_issue_957() -> None:
3121 test_input = (
3122 "from package import module as very_very_very_very_very_very_very"
3123 "_very_very_very_long_alias\n"
3124 )
3125 expected_output = (
3126 "from package import (\n"
3127 " module as very_very_very_very_very_very_very_very_very_very_long_alias\n"
3128 ")\n"
3129 )
3130 out = isort.code(
3131 code=test_input,
3132 line_length=50,
3133 use_parentheses=True,
3134 multi_line_output=WrapModes.VERTICAL_GRID_GROUPED,
3135 )
3136 assert out == expected_output
3137
3138 test_input = (
3139 "from deep.deep.deep.deep.deep.deep.deep.deep.deep.package import module as "
3140 "very_very_very_very_very_very_very_very_very_very_long_alias\n"
3141 )
3142 expected_output = (
3143 "from deep.deep.deep.deep.deep.deep.deep.deep.deep.package import (\n"
3144 " module as very_very_very_very_very_very_very_very_very_very_long_alias\n"
3145 ")\n"
3146 )
3147 out = isort.code(
3148 code=test_input,
3149 line_length=50,
3150 use_parentheses=True,
3151 multi_line_output=WrapModes.VERTICAL_GRID_GROUPED,
3152 )
3153 assert out == expected_output
3154
3155 test_input = (
3156 "from deep.deep.deep.deep.deep.deep.deep.deep.deep.package "
3157 "import very_very_very_very_very_very_very_very_very_very_long_module as very_very_very_"
3158 "very_very_very_very_very_very_very_long_alias\n"
3159 )
3160 expected_output = (
3161 "from deep.deep.deep.deep.deep.deep.deep.deep.deep.package import (\n"
3162 " very_very_very_very_very_very_very_very_very_very_long_module as very_very_very_very"
3163 "_very_very_very_very_very_very_long_alias\n"
3164 ")\n"
3165 )
3166 out = isort.code(
3167 code=test_input,
3168 line_length=50,
3169 use_parentheses=True,
3170 multi_line_output=WrapModes.VERTICAL_GRID_GROUPED,
3171 )
3172 assert out == expected_output
3173
3174
3175 def test_strict_whitespace_by_default(capsys: pytest.CaptureFixture[str]) -> None:
3176 test_input = "import os\nfrom django.conf import settings\n"
3177 assert not api.check_code_string(test_input)
3178 _, err = capsys.readouterr()
3179 assert "ERROR" in err
3180 assert err.endswith("Imports are incorrectly sorted and/or formatted.\n")
3181
3182
3183 def test_strict_whitespace_no_closing_newline_issue_676(
3184 capsys: pytest.CaptureFixture[str],
3185 ) -> None:
3186 test_input = "import os\n\nfrom django.conf import settings\n\nprint(1)"
3187 assert api.check_code_string(test_input)
3188 out, _ = capsys.readouterr()
3189 assert out == ""
3190
3191
3192 def test_ignore_whitespace(capsys: pytest.CaptureFixture[str]) -> None:
3193 test_input = "import os\nfrom django.conf import settings\n"
3194 assert api.check_code_string(test_input, ignore_whitespace=True)
3195 out, _ = capsys.readouterr()
3196 assert out == ""
3197
3198
3199 def test_import_wraps_with_comment_issue_471() -> None:
3200 """Test to ensure issue #471 is resolved"""
3201 test_input = (
3202 "from very_long_module_name import SuperLongClassName #@UnusedImport"
3203 " -- long string of comments which wrap over"
3204 )
3205 expected_output = (
3206 "from very_long_module_name import (\n"
3207 " SuperLongClassName) # @UnusedImport -- long string of comments which wrap over\n"
3208 )
3209 assert (
3210 isort.code(code=test_input, line_length=50, multi_line_output=1, use_parentheses=True)
3211 == expected_output
3212 )
3213
3214
3215 def test_import_case_produces_inconsistent_results_issue_472() -> None:
3216 """Test to ensure sorting imports with same name but different case produces
3217 the same result across platforms
3218 """
3219 test_input = (
3220 "from sqlalchemy.dialects.postgresql import ARRAY\n"
3221 "from sqlalchemy.dialects.postgresql import array\n"
3222 )
3223 assert isort.code(test_input, force_single_line=True) == test_input
3224
3225 test_input = (
3226 "from scrapy.core.downloader.handlers.http import "
3227 "HttpDownloadHandler, HTTPDownloadHandler\n"
3228 )
3229 assert isort.code(test_input, line_length=100) == test_input
3230
3231
3232 def test_inconsistent_behavior_in_python_2_and_3_issue_479() -> None:
3233 """Test to ensure Python 2 and 3 have the same behavior"""
3234 test_input = (
3235 "from workalendar.europe import UnitedKingdom\n"
3236 "\n"
3237 "from future.standard_library import hooks\n"
3238 )
3239 assert isort.code(test_input, known_first_party=["future"]) == test_input
3240
3241
3242 def test_sort_within_section_comments_issue_436() -> None:
3243 """Test to ensure sort within sections leaves comments untouched"""
3244 test_input = (
3245 "import os.path\n"
3246 "import re\n"
3247 "\n"
3248 "# report.py exists in ... comment line 1\n"
3249 "# this file needs to ... comment line 2\n"
3250 "# it must not be ... comment line 3\n"
3251 "import report\n"
3252 )
3253 assert isort.code(test_input, force_sort_within_sections=True) == test_input
3254
3255
3256 def test_sort_within_sections_with_force_to_top_issue_473() -> None:
3257 """Test to ensure it's possible to sort within sections with items forced to top"""
3258 test_input = "import z\nimport foo\nfrom foo import bar\n"
3259 assert (
3260 isort.code(code=test_input, force_sort_within_sections=True, force_to_top=["z"])
3261 == test_input
3262 )
3263
3264
3265 def test_force_sort_within_sections_with_relative_imports() -> None:
3266 """Test sorting of relative imports with force_sort_within_sections=True"""
3267 assert isort.check_code(
3268 """import .
3269 from . import foo
3270 from .. import a
3271 from ..alpha.beta import b
3272 from ..omega import c
3273 import .apple as bar
3274 from .mango import baz
3275 """,
3276 show_diff=True,
3277 force_sort_within_sections=True,
3278 )
3279
3280
3281 def test_force_sort_within_sections_with_reverse_relative_imports() -> None:
3282 """Test reverse sorting of relative imports with force_sort_within_sections=True"""
3283 assert isort.check_code(
3284 """import .
3285 from . import foo
3286 from .mango import baz
3287 from ..alpha.beta import b
3288 from .. import a
3289 from ..omega import c
3290 import .apple as bar
3291 """,
3292 show_diff=True,
3293 force_sort_within_sections=True,
3294 reverse_relative=True,
3295 )
3296
3297
3298 def test_sort_relative_in_force_sorted_sections_issue_1659() -> None:
3299 """Ensure relative imports are sorted within sections"""
3300 assert isort.check_code(
3301 """from .. import a
3302 from ..alpha.beta import b
3303 from ..omega import c
3304 import .
3305 from . import foo
3306 import .apple as bar
3307 from .mango import baz
3308 """,
3309 show_diff=True,
3310 force_sort_within_sections=True,
3311 sort_relative_in_force_sorted_sections=True,
3312 )
3313
3314
3315 def test_reverse_sort_relative_in_force_sorted_sections_issue_1659() -> None:
3316 """Ensure reverse ordered relative imports are sorted within sections"""
3317 assert isort.check_code(
3318 """import .
3319 from . import foo
3320 import .apple as bar
3321 from .mango import baz
3322 from .. import a
3323 from ..alpha.beta import b
3324 from ..omega import c
3325 """,
3326 show_diff=True,
3327 force_sort_within_sections=True,
3328 sort_relative_in_force_sorted_sections=True,
3329 reverse_relative=True,
3330 )
3331
3332
3333 def test_correct_number_of_new_lines_with_comment_issue_435() -> None:
3334 """Test to ensure that injecting a comment in-between imports
3335 doesn't mess up the new line spacing
3336 """
3337 test_input = "import foo\n\n# comment\n\n\ndef baz():\n pass\n"
3338 assert isort.code(test_input) == test_input
3339
3340
3341 def test_future_below_encoding_issue_545() -> None:
3342 """Test to ensure future is always below comment"""
3343 test_input = (
3344 "#!/usr/bin/env python\n"
3345 "from __future__ import print_function\n"
3346 "import logging\n"
3347 "\n"
3348 'print("hello")\n'
3349 )
3350 expected_output = (
3351 "#!/usr/bin/env python\n"
3352 "from __future__ import print_function\n"
3353 "\n"
3354 "import logging\n"
3355 "\n"
3356 'print("hello")\n'
3357 )
3358 assert isort.code(test_input) == expected_output
3359
3360
3361 def test_no_extra_lines_issue_557() -> None:
3362 """Test to ensure no extra lines are prepended"""
3363 test_input = (
3364 "import os\n"
3365 "\n"
3366 "from scrapy.core.downloader.handlers.http import "
3367 "HttpDownloadHandler, HTTPDownloadHandler\n"
3368 )
3369 expected_output = (
3370 "import os\n"
3371 "from scrapy.core.downloader.handlers.http import HttpDownloadHandler, "
3372 "HTTPDownloadHandler\n"
3373 )
3374 assert (
3375 isort.code(
3376 code=test_input,
3377 force_alphabetical_sort=True,
3378 force_sort_within_sections=True,
3379 line_length=100,
3380 )
3381 == expected_output
3382 )
3383
3384
3385 def test_long_import_wrap_support_with_mode_2() -> None:
3386 """Test to ensure mode 2 still allows wrapped imports with slash"""
3387 test_input = (
3388 "from foobar.foobar.foobar.foobar import \\\n"
3389 " an_even_longer_function_name_over_80_characters\n"
3390 )
3391 assert (
3392 isort.code(code=test_input, multi_line_output=WrapModes.HANGING_INDENT, line_length=80)
3393 == test_input
3394 )
3395
3396
3397 def test_pylint_comments_incorrectly_wrapped_issue_571() -> None:
3398 """Test to ensure pylint comments don't get wrapped"""
3399 test_input = (
3400 "from PyQt5.QtCore import QRegExp # @UnresolvedImport pylint: disable=import-error,"
3401 "useless-suppression\n"
3402 )
3403 expected_output = (
3404 "from PyQt5.QtCore import \\\n"
3405 " QRegExp # @UnresolvedImport pylint: disable=import-error,useless-suppression\n"
3406 )
3407 assert isort.code(test_input, line_length=60) == expected_output
3408
3409
3410 def test_ensure_async_methods_work_issue_537() -> None:
3411 """Test to ensure async methods are correctly identified"""
3412 test_input = (
3413 "from myapp import myfunction\n"
3414 "\n"
3415 "\n"
3416 "async def test_myfunction(test_client, app):\n"
3417 " a = await myfunction(test_client, app)\n"
3418 )
3419 assert isort.code(test_input) == test_input
3420
3421
3422 def test_ensure_as_imports_sort_correctly_within_from_imports_issue_590() -> None:
3423 """Test to ensure combination from and as import statements are sorted correct"""
3424 test_input = "from os import defpath\nfrom os import pathsep as separator\n"
3425 assert isort.code(test_input, force_sort_within_sections=True) == test_input
3426
3427 test_input = "from os import defpath\nfrom os import pathsep as separator\n"
3428 assert isort.code(test_input) == test_input
3429
3430 test_input = "from os import defpath\nfrom os import pathsep as separator\n"
3431 assert isort.code(test_input, force_single_line=True) == test_input
3432
3433
3434 def test_ensure_line_endings_are_preserved_issue_493() -> None:
3435 """Test to ensure line endings are not converted"""
3436 test_input = "from os import defpath\r\nfrom os import pathsep as separator\r\n"
3437 assert isort.code(test_input) == test_input
3438 test_input = "from os import defpath\rfrom os import pathsep as separator\r"
3439 assert isort.code(test_input) == test_input
3440 test_input = "from os import defpath\nfrom os import pathsep as separator\n"
3441 assert isort.code(test_input) == test_input
3442
3443
3444 @pytest.mark.parametrize("ws", [" ", "\t", "\f"])
3445 def test_line_endings_are_detected_ignoring_whitespace(ws: str) -> None:
3446 """Test to ensure line endings are not converted"""
3447 test_input = f"# foo{ws}\r\nimport a\r\n\r\ncimport z\r\n"
3448 assert isort.code(test_input) == test_input
3449 test_input = f"# foo{ws}\rimport a\r\rcimport z\r"
3450 assert isort.code(test_input) == test_input
3451 test_input = f"# foo{ws}\nimport a\n\ncimport z\n"
3452 assert isort.code(test_input) == test_input
3453
3454
3455 def test_not_splitted_sections() -> None:
3456 whiteline = "\n"
3457 stdlib_section = "import unittest\n"
3458 firstparty_section = "from app.pkg1 import mdl1\n"
3459 local_section = "from .pkg2 import mdl2\n"
3460 statement = "foo = bar\n"
3461 test_input = (
3462 stdlib_section
3463 + whiteline
3464 + firstparty_section
3465 + whiteline
3466 + local_section
3467 + whiteline
3468 + statement
3469 )
3470
3471 assert isort.code(test_input, known_first_party=["app"]) == test_input
3472 assert isort.code(test_input, no_lines_before=["LOCALFOLDER"], known_first_party=["app"]) == (
3473 stdlib_section + whiteline + firstparty_section + local_section + whiteline + statement
3474 )
3475 # by default STDLIB and FIRSTPARTY sections are split by THIRDPARTY section,
3476 # so don't merge them if THIRDPARTY imports aren't exist
3477 assert (
3478 isort.code(test_input, no_lines_before=["FIRSTPARTY"], known_first_party=["app"])
3479 == test_input
3480 )
3481 # in case when THIRDPARTY section is excluded from sections list,
3482 # it's ok to merge STDLIB and FIRSTPARTY
3483 assert isort.code(
3484 code=test_input,
3485 sections=["STDLIB", "FIRSTPARTY", "LOCALFOLDER"],
3486 no_lines_before=["FIRSTPARTY"],
3487 known_first_party=["app"],
3488 ) == (stdlib_section + firstparty_section + whiteline + local_section + whiteline + statement)
3489 # it doesn't change output, because stdlib packages don't have any whitelines before them
3490 assert (
3491 isort.code(test_input, no_lines_before=["STDLIB"], known_first_party=["app"]) == test_input
3492 )
3493
3494
3495 def test_no_lines_before_empty_section() -> None:
3496 test_input = "import first\nimport custom\n"
3497 assert (
3498 isort.code(
3499 code=test_input,
3500 known_third_party=["first"],
3501 known_custom=["custom"],
3502 sections=["THIRDPARTY", "LOCALFOLDER", "CUSTOM"],
3503 no_lines_before=["THIRDPARTY", "LOCALFOLDER", "CUSTOM"],
3504 )
3505 == test_input
3506 )
3507
3508
3509 def test_no_inline_sort() -> None:
3510 """Test to ensure multiple `from` imports in one line are not sorted if `--no-inline-sort` flag
3511 is enabled.
3512 If `--force-single-line-imports` flag is enabled, then `--no-inline-sort` is ignored.
3513 """
3514 test_input = "from foo import a, c, b\n"
3515 assert isort.code(test_input, no_inline_sort=True, force_single_line=False) == test_input
3516 assert (
3517 isort.code(test_input, no_inline_sort=False, force_single_line=False)
3518 == "from foo import a, b, c\n"
3519 )
3520 expected = "from foo import a\nfrom foo import b\nfrom foo import c\n"
3521 assert isort.code(test_input, no_inline_sort=False, force_single_line=True) == expected
3522 assert isort.code(test_input, no_inline_sort=True, force_single_line=True) == expected
3523
3524
3525 def test_relative_import_of_a_module() -> None:
3526 """Imports can be dynamically created (PEP302) and is used by modules such as six.
3527 This test ensures that these types of imports are still sorted to the correct type
3528 instead of being categorized as local.
3529 """
3530 test_input = (
3531 "from __future__ import absolute_import\n"
3532 "\n"
3533 "import itertools\n"
3534 "\n"
3535 "from six import add_metaclass\n"
3536 "\n"
3537 "from six.moves import asd\n"
3538 )
3539
3540 expected_results = (
3541 "from __future__ import absolute_import\n"
3542 "\n"
3543 "import itertools\n"
3544 "\n"
3545 "from six import add_metaclass\n"
3546 "from six.moves import asd\n"
3547 )
3548
3549 sorted_result = isort.code(test_input, force_single_line=True)
3550 assert sorted_result == expected_results
3551
3552
3553 def test_escaped_parens_sort() -> None:
3554 test_input = "from foo import \\ \n(a,\nb,\nc)\n"
3555 expected = "from foo import a, b, c\n"
3556 assert isort.code(test_input) == expected
3557
3558
3559 def test_escaped_parens_sort_with_comment() -> None:
3560 test_input = "from foo import \\ \n(a,\nb,# comment\nc)\n"
3561 expected = "from foo import b # comment\nfrom foo import a, c\n"
3562 assert isort.code(test_input) == expected
3563
3564
3565 def test_escaped_parens_sort_with_first_comment() -> None:
3566 test_input = "from foo import \\ \n(a,# comment\nb,\nc)\n"
3567 expected = "from foo import a # comment\nfrom foo import b, c\n"
3568 assert isort.code(test_input) == expected
3569
3570
3571 def test_escaped_no_parens_sort_with_first_comment() -> None:
3572 test_input = "from foo import a, \\\nb, \\\nc # comment\n"
3573 expected = "from foo import c # comment\nfrom foo import a, b\n"
3574 assert isort.code(test_input) == expected
3575
3576
3577 @pytest.mark.skip(reason="TODO: Duplicates currently not handled.")
3578 def test_to_ensure_imports_are_brought_to_top_issue_651() -> None:
3579 test_input = (
3580 "from __future__ import absolute_import, unicode_literals\n"
3581 "\n"
3582 'VAR = """\n'
3583 "multiline text\n"
3584 '"""\n'
3585 "\n"
3586 "from __future__ import unicode_literals\n"
3587 "from __future__ import absolute_import\n"
3588 )
3589 expected_output = (
3590 "from __future__ import absolute_import, unicode_literals\n"
3591 "\n"
3592 'VAR = """\n'
3593 "multiline text\n"
3594 '"""\n'
3595 )
3596 assert isort.code(test_input) == expected_output
3597
3598
3599 def test_to_ensure_importing_from_imports_module_works_issue_662() -> None:
3600 test_input = (
3601 "@wraps(fun)\n"
3602 "def __inner(*args, **kwargs):\n"
3603 " from .imports import qualname\n"
3604 "\n"
3605 " warn(description=description or qualname(fun), deprecation=deprecation, "
3606 "removal=removal)\n"
3607 )
3608 assert isort.code(test_input) == test_input
3609
3610
3611 def test_to_ensure_no_unexpected_changes_issue_666() -> None:
3612 test_input = (
3613 "from django.conf import settings\n"
3614 "from django.core.management import call_command\n"
3615 "from django.core.management.base import BaseCommand\n"
3616 "from django.utils.translation import ugettext_lazy as _\n"
3617 "\n"
3618 'TEMPLATE = """\n'
3619 "# This file is generated automatically with the management command\n"
3620 "#\n"
3621 "# manage.py bis_compile_i18n\n"
3622 "#\n"
3623 "# please dont change it manually.\n"
3624 "from django.utils.translation import ugettext_lazy as _\n"
3625 '"""\n'
3626 )
3627 assert isort.code(test_input) == test_input
3628
3629
3630 def test_to_ensure_tabs_dont_become_space_issue_665() -> None:
3631 test_input = "import os\n\n\ndef my_method():\n\tpass\n"
3632 assert isort.code(test_input) == test_input
3633
3634
3635 def test_new_lines_are_preserved() -> None:
3636 with NamedTemporaryFile("w", suffix="py", delete=False) as rn_newline:
3637 pass
3638
3639 try:
3640 with open(rn_newline.name, mode="w", newline="") as rn_newline_input:
3641 rn_newline_input.write("import sys\r\nimport os\r\n")
3642
3643 api.sort_file(rn_newline.name, settings_path=os.getcwd())
3644 with open(rn_newline.name) as new_line_file:
3645 print(new_line_file.read())
3646 with open(rn_newline.name, newline="") as rn_newline_file:
3647 rn_newline_contents = rn_newline_file.read()
3648 assert rn_newline_contents == "import os\r\nimport sys\r\n"
3649 finally:
3650 os.remove(rn_newline.name)
3651
3652 with NamedTemporaryFile("w", suffix="py", delete=False) as r_newline:
3653 pass
3654
3655 try:
3656 with open(r_newline.name, mode="w", newline="") as r_newline_input:
3657 r_newline_input.write("import sys\rimport os\r")
3658
3659 api.sort_file(r_newline.name, settings_path=os.getcwd())
3660 with open(r_newline.name, newline="") as r_newline_file:
3661 r_newline_contents = r_newline_file.read()
3662 assert r_newline_contents == "import os\rimport sys\r"
3663 finally:
3664 os.remove(r_newline.name)
3665
3666 with NamedTemporaryFile("w", suffix="py", delete=False) as n_newline:
3667 pass
3668
3669 try:
3670 with open(n_newline.name, mode="w", newline="") as n_newline_input:
3671 n_newline_input.write("import sys\nimport os\n")
3672
3673 api.sort_file(n_newline.name, settings_path=os.getcwd())
3674 with open(n_newline.name, newline="") as n_newline_file:
3675 n_newline_contents = n_newline_file.read()
3676 assert n_newline_contents == "import os\nimport sys\n"
3677 finally:
3678 os.remove(n_newline.name)
3679
3680
3681 def test_forced_separate_is_deterministic_issue_774(tmp_path: Path) -> None:
3682 config_file = tmp_path / "setup.cfg"
3683 config_file.write_text(
3684 "[isort]\nforced_separate:\n separate1\n separate2\n separate3\n separate4\n"
3685 )
3686
3687 test_input = (
3688 "import time\n"
3689 "\n"
3690 "from separate1 import foo\n"
3691 "\n"
3692 "from separate2 import bar\n"
3693 "\n"
3694 "from separate3 import baz\n"
3695 "\n"
3696 "from separate4 import quux\n"
3697 )
3698
3699 assert isort.code(test_input, settings_file=str(config_file)) == test_input
3700
3701
3702 def test_monkey_patched_urllib() -> None:
3703 with pytest.raises(ImportError):
3704 # Previous versions of isort monkey patched urllib which caused unusual
3705 # importing for other projects.
3706 from urllib import quote # type: ignore # noqa: F401, PLC0415
3707
3708
3709 def test_argument_parsing() -> None:
3710 args = parse_args(["--dt", "-t", "foo", "--skip=bar", "baz.py", "--os"])
3711 assert args["order_by_type"] is False
3712 assert args["force_to_top"] == ["foo"]
3713 assert args["skip"] == ["bar"]
3714 assert args["files"] == ["baz.py"]
3715 assert args["only_sections"] is True
3716
3717
3718 @pytest.mark.parametrize("multiprocess", [False, True])
3719 def test_command_line(
3720 tmp_path: Path, capfd: pytest.CaptureFixture[str], multiprocess: bool
3721 ) -> None:
3722 (tmp_path / "file1.py").write_text(
3723 "import re\nimport os\n\nimport contextlib\n\n\nimport isort"
3724 )
3725 (tmp_path / "file2.py").write_text(
3726 "import collections\nimport time\n\nimport abc\n\n\nimport isort"
3727 )
3728 arguments = [str(tmp_path), "--settings-path", os.getcwd()]
3729 if multiprocess:
3730 arguments.extend(["--jobs", "2"])
3731 main(arguments)
3732 assert (
3733 tmp_path / "file1.py"
3734 ).read_text() == "import contextlib\nimport os\nimport re\n\nimport isort\n"
3735 assert (
3736 tmp_path / "file2.py"
3737 ).read_text() == "import abc\nimport collections\nimport time\n\nimport isort\n"
3738 if not (sys.platform.startswith("win") or sys.platform.startswith("darwin")):
3739 out, err = capfd.readouterr()
3740 assert not [error for error in err.split("\n") if error and "warning:" not in error]
3741 # it informs us about fixing the files:
3742 assert str(tmp_path / "file1.py") in out
3743 assert str(tmp_path / "file2.py") in out
3744
3745
3746 @pytest.mark.parametrize("quiet", [False, True])
3747 def test_quiet(tmp_path: Path, capfd: pytest.CaptureFixture[str], quiet: bool) -> None:
3748 if sys.platform.startswith("win"):
3749 return
3750
3751 (tmp_path / "file1.py").write_text("import re\nimport os")
3752 (tmp_path / "file2.py").write_text("")
3753 arguments = [str(tmp_path)]
3754 if quiet:
3755 arguments.append("-q")
3756 main(arguments)
3757 out, err = capfd.readouterr()
3758 assert not err
3759 assert bool(out) != quiet
3760
3761
3762 @pytest.mark.parametrize("enabled", [False, True])
3763 def test_safety_skips(tmp_path: Path, enabled: bool) -> None:
3764 (tmp_path / "victim.py").write_text("# ...")
3765 toxdir = tmp_path / ".tox"
3766 toxdir.mkdir()
3767 (toxdir / "verysafe.py").write_text("# ...")
3768 build_dir = tmp_path / "_build" / "python3.7"
3769 build_dir.mkdir(parents=True)
3770 (build_dir / "importantsystemlibrary.py").write_text("# ...")
3771 pants_dir = tmp_path / ".pants.d"
3772 pants_dir.mkdir()
3773 (pants_dir / "pants.py").write_text("import os")
3774 if enabled:
3775 config = Config(directory=str(tmp_path))
3776 else:
3777 config = Config(skip=[], directory=str(tmp_path))
3778 skipped: list[str] = []
3779 broken: list[str] = []
3780 codes = [str(tmp_path)]
3781 files.find(codes, config, skipped, broken)
3782
3783 # if enabled files within nested unsafe directories should be skipped
3784 file_names = {
3785 os.path.relpath(f, str(tmp_path))
3786 for f in files.find([str(tmp_path)], config, skipped, broken)
3787 }
3788 if enabled:
3789 assert file_names == {"victim.py"}
3790 assert len(skipped) == 3
3791 else:
3792 assert file_names == {
3793 os.sep.join((".tox", "verysafe.py")),
3794 os.sep.join(("_build", "python3.7", "importantsystemlibrary.py")),
3795 os.sep.join((".pants.d", "pants.py")),
3796 "victim.py",
3797 }
3798 assert not skipped
3799
3800 # directly pointing to files within unsafe directories shouldn't skip them either way
3801 file_names = {
3802 os.path.relpath(f, str(toxdir))
3803 for f in files.find([str(toxdir)], Config(directory=str(toxdir)), skipped, broken)
3804 }
3805 assert file_names == {"verysafe.py"}
3806
3807
3808 @pytest.mark.parametrize(
3809 "skip_glob_assert",
3810 [
3811 ([], 0, {os.sep.join(("code", "file.py"))}),
3812 (["**/*.py"], 1, set()),
3813 (["*/code/*.py"], 1, set()),
3814 ],
3815 )
3816 def test_skip_glob(tmp_path: Path, skip_glob_assert: tuple[list[str], int, set[str]]) -> None:
3817 skip_glob, skipped_count, file_names_expected = skip_glob_assert
3818 base_dir = tmp_path / "build"
3819 code_dir = base_dir / "code"
3820 code_dir.mkdir(parents=True)
3821 (code_dir / "file.py").write_text("import os")
3822
3823 config = Config(skip_glob=skip_glob, directory=str(base_dir))
3824 skipped: list[str] = []
3825 broken: list[str] = []
3826 file_names = {
3827 os.path.relpath(f, str(base_dir))
3828 for f in files.find([str(base_dir)], config, skipped, broken)
3829 }
3830 assert len(skipped) == skipped_count
3831 assert file_names == file_names_expected
3832
3833
3834 def test_broken(tmp_path: Path) -> None:
3835 base_dir = tmp_path / "broken"
3836 base_dir.mkdir()
3837
3838 config = Config(directory=str(base_dir))
3839 skipped: list[str] = []
3840 broken: list[str] = []
3841 file_names = {
3842 os.path.relpath(f, str(base_dir))
3843 for f in files.find(["not-exist"], config, skipped, broken)
3844 }
3845 assert len(broken) == 1
3846 assert file_names == set()
3847
3848
3849 def test_comments_not_removed_issue_576() -> None:
3850 test_input = (
3851 "import distutils\n"
3852 "# this comment is important and should not be removed\n"
3853 "from sys import api_version as api_version\n"
3854 )
3855 assert isort.code(test_input) == test_input
3856
3857
3858 def test_reverse_relative_imports_issue_417() -> None:
3859 test_input = (
3860 "from . import ipsum\n"
3861 "from . import lorem\n"
3862 "from .dolor import consecteur\n"
3863 "from .sit import apidiscing\n"
3864 "from .. import donec\n"
3865 "from .. import euismod\n"
3866 "from ..mi import iaculis\n"
3867 "from ..nec import tempor\n"
3868 "from ... import diam\n"
3869 "from ... import dui\n"
3870 "from ...eu import dignissim\n"
3871 "from ...ex import metus\n"
3872 )
3873 assert isort.code(test_input, force_single_line=True, reverse_relative=True) == test_input
3874
3875
3876 def test_inconsistent_relative_imports_issue_577() -> None:
3877 test_input = (
3878 "from ... import diam\n"
3879 "from ... import dui\n"
3880 "from ...eu import dignissim\n"
3881 "from ...ex import metus\n"
3882 "from .. import donec\n"
3883 "from .. import euismod\n"
3884 "from ..mi import iaculis\n"
3885 "from ..nec import tempor\n"
3886 "from . import ipsum\n"
3887 "from . import lorem\n"
3888 "from .dolor import consecteur\n"
3889 "from .sit import apidiscing\n"
3890 )
3891 assert isort.code(test_input, force_single_line=True) == test_input
3892
3893
3894 def test_unwrap_issue_762() -> None:
3895 test_input = "from os.path \\\nimport (join, split)\n"
3896 assert isort.code(test_input) == "from os.path import join, split\n"
3897
3898 test_input = "from os.\\\n path import (join, split)"
3899 assert isort.code(test_input) == "from os.path import join, split\n"
3900
3901
3902 def test_multiple_as_imports() -> None:
3903 test_input = "from a import b as b\nfrom a import b as bb\nfrom a import b as bb_\n"
3904 test_output = isort.code(test_input)
3905 assert test_output == test_input
3906 test_output = isort.code(test_input, combine_as_imports=True)
3907 assert test_output == "from a import b as b, b as bb, b as bb_\n"
3908 test_output = isort.code(test_input)
3909 assert test_output == test_input
3910 test_output = isort.code(code=test_input, combine_as_imports=True)
3911 assert test_output == "from a import b as b, b as bb, b as bb_\n"
3912
3913 test_input = (
3914 "from a import b\nfrom a import b as b\nfrom a import b as bb\nfrom a import b as bb_\n"
3915 )
3916 test_output = isort.code(test_input)
3917 assert test_output == test_input
3918 test_output = isort.code(code=test_input, combine_as_imports=True)
3919 assert test_output == "from a import b, b as b, b as bb, b as bb_\n"
3920
3921 test_input = (
3922 "from a import b as e\nfrom a import b as c\nfrom a import b\nfrom a import b as f\n"
3923 )
3924 test_output = isort.code(test_input)
3925 assert (
3926 test_output
3927 == "from a import b\nfrom a import b as c\nfrom a import b as e\nfrom a import b as f\n"
3928 )
3929 test_output = isort.code(code=test_input, no_inline_sort=True)
3930 assert (
3931 test_output
3932 == "from a import b\nfrom a import b as c\nfrom a import b as e\nfrom a import b as f\n"
3933 )
3934 test_output = isort.code(code=test_input, combine_as_imports=True)
3935 assert test_output == "from a import b, b as c, b as e, b as f\n"
3936 test_output = isort.code(code=test_input, combine_as_imports=True, no_inline_sort=True)
3937 assert test_output == "from a import b, b as e, b as c, b as f\n"
3938
3939 test_input = "import a as a\nimport a as aa\nimport a as aa_\n"
3940 test_output = isort.code(code=test_input, combine_as_imports=True)
3941 assert test_output == test_input
3942
3943 assert test_output == "import a as a\nimport a as aa\nimport a as aa_\n"
3944 test_output = isort.code(code=test_input, combine_as_imports=True)
3945 assert test_output == test_input
3946
3947
3948 def test_all_imports_from_single_module() -> None:
3949 test_input = (
3950 "import a\n"
3951 "from a import *\n"
3952 "from a import b as d\n"
3953 "from a import z, x, y\n"
3954 "from a import b\n"
3955 "from a import w, i as j\n"
3956 "from a import b as c, g as h\n"
3957 "from a import e as f\n"
3958 )
3959 test_output = isort.code(
3960 code=test_input,
3961 combine_star=False,
3962 combine_as_imports=False,
3963 force_single_line=False,
3964 no_inline_sort=False,
3965 )
3966 assert test_output == (
3967 "import a\n"
3968 "from a import *\n"
3969 "from a import b\n"
3970 "from a import b as c\n"
3971 "from a import b as d\n"
3972 "from a import e as f\n"
3973 "from a import g as h\n"
3974 "from a import i as j\n"
3975 "from a import w, x, y, z\n"
3976 )
3977 test_input = (
3978 "import a\nfrom a import *\nfrom a import z, x, y\nfrom a import b\nfrom a import w\n"
3979 )
3980 test_output = isort.code(
3981 code=test_input,
3982 combine_star=True,
3983 combine_as_imports=False,
3984 force_single_line=False,
3985 no_inline_sort=False,
3986 )
3987 assert test_output == "import a\nfrom a import *\n"
3988 test_input += """
3989 from a import b as c
3990 from a import b as d
3991 from a import e as f
3992 from a import g as h
3993 from a import i as j
3994 """
3995 test_output = isort.code(
3996 code=test_input,
3997 combine_star=False,
3998 combine_as_imports=True,
3999 force_single_line=False,
4000 no_inline_sort=False,
4001 )
4002 assert test_output == (
4003 "import a\n"
4004 "from a import *\n"
4005 "from a import b, b as c, b as d, e as f, g as h, i as j, w, x, y, z\n"
4006 )
4007 test_output = isort.code(
4008 code=test_input,
4009 combine_star=False,
4010 combine_as_imports=False,
4011 force_single_line=True,
4012 no_inline_sort=False,
4013 )
4014 assert test_output == (
4015 "import a\n"
4016 "from a import *\n"
4017 "from a import b\n"
4018 "from a import b as c\n"
4019 "from a import b as d\n"
4020 "from a import e as f\n"
4021 "from a import g as h\n"
4022 "from a import i as j\n"
4023 "from a import w\n"
4024 "from a import x\n"
4025 "from a import y\n"
4026 "from a import z\n"
4027 )
4028 test_input = (
4029 "import a\n"
4030 "from a import *\n"
4031 "from a import b\n"
4032 "from a import b as d\n"
4033 "from a import b as c\n"
4034 "from a import z, x, y, w\n"
4035 "from a import i as j\n"
4036 "from a import g as h\n"
4037 "from a import e as f\n"
4038 )
4039 test_output = isort.code(
4040 code=test_input,
4041 combine_star=False,
4042 combine_as_imports=False,
4043 force_single_line=False,
4044 no_inline_sort=True,
4045 )
4046 assert test_output == (
4047 "import a\n"
4048 "from a import *\n"
4049 "from a import b\n"
4050 "from a import b as c\n"
4051 "from a import b as d\n"
4052 "from a import z, x, y, w\n"
4053 "from a import i as j\n"
4054 "from a import g as h\n"
4055 "from a import e as f\n"
4056 )
4057 test_input = (
4058 "import a\nfrom a import *\nfrom a import z, x, y\nfrom a import b\nfrom a import w\n"
4059 )
4060 test_output = isort.code(
4061 code=test_input,
4062 combine_star=True,
4063 combine_as_imports=True,
4064 force_single_line=False,
4065 no_inline_sort=False,
4066 )
4067 assert test_output == "import a\nfrom a import *\n"
4068 test_output = isort.code(
4069 code=test_input,
4070 combine_star=True,
4071 combine_as_imports=False,
4072 force_single_line=True,
4073 no_inline_sort=False,
4074 )
4075 assert test_output == "import a\nfrom a import *\n"
4076 test_output = isort.code(
4077 code=test_input,
4078 combine_star=True,
4079 combine_as_imports=False,
4080 force_single_line=False,
4081 no_inline_sort=True,
4082 )
4083 assert test_output == "import a\nfrom a import *\n"
4084 test_output = isort.code(
4085 code=test_input,
4086 combine_star=False,
4087 combine_as_imports=True,
4088 force_single_line=True,
4089 no_inline_sort=False,
4090 )
4091 assert test_output == (
4092 "import a\n"
4093 "from a import *\n"
4094 "from a import b\n"
4095 "from a import w\n"
4096 "from a import x\n"
4097 "from a import y\n"
4098 "from a import z\n"
4099 )
4100 test_input = (
4101 "import a\n"
4102 "from a import *\n"
4103 "from a import b\n"
4104 "from a import b as d\n"
4105 "from a import b as c\n"
4106 "from a import z, x, y, w\n"
4107 "from a import i as j\n"
4108 "from a import g as h\n"
4109 "from a import e as f\n"
4110 )
4111 test_output = isort.code(
4112 code=test_input,
4113 combine_star=False,
4114 combine_as_imports=True,
4115 force_single_line=False,
4116 no_inline_sort=True,
4117 )
4118 assert test_output == (
4119 "import a\n"
4120 "from a import *\n"
4121 "from a import b, b as d, b as c, z, x, y, w, i as j, g as h, e as f\n"
4122 )
4123 test_output = isort.code(
4124 code=test_input,
4125 combine_star=False,
4126 combine_as_imports=False,
4127 force_single_line=True,
4128 no_inline_sort=True,
4129 )
4130 assert test_output == (
4131 "import a\n"
4132 "from a import *\n"
4133 "from a import b\n"
4134 "from a import b as c\n"
4135 "from a import b as d\n"
4136 "from a import e as f\n"
4137 "from a import g as h\n"
4138 "from a import i as j\n"
4139 "from a import w\n"
4140 "from a import x\n"
4141 "from a import y\n"
4142 "from a import z\n"
4143 )
4144 test_input = (
4145 "import a\nfrom a import *\nfrom a import z, x, y\nfrom a import b\nfrom a import w\n"
4146 )
4147 test_output = isort.code(
4148 code=test_input,
4149 combine_star=True,
4150 combine_as_imports=True,
4151 force_single_line=True,
4152 no_inline_sort=False,
4153 )
4154 assert test_output == "import a\nfrom a import *\n"
4155
4156
4157 def test_noqa_issue_679() -> None:
4158 """Test to ensure that NOQA notation is being observed as expected
4159 if honor_noqa is set to `True`
4160 """
4161 test_input = """
4162 import os
4163
4164 import requestsss
4165 import zed # NOQA
4166 import ujson # NOQA
4167
4168 import foo"""
4169 test_output = """
4170 import os
4171
4172 import foo
4173 import requestsss
4174 import ujson # NOQA
4175 import zed # NOQA
4176 """
4177 test_output_honor_noqa = """
4178 import os
4179
4180 import foo
4181 import requestsss
4182
4183 import zed # NOQA
4184 import ujson # NOQA
4185 """
4186 assert isort.code(test_input) == test_output
4187 assert isort.code(test_input.lower()) == test_output.lower()
4188 assert isort.code(test_input, honor_noqa=True) == test_output_honor_noqa
4189 assert isort.code(test_input.lower(), honor_noqa=True) == test_output_honor_noqa.lower()
4190
4191
4192 def test_extract_multiline_output_wrap_setting_from_a_config_file(tmp_path: Path) -> None:
4193 editorconfig_contents = ["root = true", " [*.py]", "multi_line_output = 5"]
4194 config_file = tmp_path / ".editorconfig"
4195 config_file.write_text("\n".join(editorconfig_contents))
4196
4197 config = Config(settings_path=str(tmp_path))
4198 assert config.multi_line_output == WrapModes.VERTICAL_GRID_GROUPED
4199
4200
4201 def test_ensure_support_for_non_typed_but_cased_alphabetic_sort_issue_890() -> None:
4202 test_input = (
4203 "from pkg import BALL\n"
4204 "from pkg import RC\n"
4205 "from pkg import Action\n"
4206 "from pkg import Bacoo\n"
4207 "from pkg import RCNewCode\n"
4208 "from pkg import actual\n"
4209 "from pkg import rc\n"
4210 "from pkg import recorder\n"
4211 )
4212 expected_output = (
4213 "from pkg import Action\n"
4214 "from pkg import BALL\n"
4215 "from pkg import Bacoo\n"
4216 "from pkg import RC\n"
4217 "from pkg import RCNewCode\n"
4218 "from pkg import actual\n"
4219 "from pkg import rc\n"
4220 "from pkg import recorder\n"
4221 )
4222 assert (
4223 isort.code(
4224 code=test_input, case_sensitive=True, order_by_type=False, force_single_line=True
4225 )
4226 == expected_output
4227 )
4228
4229
4230 def test_to_ensure_empty_line_not_added_to_file_start_issue_889() -> None:
4231 test_input = "# comment\nimport os\n# comment2\nimport sys\n"
4232 assert isort.code(test_input) == test_input
4233
4234
4235 @pytest.mark.parametrize("ws", ["", " ", "\t", "\f", "\n"])
4236 def test_to_ensure_correctly_handling_of_whitespace_only_issue_811(
4237 ws: str,
4238 capsys: pytest.CaptureFixture[str],
4239 ) -> None:
4240 test_input = f'import os\nimport sys\n\n{ws}\ndef my_function():\n print("hi")\n'
4241 assert isort.check_code(test_input, ignore_whitespace=True)
4242 out, err = capsys.readouterr()
4243 assert out == ""
4244 assert err == ""
4245
4246
4247 def test_standard_library_deprecates_user_issue_778() -> None:
4248 test_input = "import os\n\nimport user\n"
4249 assert isort.code(test_input) == test_input
4250
4251
4252 @pytest.mark.skipif(sys.platform == "win32", reason="does not run on windows")
4253 def test_settings_path_skip_issue_909(tmp_path: Path) -> None:
4254 base_dir = tmp_path / "project"
4255 base_dir.mkdir()
4256 config_dir = base_dir / "conf"
4257 config_dir.mkdir()
4258 (config_dir / ".isort.cfg").write_text(
4259 "[isort]\nskip =\n file_to_be_skipped.py\nskip_glob =\n *glob_skip*\n"
4260 )
4261
4262 (base_dir / "file_glob_skip.py").write_text(
4263 'import os\n\nprint("Hello World")\n\nimport sys\nimport os\n'
4264 )
4265 (base_dir / "file_to_be_skipped.py").write_text(
4266 'import os\n\nprint("Hello World")\nimport sys\nimport os\n'
4267 )
4268
4269 test_run_directory = os.getcwd()
4270 os.chdir(str(base_dir))
4271 with pytest.raises(subprocess.CalledProcessError):
4272 # without the settings path provided: the command should not skip & identify errors
4273 subprocess.run(["isort", ".", "--check-only"], check=True)
4274 result = subprocess.run(
4275 ["isort", ".", "--check-only", "--settings-path=conf/.isort.cfg"],
4276 stdout=subprocess.PIPE,
4277 check=True,
4278 )
4279 os.chdir(str(test_run_directory))
4280
4281 assert b"skipped 2" in result.stdout.lower()
4282
4283
4284 @pytest.mark.skipif(sys.platform == "win32", reason="does not run on windows")
4285 def test_skip_paths_issue_938(tmp_path: Path) -> None:
4286 base_dir = tmp_path / "project"
4287 base_dir.mkdir()
4288 config_dir = base_dir / "conf"
4289 config_dir.mkdir()
4290 (config_dir / ".isort.cfg").write_text(
4291 "[isort]\n"
4292 "line_length = 88\n"
4293 "multi_line_output = 4\n"
4294 "lines_after_imports = 2\n"
4295 "skip_glob =\n"
4296 " migrations/**.py\n"
4297 )
4298 (base_dir / "dont_skip.py").write_text('import os\n\nprint("Hello World")\nimport sys\n')
4299
4300 migrations_dir = base_dir / "migrations"
4301 migrations_dir.mkdir()
4302 (migrations_dir / "file_glob_skip.py").write_text(
4303 'import os\n\nprint("Hello World")\n\nimport sys\n'
4304 )
4305
4306 test_run_directory = os.getcwd()
4307 os.chdir(str(base_dir))
4308 result = subprocess.run(
4309 ["isort", "dont_skip.py", "migrations/file_glob_skip.py"],
4310 stdout=subprocess.PIPE,
4311 check=True,
4312 )
4313 os.chdir(str(test_run_directory))
4314
4315 assert b"skipped" not in result.stdout.lower()
4316
4317 os.chdir(str(base_dir))
4318 result = subprocess.run(
4319 [
4320 "isort",
4321 "--filter-files",
4322 "--settings-path=conf/.isort.cfg",
4323 "dont_skip.py",
4324 "migrations/file_glob_skip.py",
4325 ],
4326 stdout=subprocess.PIPE,
4327 check=True,
4328 )
4329 os.chdir(str(test_run_directory))
4330
4331 assert b"skipped 1" in result.stdout.lower()
4332
4333
4334 def test_failing_file_check_916() -> None:
4335 test_input = (
4336 "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n"
4337 )
4338 expected_output = (
4339 "#!/usr/bin/env python\n"
4340 "# -*- coding: utf-8 -*-\n"
4341 "# FUTURE\n"
4342 "from __future__ import unicode_literals\n"
4343 )
4344 settings = {
4345 "import_heading_future": "FUTURE",
4346 "sections": ["FUTURE", "STDLIB", "NORDIGEN", "FIRSTPARTY", "THIRDPARTY", "LOCALFOLDER"],
4347 "indent": " ",
4348 "multi_line_output": 3,
4349 "lines_after_imports": 2,
4350 } # type: dict[str, Any]
4351 assert isort.code(test_input, **settings) == expected_output
4352 assert isort.code(expected_output, **settings) == expected_output
4353 assert api.check_code_string(expected_output, **settings)
4354
4355
4356 def test_import_heading_issue_905() -> None:
4357 config = {
4358 "import_heading_stdlib": "Standard library imports",
4359 "import_heading_thirdparty": "Third party imports",
4360 "import_heading_firstparty": "Local imports",
4361 "known_third_party": ["numpy"],
4362 "known_first_party": ["oklib"],
4363 } # type: dict[str, Any]
4364 test_input = (
4365 "# Standard library imports\n"
4366 "from os import path as osp\n"
4367 "\n"
4368 "# Third party imports\n"
4369 "import numpy as np\n"
4370 "\n"
4371 "# Local imports\n"
4372 "from oklib.plot_ok import imagesc\n"
4373 )
4374 assert isort.code(test_input, **config) == test_input
4375
4376
4377 def test_isort_keeps_comments_issue_691() -> None:
4378 test_input = (
4379 "import os\n"
4380 "# This will make sure the app is always imported when\n"
4381 "# Django starts so that shared_task will use this app.\n"
4382 "from .celery import app as celery_app # noqa\n"
4383 "\n"
4384 "PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))\n"
4385 "\n"
4386 "def path(*subdirectories):\n"
4387 " return os.path.join(PROJECT_DIR, *subdirectories)\n"
4388 )
4389 expected_output = (
4390 "import os\n"
4391 "\n"
4392 "# This will make sure the app is always imported when\n"
4393 "# Django starts so that shared_task will use this app.\n"
4394 "from .celery import app as celery_app # noqa\n"
4395 "\n"
4396 "PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))\n"
4397 "\n"
4398 "def path(*subdirectories):\n"
4399 " return os.path.join(PROJECT_DIR, *subdirectories)\n"
4400 )
4401 assert isort.code(test_input) == expected_output
4402
4403
4404 def test_isort_multiline_with_tab_issue_1714() -> None:
4405 test_input = "from sys \\ \n\timport version\nprint(version)\n"
4406
4407 expected_output = "from sys import version\n\nprint(version)\n"
4408
4409 assert isort.code(test_input) == expected_output
4410
4411
4412 def test_isort_ensures_blank_line_between_import_and_comment() -> None:
4413 config = {
4414 "ensure_newline_before_comments": True,
4415 "lines_between_sections": 0,
4416 "known_one": ["one"],
4417 "known_two": ["two"],
4418 "known_three": ["three"],
4419 "known_four": ["four"],
4420 "sections": [
4421 "FUTURE",
4422 "STDLIB",
4423 "FIRSTPARTY",
4424 "THIRDPARTY",
4425 "LOCALFOLDER",
4426 "ONE",
4427 "TWO",
4428 "THREE",
4429 "FOUR",
4430 ],
4431 } # type: dict[str, Any]
4432 test_input = (
4433 "import os\n"
4434 "# noinspection PyUnresolvedReferences\n"
4435 "import one.a\n"
4436 "# noinspection PyUnresolvedReferences\n"
4437 "import one.b\n"
4438 "# noinspection PyUnresolvedReferences\n"
4439 "import two.a as aa\n"
4440 "# noinspection PyUnresolvedReferences\n"
4441 "import two.b as bb\n"
4442 "# noinspection PyUnresolvedReferences\n"
4443 "from three.a import a\n"
4444 "# noinspection PyUnresolvedReferences\n"
4445 "from three.b import b\n"
4446 "# noinspection PyUnresolvedReferences\n"
4447 "from four.a import a as aa\n"
4448 "# noinspection PyUnresolvedReferences\n"
4449 "from four.b import b as bb\n"
4450 )
4451 expected_output = (
4452 "import os\n"
4453 "\n"
4454 "# noinspection PyUnresolvedReferences\n"
4455 "import one.a\n"
4456 "\n"
4457 "# noinspection PyUnresolvedReferences\n"
4458 "import one.b\n"
4459 "\n"
4460 "# noinspection PyUnresolvedReferences\n"
4461 "import two.a as aa\n"
4462 "\n"
4463 "# noinspection PyUnresolvedReferences\n"
4464 "import two.b as bb\n"
4465 "\n"
4466 "# noinspection PyUnresolvedReferences\n"
4467 "from three.a import a\n"
4468 "\n"
4469 "# noinspection PyUnresolvedReferences\n"
4470 "from three.b import b\n"
4471 "\n"
4472 "# noinspection PyUnresolvedReferences\n"
4473 "from four.a import a as aa\n"
4474 "\n"
4475 "# noinspection PyUnresolvedReferences\n"
4476 "from four.b import b as bb\n"
4477 )
4478 assert isort.code(test_input, **config) == expected_output
4479
4480
4481 def test_pyi_formatting_issue_942(tmp_path: Path) -> None:
4482 test_input = "import os\n\n\ndef my_method():\n"
4483 expected_py_output = test_input.splitlines()
4484 expected_pyi_output = "import os\n\ndef my_method():\n".splitlines()
4485 assert isort.code(test_input).splitlines() == expected_py_output
4486 assert isort.code(test_input, extension="pyi").splitlines() == expected_pyi_output
4487
4488 source_py = tmp_path / "source.py"
4489 source_py.write_text(test_input)
4490 assert (
4491 isort.code(code=Path(source_py).read_text(), file_path=Path(source_py)).splitlines()
4492 == expected_py_output
4493 )
4494
4495 source_pyi = tmp_path / "source.pyi"
4496 source_pyi.write_text(test_input)
4497 assert (
4498 isort.code(
4499 code=Path(source_pyi).read_text(), extension="pyi", file_path=Path(source_pyi)
4500 ).splitlines()
4501 == expected_pyi_output
4502 )
4503
4504 # Ensure it works for direct file API as well (see: issue #1284)
4505 source_pyi = tmp_path / "source.pyi"
4506 source_pyi.write_text(test_input)
4507 api.sort_file(Path(source_pyi))
4508
4509 assert source_pyi.read_text().splitlines() == expected_pyi_output
4510
4511
4512 def test_move_class_issue_751() -> None:
4513 test_input = (
4514 "# -*- coding: utf-8 -*-"
4515 "\n"
4516 "# Define your item pipelines here"
4517 "#"
4518 "# Don't forget to add your pipeline to the ITEM_PIPELINES setting"
4519 "# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html"
4520 "from datetime import datetime"
4521 "from .items import WeiboMblogItem"
4522 "\n"
4523 "class WeiboMblogPipeline(object):"
4524 " def process_item(self, item, spider):"
4525 " if isinstance(item, WeiboMblogItem):"
4526 " item = self._process_item(item, spider)"
4527 " return item"
4528 "\n"
4529 " def _process_item(self, item, spider):"
4530 " item['inserted_at'] = datetime.now()"
4531 " return item"
4532 "\n"
4533 )
4534 assert isort.code(test_input) == test_input
4535
4536
4537 def test_python_version() -> None:
4538 # test that the py_version can be added as flag
4539 args = parse_args(["--py=27"])
4540 assert args["py_version"] == "27"
4541
4542 args = parse_args(["--python-version=3"])
4543 assert args["py_version"] == "3"
4544
4545 test_input = "import os\n\nimport user\n"
4546 assert isort.code(test_input, py_version="3") == test_input
4547
4548 # user is part of the standard library in python 2
4549 output_python_2 = "import os\nimport user\n"
4550 assert isort.code(test_input, py_version="27") == output_python_2
4551
4552 test_input = "import os\nimport xml"
4553
4554 print(isort.code(test_input, py_version="all"))
4555
4556
4557 def test_isort_with_single_character_import() -> None:
4558 """Tests to ensure isort handles single capatilized single character imports
4559 as class objects by default
4560
4561 See Issue #376: https://github.com/pycqa/isort/issues/376
4562 """
4563 test_input = "from django.db.models import CASCADE, SET_NULL, Q\n"
4564 assert isort.code(test_input) == test_input
4565
4566
4567 def test_isort_nested_imports() -> None:
4568 """Ensure imports in a nested block get sorted correctly"""
4569 test_input = """
4570 def import_test():
4571 import sys
4572 import os
4573
4574 # my imports
4575 from . import def
4576 from . import abc
4577
4578 return True
4579 """
4580 assert (
4581 isort.code(test_input)
4582 == """
4583 def import_test():
4584 import os
4585 import sys
4586
4587 # my imports
4588 from . import abc, def
4589
4590 return True
4591 """
4592 )
4593
4594
4595 def test_isort_off() -> None:
4596 """Test that isort can be turned on and off at will using comments"""
4597 test_input = """import os
4598
4599 # isort: off
4600 import sys
4601 import os
4602 # isort: on
4603
4604 from . import local
4605 """
4606 assert isort.code(test_input) == test_input
4607
4608
4609 def test_isort_split() -> None:
4610 """Test the ability to split isort import sections"""
4611 test_input = """import os
4612 import sys
4613
4614 # isort: split
4615
4616 import os
4617 import sys
4618 """
4619 assert isort.code(test_input) == test_input
4620
4621 test_input = """import c
4622
4623 import b # isort: split
4624
4625 import a
4626 import c
4627 """
4628 assert isort.code(test_input) == test_input
4629
4630
4631 def test_comment_look_alike() -> None:
4632 """Test to ensure isort will handle what looks like a single line comment
4633 at the end of a multi-line comment.
4634 """
4635 test_input = '''
4636 """This is a multi-line comment
4637
4638 ending with what appears to be a single line comment
4639 # Single Line Comment"""
4640 import sys
4641 import os
4642 '''
4643 assert (
4644 isort.code(test_input)
4645 == '''
4646 """This is a multi-line comment
4647
4648 ending with what appears to be a single line comment
4649 # Single Line Comment"""
4650 import os
4651 import sys
4652 '''
4653 )
4654
4655
4656 def test_cimport_support() -> None:
4657 """Test to ensure cimports (Cython style imports) work"""
4658 test_input = """
4659 import os
4660 import sys
4661 import cython
4662 import platform
4663 import traceback
4664 import time
4665 import types
4666 import re
4667 import copy
4668 import inspect # used by JavascriptBindings.__SetObjectMethods()
4669 import urllib
4670 import json
4671 import datetime
4672 import random
4673
4674 if sys.version_info.major == 2:
4675 import urlparse
4676 else:
4677 from urllib import parse as urlparse
4678
4679 if sys.version_info.major == 2:
4680 from urllib import pathname2url as urllib_pathname2url
4681 else:
4682 from urllib.request import pathname2url as urllib_pathname2url
4683
4684 from cpython.version cimport PY_MAJOR_VERSION
4685 import weakref
4686
4687 # We should allow multiple string types: str, unicode, bytes.
4688 # PyToCefString() can handle them all.
4689 # Important:
4690 # If you set it to basestring, Cython will accept exactly(!)
4691 # str/unicode in Py2 and str in Py3. This won't work in Py3
4692 # as we might want to pass bytes as well. Also it will
4693 # reject string subtypes, so using it in publi API functions
4694 # would be a bad idea.
4695 ctypedef object py_string
4696
4697 # You can't use "void" along with cpdef function returning None, it is planned to be
4698 # added to Cython in the future, creating this virtual type temporarily. If you
4699 # change it later to "void" then don't forget to add "except *".
4700 ctypedef object py_void
4701 ctypedef long WindowHandle
4702
4703 from cpython cimport PyLong_FromVoidPtr
4704
4705 from cpython cimport bool as py_bool
4706 from libcpp cimport bool as cpp_bool
4707
4708 from libcpp.map cimport map as cpp_map
4709 from multimap cimport multimap as cpp_multimap
4710 from libcpp.pair cimport pair as cpp_pair
4711 from libcpp.vector cimport vector as cpp_vector
4712
4713 from libcpp.string cimport string as cpp_string
4714 from wstring cimport wstring as cpp_wstring
4715
4716 from libc.string cimport strlen
4717 from libc.string cimport memcpy
4718
4719 # preincrement and dereference must be "as" otherwise not seen.
4720 from cython.operator cimport preincrement as preinc, dereference as deref
4721
4722 # from cython.operator cimport address as addr # Address of an c++ object?
4723
4724 from libc.stdlib cimport calloc, malloc, free
4725 from libc.stdlib cimport atoi
4726
4727 # When pyx file cimports * from a pxd file and that pxd cimports * from another pxd
4728 # then these names will be visible in pyx file.
4729
4730 # Circular imports are allowed in form "cimport ...", but won't work if you do
4731 # "from ... cimport *", this is important to know in pxd files.
4732
4733 from libc.stdint cimport uint64_t
4734 from libc.stdint cimport uintptr_t
4735
4736 cimport ctime
4737
4738 IF UNAME_SYSNAME == "Windows":
4739 from windows cimport *
4740 from dpi_aware_win cimport *
4741 ELIF UNAME_SYSNAME == "Linux":
4742 from linux cimport *
4743 ELIF UNAME_SYSNAME == "Darwin":
4744 from mac cimport *
4745
4746 from cpp_utils cimport *
4747 from task cimport *
4748
4749 from cef_string cimport *
4750 cdef extern from *:
4751 ctypedef CefString ConstCefString "const CefString"
4752
4753 from cef_types_wrappers cimport *
4754 from cef_task cimport *
4755 from cef_runnable cimport *
4756
4757 from cef_platform cimport *
4758
4759 from cef_ptr cimport *
4760 from cef_app cimport *
4761 from cef_browser cimport *
4762 cimport cef_browser_static
4763 from cef_client cimport *
4764 from client_handler cimport *
4765 from cef_frame cimport *
4766
4767 # cannot cimport *, that would cause name conflicts with constants.
4768 cimport cef_types
4769 ctypedef cef_types.cef_paint_element_type_t PaintElementType
4770 ctypedef cef_types.cef_jsdialog_type_t JSDialogType
4771 from cef_types cimport CefKeyEvent
4772 from cef_types cimport CefMouseEvent
4773 from cef_types cimport CefScreenInfo
4774
4775 # cannot cimport *, name conflicts
4776 IF UNAME_SYSNAME == "Windows":
4777 cimport cef_types_win
4778 ELIF UNAME_SYSNAME == "Darwin":
4779 cimport cef_types_mac
4780 ELIF UNAME_SYSNAME == "Linux":
4781 cimport cef_types_linux
4782
4783 from cef_time cimport *
4784 from cef_drag cimport *
4785
4786 import os
4787
4788 IF CEF_VERSION == 1:
4789 from cef_v8 cimport *
4790 cimport cef_v8_static
4791 cimport cef_v8_stack_trace
4792 from v8function_handler cimport *
4793 from cef_request_cef1 cimport *
4794 from cef_web_urlrequest_cef1 cimport *
4795 cimport cef_web_urlrequest_static_cef1
4796 from web_request_client_cef1 cimport *
4797 from cef_stream cimport *
4798 cimport cef_stream_static
4799 from cef_response_cef1 cimport *
4800 from cef_stream cimport *
4801 from cef_content_filter cimport *
4802 from content_filter_handler cimport *
4803 from cef_download_handler cimport *
4804 from download_handler cimport *
4805 from cef_cookie_cef1 cimport *
4806 cimport cef_cookie_manager_namespace
4807 from cookie_visitor cimport *
4808 from cef_render_handler cimport *
4809 from cef_drag_data cimport *
4810
4811 IF UNAME_SYSNAME == "Windows":
4812 IF CEF_VERSION == 1:
4813 from http_authentication cimport *
4814
4815 IF CEF_VERSION == 3:
4816 from cef_values cimport *
4817 from cefpython_app cimport *
4818 from cef_process_message cimport *
4819 from cef_web_plugin_cef3 cimport *
4820 from cef_request_handler_cef3 cimport *
4821 from cef_request_cef3 cimport *
4822 from cef_cookie_cef3 cimport *
4823 from cef_string_visitor cimport *
4824 cimport cef_cookie_manager_namespace
4825 from cookie_visitor cimport *
4826 from string_visitor cimport *
4827 from cef_callback_cef3 cimport *
4828 from cef_response_cef3 cimport *
4829 from cef_resource_handler_cef3 cimport *
4830 from resource_handler_cef3 cimport *
4831 from cef_urlrequest_cef3 cimport *
4832 from web_request_client_cef3 cimport *
4833 from cef_command_line cimport *
4834 from cef_request_context cimport *
4835 from cef_request_context_handler cimport *
4836 from request_context_handler cimport *
4837 from cef_jsdialog_handler cimport *
4838 """
4839 expected_output = """
4840 import copy
4841 import datetime
4842 import inspect # used by JavascriptBindings.__SetObjectMethods()
4843 import json
4844 import os
4845 import platform
4846 import random
4847 import re
4848 import sys
4849 import time
4850 import traceback
4851 import types
4852 import urllib
4853
4854 import cython
4855
4856 if sys.version_info.major == 2:
4857 import urlparse
4858 else:
4859 from urllib import parse as urlparse
4860
4861 if sys.version_info.major == 2:
4862 from urllib import pathname2url as urllib_pathname2url
4863 else:
4864 from urllib.request import pathname2url as urllib_pathname2url
4865
4866 from cpython.version cimport PY_MAJOR_VERSION
4867
4868 import weakref
4869
4870 # We should allow multiple string types: str, unicode, bytes.
4871 # PyToCefString() can handle them all.
4872 # Important:
4873 # If you set it to basestring, Cython will accept exactly(!)
4874 # str/unicode in Py2 and str in Py3. This won't work in Py3
4875 # as we might want to pass bytes as well. Also it will
4876 # reject string subtypes, so using it in publi API functions
4877 # would be a bad idea.
4878 ctypedef object py_string
4879
4880 # You can't use "void" along with cpdef function returning None, it is planned to be
4881 # added to Cython in the future, creating this virtual type temporarily. If you
4882 # change it later to "void" then don't forget to add "except *".
4883 ctypedef object py_void
4884 ctypedef long WindowHandle
4885
4886 cimport ctime
4887 from cpython cimport PyLong_FromVoidPtr
4888 from cpython cimport bool as py_bool
4889 # preincrement and dereference must be "as" otherwise not seen.
4890 from cython.operator cimport dereference as deref
4891 from cython.operator cimport preincrement as preinc
4892 from libc.stdint cimport uint64_t, uintptr_t
4893 from libc.stdlib cimport atoi, calloc, free, malloc
4894 from libc.string cimport memcpy, strlen
4895 from libcpp cimport bool as cpp_bool
4896 from libcpp.map cimport map as cpp_map
4897 from libcpp.pair cimport pair as cpp_pair
4898 from libcpp.string cimport string as cpp_string
4899 from libcpp.vector cimport vector as cpp_vector
4900 from multimap cimport multimap as cpp_multimap
4901 from wstring cimport wstring as cpp_wstring
4902
4903 # from cython.operator cimport address as addr # Address of an c++ object?
4904
4905
4906 # When pyx file cimports * from a pxd file and that pxd cimports * from another pxd
4907 # then these names will be visible in pyx file.
4908
4909 # Circular imports are allowed in form "cimport ...", but won't work if you do
4910 # "from ... cimport *", this is important to know in pxd files.
4911
4912
4913
4914 IF UNAME_SYSNAME == "Windows":
4915 from dpi_aware_win cimport *
4916 from windows cimport *
4917 ELIF UNAME_SYSNAME == "Linux":
4918 from linux cimport *
4919 ELIF UNAME_SYSNAME == "Darwin":
4920 from mac cimport *
4921
4922 from cef_string cimport *
4923 from cpp_utils cimport *
4924 from task cimport *
4925
4926
4927 cdef extern from *:
4928 ctypedef CefString ConstCefString "const CefString"
4929
4930 cimport cef_browser_static
4931 # cannot cimport *, that would cause name conflicts with constants.
4932 cimport cef_types
4933 from cef_app cimport *
4934 from cef_browser cimport *
4935 from cef_client cimport *
4936 from cef_frame cimport *
4937 from cef_platform cimport *
4938 from cef_ptr cimport *
4939 from cef_runnable cimport *
4940 from cef_task cimport *
4941 from cef_types_wrappers cimport *
4942 from client_handler cimport *
4943
4944 ctypedef cef_types.cef_paint_element_type_t PaintElementType
4945 ctypedef cef_types.cef_jsdialog_type_t JSDialogType
4946 from cef_types cimport CefKeyEvent, CefMouseEvent, CefScreenInfo
4947
4948 # cannot cimport *, name conflicts
4949 IF UNAME_SYSNAME == "Windows":
4950 cimport cef_types_win
4951 ELIF UNAME_SYSNAME == "Darwin":
4952 cimport cef_types_mac
4953 ELIF UNAME_SYSNAME == "Linux":
4954 cimport cef_types_linux
4955
4956 from cef_drag cimport *
4957 from cef_time cimport *
4958
4959 import os
4960
4961 IF CEF_VERSION == 1:
4962 cimport cef_cookie_manager_namespace
4963 cimport cef_stream_static
4964 cimport cef_v8_stack_trace
4965 cimport cef_v8_static
4966 cimport cef_web_urlrequest_static_cef1
4967 from cef_content_filter cimport *
4968 from cef_cookie_cef1 cimport *
4969 from cef_download_handler cimport *
4970 from cef_drag_data cimport *
4971 from cef_render_handler cimport *
4972 from cef_request_cef1 cimport *
4973 from cef_response_cef1 cimport *
4974 from cef_stream cimport *
4975 from cef_v8 cimport *
4976 from cef_web_urlrequest_cef1 cimport *
4977 from content_filter_handler cimport *
4978 from cookie_visitor cimport *
4979 from download_handler cimport *
4980 from v8function_handler cimport *
4981 from web_request_client_cef1 cimport *
4982
4983 IF UNAME_SYSNAME == "Windows":
4984 IF CEF_VERSION == 1:
4985 from http_authentication cimport *
4986
4987 IF CEF_VERSION == 3:
4988 cimport cef_cookie_manager_namespace
4989 from cef_callback_cef3 cimport *
4990 from cef_command_line cimport *
4991 from cef_cookie_cef3 cimport *
4992 from cef_jsdialog_handler cimport *
4993 from cef_process_message cimport *
4994 from cef_request_cef3 cimport *
4995 from cef_request_context cimport *
4996 from cef_request_context_handler cimport *
4997 from cef_request_handler_cef3 cimport *
4998 from cef_resource_handler_cef3 cimport *
4999 from cef_response_cef3 cimport *
5000 from cef_string_visitor cimport *
5001 from cef_urlrequest_cef3 cimport *
5002 from cef_values cimport *
5003 from cef_web_plugin_cef3 cimport *
5004 from cefpython_app cimport *
5005 from cookie_visitor cimport *
5006 from request_context_handler cimport *
5007 from resource_handler_cef3 cimport *
5008 from string_visitor cimport *
5009 from web_request_client_cef3 cimport *
5010 """
5011 assert isort.code(test_input).strip() == expected_output.strip()
5012
5013
5014 def test_cdef_support() -> None:
5015 assert (
5016 isort.code(
5017 code="""
5018 from cpython.version cimport PY_MAJOR_VERSION
5019
5020 cdef extern from *:
5021 ctypedef CefString ConstCefString "const CefString"
5022 """
5023 )
5024 == """
5025 from cpython.version cimport PY_MAJOR_VERSION
5026
5027
5028 cdef extern from *:
5029 ctypedef CefString ConstCefString "const CefString"
5030 """
5031 )
5032
5033 assert (
5034 isort.code(
5035 code="""
5036 from cpython.version cimport PY_MAJOR_VERSION
5037
5038 cpdef extern from *:
5039 ctypedef CefString ConstCefString "const CefString"
5040 """
5041 )
5042 == """
5043 from cpython.version cimport PY_MAJOR_VERSION
5044
5045
5046 cpdef extern from *:
5047 ctypedef CefString ConstCefString "const CefString"
5048 """
5049 )
5050
5051
5052 def test_top_level_import_order() -> None:
5053 test_input = (
5054 "from rest_framework import throttling, viewsets\n"
5055 "from rest_framework.authentication import TokenAuthentication\n"
5056 )
5057 assert isort.code(test_input, force_sort_within_sections=True) == test_input
5058
5059
5060 def test_noqa_issue_1065() -> None:
5061 test_input = """
5062 #
5063 # USER SIGNALS
5064 #
5065
5066 from flask_login import user_logged_in, user_logged_out # noqa
5067
5068 from flask_security.signals import ( # noqa
5069 password_changed as user_reset_password, # noqa
5070 user_confirmed, # noqa
5071 user_registered, # noqa
5072 ) # noqa
5073
5074 from flask_principal import identity_changed as user_identity_changed # noqa
5075 """
5076 expected_output = """
5077 #
5078 # USER SIGNALS
5079 #
5080
5081 from flask_login import user_logged_in, user_logged_out # noqa
5082 from flask_principal import identity_changed as user_identity_changed # noqa
5083 from flask_security.signals import password_changed as user_reset_password # noqa
5084 from flask_security.signals import user_confirmed # noqa
5085 from flask_security.signals import user_registered # noqa
5086 """
5087 assert isort.code(test_input, line_length=100) == expected_output
5088
5089 test_input_2 = """
5090 #
5091 # USER SIGNALS
5092 #
5093
5094 from flask_login import user_logged_in, user_logged_out # noqa
5095
5096 from flask_security.signals import (
5097 password_changed as user_reset_password, # noqa
5098 user_confirmed, # noqa
5099 user_registered, # noqa
5100 )
5101
5102 from flask_principal import identity_changed as user_identity_changed # noqa
5103 """
5104 assert isort.code(test_input_2, line_length=100) == expected_output
5105
5106
5107 def test_single_line_exclusions() -> None:
5108 test_input = """
5109 # start comment
5110 from os import path, system
5111 from typing import List, TypeVar
5112 """
5113 expected_output = """
5114 # start comment
5115 from os import path
5116 from os import system
5117 from typing import List, TypeVar
5118 """
5119 assert (
5120 isort.code(code=test_input, force_single_line=True, single_line_exclusions=("typing",))
5121 == expected_output
5122 )
5123
5124
5125 def test_nested_comment_handling() -> None:
5126 test_input = """
5127 if True:
5128 import foo
5129
5130 # comment for bar
5131 """
5132 assert isort.code(test_input) == test_input
5133
5134 # If comments appear inside import sections at same indentation they can be re-arranged.
5135 test_input = """
5136 if True:
5137 import sys
5138
5139 # os import
5140 import os
5141 """
5142 expected_output = """
5143 if True:
5144 # os import
5145 import os
5146 import sys
5147 """
5148 assert isort.code(test_input) == expected_output
5149
5150 # Comments shouldn't be unexpectedly rearranged. See issue #1090.
5151 test_input = """
5152 def f():
5153 # comment 1
5154 # comment 2
5155
5156 # comment 3
5157 # comment 4
5158 from a import a
5159 from b import b
5160
5161 """
5162 assert isort.code(test_input) == test_input
5163
5164 # Whitespace shouldn't be adjusted for nested imports. See issue #1090.
5165 test_input = """
5166 try:
5167 import foo
5168 except ImportError:
5169 import bar
5170 """
5171 assert isort.code(test_input) == test_input
5172
5173
5174 def test_comments_top_of_file() -> None:
5175 """Test to ensure comments at top of file are correctly handled. See issue #1091."""
5176 test_input = """# comment 1
5177
5178 # comment 2
5179 # comment 3
5180 # comment 4
5181 from foo import *
5182 """
5183 assert isort.code(test_input) == test_input
5184
5185 test_input = """# -*- coding: utf-8 -*-
5186
5187 # Define your item pipelines here
5188 #
5189 # Don't forget to add your pipeline to the ITEM_PIPELINES setting
5190 # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
5191 from datetime import datetime
5192
5193 from .items import WeiboMblogItem
5194
5195
5196 class WeiboMblogPipeline(object):
5197 def process_item(self, item, spider):
5198 if isinstance(item, WeiboMblogItem):
5199 item = self._process_item(item, spider)
5200 return item
5201
5202 def _process_item(self, item, spider):
5203 item['inserted_at'] = datetime.now()
5204 return item
5205 """
5206 assert isort.code(test_input) == test_input
5207
5208
5209 def test_multiple_aliases() -> None:
5210 """Test to ensure isort will retain multiple aliases. See issue #1037"""
5211 test_input = """import datetime
5212 import datetime as datetime
5213 import datetime as dt
5214 import datetime as dt2
5215 """
5216 assert isort.code(code=test_input) == test_input
5217
5218
5219 def test_parens_in_comment() -> None:
5220 """Test to ensure isort can handle parens placed in comments. See issue #1103"""
5221 test_input = """from foo import ( # (some text in brackets)
5222 bar,
5223 )
5224 """
5225 expected_output = "from foo import bar # (some text in brackets)\n"
5226 assert isort.code(test_input) == expected_output
5227
5228
5229 def test_as_imports_mixed() -> None:
5230 """Test to ensure as imports can be mixed with non as. See issue #908"""
5231 test_input = """from datetime import datetime
5232 import datetime.datetime as dt
5233 """
5234 expected_output = """import datetime.datetime as dt
5235 from datetime import datetime
5236 """
5237 assert isort.code(test_input) == expected_output
5238
5239
5240 def test_no_sections_with_future() -> None:
5241 """Test to ensure no_sections works with future. See issue #807"""
5242 test_input = """from __future__ import print_function
5243 import os
5244 """
5245 expected_output = """from __future__ import print_function
5246
5247 import os
5248 """
5249 assert isort.code(test_input, no_sections=True) == expected_output
5250
5251
5252 def test_no_sections_with_as_import() -> None:
5253 """Test to ensure no_sections work with as import."""
5254 test_input = """import oumpy as np
5255 import sympy
5256 """
5257 assert isort.code(test_input, no_sections=True) == test_input
5258
5259
5260 def test_no_lines_too_long() -> None:
5261 """Test to ensure no lines end up too long. See issue: #1015"""
5262 test_input = """from package1 import first_package, \
5263 second_package
5264 from package2 import \\
5265 first_package
5266 """
5267 expected_output = """from package1 import \\
5268 first_package, \\
5269 second_package
5270 from package2 import \\
5271 first_package
5272 """
5273 assert isort.code(test_input, line_length=25, multi_line_output=2) == expected_output
5274
5275
5276 def test_python_future_category() -> None:
5277 """Test to ensure a manual python future category will work as needed to install aliases
5278
5279 see: Issue #1005
5280 """
5281 test_input = """from __future__ import absolute_import
5282
5283 # my future comment
5284 from future import standard_library
5285
5286 standard_library.install_aliases()
5287
5288 import os
5289 import re
5290 import time
5291
5292 from logging.handlers import SysLogHandler
5293
5294 from builtins import len, object, str
5295
5296 from katlogger import log_formatter, log_rollover
5297
5298 from .query_elastic import QueryElastic
5299 """
5300 expected_output = """from __future__ import absolute_import
5301
5302 # my future comment
5303 from future import standard_library
5304
5305 standard_library.install_aliases()
5306
5307 # Python Standard Library
5308 import os
5309 import re
5310 import time
5311
5312 from builtins import len, object, str
5313 from logging.handlers import SysLogHandler
5314
5315 # CAM Packages
5316 from katlogger import log_formatter, log_rollover
5317
5318 # Explicitly Local
5319 from .query_elastic import QueryElastic
5320 """
5321 assert (
5322 isort.code(
5323 code=test_input,
5324 force_grid_wrap=False,
5325 include_trailing_comma=True,
5326 indent=4,
5327 line_length=90,
5328 multi_line_output=3,
5329 lines_between_types=1,
5330 sections=[
5331 "FUTURE_LIBRARY",
5332 "FUTURE_THIRDPARTY",
5333 "STDLIB",
5334 "THIRDPARTY",
5335 "FIRSTPARTY",
5336 "LOCALFOLDER",
5337 ],
5338 import_heading_stdlib="Python Standard Library",
5339 import_heading_thirdparty="Third Library",
5340 import_heading_firstparty="CAM Packages",
5341 import_heading_localfolder="Explicitly Local",
5342 known_first_party=["katlogger"],
5343 known_future_thirdparty=["future"],
5344 )
5345 == expected_output
5346 )
5347
5348
5349 def test_combine_star_comments_above() -> None:
5350 input_text = """from __future__ import absolute_import
5351
5352 # my future comment
5353 from future import *, something
5354 """
5355 expected_output = """from __future__ import absolute_import
5356
5357 # my future comment
5358 from future import *
5359 """
5360 assert isort.code(input_text, combine_star=True) == expected_output
5361
5362
5363 def test_only_sections() -> None:
5364 """Test to ensure that the within sections relative position of imports are maintained"""
5365 test_input = (
5366 "import sys\n"
5367 "\n"
5368 "import numpy as np\n"
5369 "\n"
5370 "import os\n"
5371 "from os import path as ospath\n"
5372 "\n"
5373 "import pandas as pd\n"
5374 "\n"
5375 "import math\n"
5376 "import .views\n"
5377 "from collections import defaultdict\n"
5378 )
5379
5380 assert (
5381 isort.code(test_input, only_sections=True)
5382 == (
5383 "import sys\n"
5384 "import os\n"
5385 "import math\n"
5386 "from os import path as ospath\n"
5387 "from collections import defaultdict\n"
5388 "\n"
5389 "import numpy as np\n"
5390 "import pandas as pd\n"
5391 "\n"
5392 "import .views\n"
5393 )
5394 == isort.code(test_input, only_sections=True, force_single_line=True)
5395 )
5396
5397 # test to ensure that from_imports remain intact with only_sections
5398 test_input = "from foo import b, a, c\n"
5399
5400 assert isort.code(test_input, only_sections=True) == test_input
5401
5402
5403 def test_combine_straight_imports() -> None:
5404 """Tests to ensure that combine_straight_imports works correctly"""
5405
5406 test_input = "import os\nimport sys\n# this is a comment\nimport math # inline comment\n"
5407
5408 assert isort.code(test_input, combine_straight_imports=True) == (
5409 "# this is a comment\nimport math, os, sys # inline comment\n"
5410 )
5411
5412 # test to ensure that combine_straight_import works with only_sections
5413
5414 test_input = "import sys, os\nimport a\nimport math\nimport b\n"
5415
5416 assert isort.code(test_input, combine_straight_imports=True, only_sections=True) == (
5417 "import sys, os, math\n\nimport a, b\n"
5418 )
5419
5420
5421 def test_find_imports_in_code() -> None:
5422 test_input = (
5423 "import first_straight\n"
5424 "\n"
5425 "import second_straight\n"
5426 "from first_from import first_from_function_1, first_from_function_2\n"
5427 "import bad_name as good_name\n"
5428 "from parent.some_bad_defs import bad_name_1 as ok_name_1, bad_name_2 as ok_name_2\n"
5429 "\n"
5430 "# isort: list\n"
5431 "__all__ = ['b', 'c', 'a']\n"
5432 "\n"
5433 "def bla():\n"
5434 " import needed_in_bla_2\n"
5435 "\n"
5436 "\n"
5437 " import needed_in_bla\n"
5438 " pass"
5439 "\n"
5440 "def bla_bla():\n"
5441 " import needed_in_bla_bla\n"
5442 "\n"
5443 " #import not_really_an_import\n"
5444 " pass"
5445 "\n"
5446 "import needed_in_end\n"
5447 )
5448 identified_imports = list(map(str, api.find_imports_in_code(test_input)))
5449 assert identified_imports == [
5450 ":1 import first_straight",
5451 ":3 import second_straight",
5452 ":4 from first_from import first_from_function_1",
5453 ":4 from first_from import first_from_function_2",
5454 ":5 import bad_name as good_name",
5455 ":6 from parent.some_bad_defs import bad_name_1 as ok_name_1",
5456 ":6 from parent.some_bad_defs import bad_name_2 as ok_name_2",
5457 ":12 indented import needed_in_bla_2",
5458 ":15 indented import needed_in_bla",
5459 ":18 indented import needed_in_bla_bla",
5460 ":22 import needed_in_end",
5461 ]
5462
5463
5464 def test_find_imports_in_stream() -> None:
5465 """Ensure that find_imports_in_stream can work with nonseekable streams like STDOUT"""
5466
5467 class NonSeekableTestStream(StringIO):
5468 def seek(self, offset: int, whence: int = os.SEEK_SET, /) -> int:
5469 raise OSError("Stream is not seekable")
5470
5471 def seekable(self) -> bool:
5472 return False
5473
5474 test_input = NonSeekableTestStream("import m2\nimport m1\nnot_import = 7")
5475 identified_imports = list(map(str, api.find_imports_in_stream(test_input)))
5476 assert identified_imports == [":1 import m2", ":2 import m1"]
5477
5478
5479 def test_split_on_trailing_comma() -> None:
5480 test_input = "from lib import (a, b, c,)"
5481 expected_output = """from lib import (
5482 a,
5483 b,
5484 c,
5485 )
5486 """
5487
5488 output = isort.code(test_input, split_on_trailing_comma=True)
5489 assert output == expected_output
5490
5491 output = isort.code(expected_output, split_on_trailing_comma=True)
5492 assert output == expected_output
5493
5494
5495 def test_split_on_trailing_comma_wih_as() -> None:
5496 test_input = "from lib import (a as b,)"
5497 expected_output = """from lib import a as b
5498 """
5499
5500 output = isort.code(test_input, split_on_trailing_comma=True)
5501 assert output == expected_output
5502
5503 output = isort.code(expected_output, split_on_trailing_comma=True)
5504 assert output == expected_output
5505
5506
5507 def test_split_on_trailing_comma_stable_with_mixed_as_imports_issue_2352() -> None:
5508 """Regression test for https://github.com/PyCQA/isort/issues/2352.
5509
5510 isort should produce stable output when a module has both aliased and non-aliased imports with
5511 `include_trailing_comma` enabled. A single non-aliased import remaining after the aliased
5512 imports should not be force-wrapped into multi-line format merely because a trailing comma was
5513 recorded for the module.
5514 """
5515 # Test case from the original issue report
5516 test_input = """from django.db.models.sql.compiler import (
5517 SQLAggregateCompiler,
5518 SQLCompiler,
5519 SQLDeleteCompiler,
5520 )
5521 from django.db.models.sql.compiler import SQLInsertCompiler as BaseSQLInsertCompiler
5522 from django.db.models.sql.compiler import SQLUpdateCompiler
5523 """
5524 output = isort.code(
5525 test_input,
5526 include_trailing_comma=True,
5527 split_on_trailing_comma=True,
5528 line_length=88,
5529 )
5530 assert output == test_input
5531
5532 expected_output_with_combine = """from django.db.models.sql.compiler import (
5533 SQLAggregateCompiler,
5534 SQLCompiler,
5535 SQLDeleteCompiler,
5536 SQLInsertCompiler as BaseSQLInsertCompiler,
5537 SQLUpdateCompiler,
5538 )
5539 """
5540 output = isort.code(
5541 test_input,
5542 include_trailing_comma=True,
5543 split_on_trailing_comma=True,
5544 line_length=88,
5545 combine_as_imports=True,
5546 )
5547 assert (
5548 output
5549 == expected_output_with_combine
5550 == isort.code(
5551 expected_output_with_combine,
5552 include_trailing_comma=True,
5553 split_on_trailing_comma=True,
5554 line_length=88,
5555 combine_as_imports=True,
5556 )
5557 )
5558
5559
5560 def test_split_on_trailing_comma_stable_with_use_parentheses_2352() -> None:
5561 """Regression test for https://github.com/PyCQA/isort/issues/2352.
5562
5563 isort should produce stable output when a module has both aliased and non-aliased imports with
5564 `include_trailing_comma` and `use_parentheses` enabled. A single non-aliased import remaining
5565 after the aliased imports should not be force-wrapped into multi-line format merely because a
5566 trailing comma was recorded for the module.
5567 """
5568 test_input = r"""
5569 from another_file_aaaaaaaaaaaaaaaaaa import \
5570 SOME_THING_CONSTANT as SOME_THING_CONSTANT_RENAMED
5571 from another_file_aaaaaaaaaaaaaaaaaa import some_func
5572 """
5573
5574 expected_output = """
5575 from another_file_aaaaaaaaaaaaaaaaaa import (
5576 SOME_THING_CONSTANT as SOME_THING_CONSTANT_RENAMED,
5577 )
5578 from another_file_aaaaaaaaaaaaaaaaaa import some_func
5579 """
5580
5581 output = isort.code(
5582 test_input,
5583 include_trailing_comma=True,
5584 use_parentheses=True,
5585 multi_line_output=3,
5586 )
5587 assert output == expected_output
5588 # Run again on actual output
5589 assert output == isort.code(
5590 output,
5591 include_trailing_comma=True,
5592 use_parentheses=True,
5593 multi_line_output=3,
5594 )
5595
5596
5597 def test_infinite_loop_in_unmatched_parenthesis() -> None:
5598 test_input = "from os import ("
5599
5600 # ensure a syntax error is raised for unmatched parenthesis
5601 with pytest.raises(ExistingSyntaxErrors):
5602 isort.code(test_input)
5603
5604 test_input = """from os import (
5605 path,
5606
5607 walk
5608 )
5609 """
5610
5611 # ensure other cases are handled correctly
5612 assert isort.code(test_input) == "from os import path, walk\n"
5613
5614
5615 def test_reexport() -> None:
5616 test_input = """__all__ = ('foo', 'bar')
5617 """
5618 expd_output = """__all__ = ("bar", "foo")
5619 """
5620 assert isort.code(test_input, config=Config(sort_reexports=True)) == expd_output
5621
5622
5623 def test_reexport_leave_alone_if_not_enabled() -> None:
5624 test_input = """__all__ = ('foo', 'bar')
5625 """
5626 assert isort.code(test_input) == test_input
5627
5628
5629 def test_reexport_multiline() -> None:
5630 test_input = """__all__ = (
5631 'foo',
5632 'bar',
5633 )
5634 """
5635 expd_output = """__all__ = ("bar", "foo")
5636 """
5637 assert isort.code(test_input, config=Config(sort_reexports=True)) == expd_output
5638
5639
5640 def test_reexport_list() -> None:
5641 test_input = """__all__ = ['foo', 'bar']
5642 """
5643 expd_output = """__all__ = ["bar", "foo"]
5644 """
5645 assert isort.code(test_input, config=Config(sort_reexports=True)) == expd_output
5646
5647
5648 def test_reexport_set() -> None:
5649 test_input = """__all__ = {'foo', 'bar'}
5650 """
5651 expd_output = """__all__ = {"bar", "foo"}
5652 """
5653 assert isort.code(test_input, config=Config(sort_reexports=True)) == expd_output
5654
5655
5656 def test_reexport_bare() -> None:
5657 test_input = """__all__ = 'foo', 'bar'
5658 """
5659 expd_output = """__all__ = ("bar", "foo")
5660 """
5661 assert isort.code(test_input, config=Config(sort_reexports=True)) == expd_output
5662
5663
5664 def test_reexport_no_spaces() -> None:
5665 test_input = """__all__=('foo', 'bar')
5666 """
5667 expd_output = """__all__ = ("bar", "foo")
5668 """
5669 assert isort.code(test_input, config=Config(sort_reexports=True)) == expd_output
5670
5671
5672 def test_reexport_keeps_trailing_comment() -> None:
5673 test_input = """__all__ = ['foo', 'bar'] # public names
5674 """
5675 expd_output = """__all__ = ["bar", "foo"] # public names
5676 """
5677 assert isort.code(test_input, config=Config(sort_reexports=True)) == expd_output
5678
5679
5680 def test_reexport_keeps_trailing_comment_with_equals() -> None:
5681 test_input = """__all__ = ['foo', 'bar'] # note: key = value
5682 """
5683 expd_output = """__all__ = ["bar", "foo"] # note: key = value
5684 """
5685 assert isort.code(test_input, config=Config(sort_reexports=True)) == expd_output
5686
5687
5688 def test_isort_list_keeps_trailing_comment_with_equals() -> None:
5689 test_input = """# isort: list
5690 __all__ = ['foo', 'bar'] # note: key = value
5691 """
5692 expd_output = """# isort: list
5693 __all__ = ["bar", "foo"] # note: key = value
5694 """
5695 assert isort.code(test_input) == expd_output
5696
5697
5698 def test_reexport_not_first_line() -> None:
5699 test_input = """import random
5700
5701 __all__ = ('foo', 'bar')
5702 """
5703 expd_output = """import random
5704
5705 __all__ = ("bar", "foo")
5706 """
5707 assert isort.code(test_input, config=Config(sort_reexports=True)) == expd_output
5708
5709
5710 def test_reexport_not_last_line() -> None:
5711 test_input = """__all__ = ('foo', 'bar')
5712
5713 meme = "rickroll"
5714 """
5715 expd_output = """__all__ = ("bar", "foo")
5716
5717 meme = "rickroll"
5718 """
5719 assert isort.code(test_input, config=Config(sort_reexports=True)) == expd_output
5720
5721
5722 def test_reexport_multiline_import() -> None:
5723 test_input = """from m import (
5724 bar,
5725 foo,
5726 )
5727 __all__ = [
5728 "foo",
5729 "bar",
5730 ]
5731 """
5732 expd_output = """from m import bar, foo
5733
5734 __all__ = ["bar", "foo"]
5735 """
5736 assert isort.code(test_input, config=Config(sort_reexports=True)) == expd_output
5737
5738
5739 def test_reexport_multiline_in_center() -> None:
5740 test_input = """from m import (
5741 bar,
5742 foo,
5743 )
5744 __all__ = [
5745 "foo",
5746 "bar",
5747 ]
5748
5749 test
5750 """
5751 expd_output = """from m import bar, foo
5752
5753 __all__ = ["bar", "foo"]
5754
5755 test
5756 """
5757 assert isort.code(test_input, config=Config(sort_reexports=True)) == expd_output
5758
5759
5760 def test_reexport_multiline_long_rollback() -> None:
5761 test_input = """from m import foo, bar
5762 __all__ = [ "foo",
5763 "bar",
5764 ]
5765
5766 test
5767 """
5768 expd_output = """from m import bar, foo
5769
5770 __all__ = ["bar", "foo"]
5771
5772 test
5773 """
5774 assert isort.code(test_input, config=Config(sort_reexports=True)) == expd_output
5775
5776
5777 def test_noqa_multiline_hanging_indent() -> None:
5778 test_input = (
5779 "from aaaaaaa import bbbbbbbbbbbbbbbbb, ccccccccccccccccccc, dddddddddddddddd"
5780 "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee, \\\n"
5781 " fffffffffffffffffffff # noqa: E402\n"
5782 "\n"
5783 "print(fffffffffffffffffffff)\n"
5784 "print(dddddddddddddddd)\n"
5785 )
5786 output = isort.code(test_input, line_length=120, multi_line_output=WrapModes.HANGING_INDENT)
5787 assert output == test_input
5788
5789
5790 @pytest.mark.parametrize(
5791 (
5792 "actual_imports",
5793 "expected_sort",
5794 ),
5795 [
5796 (
5797 ("from __future__ import annotations\nimport __future__\n"),
5798 ("from __future__ import annotations\nimport __future__\n"),
5799 ),
5800 (
5801 (
5802 "import __future__\n\n"
5803 "from __future__ import generator_stop\n"
5804 "from __future__ import annotations\n\n"
5805 "from concurrent.futures import ThreadPoolExecutor\n\n"
5806 ),
5807 (
5808 "from __future__ import annotations, generator_stop\n"
5809 "import __future__\n\n"
5810 "from concurrent.futures import ThreadPoolExecutor\n"
5811 ),
5812 ),
5813 (
5814 ("from __future__ import annotations\nimport sys\n"),
5815 ("from __future__ import annotations\n\nimport sys\n"),
5816 ),
5817 (("import __future__\nimport sys\n"), ("import __future__\n\nimport sys\n")),
5818 (
5819 ("import __future__ as future\nfrom __future__ import annotations\n"),
5820 ("from __future__ import annotations\nimport __future__ as future\n"),
5821 ),
5822 (
5823 ("# Copyright 2026\nimport __future__\nfrom __future__ import annotations\n"),
5824 ("# Copyright 2026\nfrom __future__ import annotations\nimport __future__\n"),
5825 ),
5826 (
5827 ("import __future__\nfrom __future__ import *\n"),
5828 ("from __future__ import *\nimport __future__\n"),
5829 ),
5830 (
5831 (
5832 "from __future__ import annotations\n"
5833 "import __future__\n"
5834 "from __future__ import annotations\n"
5835 ),
5836 ("from __future__ import annotations\nimport __future__\n"),
5837 ),
5838 (
5839 (
5840 "import sys\n"
5841 "from __future__ import annotations\n"
5842 "import os\n"
5843 "import __future__\n"
5844 "from pathlib import Path\n"
5845 ),
5846 (
5847 "from __future__ import annotations\n"
5848 "import __future__\n\n"
5849 "import os\n"
5850 "import sys\n"
5851 "from pathlib import Path\n"
5852 ),
5853 ),
5854 ],
5855 )
5856 def test_dunder_future_import(actual_imports: str, expected_sort: str) -> None:
5857 output = isort.code(actual_imports)
5858 assert output == expected_sort
5859
5860
5861 def test_builtin_modules() -> None:
5862 test_input = (
5863 "from typing import Iterable, Iterator, TypeVar, cast\n"
5864 "\n"
5865 "from _collections_abc import dict_items, dict_keys, dict_values\n"
5866 "from python_none_objects import NoneIterable\n"
5867 "from _codecs import encode\n"
5868 "from nt import environ\n"
5869 )
5870 test_output = (
5871 "from _codecs import encode\n"
5872 "from _collections_abc import dict_items, dict_keys, dict_values\n"
5873 "from nt import environ\n"
5874 "from typing import Iterable, Iterator, TypeVar, cast\n"
5875 "\n"
5876 "from python_none_objects import NoneIterable\n"
5877 )
5878 assert isort.code(test_input) == test_output