diff --git a/CHANGELOG.md b/CHANGELOG.md index aaeae1915..45194c907 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +19,7 @@ Semantic versioning in our case means: - Fixes multiple `if` support for `InconsistentComprehensionViolation` - Fixes that `NestedTernaryViolation` was not reported for a comprehension - Fixes that `ConstantConditionViolation` was not reported for a comprehension - +- Fix false positive `InfiniteWhileLoopViolation` for `try` #1857 ### Misc - Refactors how `tokenize` tests are executed, now we have an option to compile fixture code to make sure it is syntatically valid diff --git a/tests/test_visitors/test_ast/test_loops/test_loops/test_infinite_while_loops.py b/tests/test_visitors/test_ast/test_loops/test_loops/test_infinite_while_loops.py index 8f85048d9..3bf62c734 100644 --- a/tests/test_visitors/test_ast/test_loops/test_loops/test_infinite_while_loops.py +++ b/tests/test_visitors/test_ast/test_loops/test_loops/test_infinite_while_loops.py @@ -50,6 +50,33 @@ def wrapper(): {1} """ +while1 = """ +while True: + try: + ... + except: + ... +""" + +while2 = """ +while other: + while True: + try: + ... + except: + ... +""" + + +while3 = """ +def wrapper(): + while True: + try: + ... + except: + ... +""" + @pytest.mark.parametrize('template', [ template_simple, @@ -58,6 +85,9 @@ def wrapper(): template_nested_if, template_function, template_other, + while1, + while2, + while3, ]) @pytest.mark.parametrize('keyword', [ 'break', diff --git a/wemake_python_styleguide/visitors/ast/loops.py b/wemake_python_styleguide/visitors/ast/loops.py index 383e59916..edb2245e7 100644 --- a/wemake_python_styleguide/visitors/ast/loops.py +++ b/wemake_python_styleguide/visitors/ast/loops.py @@ -220,6 +220,13 @@ def _check_infinite_while_loop(self, node: AnyLoop) -> None: if not isinstance(node, ast.While): return + has_try = any( + isinstance(sub_node, ast.Try) + for sub_node in ast.walk(node) + ) + if has_try: + return + real_node = operators.unwrap_unary_node(node.test) if isinstance(real_node, ast.NameConstant) and real_node.value is True: if not loops.has_break(node, break_nodes=self._breaks):