30 lines
1.4 KiB
Python
30 lines
1.4 KiB
Python
import ast
|
|
import subprocess
|
|
import unittest
|
|
|
|
from test_python_floor import ROOT
|
|
|
|
|
|
def bound(node: ast.Import | ast.ImportFrom) -> list[str]:
|
|
return [alias.asname or alias.name for alias in node.names]
|
|
|
|
|
|
def unsorted_imports(source: str) -> list[int]:
|
|
"""The line numbers of imports whose names are out of order, or whose first name sorts before the first name of the import on the line above, ignoring case."""
|
|
imports = [node for node in ast.parse(source).body if isinstance(node, ast.Import | ast.ImportFrom)]
|
|
names_out = [node.lineno for node in imports if bound(node) != sorted(bound(node), key=str.casefold)]
|
|
lines_out = [node.lineno for above, node in zip(imports, imports[1:]) if node.lineno == above.end_lineno + 1 and bound(node)[0].casefold() < bound(above)[0].casefold()]
|
|
return sorted(set(names_out + lines_out))
|
|
|
|
|
|
class ImportOrder(unittest.TestCase):
|
|
def test_each_python_file_sorts_its_imports_by_their_first_binding(self):
|
|
listed = subprocess.run(["git", "ls-files", "*.py", "bin/loop-claude"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split()
|
|
self.assertIn("bin/loop-claude", listed)
|
|
for name in listed:
|
|
with self.subTest(name):
|
|
self.assertEqual(unsorted_imports((ROOT / name).read_text(encoding="utf-8")), [])
|
|
|
|
def test_a_case_insensitive_name_out_of_order_is_found(self):
|
|
self.assertEqual(unsorted_imports("import B\nimport a\n\nfrom x import C, b\n"), [2, 4])
|