def test_isort_doesnt_remove_as_imports_when_combine_star_issue_1380(): """Test to ensure isort will not remove as imports along side other imports when requested to combine star imports together. See: https://github.com/PyCQA/isort/issues/1380 """ test_input = """ from a import a from a import * from a import b from a import b as y from a import c """ assert (isort.code( test_input, combine_star=True, ) == isort.code(test_input, combine_star=True, force_single_line=True) == isort.code( test_input, combine_star=True, force_single_line=True, combine_as_imports=True, ) == """ from a import * from a import b as y """)
def test_isort_enables_floating_imports_to_top_of_module_issue_1228(): """Test to ensure isort will allow floating all non-indented imports to the top of a file. See: https://github.com/timothycrosley/isort/issues/1228. """ assert (isort.code( """ import os def my_function_1(): pass import sys def my_function_2(): pass """, float_to_top=True, ) == """ import os import sys def my_function_1(): pass def my_function_2(): pass """) assert (isort.code( """ import os def my_function_1(): pass # isort: split import sys def my_function_2(): pass """, float_to_top=True, ) == """ import os def my_function_1(): pass # isort: split import sys def my_function_2(): pass """)
def test_incorrect_grouping_when_comments_issue_1396(): """Test to ensure isort groups import correct independent of the comments present. See: https://github.com/pycqa/isort/issues/1396 """ assert (isort.code( """from django.shortcuts import render from apps.profiler.models import Project from django.contrib.auth.decorators import login_required from django.views.generic import ( # ListView, # DetailView, TemplateView, # CreateView, # View ) """, line_length=88, known_first_party=["apps"], known_django=["django"], sections=[ "FUTURE", "STDLIB", "DJANGO", "THIRDPARTY", "FIRSTPARTY", "LOCALFOLDER" ], ) == """from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.views.generic import \\ TemplateView # ListView,; DetailView,; CreateView,; View from apps.profiler.models import Project """) assert (isort.code( """from django.contrib.auth.decorators import login_required from django.shortcuts import render from apps.profiler.models import Project from django.views.generic import ( # ListView,; DetailView,; CreateView,; View TemplateView, ) """, line_length=88, known_first_party=["apps"], known_django=["django"], sections=[ "FUTURE", "STDLIB", "DJANGO", "THIRDPARTY", "FIRSTPARTY", "LOCALFOLDER" ], include_trailing_comma=True, multi_line_output=3, force_grid_wrap=0, use_parentheses=True, ensure_newline_before_comments=True, ) == """from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.views.generic import ( # ListView,; DetailView,; CreateView,; View TemplateView, ) from apps.profiler.models import Project """)
def test_isort_off_and_on(): """Test so ensure isort: off action comment and associated on action comment work together""" # as top of file comment assert (isort.code("""# isort: off import a import a # isort: on import a import a """) == """# isort: off import a import a # isort: on import a """) # as middle comment assert (isort.code(""" import a import a # isort: off import a import a """) == """ import a # isort: off import a import a """)
def test_isort_supports_formatting_plugins_issue_1353(): """Test to ensure isort provides a way to create and share formatting plugins. See: https://github.com/pycqa/isort/issues/1353. """ assert isort.code("import a", formatter="example") == "import a\n" # formatting plugin with pytest.raises(exceptions.FormattingPluginDoesNotExist): assert isort.code("import a", formatter="madeupfake") == "import a\n" # non-existent plugin
def test_isort_supports_append_only_imports_issue_727(): """Test to ensure isort provides a way to only add imports as an append. See: https://github.com/pycqa/isort/issues/727. """ assert isort.code("", add_imports=["from __future__ import absolute_imports"]) == "" assert ( isort.code("import os", add_imports=["from __future__ import absolute_imports"]) == """from __future__ import absolute_imports import os """ ) # issue 1838: don't append in middle of class assert isort.check_code( '''class C: """a """ # comment ''', append_only=True, add_imports=["from __future__ import annotations"], show_diff=True, )
def test_isort_is_idempotent(config: isort.Config, disregard_skip: bool) -> None: try: result = isort.code(CODE_SNIPPET, config=config, disregard_skip=disregard_skip) result = isort.code(result, config=config, disregard_skip=disregard_skip) assert result == isort.code(result, config=config, disregard_skip=disregard_skip) except ValueError: pass
def test_blank_lined_removed_issue_1275(): """Ensure isort doesn't accidentally remove blank lines after doc strings and before imports. See: https://github.com/timothycrosley/isort/issues/1275 """ assert (isort.code('''""" My docstring """ from b import thing from a import other_thing ''') == '''""" My docstring """ from a import other_thing from b import thing ''') assert (isort.code( '''""" My docstring """ from b import thing from a import other_thing ''', add_imports=["from b import thing"], ) == '''""" My docstring """ from a import other_thing from b import thing ''')
def test_autofix_mixed_indent_imports_1575(): """isort should automatically fix import statements that are sent in with incorrect mixed indentation. See: https://github.com/PyCQA/isort/issues/1575 """ assert (isort.code(""" import os import os """) == """ import os """) assert (isort.code(""" def one(): import os import os """) == """ def one(): import os import os """) assert (isort.code(""" import os import os import os import os import os """) == """ import os """)
def test_isort_should_produce_the_same_code_on_subsequent_runs_issue_1799( tmpdir): code = """import sys if sys.version_info[:2] >= (3, 8): # TODO: Import directly (no need for conditional) when `python_requires = >= 3.8` from importlib.metadata import PackageNotFoundError, version # pragma: no cover else: from importlib_metadata import PackageNotFoundError, version # pragma: no cover """ config_file = tmpdir.join(".isort.cfg") config_file.write("""[isort] profile=black src_paths=isort,test line_length=100 skip=.tox,.venv,build,dist,docs,tests extra_standard_library=pkg_resources,setuptools,typing known_test=pytest known_first_party=ibpt sections=FUTURE,STDLIB,TEST,THIRDPARTY,FIRSTPARTY,LOCALFOLDER import_heading_firstparty=internal import_heading_thirdparty=external """) settings = isort.settings.Config(str(config_file)) assert isort.code(code, config=settings) == isort.code(isort.code( code, config=settings), config=settings)
def test_isort_provides_official_api_for_diff_output_issue_1335(): """Test to ensure isort API for diff capturing allows capturing diff without sys.stdout. See: https://github.com/pycqa/isort/issues/1335. """ diff_output = StringIO() isort.code("import b\nimport a\n", show_diff=diff_output) diff_output.seek(0) assert "+import a" in diff_output.read()
def test_isort_supports_shared_profiles_issue_970(): """Test to ensure isort provides a way to use shared profiles. See: https://github.com/pycqa/isort/issues/970. """ assert isort.code("import a", profile="example") == "import a\n" # shared profile assert isort.code("import a", profile="black") == "import a\n" # bundled profile with pytest.raises(exceptions.ProfileDoesNotExist): assert isort.code("import a", profile="madeupfake") == "import a\n" # non-existent profile
def test_isort_correctly_handles_unix_vs_linux_newlines_issue_1566(): import_statement = ( "from impacket.smb3structs import (\n" "SMB2_CREATE, SMB2_FLAGS_DFS_OPERATIONS, SMB2_IL_IMPERSONATION, " "SMB2_OPLOCK_LEVEL_NONE, SMB2Create," "\nSMB2Create_Response, SMB2Packet)\n") assert isort.code(import_statement, line_length=120) == isort.code( import_statement.replace("\n", "\r\n"), line_length=120).replace("\r\n", "\n")
def test_isort_automatically_removes_duplicate_aliases_issue_1193(): """Test to ensure isort can automatically remove duplicate aliases. See: https://github.com/pycqa/isort/issues/1281 """ assert isort.check_code("from urllib import parse as parse\n", show_diff=True) assert ( isort.code("from urllib import parse as parse", remove_redundant_aliases=True) == "from urllib import parse\n" ) assert isort.check_code("import os as os\n", show_diff=True) assert isort.code("import os as os", remove_redundant_aliases=True) == "import os\n"
def isort_test(code: str, expected_output: str = "", **config): """Runs isort against the given code snippet and ensures that it gives consistent output accross multiple runs, and if an expected_output is given - that it matches that. """ expected_output = expected_output or code output = isort.code(code, **config) assert output == expected_output assert output == isort.code(output, **config)
def test_isort_is_idempotent(source_code: str, config: isort.Config, disregard_skip: bool) -> None: # NOTE: if this test finds a bug, please notify @Zac-HD so that it can be added to the # Hypothesmith trophy case. This really helps with research impact evaluations! _record_targets(source_code) result = isort.code(source_code, config=config, disregard_skip=disregard_skip) assert result == isort.code(result, config=config, disregard_skip=disregard_skip)
def test_isort_supports_append_only_imports_issue_727(): """Test to ensure isort provides a way to only add imports as an append. See: https://github.com/pycqa/isort/issues/727. """ assert isort.code("", add_imports=["from __future__ import absolute_imports"]) == "" assert ( isort.code("import os", add_imports=["from __future__ import absolute_imports"]) == """from __future__ import absolute_imports import os """ )
def test_combine_as_does_not_lose_comments_issue_1381(): """Test to ensure isort doesn't lose comments when --combine-as is used. See: https://github.com/pycqa/isort/issues/1381 """ test_input = """ from smtplib import SMTPConnectError, SMTPNotSupportedError # important comment """ assert "# important comment" in isort.code(test_input, combine_as_imports=True) test_input = """ from appsettings import AppSettings, ObjectSetting, StringSetting # type: ignore """ assert "# type: ignore" in isort.code(test_input, combine_as_imports=True)
def test_moving_comments_issue_726(): test_input = ("from Blue import models as BlueModels\n" "# comment for PlaidModel\n" "from Plaid.models import PlaidModel\n") assert isort.code(test_input, force_sort_within_sections=True) == test_input test_input = ("# comment for BlueModels\n" "from Blue import models as BlueModels\n" "# comment for PlaidModel\n" "# another comment for PlaidModel\n" "from Plaid.models import PlaidModel\n") assert isort.code(test_input, force_sort_within_sections=True) == test_input
def test_ensure_new_line_before_comments_mixed_with_ensure_newline_before_comments_1295(): """Tests to ensure that the black profile can be used in conjunction with force_sort_within_sections. See: https://github.com/pycqa/isort/issues/1295 """ test_input = """ from openzwave.group import ZWaveGroup from openzwave.network import ZWaveNetwork # pylint: disable=import-error from openzwave.option import ZWaveOption """ assert isort.code(test_input, profile="black") == test_input assert isort.code(test_input, profile="black", force_sort_within_sections=True) == test_input
def test_isort_can_turn_off_import_adds_with_action_comment_issue_1737(): assert ( isort.code( """ import os """, add_imports=[ "from __future__ import absolute_imports", "from __future__ import annotations", ], ) == """ from __future__ import absolute_imports, annotations import os """ ) assert isort.check_code( """ # isort: dont-add-imports import os """, show_diff=True, add_imports=[ "from __future__ import absolute_imports", "from __future__ import annotations", ], ) assert ( isort.code( """ # isort: dont-add-import: from __future__ import annotations import os """, add_imports=[ "from __future__ import absolute_imports", "from __future__ import annotations", ], ) == """ # isort: dont-add-import: from __future__ import annotations from __future__ import absolute_imports import os """ )
def test_extra_blank_line_added_nested_imports_issue_1290(): """Ensure isort doesn't added unecessary blank lines above nested imports. See: https://github.com/timothycrosley/isort/issues/1290 """ test_input = '''from typing import TYPE_CHECKING # Special imports from special import thing if TYPE_CHECKING: # Special imports from special import another_thing def func(): """Docstring""" # Special imports from special import something_else return ''' assert (isort.code( test_input, import_heading_special="Special imports", known_special=["special"], sections=[ "FUTURE", "STDLIB", "THIRDPARTY", "SPECIAL", "FIRSTPARTY", "LOCALFOLDER" ], ) == test_input)
def test_isort_shouldnt_add_extra_new_line_when_fass_and_n_issue_1315(): """Test to ensure isort doesnt add a second extra new line when combining --fss and -n options. See: https://github.com/timothycrosley/isort/issues/1315 """ assert isort.check_code( """import sys # Comment canary from . import foo """, ensure_newline_before_comments=True, # -n force_sort_within_sections=True, # -fss show_diff=True, # for better debugging in the case the test case fails. ) assert (isort.code( """ from . import foo # Comment canary from .. import foo """, ensure_newline_before_comments=True, force_sort_within_sections=True, ) == """ from . import foo # Comment canary from .. import foo """)
def test_windows_newline_issue_1277(): """Test to ensure windows new lines are correctly handled within indented scopes. See: https://github.com/timothycrosley/isort/issues/1277 """ assert ( isort.code("\ndef main():\r\n import time\r\n\n import sys\r\n") == "\ndef main():\r\n import sys\r\n import time\r\n")
def test_no_extra_blank_lines_in_methods_issue_1293(): """Test to ensure isort isn't introducing extra lines in methods that contain imports See: https://github.com/timothycrosley/isort/issues/1293 """ test_input = """ class Something(object): def on_email_deleted(self, email): from hyperkitty.tasks import rebuild_thread_cache_new_email # update or cleanup thread # noqa: E303 (isort issue) if self.emails.count() == 0: ... """ assert isort.code(test_input) == test_input assert isort.code(test_input, lines_after_imports=2) == test_input
def test_no_extra_lines_for_imports_in_functions_issue_1277(): """Test to ensure isort doesn't introduce extra blank lines for imports within function. See: https://github.com/timothycrosley/isort/issues/1277 """ test_input = """ def main(): import time import sys """ expected_output = """ def main(): import sys import time """ assert isort.code(isort.code(isort.code(test_input))) == expected_output
def test_combine_as_does_not_lose_comments_issue_1321(): """Test to ensure isort doesn't lose comments when --combine-as is used. See: https://github.com/timothycrosley/isort/issues/1321 """ test_input = """ from foo import * # noqa from foo import bar as quux # other from foo import x as a # noqa import operator as op # op comment import datetime as dtime # dtime comment from datetime import date as d # dcomm from datetime import datetime as dt # dtcomm """ expected_output = """ import datetime as dtime # dtime comment import operator as op # op comment from datetime import date as d, datetime as dt # dcomm; dtcomm from foo import * # noqa from foo import bar as quux, x as a # other; noqa """ assert isort.code(test_input, combine_as_imports=True) == expected_output
def test_isort_doesnt_misplace_add_import_issue_1445(): """Test to ensure isort won't misplace an added import depending on docstring position See: https://github.com/PyCQA/isort/issues/1445 """ assert (isort.code( '''#!/usr/bin/env python """module docstring""" ''', add_imports=["import os"], ) == '''#!/usr/bin/env python """module docstring""" import os ''') assert isort.check_code( '''#!/usr/bin/env python """module docstring""" import os ''', add_imports=["import os"], show_diff=True, )
def generate_code(service_name: str, doc: bool = False) -> str: model = load_service(service_name) output = io.StringIO() generate_service_types(output, model, doc=doc) generate_service_api(output, model, doc=doc) code = output.getvalue() try: import autoflake import isort from black import FileMode, format_str # try to format with black code = format_str(code, mode=FileMode(line_length=100)) # try to remove unused imports code = autoflake.fix_code(code, remove_all_unused_imports=True) # try to sort imports code = isort.code(code, config=isort.Config(profile="black", line_length=100)) except Exception: pass return code
def test_isort_shouldnt_fail_on_long_from_with_dot_issue_1190(): """Test to ensure that isort will correctly handle formatting a long from import that contains a dot. See: https://github.com/pycqa/isort/issues/1190 """ assert ( isort.code( """ from this_is_a_very_long_import_statement.that_will_occur_across_two_lines\\ .when_the_line_length.is_only_seventynine_chars import ( function1, function2, ) """, line_length=79, multi_line_output=3, ) == """ from this_is_a_very_long_import_statement.that_will_occur_across_two_lines""" """.when_the_line_length.is_only_seventynine_chars import ( function1, function2 ) """ )