From 663bd4da3511a9a034faad1f4041a8918541073f Mon Sep 17 00:00:00 2001 From: Lyz Date: Tue, 21 Dec 2021 13:15:17 +0100 Subject: [PATCH] feat: support multi paragraph sections inside the TYPE_CHECKING block --- src/autoimport/model.py | 3 ++- tests/unit/test_services.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/autoimport/model.py b/src/autoimport/model.py index 43bf76e..f00cf37 100644 --- a/src/autoimport/model.py +++ b/src/autoimport/model.py @@ -33,6 +33,7 @@ "StringIO": "from io import StringIO", "suppress": "from contextlib import suppress", "TempdirFactory": "from _pytest.tmpdir import TempdirFactory", + "tz": "from dateutil import tz", "YAMLError": "from yaml import YAMLError", } @@ -165,7 +166,7 @@ def _extract_typing_statements(self, source_lines: List[str]) -> None: self.typing.append(source_lines[typing_start_line]) typing_start_line += 1 for line in source_lines[typing_start_line:]: - if not re.match(r"^\s+.*", line): + if not re.match(r"^\s+.*", line) and line != "": break self.typing.append(line) diff --git a/tests/unit/test_services.py b/tests/unit/test_services.py index e848570..93de538 100644 --- a/tests/unit/test_services.py +++ b/tests/unit/test_services.py @@ -712,6 +712,34 @@ def read_book(book: Book): assert result == source +def test_fix_respects_multiparagraph_type_checking_import_statements() -> None: + """ + Given: Code with two paragraphs of imports inside an if TYPE_CHECKING block + When: Fix code is run. + Then: The imports are not moved above the if statement. + """ + source = dedent( + """\ + import os + from typing import TYPE_CHECKING + + if TYPE_CHECKING: + from .model import Book + + from other import Other + + os.getcwd() + + + def read_book(book: Book, other: Other): + pass""" + ) + + result = fix_code(source) + + assert result == source + + def test_fix_respects_try_except_in_import_statements() -> None: """ Given: Code with try except statements in the imports.