Skip to content

Commit

Permalink
SIM106: Remove false-positives (#95)
Browse files Browse the repository at this point in the history
Don't trigger if the 'else' block ends with a ValueError or a NotImplementedError.

Closes #87
  • Loading branch information
MartinThoma committed Feb 10, 2022
1 parent 79a87b9 commit d06d85d
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
12 changes: 12 additions & 0 deletions flake8_simplify.py
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,18 @@ def _get_sim106(node: ast.If) -> List[Tuple[int, int, str]]:
)
if not (just_one or many):
return errors
ast_raise = node.orelse[-1]
if not isinstance(ast_raise, ast.Raise):
return errors
ast_raised = ast_raise.exc
if (
isinstance(ast_raised, ast.Call)
and ast_raised.func
and isinstance(ast_raised.func, ast.Name)
and ast_raised.func.id in ["ValueError", "NotImplementedError"]
):
return errors

errors.append((node.lineno, node.col_offset, SIM106))
return errors

Expand Down
29 changes: 24 additions & 5 deletions tests/test_simplify.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,14 +195,33 @@ def test_sim106():
assert ret == {"1:0 SIM106 Handle error-cases first"}


def test_sim106_no():
ret = _results(
@pytest.mark.parametrize(
"s",
(
"""if image_extension in ['.jpg', '.jpeg']:
return 'JPEG'
elif image_extension in ['.png']:
return 'PNG'
else:
raise ValueError("Unknwon image extension {image extension}")""",
"""if image_extension in ['.jpg', '.jpeg']:
return 'JPEG'
elif image_extension in ['.png']:
return 'PNG'
else:
logger.error("Unknwon image extension {image extension}")
raise ValueError("Unknwon image extension {image extension}")""",
"""if cond:
raise Exception
else:
raise Exception"""
)
assert ret == set()
raise Exception""",
),
ids=["ValueError", "ValueError-with-logging", "TwoExceptions"],
)
def test_sim106_false_positive(s):
ret = _results(s)
for el in ret:
assert "SIM106" not in el


def test_sim107():
Expand Down

0 comments on commit d06d85d

Please sign in to comment.