|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +import pytest |
| 4 | + |
| 5 | +from wemake_python_styleguide.violations.refactoring import ( |
| 6 | + ImplicitNegativeIndexViolation, |
| 7 | +) |
| 8 | +from wemake_python_styleguide.visitors.ast.subscripts import CorrectKeyVisitor |
| 9 | + |
| 10 | + |
| 11 | +@pytest.mark.parametrize('code', [ |
| 12 | + 'some_list[len(some_list) - 1]', |
| 13 | + 'some_list[len(some_list) - 1.0]', |
| 14 | + 'some_list[len(some_list) - 5]', |
| 15 | + 'some_list[len(some_list) - name]', |
| 16 | + 'some_list[len(some_list) - call()]', |
| 17 | + 'some_list[len(some_list) - name.attr]', |
| 18 | + 'some_list[len(some_list) - name["a"]]', |
| 19 | + 'attr.some_list[len(attr.some_list) - 1]', |
| 20 | +]) |
| 21 | +def test_implicit_negative_index( |
| 22 | + assert_errors, |
| 23 | + parse_ast_tree, |
| 24 | + code, |
| 25 | + default_options, |
| 26 | +): |
| 27 | + """Testing that implicit negative indexes are forbidden.""" |
| 28 | + tree = parse_ast_tree(code) |
| 29 | + |
| 30 | + visitor = CorrectKeyVisitor(default_options, tree=tree) |
| 31 | + visitor.run() |
| 32 | + |
| 33 | + assert_errors(visitor, [ImplicitNegativeIndexViolation]) |
| 34 | + |
| 35 | + |
| 36 | +@pytest.mark.parametrize('code', [ |
| 37 | + 'some_list[len(other_list) - 1]', |
| 38 | + 'some_list[len(some_list) + 1]', |
| 39 | + 'some_list[len(some_list)]', |
| 40 | + 'some_list[sum(some_list) + 1]', |
| 41 | + 'some_list[len(some_list) + 1 + 2]', |
| 42 | + 'some_list[-1]', |
| 43 | + 'some_list[1]', |
| 44 | + 'some_list[-name]', |
| 45 | + 'some_list[name.attr]', |
| 46 | + 'some_list[call() + 1]', |
| 47 | + 'some_list[some[key]]', |
| 48 | +]) |
| 49 | +def test_regular_len_calls( |
| 50 | + assert_errors, |
| 51 | + parse_ast_tree, |
| 52 | + code, |
| 53 | + default_options, |
| 54 | +): |
| 55 | + """Testing that explicit negative calls are fine.""" |
| 56 | + tree = parse_ast_tree(code) |
| 57 | + |
| 58 | + visitor = CorrectKeyVisitor(default_options, tree=tree) |
| 59 | + visitor.run() |
| 60 | + |
| 61 | + assert_errors(visitor, []) |
0 commit comments