Skip to content

Commit

Permalink
feat(analyzers): add analyzer for log error
Browse files Browse the repository at this point in the history
  • Loading branch information
guilatrova committed Jul 31, 2021
1 parent a74d97b commit 4c755e5
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/tests/analyzers_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,17 @@ def test_try_inner_raise():
violation = violations[0]

assert_inner_raise(21, 12, violation)


def test_log_error():
tree = read_sample("log_error")
analyzer = analyzers.LogErrorAnalyzer()
code, msg = codes.USE_LOGGING_EXCEPTION

assert_log_error = partial(assert_violation, code, msg)

violations = analyzer.check(tree, "filename")
assert len(violations) == 1
violation = violations[0]

assert_log_error(10, 8, violation)
18 changes: 18 additions & 0 deletions src/tryceratops/analyzers/exception_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,21 @@ def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None:
self._mark_violation(first_child)

self.generic_visit(node)


class LogErrorAnalyzer(BaseAnalyzer):
violation_code = codes.USE_LOGGING_EXCEPTION

@visit_error_handler
def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None:
for stm in ast.walk(node):
if isinstance(stm, ast.Expr):
if isinstance(stm.value, ast.Call):
if isinstance(stm.value.func, ast.Attribute):
possible_log_node = stm.value.func
object_method = possible_log_node.attr

if object_method == "error":
self._mark_violation(possible_log_node)

self.generic_visit(node)
1 change: 1 addition & 0 deletions src/tryceratops/analyzers/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
except_analyzers.ExceptReraiseWithoutCauseAnalyzer,
except_analyzers.ExceptVerboseReraiseAnalyzer,
except_analyzers.ExceptBroadPassAnalyzer,
except_analyzers.LogErrorAnalyzer,
try_analyzers.TryConsiderElseAnalyzer,
try_analyzers.TryShouldntRaiseAnalyzer,
}
Expand Down
3 changes: 3 additions & 0 deletions src/tryceratops/violations/codes.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
CONSIDER_ELSE = ("TC300", "Consider moving this statement to an 'else' block")
RAISE_WITHIN_TRY = ("TC301", "Abstract raise to an inner function")

# TC4xx - Logging
USE_LOGGING_EXCEPTION = ("TC400", "Use logging '.exception' instead of 'error'")

CODE_CHOICES = {
"TC002",
Expand All @@ -35,4 +37,5 @@
"TC202",
"TC300",
"TC301",
"TC400",
}

0 comments on commit 4c755e5

Please sign in to comment.