Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Backport maintenance/2.17.x] Fix incorrect preferred-modules matches #8481

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions doc/whatsnew/fragments/8453.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix a regression of ``preferred-modules`` where a partial match was used instead of the required full match.

Closes #8453
10 changes: 9 additions & 1 deletion pylint/checkers/imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -922,7 +922,15 @@ def _check_preferred_module(self, node: ImportNode, mod_path: str) -> None:
mod_compare = [f"{node.modname}.{name[0]}" for name in node.names]

# find whether there are matches with the import vs preferred_modules keys
matches = [k for k in self.preferred_modules for mod in mod_compare if k in mod]
matches = [
k
for k in self.preferred_modules
for mod in mod_compare
# exact match
if k == mod
# checks for base module matches
or k in mod.split(".")[0]
]

# if we have matches, add message
if matches:
Expand Down
17 changes: 17 additions & 0 deletions tests/checkers/unittest_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,23 @@ def test_preferred_module(capsys: CaptureFixture[str]) -> None:
# assert there were no errors
assert len(errors) == 0

# Test for challenges with preferred modules indefinite matches
Run(
[
f"{os.path.join(REGR_DATA, 'preferred_module/unpreferred_submodule.py')}",
"-d all",
"-e preferred-module",
# prefer pathlib instead of random (testing to avoid regression)
# pathlib shouldn't match with path, which is in the test file
"--preferred-modules=random:pathlib",
],
exit=False,
)
_, errors = capsys.readouterr()

# Assert there were no errors
assert len(errors) == 0

@staticmethod
def test_allow_reexport_package(capsys: CaptureFixture[str]) -> None:
"""Test --allow-reexport-from-package option."""
Expand Down