Skip to content

Commit

Permalink
Avoid KeyError when imports are duplicated.
Browse files Browse the repository at this point in the history
Because we do block splitting before deduplication, it could previously try to pop the same name twice.

Fixes facebook#194
  • Loading branch information
thatch committed Aug 5, 2022
1 parent 70839cb commit 486c8f8
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 2 deletions.
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ include = usort/*
omit = usort/tests/*

[coverage:report]
fail_under = 70
fail_under = 92
precision = 1
show_missing = True
skip_covered = True
Expand Down
9 changes: 8 additions & 1 deletion usort/sorting.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,14 @@ def split_inplace(self, block: SortableBlock, overlap: Set[str]) -> SortableBloc
# move imported names metadata
for imp in new.imports:
for key in list(imp.imported_names):
new.imported_names[key] = block.imported_names.pop(key)
name = block.imported_names.pop(key, None)
if name is not None:
# Normally we wouldn't see multiple copies of a key because that
# would have caused a block split already, but if an import is
# just verbatim repeated, it's not technically shadowing.
# If that's the case, we've already popped it and achieved the
# goal of this block.
new.imported_names[key] = name

return new

Expand Down
2 changes: 2 additions & 0 deletions usort/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from .cli import CliTest
from .config import ConfigTest
from .functional import BasicOrderingTest, UsortStringFunctionalTest
from .sorting import SplitTest
from .stdlibs import StdlibsTest
from .translate import IsSortableTest, SortableImportTest
from .types import TypesTest
Expand All @@ -21,4 +22,5 @@
"StdlibsTest",
"TypesTest",
"UtilTest",
"SplitTest",
]
15 changes: 15 additions & 0 deletions usort/tests/functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -879,6 +879,21 @@ def test_sort_implicit_blocks3(self) -> None:
""",
)

def test_sort_merging_and_implicit_blocks(self) -> None:
self.assertUsortResult(
"""
from a import x
from b import y
from b import y
from c import x
""",
"""
from a import x
from b import y
from c import x
""",
)

def test_skip_directives(self) -> None:
"""Test both usort:skip and isort:skip on single line imports"""
self.assertUsortResult(
Expand Down

0 comments on commit 486c8f8

Please sign in to comment.