diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/bad_builtin/bad_builtin_extension.py b/testbed/pylint-dev__pylint/tests/functional/ext/bad_builtin/bad_builtin_extension.py new file mode 100644 index 0000000000000000000000000000000000000000..fd3e5c054af7ac9dca3f36d6bd88c6dfceee98ee --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/bad_builtin/bad_builtin_extension.py @@ -0,0 +1,4 @@ +# pylint: disable=missing-docstring + +TEST = map(str, (1, 2, 3)) # [bad-builtin] +TEST1 = filter(str, (1, 2, 3)) # [bad-builtin] diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/bad_builtin/bad_builtin_extension.rc b/testbed/pylint-dev__pylint/tests/functional/ext/bad_builtin/bad_builtin_extension.rc new file mode 100644 index 0000000000000000000000000000000000000000..e7f2e1dbd9998218ae0838a1008e607830c90b2d --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/bad_builtin/bad_builtin_extension.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins=pylint.extensions.bad_builtin, diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/bad_builtin/bad_builtin_extension.txt b/testbed/pylint-dev__pylint/tests/functional/ext/bad_builtin/bad_builtin_extension.txt new file mode 100644 index 0000000000000000000000000000000000000000..3ab87ba8f70d8917ef895b77cdc248efea1090b4 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/bad_builtin/bad_builtin_extension.txt @@ -0,0 +1,2 @@ +bad-builtin:3:7:3:26::Used builtin function 'map'. Using a list comprehension can be clearer.:UNDEFINED +bad-builtin:4:8:4:30::Used builtin function 'filter'. Using a list comprehension can be clearer.:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/bad_builtin/bad_builtins.py b/testbed/pylint-dev__pylint/tests/functional/ext/bad_builtin/bad_builtins.py new file mode 100644 index 0000000000000000000000000000000000000000..9737e0ffcc2a9b6d4e8a5f2a8ce90fb7b3d9bcd7 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/bad_builtin/bad_builtins.py @@ -0,0 +1,3 @@ +# pylint: disable=missing-docstring +input("Yes or no ? (Y=1, n=0)") # [bad-builtin] +print(map(str, filter(1, [1, 2, 3]))) # [bad-builtin, bad-builtin, bad-builtin] diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/bad_builtin/bad_builtins.rc b/testbed/pylint-dev__pylint/tests/functional/ext/bad_builtin/bad_builtins.rc new file mode 100644 index 0000000000000000000000000000000000000000..9598ce0f6e05401497be26f27621357519711b35 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/bad_builtin/bad_builtins.rc @@ -0,0 +1,5 @@ +[MAIN] +load-plugins = pylint.extensions.bad_builtin + +[pylint.DEPRECATED_BUILTINS] +bad-functions=map,input,filter,print diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/bad_builtin/bad_builtins.txt b/testbed/pylint-dev__pylint/tests/functional/ext/bad_builtin/bad_builtins.txt new file mode 100644 index 0000000000000000000000000000000000000000..737a81d1b6cb90878ed3fef9064c8ead122f2d47 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/bad_builtin/bad_builtins.txt @@ -0,0 +1,4 @@ +bad-builtin:2:0:2:31::Used builtin function 'input':UNDEFINED +bad-builtin:3:15:3:35::Used builtin function 'filter'. Using a list comprehension can be clearer.:UNDEFINED +bad-builtin:3:6:3:36::Used builtin function 'map'. Using a list comprehension can be clearer.:UNDEFINED +bad-builtin:3:0:3:37::Used builtin function 'print':UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/broad_try_clause/broad_try_clause_extension.py b/testbed/pylint-dev__pylint/tests/functional/ext/broad_try_clause/broad_try_clause_extension.py new file mode 100644 index 0000000000000000000000000000000000000000..6fc85c6b27de7b31acaa1381c34434c88ccf05e7 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/broad_try_clause/broad_try_clause_extension.py @@ -0,0 +1,49 @@ +# pylint: disable=missing-docstring, invalid-name + +MY_DICTIONARY = {"key_one": 1, "key_two": 2, "key_three": 3} + +try: # [too-many-try-statements] + value = MY_DICTIONARY["key_one"] + value += 1 + print("This one has an except clause only.") +except KeyError: + pass + +try: # [too-many-try-statements] + value = MY_DICTIONARY["key_one"] + value += 1 + print("This one has a finally clause only.") +finally: + pass + +try: # [too-many-try-statements] + value = MY_DICTIONARY["key_one"] + value += 1 + print("This one has an except clause...") + print("and also a finally clause!") +except KeyError: + pass +finally: + pass + +try: # [too-many-try-statements] + if "key_one" in MY_DICTIONARY: + entered_if_body = True + print("This verifies that content inside of an if statement is counted too.") + else: + entered_if_body = False + + while False: + print("This verifies that content inside of a while loop is counted too.") + + for item in []: + print("This verifies that content inside of a for loop is counted too.") + + +except KeyError: + pass + +try: + value = MY_DICTIONARY["key_one"] +except KeyError: + value = 0 diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/broad_try_clause/broad_try_clause_extension.rc b/testbed/pylint-dev__pylint/tests/functional/ext/broad_try_clause/broad_try_clause_extension.rc new file mode 100644 index 0000000000000000000000000000000000000000..438a80b6d0fa423b09c0707987bacd2decd9d9f7 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/broad_try_clause/broad_try_clause_extension.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins=pylint.extensions.broad_try_clause, diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/broad_try_clause/broad_try_clause_extension.txt b/testbed/pylint-dev__pylint/tests/functional/ext/broad_try_clause/broad_try_clause_extension.txt new file mode 100644 index 0000000000000000000000000000000000000000..d8d2c3e77c69a3c8a31c82bac84b800460cb1778 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/broad_try_clause/broad_try_clause_extension.txt @@ -0,0 +1,4 @@ +too-many-try-statements:5:0:10:8::try clause contains 3 statements, expected at most 1:UNDEFINED +too-many-try-statements:12:0:17:8::try clause contains 3 statements, expected at most 1:UNDEFINED +too-many-try-statements:19:0:25:8::try clause contains 4 statements, expected at most 1:UNDEFINED +too-many-try-statements:29:0:44:8::try clause contains 7 statements, expected at most 1:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/check_elif/check_elif.py b/testbed/pylint-dev__pylint/tests/functional/ext/check_elif/check_elif.py new file mode 100644 index 0000000000000000000000000000000000000000..f10e78511c8c6ee31aa0010c48f10a2454d599b3 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/check_elif/check_elif.py @@ -0,0 +1,48 @@ +# pylint: disable=no-else-raise,unsupported-membership-test,using-constant-test, comparison-of-constants + +"""Checks use of "else if" triggers a refactor message""" +from typing import Union, Sequence, Any, Mapping + + +def my_function(): + """docstring""" + myint = 2 + if myint > 5: + pass + else: + if myint <= 5: # [else-if-used] + pass + else: + myint = 3 + if myint > 2: + if myint > 3: + pass + elif myint == 3: + pass + elif myint < 3: + pass + else: + if myint: # [else-if-used] + pass + else: + if myint: + pass + myint = 4 + + +def _if_in_fstring_comprehension_with_elif( + params: Union[Sequence[Any], Mapping[str, Any]] +): + order = {} + if "z" not in "false": + raise TypeError( + f" {', '.join(sorted(i for i in order or () if i not in params))}" + ) + elif "z" not in "true": + pass + else: + if "t" not in "false": # [else-if-used] + raise TypeError("d") + else: + if "y" in "life": # [else-if-used] + print("e") diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/check_elif/check_elif.rc b/testbed/pylint-dev__pylint/tests/functional/ext/check_elif/check_elif.rc new file mode 100644 index 0000000000000000000000000000000000000000..4010739ec2a05d0c20734375249ab8af43fc1f1d --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/check_elif/check_elif.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins=pylint.extensions.check_elif, diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/check_elif/check_elif.txt b/testbed/pylint-dev__pylint/tests/functional/ext/check_elif/check_elif.txt new file mode 100644 index 0000000000000000000000000000000000000000..2874795e587fa7d4ed4200fc3f05e4d801b4220d --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/check_elif/check_elif.txt @@ -0,0 +1,4 @@ +else-if-used:13:8:30:25:my_function:"Consider using ""elif"" instead of ""else"" then ""if"" to remove one indentation level":HIGH +else-if-used:25:20:26:28:my_function:"Consider using ""elif"" instead of ""else"" then ""if"" to remove one indentation level":HIGH +else-if-used:44:8:48:26:_if_in_fstring_comprehension_with_elif:"Consider using ""elif"" instead of ""else"" then ""if"" to remove one indentation level":HIGH +else-if-used:47:12:48:26:_if_in_fstring_comprehension_with_elif:"Consider using ""elif"" instead of ""else"" then ""if"" to remove one indentation level":HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_assignment_expr.py b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_assignment_expr.py new file mode 100644 index 0000000000000000000000000000000000000000..4f9a8370031e13b8019c8ba47cbccaf82ce94226 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_assignment_expr.py @@ -0,0 +1,159 @@ +# pylint: disable=missing-docstring,invalid-name,undefined-variable,too-few-public-methods + +a1 = 2 +if a1: # [consider-using-assignment-expr] + ... + +# Do not suggest assignment expressions if assignment spans multiple lines +a2 = ( + 1, +) +if a2: + ... + +# Only first name should be replaced +a3 = 2 +if a3 == a3_a: # [consider-using-assignment-expr] + ... + +# Above black line length +a4 = some_loooooooonnnnnngggg_object_name.with_some_really_long_function_name(arg) +if a4: + ... + +def func_a(): + a5 = some___object.function_name_is_just_long_enough_to_fit_in_line() # some comment + if a5 is None: # [consider-using-assignment-expr] + ... + + # Using assignment expression would result in line being 89 chars long + a6 = some_long_object.function_name_is_too_long_enough_to_fit___line() + if a6 is None: + ... + +# Previous unrelate note should not match +print("") +if a7: + ... + + +b1: int = 2 +if b1: # [consider-using-assignment-expr] + ... + +b2 = some_function(2, 3) +if b2: # [consider-using-assignment-expr] + ... + +b3 = some_object.variable +if b3: # [consider-using-assignment-expr] + ... + + +# UnaryOp +c1 = 2 +if not c1: # [consider-using-assignment-expr] + ... + + +# Compare +d1 = 2 +if d1 is True: # [consider-using-assignment-expr] + ... + +d2 = 2 +if d2 is not None: # [consider-using-assignment-expr] + ... + +d3 = 2 +if d3 == 2: # [consider-using-assignment-expr] + ... + + +# ----- +# Don't emit warning if match statement would be a better fit +o1 = 2 +if o1 == 1: + ... +elif o1 == 2: + ... +elif o1 == 3: + ... + +o2 = 2 +if o2 == 1: + ... +elif o2: + ... + +o3 = 2 +if o3 == 1: # [consider-using-assignment-expr] + ... +else: + ... + +o4 = 2 +if o4 == 1: # [consider-using-assignment-expr] + ... +elif o4 and o4_other: + ... + +o5 = 2 +if o5 == 1: # [consider-using-assignment-expr] + ... +elif o5_other == 1: + ... + +o6 = 2 +if o6 == 1: # [consider-using-assignment-expr] + ... +elif o6_other: + ... + +def func_p(): + p1 = 2 + if p1 == 1: + return + if p1 == 2: + return + + p2 = 2 + if p2 == 1: + return + if p2: + return + + p3 = 2 + if p3 == 1: # [consider-using-assignment-expr] + ... + else: + ... + + p4 = 2 + if p4 == 1: # [consider-using-assignment-expr] + ... + elif p4 and p4_other: + ... + + p5 = 2 + if p5 == 1: # [consider-using-assignment-expr] + ... + elif p5_other == 1: + ... + + p6 = 2 + if p6 == 1: # [consider-using-assignment-expr] + ... + elif p6_other: + ... + + +# ----- +# Assignment expression does NOT work for attribute access +# Make sure not to emit message! +class A: + var = 1 + +A.var = 2 +if A.var: + ... diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_assignment_expr.rc b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_assignment_expr.rc new file mode 100644 index 0000000000000000000000000000000000000000..6d3ba769b91ce61a25e7941e64e0ae7234ea0a69 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_assignment_expr.rc @@ -0,0 +1,6 @@ +[MAIN] +load-plugins=pylint.extensions.code_style +py-version=3.8 + +[CODE_STYLE] +max-line-length-suggestions=88 diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_assignment_expr.txt b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_assignment_expr.txt new file mode 100644 index 0000000000000000000000000000000000000000..1e46656b1d16e483c800f99407b0ab8a8bef87bd --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_assignment_expr.txt @@ -0,0 +1,18 @@ +consider-using-assignment-expr:4:3:4:5::"Use 'if (a1 := 2):' instead":UNDEFINED +consider-using-assignment-expr:16:3:16:5::"Use 'if (a3 := 2) == a3_a:' instead":UNDEFINED +consider-using-assignment-expr:26:7:26:9:func_a:"Use 'if (a5 := some___object.function_name_is_just_long_enough_to_fit_in_line()) is None:' instead":UNDEFINED +consider-using-assignment-expr:41:3:41:5::"Use 'if (b1 := 2):' instead":UNDEFINED +consider-using-assignment-expr:45:3:45:5::"Use 'if (b2 := some_function(2, 3)):' instead":UNDEFINED +consider-using-assignment-expr:49:3:49:5::"Use 'if (b3 := some_object.variable):' instead":UNDEFINED +consider-using-assignment-expr:55:7:55:9::"Use 'if not (c1 := 2):' instead":UNDEFINED +consider-using-assignment-expr:61:3:61:5::"Use 'if (d1 := 2) is True:' instead":UNDEFINED +consider-using-assignment-expr:65:3:65:5::"Use 'if (d2 := 2) is not None:' instead":UNDEFINED +consider-using-assignment-expr:69:3:69:5::"Use 'if (d3 := 2) == 2:' instead":UNDEFINED +consider-using-assignment-expr:90:3:90:5::"Use 'if (o3 := 2) == 1:' instead":UNDEFINED +consider-using-assignment-expr:96:3:96:5::"Use 'if (o4 := 2) == 1:' instead":UNDEFINED +consider-using-assignment-expr:102:3:102:5::"Use 'if (o5 := 2) == 1:' instead":UNDEFINED +consider-using-assignment-expr:108:3:108:5::"Use 'if (o6 := 2) == 1:' instead":UNDEFINED +consider-using-assignment-expr:127:7:127:9:func_p:"Use 'if (p3 := 2) == 1:' instead":UNDEFINED +consider-using-assignment-expr:133:7:133:9:func_p:"Use 'if (p4 := 2) == 1:' instead":UNDEFINED +consider-using-assignment-expr:139:7:139:9:func_p:"Use 'if (p5 := 2) == 1:' instead":UNDEFINED +consider-using-assignment-expr:145:7:145:9:func_p:"Use 'if (p6 := 2) == 1:' instead":UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_augmented_assign.py b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_augmented_assign.py new file mode 100644 index 0000000000000000000000000000000000000000..417bc5c0be88924ad8e45198b86f42978920438c --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_augmented_assign.py @@ -0,0 +1,135 @@ +"""Tests for consider-using-augmented-assign.""" + +# pylint: disable=invalid-name,too-few-public-methods,import-error,consider-using-f-string,missing-docstring + +from unknown import Unknown + +x = 1 + +# summation is commutative (for integer and float, but not for string) +x = x + 3 # [consider-using-augmented-assign] +x = 3 + x # [consider-using-augmented-assign] +x = x + "3" # [consider-using-augmented-assign] +x = "3" + x + +# We don't warn on intricate expressions as we lack knowledge of simplifying such +# expressions which is necessary to see if they can become augmented +x, y = 1 + x, 2 + x +x = 1 + x - 2 +x = 1 + x + 2 + +# For anything other than a float or an int we only want to warn on +# assignments where the 'itself' is on the left side of the assignment +my_list = [2, 3, 4] +my_list = [1] + my_list + + +class MyClass: + """Simple base class.""" + + def __init__(self) -> None: + self.x = 1 + self.x = self.x + 1 # [consider-using-augmented-assign] + self.x = 1 + self.x # [consider-using-augmented-assign] + + x = 1 # [redefined-outer-name] + self.x = x + + +instance = MyClass() + +x = instance.x + 1 + +my_str = "" +my_str = my_str + "foo" # [consider-using-augmented-assign] +my_str = "foo" + my_str + +my_bytes = b"" +my_bytes = my_bytes + b"foo" # [consider-using-augmented-assign] +my_bytes = b"foo" + my_bytes + + +def return_str() -> str: + """Return a string.""" + return "" + + +# Currently we disregard all calls +my_str = return_str() + my_str +my_str = my_str % return_str() +my_str = my_str % 1 # [consider-using-augmented-assign] +my_str = my_str % (1, 2) # [consider-using-augmented-assign] +my_str = "%s" % my_str +my_str = return_str() % my_str +my_str = Unknown % my_str +my_str = my_str % Unknown # [consider-using-augmented-assign] + +# subtraction is anti-commutative +x = x - 3 # [consider-using-augmented-assign] +x = 3 - x + +# multiplication is commutative +x = x * 3 # [consider-using-augmented-assign] +x = 3 * x # [consider-using-augmented-assign] + +# division is not commutative +x = x / 3 # [consider-using-augmented-assign] +x = 3 / x + +# integer division is not commutative +x = x // 3 # [consider-using-augmented-assign] +x = 3 // x + +# Left shift operator is not commutative +x = x << 3 # [consider-using-augmented-assign] +x = 3 << x + +# Right shift operator is not commutative +x = x >> 3 # [consider-using-augmented-assign] +x = 3 >> x + +# modulo is not commutative +x = x % 3 # [consider-using-augmented-assign] +x = 3 % x + +# exponential is not commutative +x = x**3 # [consider-using-augmented-assign] +x = 3**x + +# XOR is commutative +x = x ^ 3 # [consider-using-augmented-assign] +x = 3 ^ x # [consider-using-augmented-assign] + +# Bitwise AND operator is commutative +x = x & 3 # [consider-using-augmented-assign] +x = 3 & x # [consider-using-augmented-assign] + +# Bitwise OR operator is commutative +x = x | 3 # [consider-using-augmented-assign] +x = 3 | x # [consider-using-augmented-assign] + +x = x > 3 +x = 3 > x + +x = x < 3 +x = 3 < x + +x = x >= 3 +x = 3 >= x + +x = x <= 3 +x = 3 <= x + + +# https://github.com/PyCQA/pylint/issues/8086 +# consider-using-augmented-assign should only be flagged +# if names attribute names match exactly. + +class A: + def __init__(self) -> None: + self.a = 1 + self.b = A() + + def test(self) -> None: + self.a = self.a + 1 # [consider-using-augmented-assign] + self.b.a = self.a + 1 # Names don't match! diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_augmented_assign.rc b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_augmented_assign.rc new file mode 100644 index 0000000000000000000000000000000000000000..584602294613eb4363aed11affea7d85c3e881ee --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_augmented_assign.rc @@ -0,0 +1,3 @@ +[MAIN] +load-plugins=pylint.extensions.code_style +enable=consider-using-augmented-assign diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_augmented_assign.txt b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_augmented_assign.txt new file mode 100644 index 0000000000000000000000000000000000000000..f820eb67bfe7e7a626ca7fda2f4aafca4718951e --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_augmented_assign.txt @@ -0,0 +1,27 @@ +consider-using-augmented-assign:10:0:10:9::Use '+=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:11:0:11:9::Use '+=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:12:0:12:11::Use '+=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:32:8:32:27:MyClass.__init__:Use '+=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:33:8:33:27:MyClass.__init__:Use '+=' to do an augmented assign directly:INFERENCE +redefined-outer-name:35:8:35:9:MyClass.__init__:Redefining name 'x' from outer scope (line 7):UNDEFINED +consider-using-augmented-assign:44:0:44:23::Use '+=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:48:0:48:28::Use '+=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:60:0:60:19::Use '%=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:61:0:61:24::Use '%=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:65:0:65:25::Use '%=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:68:0:68:9::Use '-=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:72:0:72:9::Use '*=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:73:0:73:9::Use '*=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:76:0:76:9::Use '/=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:80:0:80:10::Use '//=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:84:0:84:10::Use '<<=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:88:0:88:10::Use '>>=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:92:0:92:9::Use '%=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:96:0:96:8::Use '**=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:100:0:100:9::Use '^=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:101:0:101:9::Use '^=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:104:0:104:9::Use '&=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:105:0:105:9::Use '&=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:108:0:108:9::Use '|=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:109:0:109:9::Use '|=' to do an augmented assign directly:INFERENCE +consider-using-augmented-assign:134:8:134:27:A.test:Use '+=' to do an augmented assign directly:INFERENCE diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_namedtuple_or_dataclass.py b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_namedtuple_or_dataclass.py new file mode 100644 index 0000000000000000000000000000000000000000..c72ca3d06c3b907518435de56d4b029986f394ab --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_namedtuple_or_dataclass.py @@ -0,0 +1,79 @@ +# pylint: disable=missing-docstring,too-few-public-methods,unused-variable,no-name-in-module +from typing import Final + +class Foo: + BAR = "bar" + +KEY_3 = "key_3" + + +# Subdicts have at least 1 common key +MAPPING_1 = { # [consider-using-namedtuple-or-dataclass] + "entry_1": {"key_1": 0, "key_2": 1, "key_diff_1": 2}, + "entry_2": {"key_1": 0, "key_2": 1, "key_diff_2": 3}, +} +MAPPING_2 = { # [consider-using-namedtuple-or-dataclass] + "entry_1": {KEY_3: None, Foo.BAR: None}, + "entry_2": {KEY_3: None, Foo.BAR: None}, +} + +# ints are not valid fieldnames for namedtuples +MAPPING_3 = { + "entry_1": {0: None, 1: None}, + "entry_2": {0: None, 1: None}, +} + +# Subdicts have no common keys +MAPPING_4 = { + "entry_1": {"key_3": 0, "key_4": 1, "key_diff_1": 2}, + "entry_2": {"key_1": 0, "key_2": 1, "key_diff_2": 3}, +} + +def func(): + # Not in module scope + mapping_4 = { + "entry_1": {"key_1": 0, "key_2": 1}, + "entry_2": {"key_1": 0, "key_2": 1}, + } + + mapping_5: Final = { # [consider-using-namedtuple-or-dataclass] + "entry_1": {"key_1": 0, "key_2": 1}, + "entry_2": {"key_1": 0, "key_2": 1}, + } + + +# lists must have the same length +MAPPING_6 = { # [consider-using-namedtuple-or-dataclass] + "entry_1": [1, "a", set()], + "entry_2": [2, "b", set()], +} +MAPPING_7 = { + "entry_1": [], + "entry_2": [], +} +MAPPING_8 = { + "entry_1": [1], + "entry_2": [2, "b"], +} +MAPPING_9 = { # [consider-using-namedtuple-or-dataclass] + "entry_1": (1, "a"), + "entry_2": (2, "b"), +} + +# No entry can't contain only dicts +MAPPING_10 = { + "entry_1": [ + {"key_1": None, "key_2": None}, + ], + "entry_2": [None] +} + +# No either dict, tuple, or list as dict values +MAPPING_11 = { + "entry_1": 1, + "entry_2": 2, +} +MAPPING_12 = { + "entry_1": "", + "entry_2": "", +} diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_namedtuple_or_dataclass.rc b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_namedtuple_or_dataclass.rc new file mode 100644 index 0000000000000000000000000000000000000000..8663ab085d72030f049c6ba071a4e1786ce0e527 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_namedtuple_or_dataclass.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins=pylint.extensions.code_style diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_namedtuple_or_dataclass.txt b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_namedtuple_or_dataclass.txt new file mode 100644 index 0000000000000000000000000000000000000000..d8772c1a4269cb0d88927ced01de88cee4cc92fb --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_namedtuple_or_dataclass.txt @@ -0,0 +1,5 @@ +consider-using-namedtuple-or-dataclass:11:12:14:1::Consider using namedtuple or dataclass for dictionary values:UNDEFINED +consider-using-namedtuple-or-dataclass:15:12:18:1::Consider using namedtuple or dataclass for dictionary values:UNDEFINED +consider-using-namedtuple-or-dataclass:39:23:42:5:func:Consider using namedtuple or dataclass for dictionary values:UNDEFINED +consider-using-namedtuple-or-dataclass:46:12:49:1::Consider using namedtuple or dataclass for dictionary values:UNDEFINED +consider-using-namedtuple-or-dataclass:58:12:61:1::Consider using namedtuple or dataclass for dictionary values:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_tuple.py b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_tuple.py new file mode 100644 index 0000000000000000000000000000000000000000..57178c34ea1db528884d481a33578f1fd0662429 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_tuple.py @@ -0,0 +1,31 @@ +# pylint: disable=invalid-name,missing-docstring,pointless-statement,unnecessary-comprehension + +var = (1, 2, 3) + +for x in var: + pass +for x in (1, 2, 3): + pass +for x in [1, 2, 3]: # [consider-using-tuple] + pass + +(x for x in var) +(x for x in (1, 2, 3)) +(x for x in [1, 2, 3]) # [consider-using-tuple] + +[x for x in var] +[x for x in (1, 2, 3)] +[x for x in [1, 2, 3]] # [consider-using-tuple] + + +for x in [*var]: # [consider-using-tuple] + pass +for x in [2, *var]: # [consider-using-tuple] + pass + +[x for x in [*var, 2]] # [consider-using-tuple] + + +# Don't emit warning for sets as this is handled by builtin checker +(x for x in {1, 2, 3}) # [use-sequence-for-iteration] +[x for x in {*var, 2}] diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_tuple.rc b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_tuple.rc new file mode 100644 index 0000000000000000000000000000000000000000..8663ab085d72030f049c6ba071a4e1786ce0e527 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_tuple.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins=pylint.extensions.code_style diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_tuple.txt b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_tuple.txt new file mode 100644 index 0000000000000000000000000000000000000000..565f5f7784d8d55c1decf425baf42f45928cf57f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_consider_using_tuple.txt @@ -0,0 +1,7 @@ +consider-using-tuple:9:9:9:18::Consider using an in-place tuple instead of list:UNDEFINED +consider-using-tuple:14:12:14:21::Consider using an in-place tuple instead of list:UNDEFINED +consider-using-tuple:18:12:18:21::Consider using an in-place tuple instead of list:UNDEFINED +consider-using-tuple:21:9:21:15::Consider using an in-place tuple instead of list:UNDEFINED +consider-using-tuple:23:9:23:18::Consider using an in-place tuple instead of list:UNDEFINED +consider-using-tuple:26:12:26:21::Consider using an in-place tuple instead of list:UNDEFINED +use-sequence-for-iteration:30:12:30:21::Use a sequence type when iterating over values:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_default.py b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_default.py new file mode 100644 index 0000000000000000000000000000000000000000..bd4edab36e615408a4d4fbbc64c4d028c8f0ff3c --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_default.py @@ -0,0 +1,6 @@ +"""Test default configuration for code-style checker.""" +# pylint: disable=invalid-name + +# consider-using-augmented-assign is disabled by default +x = 1 +x = x + 1 diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_default.rc b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_default.rc new file mode 100644 index 0000000000000000000000000000000000000000..8663ab085d72030f049c6ba071a4e1786ce0e527 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_default.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins=pylint.extensions.code_style diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_py_version_35.py b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_py_version_35.py new file mode 100644 index 0000000000000000000000000000000000000000..80f75b6544e5bde9307053d7a3a39e5a8ef754b9 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_py_version_35.py @@ -0,0 +1,7 @@ +"""No warnings should be emitted for features that require Python > 3.5""" +# pylint: disable=invalid-name + +# consider-using-assignment-expr -> requires Python 3.8 +a1 = 2 +if a1: + ... diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_py_version_35.rc b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_py_version_35.rc new file mode 100644 index 0000000000000000000000000000000000000000..1c2b2fc2e68bdf407e473f192610d0a73e526dda --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/code_style/cs_py_version_35.rc @@ -0,0 +1,3 @@ +[MAIN] +load-plugins=pylint.extensions.code_style +py-version=3.5 diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/comparison_placement/misplaced_comparison_constant.py b/testbed/pylint-dev__pylint/tests/functional/ext/comparison_placement/misplaced_comparison_constant.py new file mode 100644 index 0000000000000000000000000000000000000000..82751f2b26c785a46af9a4b30f7380698586a388 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/comparison_placement/misplaced_comparison_constant.py @@ -0,0 +1,50 @@ +"""Check that the constants are on the right side of the comparisons""" + +# pylint: disable=singleton-comparison, missing-docstring, too-few-public-methods +# pylint: disable=comparison-of-constants + +class MyClass: + def __init__(self): + self.attr = 1 + + def dummy_return(self): + return self.attr + +def dummy_return(): + return 2 + +def bad_comparisons(): + """this is not ok""" + instance = MyClass() + for i in range(10): + if 5 <= i: # [misplaced-comparison-constant] + pass + if 1 == i: # [misplaced-comparison-constant] + pass + if 3 < dummy_return(): # [misplaced-comparison-constant] + pass + if 4 != instance.dummy_return(): # [misplaced-comparison-constant] + pass + if 1 == instance.attr: # [misplaced-comparison-constant] + pass + if "aaa" == instance.attr: # [misplaced-comparison-constant] + pass + +def good_comparison(): + """this is ok""" + for i in range(10): + if i == 5: + pass + +def double_comparison(): + """Check that we return early for non-binary comparison""" + for i in range(10): + if i == 1 == 2: + pass + if 2 <= i <= 8: + print("Between 2 and 8 inclusive") + +def const_comparison(): + """Check that we return early for comparison of two constants""" + if 1 == 2: + pass diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/comparison_placement/misplaced_comparison_constant.rc b/testbed/pylint-dev__pylint/tests/functional/ext/comparison_placement/misplaced_comparison_constant.rc new file mode 100644 index 0000000000000000000000000000000000000000..bece9a583daf7604e9a132d48597dbef1bb2cdd1 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/comparison_placement/misplaced_comparison_constant.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins=pylint.extensions.comparison_placement, diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/comparison_placement/misplaced_comparison_constant.txt b/testbed/pylint-dev__pylint/tests/functional/ext/comparison_placement/misplaced_comparison_constant.txt new file mode 100644 index 0000000000000000000000000000000000000000..bc18506c7dae5baa37c25311f9c8a728a03b8b55 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/comparison_placement/misplaced_comparison_constant.txt @@ -0,0 +1,6 @@ +misplaced-comparison-constant:20:11:20:17:bad_comparisons:Comparison should be i >= 5:UNDEFINED +misplaced-comparison-constant:22:11:22:17:bad_comparisons:Comparison should be i == 1:UNDEFINED +misplaced-comparison-constant:24:11:24:29:bad_comparisons:Comparison should be dummy_return() > 3:UNDEFINED +misplaced-comparison-constant:26:11:26:39:bad_comparisons:Comparison should be instance.dummy_return() != 4:UNDEFINED +misplaced-comparison-constant:28:11:28:29:bad_comparisons:Comparison should be instance.attr == 1:UNDEFINED +misplaced-comparison-constant:30:11:30:33:bad_comparisons:Comparison should be instance.attr == 'aaa':UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/confusing_elif/confusing_elif.py b/testbed/pylint-dev__pylint/tests/functional/ext/confusing_elif/confusing_elif.py new file mode 100644 index 0000000000000000000000000000000000000000..002931de3d97332ec6e010e0c41e9370fcf43e4a --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/confusing_elif/confusing_elif.py @@ -0,0 +1,143 @@ +# pylint: disable=missing-module-docstring, missing-function-docstring + + +def triggered_if_if_block_ends_with_elif(machine, old_conf, new_conf): + """Example code that will trigger the message + + Given an if-elif construct + When the body of the if ends with an elif + Then the message confusing-consecutive-elif must be triggered. + """ + if old_conf: + if not new_conf: + machine.disable() + elif old_conf.value != new_conf.value: + machine.disable() + machine.enable(new_conf.value) + elif new_conf: # [confusing-consecutive-elif] + machine.enable(new_conf.value) + + +def not_triggered_if_indented_block_ends_with_else(machine, old_conf, new_conf): + """Example code must not trigger the message, because the inner block ends with else. + + Given an if-elif construct + When the body of the if ends with an else + Then no message shall be triggered. + """ + if old_conf: + if not new_conf: + machine.disable() + elif old_conf.value != new_conf.value: + machine.disable() + machine.enable(new_conf.value) + else: + pass + elif new_conf: + machine.enable(new_conf.value) + + +def not_triggered_if_indentend_block_ends_with_call(machine, old_conf, new_conf): + """ + Example code must not trigger the message, + + Given an if-elif construct + When the body of the if ends with a function call + Then no message shall be triggered. + + Note: There is nothing special about the body ending with a function call. + This is just taken as a representative value for the equivalence class of + "every node class unrelated to if/elif/else". + """ + if old_conf: + if not new_conf: + machine.disable() + elif old_conf.value != new_conf.value: + machine.disable() + machine.enable(new_conf.value) + print("Processed old configuration...") + elif new_conf: + machine.enable(new_conf.value) + + +def triggered_if_elif_block_ends_with_elif(machine, old_conf, new_conf, new_new_conf): + """Example code that will trigger the message + + Given an if-elif-elif construct + When the body of the first elif ends with an elif + Then the message confusing-consecutive-elif must be triggered. + """ + if old_conf: + machine.disable() + elif not new_conf: + if new_new_conf: + machine.disable() + elif old_conf.value != new_conf.value: + machine.disable() + machine.enable(new_conf.value) + elif new_conf: # [confusing-consecutive-elif] + machine.enable(new_conf.value) + + +def triggered_if_block_ends_with_if(machine, old_conf, new_conf, new_new_conf): + """Example code that will trigger the message + + Given an if-elif construct + When the body of the if ends with an if + Then the message confusing-consecutive-elif must be triggered. + """ + if old_conf: + if new_new_conf: + machine.disable() + elif new_conf: # [confusing-consecutive-elif] + machine.enable(new_conf.value) + + +def not_triggered_if_indented_block_ends_with_ifexp(machine, old_conf, new_conf): + """ + Example code must not trigger the message, + + Given an if-elif construct + When the body of the if ends with an if expression + Then no message shall be triggered. + """ + if old_conf: + if not new_conf: + machine.disable() + print("Processed old configuration...") + elif new_conf: + machine.enable(new_conf.value) + + +def not_triggered_if_outer_block_does_not_have_elif(machine, old_conf, new_conf): + """Example code must not trigger the message + + Given an if construct without an elif + When the body of the if ends with an if + Then no message shall be triggered. + """ + if old_conf: + if not new_conf: + machine.disable() + elif old_conf.value != new_conf.value: + machine.disable() + machine.enable(new_conf.value) + else: + pass + + +def not_triggered_if_outer_block_continues_with_if(machine, old_conf, new_conf, new_new_conf): + """Example code that will trigger the message + + Given an if construct which continues with a new if construct + When the body of the first if ends with an if expression + Then no message shall be triggered. + """ + if old_conf: + if new_new_conf: + machine.disable() + elif old_conf.value != new_conf.value: + machine.disable() + machine.enable(new_conf.value) + if new_conf: + machine.enable(new_conf.value) diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/confusing_elif/confusing_elif.rc b/testbed/pylint-dev__pylint/tests/functional/ext/confusing_elif/confusing_elif.rc new file mode 100644 index 0000000000000000000000000000000000000000..6ceabfd96230c16daa7472b5af9efdc78347dcb9 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/confusing_elif/confusing_elif.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins=pylint.extensions.confusing_elif diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/confusing_elif/confusing_elif.txt b/testbed/pylint-dev__pylint/tests/functional/ext/confusing_elif/confusing_elif.txt new file mode 100644 index 0000000000000000000000000000000000000000..35487e9df33b811f9186c1877b86177625221ba3 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/confusing_elif/confusing_elif.txt @@ -0,0 +1,3 @@ +confusing-consecutive-elif:17:4:18:38:triggered_if_if_block_ends_with_elif:Consecutive elif with differing indentation level, consider creating a function to separate the inner elif:UNDEFINED +confusing-consecutive-elif:78:4:79:38:triggered_if_elif_block_ends_with_elif:Consecutive elif with differing indentation level, consider creating a function to separate the inner elif:UNDEFINED +confusing-consecutive-elif:92:4:93:38:triggered_if_block_ends_with_if:Consecutive elif with differing indentation level, consider creating a function to separate the inner elif:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/consider_ternary_expression/consider_ternary_expression.py b/testbed/pylint-dev__pylint/tests/functional/ext/consider_ternary_expression/consider_ternary_expression.py new file mode 100644 index 0000000000000000000000000000000000000000..5a6700ebef53afa272efd9c3f291f49e1ab5820b --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/consider_ternary_expression/consider_ternary_expression.py @@ -0,0 +1,36 @@ +# pylint: disable=invalid-name, undefined-variable, unused-variable, missing-function-docstring, missing-module-docstring +# pylint: disable=unsupported-assignment-operation, line-too-long + +if f(): # [consider-ternary-expression] + x = 4 +else: + x = 5 + +if g(): + y = 3 +elif h(): + y = 4 +else: + y = 5 + +def a(): + if i(): # [consider-ternary-expression] + z = 4 + else: + z = 5 + +if f(): + x = 4 + print(x) +else: + x = 5 + +if f(): + x[0] = 4 +else: + x = 5 + +if f(): + x = 4 +else: + y = 5 diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/consider_ternary_expression/consider_ternary_expression.rc b/testbed/pylint-dev__pylint/tests/functional/ext/consider_ternary_expression/consider_ternary_expression.rc new file mode 100644 index 0000000000000000000000000000000000000000..11dbbe8f7987ac2d201c7a02b0b4ad236c3c0116 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/consider_ternary_expression/consider_ternary_expression.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins=pylint.extensions.consider_ternary_expression, diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/consider_ternary_expression/consider_ternary_expression.txt b/testbed/pylint-dev__pylint/tests/functional/ext/consider_ternary_expression/consider_ternary_expression.txt new file mode 100644 index 0000000000000000000000000000000000000000..d7898e61bf1fbac000977c05d698adef2a0d3344 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/consider_ternary_expression/consider_ternary_expression.txt @@ -0,0 +1,2 @@ +consider-ternary-expression:4:0:7:9::Consider rewriting as a ternary expression:UNDEFINED +consider-ternary-expression:17:4:20:13:a:Consider rewriting as a ternary expression:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/docparams.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/docparams.py new file mode 100644 index 0000000000000000000000000000000000000000..0d033d4ca8098506c83e144fb811c2b9c4ccd3d3 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/docparams.py @@ -0,0 +1,108 @@ +"""Fixture for testing missing documentation in docparams.""" +# pylint: disable=broad-exception-raised + +def _private_func1( # [missing-return-doc, missing-return-type-doc, missing-any-param-doc] + param1, +): + """This is a test docstring without returns""" + return param1 + + +def _private_func2( # [missing-yield-doc, missing-yield-type-doc, missing-any-param-doc] + param1, +): + """This is a test docstring without yields""" + yield param1 + + +def _private_func3(param1): # [missing-raises-doc, missing-any-param-doc] + """This is a test docstring without raises""" + raise Exception("Example") + + +def public_func1(param1): # [missing-any-param-doc] + """This is a test docstring without params""" + print(param1) + + +# pylint: disable-next=line-too-long +async def _async_private_func1( # [missing-return-doc, missing-return-type-doc, missing-any-param-doc] + param1, +): + """This is a test docstring without returns""" + return param1 + + +# pylint: disable-next=line-too-long +async def _async_private_func2( # [missing-yield-doc, missing-yield-type-doc, missing-any-param-doc] + param1, +): + """This is a test docstring without yields""" + yield param1 + + +async def _async_private_func3(param1): # [missing-raises-doc, missing-any-param-doc] + """This is a test docstring without raises""" + raise Exception("Example") + + +async def async_public_func1(param1): # [missing-any-param-doc] + """This is a test docstring without params""" + print(param1) + + +def differing_param_doc(par1: int) -> int: # [differing-param-doc] + """This is a test docstring documenting one non-existing param + + :param par1: some param + :param param: some param + :return: the sum of the params + """ + + return par1 + + +def differing_param_doc_kwords_only(*, par1: int) -> int: # [differing-param-doc] + """This is a test docstring documenting one non-existing param + + :param par1: some param + :param param: some param + :return: the sum of the params + """ + + return par1 + + +def missing_type_doc(par1) -> int: # [missing-type-doc] + """This is a test docstring params where the type is not specified + + :param par1: some param + :return: the param + """ + + return par1 + + +def missing_type_doc_kwords_only(*, par1) -> int: # [missing-type-doc] + """This is a test docstring params where the type is not specified + + :param par1: some param + :return: the param + """ + + return par1 + + +def params_are_documented(par1: int, *, par2: int) -> int: + """This is a test docstring params where nothing is raised as it is all documented + + :param par1: some param + :param par2: some other param + :return: the sum of params + """ + + return par1 + par2 + + +# Only check raise nodes within FunctionDefs +raise Exception() diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/docparams.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/docparams.rc new file mode 100644 index 0000000000000000000000000000000000000000..2a09f2f6d55a6d87ddfec6b85d687ee88926a356 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/docparams.rc @@ -0,0 +1,9 @@ +[MAIN] +load-plugins = pylint.extensions.docparams +no-docstring-rgx = ONLYVERYSPECIFICFUNCTIONS + +[BASIC] +accept-no-param-doc = no +accept-no-raise-doc = no +accept-no-return-doc = no +accept-no-yields-doc = no diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/docparams.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/docparams.txt new file mode 100644 index 0000000000000000000000000000000000000000..2504e2b630066a2ad28bd6ba89fb94b9741c2939 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/docparams.txt @@ -0,0 +1,22 @@ +missing-any-param-doc:4:0:4:18:_private_func1:"Missing any documentation in ""_private_func1""":HIGH +missing-return-doc:4:0:4:18:_private_func1:Missing return documentation:HIGH +missing-return-type-doc:4:0:4:18:_private_func1:Missing return type documentation:HIGH +missing-any-param-doc:11:0:11:18:_private_func2:"Missing any documentation in ""_private_func2""":HIGH +missing-yield-doc:11:0:11:18:_private_func2:Missing yield documentation:HIGH +missing-yield-type-doc:11:0:11:18:_private_func2:Missing yield type documentation:HIGH +missing-any-param-doc:18:0:18:18:_private_func3:"Missing any documentation in ""_private_func3""":HIGH +missing-raises-doc:18:0:18:18:_private_func3:"""Exception"" not documented as being raised":HIGH +missing-any-param-doc:23:0:23:16:public_func1:"Missing any documentation in ""public_func1""":HIGH +missing-any-param-doc:29:0:29:30:_async_private_func1:"Missing any documentation in ""_async_private_func1""":HIGH +missing-return-doc:29:0:29:30:_async_private_func1:Missing return documentation:HIGH +missing-return-type-doc:29:0:29:30:_async_private_func1:Missing return type documentation:HIGH +missing-any-param-doc:37:0:37:30:_async_private_func2:"Missing any documentation in ""_async_private_func2""":HIGH +missing-yield-doc:37:0:37:30:_async_private_func2:Missing yield documentation:HIGH +missing-yield-type-doc:37:0:37:30:_async_private_func2:Missing yield type documentation:HIGH +missing-any-param-doc:44:0:44:30:_async_private_func3:"Missing any documentation in ""_async_private_func3""":HIGH +missing-raises-doc:44:0:44:30:_async_private_func3:"""Exception"" not documented as being raised":HIGH +missing-any-param-doc:49:0:49:28:async_public_func1:"Missing any documentation in ""async_public_func1""":HIGH +differing-param-doc:54:0:54:23:differing_param_doc:"""param"" differing in parameter documentation":HIGH +differing-param-doc:65:0:65:35:differing_param_doc_kwords_only:"""param"" differing in parameter documentation":HIGH +missing-type-doc:76:0:76:20:missing_type_doc:"""par1"" missing in parameter type documentation":HIGH +missing-type-doc:86:0:86:32:missing_type_doc_kwords_only:"""par1"" missing in parameter type documentation":HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/docparams_py38.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/docparams_py38.py new file mode 100644 index 0000000000000000000000000000000000000000..7044fb369dd5c4f821ad548d2707d1c6d60235c4 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/docparams_py38.py @@ -0,0 +1,34 @@ +"""Fixture for testing missing documentation in docparams (Python >=3.8 only).""" + + +def differing_param_doc_pos_only(par1: int, /) -> int: # [differing-param-doc] + """This is a test docstring documenting one non-existing param + + :param par1: some param + :param param: some param + :return: the sum of the params + """ + + return par1 + + +def missing_type_doc_pos_only(par1, /) -> int: # [missing-type-doc] + """This is a test docstring params where the type is not specified + + :param par1: some param + :return: the param + """ + + return par1 + + +def params_are_documented(par1: int, /, par2: int, *, par3: int) -> int: + """This is a test docstring params where nothing is raised as it is all documented + + :param par1: some param + :param par2: some other param + :param par3: some other param + :return: the sum of params + """ + + return par1 + par2 + par3 diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/docparams_py38.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/docparams_py38.rc new file mode 100644 index 0000000000000000000000000000000000000000..8b1c24508841a72fc0c75bebbfd88a62a96419f8 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/docparams_py38.rc @@ -0,0 +1,11 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-param-doc = no +accept-no-raise-doc = no +accept-no-return-doc = no +accept-no-yields-doc = no + +[testoptions] +min_pyver=3.8 diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/docparams_py38.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/docparams_py38.txt new file mode 100644 index 0000000000000000000000000000000000000000..ce2ac77615fc35ddcdc8553f3c1b9a099f9dbdf5 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/docparams_py38.txt @@ -0,0 +1,2 @@ +differing-param-doc:4:0:4:32:differing_param_doc_pos_only:"""param"" differing in parameter documentation":HIGH +missing-type-doc:15:0:15:29:missing_type_doc_pos_only:"""par1"" missing in parameter type documentation":HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/missing_param_doc.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/missing_param_doc.py new file mode 100644 index 0000000000000000000000000000000000000000..e72507a785982bf5b197464cb010f514769f92a2 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/missing_param_doc.py @@ -0,0 +1,142 @@ +#pylint: disable=missing-module-docstring + +def foobar1(arg1, arg2): #[missing-any-param-doc] + """function foobar ... + """ + print(arg1, arg2) + +def foobar2(arg1, arg2): #[missing-any-param-doc] + """function foobar ... + Parameters + ---------- + """ + print(arg1, arg2) + +def foobar3(arg1, arg2, arg3): #[missing-param-doc, missing-type-doc] + """function foobar ... + Parameters + ---------- + arg1: int + arg3: float + """ + print(arg1, arg2, arg3) + +def foobar4(arg1, arg2): #[missing-param-doc, missing-type-doc] + """function foobar ... + Parameters + ---------- + arg1: int + description + """ + print(arg1, arg2) + +def foobar5(arg1, arg2): #[missing-type-doc] + """function foobar ... + Parameters + ---------- + arg1: + description + arg2: str + """ + print(arg1, arg2) + +def foobar6(arg1, arg2, arg3): #[missing-param-doc, missing-type-doc] + """function foobar ... + Parameters + ---------- + arg1: int + description + arg2: int + """ + print(arg1, arg2, arg3) + +def foobar7(arg1, arg2): #[missing-any-param-doc] + """function foobar ... + Parameters + ---------- + arg1 + """ + print(arg1, arg2) + +def foobar8(arg1): #[missing-any-param-doc] + """function foobar""" + + print(arg1) + +def foobar9(arg1, arg2, arg3): + """function foobar ... + Parameters + ---------- + arg1: int + arg2: int + arg3: str + """ + print(arg1, arg2, arg3) + +def foobar10(arg1, arg2, arg3): #[missing-type-doc] + """function foobar ... + Parameters + ---------- + arg1: + desc1 + arg2: int + arg3: + desc3 + """ + print(arg1, arg2, arg3) + +def foobar11(arg1, arg2): #[missing-any-param-doc] + """function foobar ... + Args + ---------- + arg1 + arg2 + """ + print(arg1, arg2) + +def foobar12(arg1, arg2, arg3): #[missing-param-doc, missing-type-doc] + """function foobar ... + Args + ---------- + arg1: int + arg2: + does something + arg3 + """ + print(arg1, arg2, arg3) + +def foobar13(arg1, *args, arg3=";"): + """Description of the function + + Parameters + ---------- + arg1 : str + Path to the input. + *args : + Relevant parameters. + arg3 : str, optional + File separator. + """ + print(arg1, args, arg3) + +def foobar14(arg1, *args): + """Description of the function + + Parameters + ---------- + arg1 : str + Path to the input. + *args : + Relevant parameters. + """ + print(arg1, args) + +def foobar15(*args): + """Description of the function + + Parameters + ---------- + *args : + Relevant parameters. + """ + print(args) diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/missing_param_doc.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/missing_param_doc.rc new file mode 100644 index 0000000000000000000000000000000000000000..2e63824f632a0f09eb3e9e7a2a84c2a3bd670ec2 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/missing_param_doc.rc @@ -0,0 +1,8 @@ +[MAIN] +load-plugins=pylint.extensions.docparams, + +[PARAMETER_DOCUMENTATION] +accept-no-param-doc=no +accept-no-raise-doc=no +accept-no-return-doc=no +accept-no-yields-doc=no diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/missing_param_doc.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/missing_param_doc.txt new file mode 100644 index 0000000000000000000000000000000000000000..fdf4da93f4b85c982387d7934e06154bbe415f7a --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/missing_param_doc.txt @@ -0,0 +1,15 @@ +missing-any-param-doc:3:0:3:11:foobar1:"Missing any documentation in ""foobar1""":HIGH +missing-any-param-doc:8:0:8:11:foobar2:"Missing any documentation in ""foobar2""":HIGH +missing-param-doc:15:0:15:11:foobar3:"""arg2"" missing in parameter documentation":HIGH +missing-type-doc:15:0:15:11:foobar3:"""arg2"" missing in parameter type documentation":HIGH +missing-param-doc:24:0:24:11:foobar4:"""arg2"" missing in parameter documentation":HIGH +missing-type-doc:24:0:24:11:foobar4:"""arg2"" missing in parameter type documentation":HIGH +missing-type-doc:33:0:33:11:foobar5:"""arg1"" missing in parameter type documentation":HIGH +missing-param-doc:43:0:43:11:foobar6:"""arg3"" missing in parameter documentation":HIGH +missing-type-doc:43:0:43:11:foobar6:"""arg3"" missing in parameter type documentation":HIGH +missing-any-param-doc:53:0:53:11:foobar7:"Missing any documentation in ""foobar7""":HIGH +missing-any-param-doc:61:0:61:11:foobar8:"Missing any documentation in ""foobar8""":HIGH +missing-type-doc:76:0:76:12:foobar10:"""arg1, arg3"" missing in parameter type documentation":HIGH +missing-any-param-doc:88:0:88:12:foobar11:"Missing any documentation in ""foobar11""":HIGH +missing-param-doc:97:0:97:12:foobar12:"""arg3"" missing in parameter documentation":HIGH +missing-type-doc:97:0:97:12:foobar12:"""arg2, arg3"" missing in parameter type documentation":HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc.py new file mode 100644 index 0000000000000000000000000000000000000000..6039c4b2005c8b80981ab447434893807b091d71 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc.py @@ -0,0 +1,12 @@ +"""Tests for missing-param-doc and missing-type-doc for non-specified style docstrings +with accept-no-param-doc = yes +""" +# pylint: disable=invalid-name, unused-argument + + +def test_tolerate_no_param_documentation_at_all(x, y): + """Example of a function with no parameter documentation at all + + No error message is emitted. + + missing parameter documentation""" diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc.rc new file mode 100644 index 0000000000000000000000000000000000000000..2bd8899cd59273f386970f1a6f7bfab54dfd2b83 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc.rc @@ -0,0 +1,7 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-param-doc=yes +docstring-min-length: -1 +no-docstring-rgx=^$ diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required.py new file mode 100644 index 0000000000000000000000000000000000000000..0726455051ef762bcccf21c0e4f14dede93beeaa --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required.py @@ -0,0 +1,51 @@ +"""Tests for missing-param-doc and missing-type-doc for non-specified style docstrings +with accept-no-param-doc = no +""" +# pylint: disable=invalid-name, unused-argument, too-few-public-methods + + +def test_don_t_tolerate_no_param_documentation_at_all(x, y): # [missing-any-param-doc] + """Example of a function with no parameter documentation at all + + Missing documentation error message is emitted. + + missing parameter documentation""" + + +def test_see_tolerate_no_param_documentation_at_all(x, y): + """Example for the usage of "For the parameters, see" + to suppress missing-param warnings. + + For the parameters, see :func:`blah` + """ + + +class ClassFoo: + """Example usage of "For the parameters, see" in init docstring""" + + def __init__(self, x, y): + """docstring foo constructor + + For the parameters, see :func:`bla` + """ + + +class ClassFooTwo: + """test_see_sentence_for_constr_params_in_class + Example usage of "For the parameters, see" in class docstring + + For the parameters, see :func:`bla` + """ + + def __init__(self, x, y): + """init""" + + +def test_kwonlyargs_are_taken_in_account( # [missing-param-doc, missing-type-doc] + arg, *, kwonly, missing_kwonly +): + """The docstring + + :param int arg: The argument. + :param bool kwonly: A keyword-arg. + """ diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required.rc new file mode 100644 index 0000000000000000000000000000000000000000..8150c6ff2abb75e49b68dc2d324dde7a4caee3a0 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required.rc @@ -0,0 +1,7 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-param-doc=no +docstring-min-length: -1 +no-docstring-rgx=^$ diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required.txt new file mode 100644 index 0000000000000000000000000000000000000000..3f1ebda5768e5649fa5fb5a085e228582b4be35a --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required.txt @@ -0,0 +1,3 @@ +missing-any-param-doc:7:0:7:53:test_don_t_tolerate_no_param_documentation_at_all:"Missing any documentation in ""test_don_t_tolerate_no_param_documentation_at_all""":HIGH +missing-param-doc:44:0:44:40:test_kwonlyargs_are_taken_in_account:"""missing_kwonly"" missing in parameter documentation":HIGH +missing-type-doc:44:0:44:40:test_kwonlyargs_are_taken_in_account:"""missing_kwonly"" missing in parameter type documentation":HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Google.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Google.py new file mode 100644 index 0000000000000000000000000000000000000000..92646a87f4e8041b059fae5083a625b7231660fe --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Google.py @@ -0,0 +1,447 @@ +"""Tests for missing-param-doc and missing-type-doc for Google style docstrings +with accept-no-param-doc = no + +Styleguide: +https://google.github.io/styleguide/pyguide.html#doc-function-args +""" +# pylint: disable=invalid-name, unused-argument, undefined-variable +# pylint: disable=line-too-long, too-few-public-methods, missing-class-docstring +# pylint: disable=missing-function-docstring, function-redefined, inconsistent-return-statements +# pylint: disable=dangerous-default-value, too-many-arguments + + +def test_multi_line_parameters(param: int) -> None: + """Checks that multi line parameters lists are checked correctly + See https://github.com/PyCQA/pylint/issues/5452 + + Args: + param: + a description + """ + print(param) + + +def test_missing_func_params_in_google_docstring( # [missing-param-doc, missing-type-doc] + x, y, z +): + """Example of a function with missing Google style parameter + documentation in the docstring + + Args: + x: bla + z (int): bar + + some other stuff + """ + + +def test_missing_func_params_with_annotations_in_google_docstring(x: int, y: bool, z): + """Example of a function with missing Google style parameter + documentation in the docstring. + + Args: + x: bla + y: blah blah + z (int): bar + + some other stuff + """ + + +def test_missing_type_doc_google_docstring_exempt_kwonly_args( + arg1: int, arg2: int, *, value1: str, value2: str +): + """Code to show failure in missing-type-doc + + Args: + arg1: First argument. + arg2: Second argument. + value1: First kwarg. + value2: Second kwarg. + """ + print("NOTE: It doesn't like anything after the '*'.") + + +def test_default_arg_with_annotations_in_google_docstring( + x: int, y: bool, z: int = 786 +): + """Example of a function with missing Google style parameter + documentation in the docstring. + + Args: + x: bla + y: blah blah + z: bar + + some other stuff + """ + + +def test_missing_func_params_with_partial_annotations_in_google_docstring( # [missing-type-doc] + x, y: bool, z +): + """Example of a function with missing Google style parameter + documentation in the docstring. + + Args: + x: bla + y: blah blah + z (int): bar + + some other stuff + """ + + +def test_non_builtin_annotations_in_google_docstring( + bottomleft: Point, topright: Point +) -> float: + """Example of a function with missing Google style parameter + documentation in the docstring. + Args: + bottomleft: bottom left point of rectangle + topright: top right point of rectangle + """ + + +def test_non_builtin_annotations_for_returntype_in_google_docstring( + bottomleft: Point, topright: Point +) -> Point: + """Example of a function with missing Google style parameter + documentation in the docstring. + Args: + bottomleft: bottom left point of rectangle + topright: top right point of rectangle + """ + + +def test_func_params_and_keyword_params_in_google_docstring(this, other, that=True): + """Example of a function with Google style parameter split + in Args and Keyword Args in the docstring + + Args: + this (str): Printed first + other (int): Other args + + Keyword Args: + that (bool): Printed second + """ + print(this, that, other) + + +def test_func_params_and_wrong_keyword_params_in_google_docstring( # [missing-param-doc, missing-type-doc, differing-param-doc, differing-type-doc] + this, other, that=True +): + """Example of a function with Google style parameter split + in Args and Keyword Args in the docstring but with wrong keyword args + + Args: + this (str): Printed first + other (int): Other args + + Keyword Args: + these (bool): Printed second + """ + print(this, that, other) + + +class Foo: + def test_missing_method_params_in_google_docstring( # [missing-param-doc, missing-type-doc] + self, x, y + ): + """Example of a class method with missing parameter documentation in + the Google style docstring + + missing parameter documentation + + Args: + x: bla + """ + + +def test_existing_func_params_in_google_docstring(xarg, yarg, zarg, warg): + """Example of a function with correctly documented parameters and + return values (Google style) + + Args: + xarg (int): bla xarg + yarg (my.qualified.type): bla + bla yarg + + zarg (int): bla zarg + warg (my.qualified.type): bla warg + + Returns: + float: sum + """ + return xarg + yarg + + +def test_wrong_name_of_func_params_in_google_docstring_one( # [missing-param-doc, missing-type-doc, differing-param-doc, differing-type-doc] + xarg, yarg, zarg +): + """Example of functions with inconsistent parameter names in the + signature and in the Google style documentation + + Args: + xarg1 (int): bla xarg + yarg (float): bla yarg + + zarg1 (str): bla zarg + """ + return xarg + yarg + + +def test_wrong_name_of_func_params_in_google_docstring_two( # [differing-param-doc, differing-type-doc] + xarg, yarg +): + """Example of functions with inconsistent parameter names in the + signature and in the Google style documentation + + Args: + yarg1 (float): bla yarg + + For the other parameters, see bla. + """ + return xarg + yarg + + +def test_see_sentence_for_func_params_in_google_docstring(xarg, yarg): + """Example for the usage of "For the other parameters, see" to avoid + too many repetitions, e.g. in functions or methods adhering to a + given interface (Google style) + + Args: + yarg (float): bla yarg + + For the other parameters, see :func:`bla` + """ + return xarg + yarg + + +class ClassFoo: # [missing-param-doc, missing-type-doc] + """test_constr_params_in_class_google + Example of a class with missing constructor parameter documentation + (Google style) + + Everything is completely analogous to functions. + + Args: + y: bla + + missing constructor parameter documentation + """ + + def __init__(self, x, y): + pass + + +class ClassFoo: + def __init__(self, x, y): # [missing-param-doc, missing-type-doc] + """test_constr_params_in_init_google + Example of a class with missing constructor parameter documentation + (Google style) + + Args: + y: bla + + missing constructor parameter documentation + """ + + +class ClassFoo: # [multiple-constructor-doc,missing-param-doc, missing-type-doc] + """test_constr_params_in_class_and_init_google + Example of a class with missing constructor parameter documentation + in both the init docstring and the class docstring + (Google style) + + Everything is completely analogous to functions. + + Args: + y: bla + + missing constructor parameter documentation + """ + + def __init__(self, x, y): # [missing-param-doc, missing-type-doc] + """docstring foo + + Args: + y: bla + + missing constructor parameter documentation + """ + + +def test_warns_missing_args_google(named_arg, *args): # [missing-param-doc] + """The docstring + + Args: + named_arg (object): Returned + + Returns: + object or None: Maybe named_arg + """ + if args: + return named_arg + + +def test_warns_missing_kwargs_google(named_arg, **kwargs): # [missing-param-doc] + """The docstring + + Args: + named_arg (object): Returned + + Returns: + object or None: Maybe named_arg + """ + if kwargs: + return named_arg + + +def test_finds_args_without_type_google(named_arg, *args): + """The docstring + + Args: + named_arg (object): Returned + *args: Optional arguments + + Returns: + object or None: Maybe named_arg + """ + if args: + return named_arg + + +def test_finds_kwargs_without_type_google(named_arg, **kwargs): + """The docstring + + Args: + named_arg (object): Returned + **kwargs: Keyword arguments + + Returns: + object or None: Maybe named_arg + """ + if kwargs: + return named_arg + + +def test_finds_kwargs_without_asterisk_google(named_arg, **kwargs): + """The docstring + + Args: + named_arg (object): Returned + kwargs: Keyword arguments + + Returns: + object or None: Maybe named_arg + """ + if kwargs: + return named_arg + + +def test_finds_escaped_args_google(value: int, *args: Any) -> None: + """This is myfunc. + + Args: + \\*args: this is args + value: this is value + """ + print(*args, value) + + +def test_finds_args_with_xref_type_google(named_arg, **kwargs): + """The docstring + + Args: + named_arg (`example.value`): Returned + **kwargs: Keyword arguments + + Returns: + `example.value`: Maybe named_arg + """ + if kwargs: + return named_arg + + +def test_ignores_optional_specifier_google( + param1, param2, param3=(), param4=[], param5=[], param6=True +): + """Do something. + + Args: + param1 (str): Description. + param2 (dict(str, int)): Description. + param3 (tuple(str), optional): Defaults to empty. Description. + param4 (List[str], optional): Defaults to empty. Description. + param5 (list[tuple(str)], optional): Defaults to empty. Description. + param6 (bool, optional): Defaults to True. Description. + + Returns: + int: Description. + """ + return param1, param2, param3, param4, param5, param6 + + +def test_finds_multiple_complex_types_google( + named_arg_one, + named_arg_two, + named_arg_three, + named_arg_four, + named_arg_five, + named_arg_six, + named_arg_seven, + named_arg_eight, + named_arg_nine, + named_arg_ten, +): + """The google docstring + + Args: + named_arg_one (dict(str, str)): Returned + named_arg_two (dict[str, str]): Returned + named_arg_three (int or str): Returned + named_arg_four (tuple(int or str)): Returned + named_arg_five (tuple(int) or list(int)): Returned + named_arg_six (tuple(int or str) or list(int or str)): Returned + named_arg_seven (dict(str,str)): Returned + named_arg_eight (dict[str,str]): Returned + named_arg_nine (tuple(int)): Returned + named_arg_ten (list[tokenize.TokenInfo]): Returned + + Returns: + dict(str, str): named_arg_one + dict[str, str]: named_arg_two + int or str: named_arg_three + tuple(int or str): named_arg_four + tuple(int) or list(int): named_arg_five + tuple(int or str) or list(int or str): named_arg_six + dict(str,str): named_arg_seven + dict[str,str]: named_arg_eight + tuple(int): named_arg_nine + list[tokenize.TokenInfo]: named_arg_ten + """ + return ( + named_arg_one, + named_arg_two, + named_arg_three, + named_arg_four, + named_arg_five, + named_arg_six, + named_arg_seven, + named_arg_eight, + named_arg_nine, + named_arg_ten, + ) + +def test_escape_underscore(something: int, raise_: bool = False) -> bool: + """Tests param with escaped _ is handled correctly. + + Args: + something: the something + raise\\_: the other + + Returns: + something + """ + return something and raise_ diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Google.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Google.rc new file mode 100644 index 0000000000000000000000000000000000000000..8150c6ff2abb75e49b68dc2d324dde7a4caee3a0 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Google.rc @@ -0,0 +1,7 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-param-doc=no +docstring-min-length: -1 +no-docstring-rgx=^$ diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Google.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Google.txt new file mode 100644 index 0000000000000000000000000000000000000000..33a479d11d69d542ece046883c989c6ee3586dc0 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Google.txt @@ -0,0 +1,26 @@ +missing-param-doc:24:0:24:48:test_missing_func_params_in_google_docstring:"""y"" missing in parameter documentation":HIGH +missing-type-doc:24:0:24:48:test_missing_func_params_in_google_docstring:"""x, y"" missing in parameter type documentation":HIGH +missing-type-doc:80:0:80:73:test_missing_func_params_with_partial_annotations_in_google_docstring:"""x"" missing in parameter type documentation":HIGH +differing-param-doc:131:0:131:65:test_func_params_and_wrong_keyword_params_in_google_docstring:"""these"" differing in parameter documentation":HIGH +differing-type-doc:131:0:131:65:test_func_params_and_wrong_keyword_params_in_google_docstring:"""these"" differing in parameter type documentation":HIGH +missing-param-doc:131:0:131:65:test_func_params_and_wrong_keyword_params_in_google_docstring:"""that"" missing in parameter documentation":HIGH +missing-type-doc:131:0:131:65:test_func_params_and_wrong_keyword_params_in_google_docstring:"""that"" missing in parameter type documentation":HIGH +missing-param-doc:148:4:148:54:Foo.test_missing_method_params_in_google_docstring:"""y"" missing in parameter documentation":HIGH +missing-type-doc:148:4:148:54:Foo.test_missing_method_params_in_google_docstring:"""x, y"" missing in parameter type documentation":HIGH +differing-param-doc:179:0:179:58:test_wrong_name_of_func_params_in_google_docstring_one:"""xarg1, zarg1"" differing in parameter documentation":HIGH +differing-type-doc:179:0:179:58:test_wrong_name_of_func_params_in_google_docstring_one:"""xarg1, zarg1"" differing in parameter type documentation":HIGH +missing-param-doc:179:0:179:58:test_wrong_name_of_func_params_in_google_docstring_one:"""xarg, zarg"" missing in parameter documentation":HIGH +missing-type-doc:179:0:179:58:test_wrong_name_of_func_params_in_google_docstring_one:"""xarg, zarg"" missing in parameter type documentation":HIGH +differing-param-doc:194:0:194:58:test_wrong_name_of_func_params_in_google_docstring_two:"""yarg1"" differing in parameter documentation":HIGH +differing-type-doc:194:0:194:58:test_wrong_name_of_func_params_in_google_docstring_two:"""yarg1"" differing in parameter type documentation":HIGH +missing-param-doc:221:0:221:14:ClassFoo:"""x"" missing in parameter documentation":HIGH +missing-type-doc:221:0:221:14:ClassFoo:"""x, y"" missing in parameter type documentation":HIGH +missing-param-doc:239:4:239:16:ClassFoo.__init__:"""x"" missing in parameter documentation":HIGH +missing-type-doc:239:4:239:16:ClassFoo.__init__:"""x, y"" missing in parameter type documentation":HIGH +missing-param-doc:251:0:251:14:ClassFoo:"""x"" missing in parameter documentation":HIGH +missing-type-doc:251:0:251:14:ClassFoo:"""x, y"" missing in parameter type documentation":HIGH +multiple-constructor-doc:251:0:251:14:ClassFoo:"""ClassFoo"" has constructor parameters documented in class and __init__":HIGH +missing-param-doc:265:4:265:16:ClassFoo.__init__:"""x"" missing in parameter documentation":HIGH +missing-type-doc:265:4:265:16:ClassFoo.__init__:"""x, y"" missing in parameter type documentation":HIGH +missing-param-doc:275:0:275:34:test_warns_missing_args_google:"""*args"" missing in parameter documentation":HIGH +missing-param-doc:288:0:288:36:test_warns_missing_kwargs_google:"""**kwargs"" missing in parameter documentation":HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Numpy.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..5626ad385b284075eb9ae82b971f47794821a117 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Numpy.py @@ -0,0 +1,424 @@ +"""Tests for missing-param-doc and missing-type-doc for Numpy style docstrings +with accept-no-param-doc = no +""" +# pylint: disable=invalid-name, unused-argument, undefined-variable, too-many-arguments +# pylint: disable=line-too-long, too-few-public-methods, missing-class-docstring +# pylint: disable=missing-function-docstring, function-redefined, inconsistent-return-statements + + +def test_missing_func_params_in_numpy_docstring( # [missing-param-doc, missing-type-doc] + x, y, z +): + """Example of a function with missing NumPy style parameter + documentation in the docstring + + Parameters + ---------- + x: + bla + z: int + bar + + some other stuff + """ + + +class Foo: + def test_missing_method_params_in_numpy_docstring( # [missing-param-doc, missing-type-doc] + self, x, y + ): + """Example of a class method with missing parameter documentation in + the Numpy style docstring + + missing parameter documentation + + Parameters + ---------- + x: + bla + """ + + +def test_existing_func_params_in_numpy_docstring(xarg, yarg, zarg, warg): + """Example of a function with correctly documented parameters and + return values (Numpy style) + + Parameters + ---------- + xarg: int + bla xarg + yarg: my.qualified.type + bla yarg + + zarg: int + bla zarg + warg: my.qualified.type + bla warg + + Returns + ------- + float + sum + """ + return xarg + yarg + + +def test_wrong_name_of_func_params_in_numpy_docstring( # [missing-param-doc, missing-type-doc, differing-param-doc, differing-type-doc] + xarg, yarg, zarg +): + """Example of functions with inconsistent parameter names in the + signature and in the Numpy style documentation + + Parameters + ---------- + xarg1: int + bla xarg + yarg: float + bla yarg + + zarg1: str + bla zarg + """ + return xarg + yarg + + +def test_wrong_name_of_func_params_in_numpy_docstring_two( # [differing-param-doc, differing-type-doc] + xarg, yarg +): + """Example of functions with inconsistent parameter names in the + signature and in the Numpy style documentation + + Parameters + ---------- + yarg1: float + bla yarg + + For the other parameters, see bla. + """ + return xarg + yarg + + +def test_see_sentence_for_func_params_in_numpy_docstring(xarg, yarg): + """Example for the usage of "For the other parameters, see" to avoid + too many repetitions, e.g. in functions or methods adhering to a + given interface (Numpy style) + + Parameters + ---------- + yarg: float + bla yarg + + For the other parameters, see :func:`bla` + """ + return xarg + yarg + + +class ClassFoo: # [missing-param-doc, missing-type-doc] + """test_constr_params_in_class_numpy + Example of a class with missing constructor parameter documentation + (Numpy style) + + Everything is completely analogous to functions. + + Parameters + ---------- + y: + bla + + missing constructor parameter documentation + """ + + def __init__(self, x, y): + pass + + +class ClassFoo: + """test_constr_params_and_attributes_in_class_numpy + Example of a class with correct constructor parameter documentation + and an attributes section (Numpy style) + + Parameters + ---------- + foobar : str + Something. + + Attributes + ---------- + barfoor : str + Something. + """ + + def __init__(self, foobar): + self.barfoo = None + + +class ClassFoo: + def __init__(self, x, y): # [missing-param-doc, missing-type-doc] + """test_constr_params_in_init_numpy + Example of a class with missing constructor parameter documentation + (Numpy style) + + Everything is completely analogous to functions. + + Parameters + ---------- + y: + bla + + missing constructor parameter documentation + """ + + +class ClassFoo: # [multiple-constructor-doc, missing-param-doc, missing-type-doc] + """test_constr_params_in_class_and_init_numpy + Example of a class with missing constructor parameter documentation + in both the init docstring and the class docstring + (Numpy style) + + Everything is completely analogous to functions. + + Parameters + ---------- + y: + bla + + missing constructor parameter documentation + """ + + def __init__(self, x, y): # [missing-param-doc, missing-type-doc] + """docstring foo + + Parameters + ---------- + y: + bla + + missing constructor parameter documentation + """ + + +def test_warns_missing_args_numpy(named_arg, *args): # [missing-param-doc] + """The docstring + + Args + ---- + named_arg : object + Returned + + Returns + ------- + object or None + Maybe named_arg + """ + if args: + return named_arg + + +def test_warns_missing_kwargs_numpy(named_arg, **kwargs): # [missing-param-doc] + """The docstring + + Args + ---- + named_arg : object + Returned + + Returns + ------- + object or None + Maybe named_arg + """ + if kwargs: + return named_arg + + +def test_finds_args_without_type_numpy( # [missing-type-doc] + named_arg, typed_arg: bool, untyped_arg, *args +): + """The docstring + + Args + ---- + named_arg : object + Returned + typed_arg + Other argument without numpy type annotation + untyped_arg + Other argument without any type annotation + *args : + Optional Arguments + + Returns + ------- + object or None + Maybe named_arg + """ + if args: + return named_arg + + +def test_finds_args_with_xref_type_numpy(named_arg, *args): + """The docstring + + Args + ---- + named_arg : `example.value` + Returned + *args : + Optional Arguments + + Returns + ------- + `example.value` + Maybe named_arg + """ + if args: + return named_arg + + +def test_finds_kwargs_without_type_numpy(named_arg, **kwargs): + """The docstring + + Args + ---- + named_arg : object + Returned + **kwargs : + Keyword arguments + + Returns + ------- + object or None + Maybe named_arg + """ + if kwargs: + return named_arg + + +def test_finds_kwargs_without_asterisk_numpy(named_arg, **kwargs): + """The docstring + + Args + ---- + named_arg : object + Returned + kwargs : + Keyword arguments + + Returns + ------- + object or None + Maybe named_arg + """ + if kwargs: + return named_arg + + +def my_func( + named_arg_one, + named_arg_two, + named_arg_three, + named_arg_four, + named_arg_five, + named_arg_six, + named_arg_seven, + named_arg_eight, +): + """The docstring + + Args + ---- + named_arg_one : dict(str,str) + Returned + named_arg_two : dict[str,str] + Returned + named_arg_three : tuple(int) + Returned + named_arg_four : list[tokenize.TokenInfo] + Returned + named_arg_five : int or str + Returned + named_arg_six : tuple(int or str) + Returned + named_arg_seven : tuple(int) or list(int) + Returned + named_arg_eight : tuple(int or str) or list(int or str) + Returned + + Returns + ------- + dict(str,str) + named_arg_one + dict[str,str] + named_arg_two + tuple(int) + named_arg_three + list[tokenize.TokenInfo] + named_arg_four + int or str + named_arg_five + tuple(int or str) + named_arg_six + tuple(int) or list(int) + named_arg_seven + tuple(int or str) or list(int or str) + named_arg_eight + """ + return ( + named_arg_one, + named_arg_two, + named_arg_three, + named_arg_four, + named_arg_five, + named_arg_six, + named_arg_seven, + named_arg_eight, + ) + + +def test_ignores_optional_specifier_numpy(param, param2="all"): + """Do something. + + Parameters + ---------- + param : str + Description. + param2 : str, optional + Description (the default is 'all'). + + Returns + ------- + int + Description. + """ + return param, param2 + + +def test_with_list_of_default_values(arg, option, option2): + """Reported in https://github.com/PyCQA/pylint/issues/4035. + + Parameters + ---------- + arg : int + The number of times to print it. + option : {"y", "n"} + Do I do it? + option2 : {"y", None, "n"} + Do I do it? + + """ + return arg, option, option2 + + +def test_with_descriptions_instead_of_typing(arg, axis, option): + """We choose to accept description in place of typing as well. + + See: https://github.com/PyCQA/pylint/pull/7398. + + Parameters + ---------- + arg : a number type. + axis : int or None + option : {"y", "n"} + Do I do it? + """ + return arg, option diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Numpy.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Numpy.rc new file mode 100644 index 0000000000000000000000000000000000000000..8150c6ff2abb75e49b68dc2d324dde7a4caee3a0 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Numpy.rc @@ -0,0 +1,7 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-param-doc=no +docstring-min-length: -1 +no-docstring-rgx=^$ diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Numpy.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Numpy.txt new file mode 100644 index 0000000000000000000000000000000000000000..a58b9c7cad3c755e78e684c1b177778e537e0eaf --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Numpy.txt @@ -0,0 +1,22 @@ +missing-param-doc:9:0:9:47:test_missing_func_params_in_numpy_docstring:"""y"" missing in parameter documentation":HIGH +missing-type-doc:9:0:9:47:test_missing_func_params_in_numpy_docstring:"""x, y"" missing in parameter type documentation":HIGH +missing-param-doc:27:4:27:53:Foo.test_missing_method_params_in_numpy_docstring:"""y"" missing in parameter documentation":HIGH +missing-type-doc:27:4:27:53:Foo.test_missing_method_params_in_numpy_docstring:"""x, y"" missing in parameter type documentation":HIGH +differing-param-doc:66:0:66:53:test_wrong_name_of_func_params_in_numpy_docstring:"""xarg1, zarg1"" differing in parameter documentation":HIGH +differing-type-doc:66:0:66:53:test_wrong_name_of_func_params_in_numpy_docstring:"""xarg1, zarg1"" differing in parameter type documentation":HIGH +missing-param-doc:66:0:66:53:test_wrong_name_of_func_params_in_numpy_docstring:"""xarg, zarg"" missing in parameter documentation":HIGH +missing-type-doc:66:0:66:53:test_wrong_name_of_func_params_in_numpy_docstring:"""xarg, zarg"" missing in parameter type documentation":HIGH +differing-param-doc:85:0:85:57:test_wrong_name_of_func_params_in_numpy_docstring_two:"""yarg1"" differing in parameter documentation":HIGH +differing-type-doc:85:0:85:57:test_wrong_name_of_func_params_in_numpy_docstring_two:"""yarg1"" differing in parameter type documentation":HIGH +missing-param-doc:116:0:116:14:ClassFoo:"""x"" missing in parameter documentation":HIGH +missing-type-doc:116:0:116:14:ClassFoo:"""x, y"" missing in parameter type documentation":HIGH +missing-param-doc:156:4:156:16:ClassFoo.__init__:"""x"" missing in parameter documentation":HIGH +missing-type-doc:156:4:156:16:ClassFoo.__init__:"""x, y"" missing in parameter type documentation":HIGH +missing-param-doc:172:0:172:14:ClassFoo:"""x"" missing in parameter documentation":HIGH +missing-type-doc:172:0:172:14:ClassFoo:"""x, y"" missing in parameter type documentation":HIGH +multiple-constructor-doc:172:0:172:14:ClassFoo:"""ClassFoo"" has constructor parameters documented in class and __init__":HIGH +missing-param-doc:188:4:188:16:ClassFoo.__init__:"""x"" missing in parameter documentation":HIGH +missing-type-doc:188:4:188:16:ClassFoo.__init__:"""x, y"" missing in parameter type documentation":HIGH +missing-param-doc:200:0:200:33:test_warns_missing_args_numpy:"""*args"" missing in parameter documentation":HIGH +missing-param-doc:217:0:217:35:test_warns_missing_kwargs_numpy:"""**kwargs"" missing in parameter documentation":HIGH +missing-type-doc:234:0:234:38:test_finds_args_without_type_numpy:"""untyped_arg"" missing in parameter type documentation":HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Sphinx.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Sphinx.py new file mode 100644 index 0000000000000000000000000000000000000000..a2a2f7c92c4edd0a4bcabf1b3fe455fcc2a3bcc8 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Sphinx.py @@ -0,0 +1,498 @@ +"""Tests for missing-param-doc and missing-type-doc for Sphinx style docstrings +with accept-no-param-doc = no""" +# pylint: disable=function-redefined, invalid-name, undefined-variable, missing-class-docstring +# pylint: disable=unused-argument, too-few-public-methods, unnecessary-pass, line-too-long +# pylint: disable=missing-function-docstring, disallowed-name + + +def test_missing_func_params_in_sphinx_docstring( # [missing-param-doc, missing-type-doc] + x, y, z +): + """Example of a function with missing Sphinx parameter documentation in + the docstring + + :param x: bla + + :param int z: bar + """ + pass + + +class Foo: + def test_missing_method_params_in_sphinx_docstring( # [missing-param-doc, missing-type-doc] + self, x, y + ): + """Example of a class method with missing parameter documentation in + the Sphinx style docstring + + missing parameter documentation + + :param x: bla + """ + pass + + +def test_existing_func_params_in_sphinx_docstring(xarg, yarg, zarg, warg): + """Example of a function with correctly documented parameters and + return values (Sphinx style) + + :param xarg: bla xarg + :type xarg: int + + :parameter yarg: bla yarg + :type yarg: my.qualified.type + + :arg int zarg: bla zarg + + :keyword my.qualified.type warg: bla warg + + :return: sum + :rtype: float + """ + return xarg + yarg + + +def test_wrong_name_of_func_params_in_sphinx_docstring( # [missing-param-doc, missing-type-doc, differing-param-doc, differing-type-doc] + xarg, yarg, zarg +): + """Example of functions with inconsistent parameter names in the + signature and in the Sphinx style documentation + + :param xarg1: bla xarg + :type xarg: int + + :param yarg: bla yarg + :type yarg1: float + + :param str zarg1: bla zarg + """ + return xarg + yarg + + +def test_wrong_name_of_func_params_in_sphinx_docstring_two( # [differing-param-doc, differing-type-doc] + xarg, yarg, zarg +): + """Example of functions with inconsistent parameter names in the + signature and in the Sphinx style documentation + + :param yarg1: bla yarg + :type yarg1: float + + For the other parameters, see bla. + """ + return xarg + yarg + + +def test_see_sentence_for_func_params_in_sphinx_docstring(xarg, yarg) -> None: + """Example for the usage of "For the other parameters, see" to avoid + too many repetitions, e.g. in functions or methods adhering to a + given interface (Sphinx style) + + :param yarg: bla yarg + :type yarg: float + + For the other parameters, see :func:`bla` + """ + return xarg + yarg + + +class ClassFoo: # [missing-param-doc, missing-type-doc] + """test_constr_params_in_class_sphinx + Example of a class with missing constructor parameter documentation + (Sphinx style) + + Everything is completely analogous to functions. + + :param y: bla + + missing constructor parameter documentation + """ + + def __init__(self, x, y): + pass + + +class ClassFoo: + def __init__(self, x, y): # [missing-param-doc, missing-type-doc] + """test_constr_params_in_init_sphinx + Example of a class with missing constructor parameter documentation + (Sphinx style) + + Everything is completely analogous to functions. + + :param y: bla + + missing constructor parameter documentation + """ + + pass + + +class ClassFoo: # [multiple-constructor-doc, missing-param-doc, missing-type-doc] + """test_constr_params_in_class_and_init_sphinx + Example of a class with missing constructor parameter documentation + in both the init docstring and the class docstring + (Sphinx style) + + Everything is completely analogous to functions. + + :param y: None + + missing constructor parameter documentation + """ + + def __init__(self, x, y): # [missing-param-doc, missing-type-doc] + """docstring foo + + :param y: bla + + missing constructor parameter documentation + """ + pass + + +def test_warns_missing_args_sphinx( # [missing-param-doc, inconsistent-return-statements] + named_arg, *args +): + """The docstring + + :param named_arg: Returned + :type named_arg: object + + :returns: Maybe named_arg + :rtype: object or None + """ + if args: + return named_arg + + +def test_warns_missing_kwargs_sphinx( # [missing-param-doc, inconsistent-return-statements] + named_arg, **kwargs +): + """The docstring + + :param named_arg: Returned + :type named_arg: object + + :returns: Maybe named_arg + :rtype: object or None + """ + if kwargs: + return named_arg + + +def test_finds_args_without_type_sphinx( # [missing-param-doc, inconsistent-return-statements] + named_arg, *args +): + """The docstring + + :param named_arg: Returned + :type named_arg: object + + :param *args: Optional arguments + + :returns: Maybe named_arg + :rtype: object or None + """ + if args: + return named_arg + + +def test_finds_kwargs_without_type_sphinx( # [missing-param-doc, inconsistent-return-statements] + named_arg, **kwargs +): + """The docstring + + :param named_arg: Returned + :type named_arg: object + + :param **kwargs: Keyword arguments + + :returns: Maybe named_arg + :rtype: object or None + """ + if kwargs: + return named_arg + + +def test_finds_args_without_type_sphinx( # [inconsistent-return-statements] + named_arg, *args +): + r"""The Sphinx docstring + In Sphinx docstrings asterisks should be escaped. + See https://github.com/PyCQA/pylint/issues/5406 + + :param named_arg: Returned + :type named_arg: object + + :param \*args: Optional arguments + + :returns: Maybe named_arg + :rtype: object or None + """ + if args: + return named_arg + + +def test_finds_kwargs_without_type_sphinx( # [inconsistent-return-statements] + named_arg, **kwargs +): + r"""The Sphinx docstring + In Sphinx docstrings asterisks should be escaped. + See https://github.com/PyCQA/pylint/issues/5406 + + :param named_arg: Returned + :type named_arg: object + + :param \**kwargs: Keyword arguments + + :returns: Maybe named_arg + :rtype: object or None + """ + if kwargs: + return named_arg + + +def test_finds_args_without_type_sphinx( # [inconsistent-return-statements] + named_arg, *args +): + r"""The Sphinx docstring + We can leave the asterisk out. + + :param named_arg: Returned + :type named_arg: object + + :param args: Optional arguments + + :returns: Maybe named_arg + :rtype: object or None + """ + if args: + return named_arg + + +def test_finds_kwargs_without_type_sphinx( # [inconsistent-return-statements] + named_arg, **kwargs +): + r"""The Sphinx docstring + We can leave the asterisk out. + + :param named_arg: Returned + :type named_arg: object + + :param kwargs: Keyword arguments + + :returns: Maybe named_arg + :rtype: object or None + """ + if kwargs: + return named_arg + + +class Foo: + """test_finds_missing_raises_from_setter_sphinx + Example of a setter having missing raises documentation in + the Sphinx style docstring of the property + """ + + @property + def foo(self): # [missing-raises-doc] + """docstring ... + + :type: int + """ + return 10 + + @foo.setter + def foo(self, value): + raise AttributeError() + + +class Foo: + """test_finds_missing_raises_in_setter_sphinx + Example of a setter having missing raises documentation in + its own Sphinx style docstring + """ + + @property + def foo(self): + """docstring ... + + :type: int + :raises RuntimeError: Always + """ + raise RuntimeError() + return 10 # [unreachable] + + @foo.setter + def foo(self, value): # [missing-raises-doc, missing-param-doc, missing-type-doc] + """setter docstring ... + + :type: None + """ + raise AttributeError() + + +class Foo: + """test_finds_property_return_type_sphinx + Example of a property having return documentation in + a Sphinx style docstring + """ + + @property + def foo(self): + """docstring ... + + :type: int + """ + return 10 + + +class Foo: + """test_finds_annotation_property_return_type_sphinx + Example of a property having missing return documentation in + a Sphinx style docstring + """ + + @property + def foo(self) -> int: + """docstring ... + + :raises RuntimeError: Always + """ + raise RuntimeError() + return 10 # [unreachable] + + +class Foo: + def test_useless_docs_ignored_argument_names_sphinx( # [useless-type-doc, useless-param-doc] + self, arg, _, _ignored + ): + """Example of a method documenting the return type that an + implementation should return. + + :param arg: An argument. + :type arg: int + + :param _: Another argument. + :type _: float + + :param _ignored: Ignored argument. + """ + pass + + +def test_finds_multiple_types_sphinx_one(named_arg): + """The Sphinx docstring + + :param named_arg: Returned + :type named_arg: dict(str, str) + + :returns: named_arg + :rtype: dict(str, str) + """ + return named_arg + + +def test_finds_multiple_types_sphinx_two(named_arg): + """The Sphinx docstring + + :param named_arg: Returned + :type named_arg: dict[str, str] + + :returns: named_arg + :rtype: dict[str, str] + """ + return named_arg + + +def test_finds_multiple_types_sphinx_three(named_arg): + """The Sphinx docstring + + :param named_arg: Returned + :type named_arg: int or str + + :returns: named_arg + :rtype: int or str + """ + return named_arg + + +def test_finds_multiple_types_sphinx_four(named_arg): + """The Sphinx docstring + + :param named_arg: Returned + :type named_arg: tuple(int or str) + + :returns: named_arg + :rtype: tuple(int or str) + """ + return named_arg + + +def test_finds_multiple_types_sphinx_five(named_arg): + """The Sphinx docstring + + :param named_arg: Returned + :type named_arg: tuple(int) or list(int) + + :returns: named_arg + :rtype: tuple(int) or list(int) + """ + return named_arg + + +def test_finds_multiple_types_sphinx_six(named_arg): + """The Sphinx docstring + + :param named_arg: Returned + :type named_arg: tuple(int or str) or list(int or str) + + :returns: named_arg + :rtype: tuple(int or str) or list(int or str) + """ + return named_arg + + +def test_finds_compact_container_types_sphinx_one(named_arg): + """The Sphinx docstring + + :param dict(str,str) named_arg: Returned + + :returns: named_arg + :rtype: dict(str,str) + """ + return named_arg + + +def test_finds_compact_container_types_sphinx_two(named_arg): + """The Sphinx docstring + + :param dict[str,str] named_arg: Returned + + :returns: named_arg + :rtype: dict[str,str] + """ + return named_arg + + +def test_finds_compact_container_types_sphinx_three(named_arg): + """The Sphinx docstring + + :param tuple(int) named_arg: Returned + + :returns: named_arg + :rtype: tuple(int) + """ + return named_arg + + +def test_finds_compact_container_types_sphinx_four(named_arg): + """The Sphinx docstring + + :param list[tokenize.TokenInfo] named_arg: Returned + + :returns: named_arg + :rtype: list[tokenize.TokenInfo] + """ + return named_arg diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Sphinx.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Sphinx.rc new file mode 100644 index 0000000000000000000000000000000000000000..2900924f8f90569a7f9944eeb93c69c63f1d103e --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Sphinx.rc @@ -0,0 +1,8 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-param-doc=no +accept-no-raise-doc=no +no-docstring-rgx=^$ +docstring-min-length: -1 diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Sphinx.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Sphinx.txt new file mode 100644 index 0000000000000000000000000000000000000000..b3819fff79c39cf7806c498bf61491c54e33e167 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_Sphinx.txt @@ -0,0 +1,39 @@ +missing-param-doc:8:0:8:48:test_missing_func_params_in_sphinx_docstring:"""y"" missing in parameter documentation":HIGH +missing-type-doc:8:0:8:48:test_missing_func_params_in_sphinx_docstring:"""x, y"" missing in parameter type documentation":HIGH +missing-param-doc:22:4:22:54:Foo.test_missing_method_params_in_sphinx_docstring:"""y"" missing in parameter documentation":HIGH +missing-type-doc:22:4:22:54:Foo.test_missing_method_params_in_sphinx_docstring:"""x, y"" missing in parameter type documentation":HIGH +differing-param-doc:55:0:55:54:test_wrong_name_of_func_params_in_sphinx_docstring:"""xarg1, zarg1"" differing in parameter documentation":HIGH +differing-type-doc:55:0:55:54:test_wrong_name_of_func_params_in_sphinx_docstring:"""yarg1, zarg1"" differing in parameter type documentation":HIGH +missing-param-doc:55:0:55:54:test_wrong_name_of_func_params_in_sphinx_docstring:"""xarg, zarg"" missing in parameter documentation":HIGH +missing-type-doc:55:0:55:54:test_wrong_name_of_func_params_in_sphinx_docstring:"""yarg, zarg"" missing in parameter type documentation":HIGH +differing-param-doc:72:0:72:58:test_wrong_name_of_func_params_in_sphinx_docstring_two:"""yarg1"" differing in parameter documentation":HIGH +differing-type-doc:72:0:72:58:test_wrong_name_of_func_params_in_sphinx_docstring_two:"""yarg1"" differing in parameter type documentation":HIGH +missing-param-doc:99:0:99:14:ClassFoo:"""x"" missing in parameter documentation":HIGH +missing-type-doc:99:0:99:14:ClassFoo:"""x, y"" missing in parameter type documentation":HIGH +missing-param-doc:116:4:116:16:ClassFoo.__init__:"""x"" missing in parameter documentation":HIGH +missing-type-doc:116:4:116:16:ClassFoo.__init__:"""x, y"" missing in parameter type documentation":HIGH +missing-param-doc:131:0:131:14:ClassFoo:"""x"" missing in parameter documentation":HIGH +missing-type-doc:131:0:131:14:ClassFoo:"""x, y"" missing in parameter type documentation":HIGH +multiple-constructor-doc:131:0:131:14:ClassFoo:"""ClassFoo"" has constructor parameters documented in class and __init__":HIGH +missing-param-doc:144:4:144:16:ClassFoo.__init__:"""x"" missing in parameter documentation":HIGH +missing-type-doc:144:4:144:16:ClassFoo.__init__:"""x, y"" missing in parameter type documentation":HIGH +inconsistent-return-statements:154:0:154:34:test_warns_missing_args_sphinx:Either all return statements in a function should return an expression, or none of them should.:UNDEFINED +missing-param-doc:154:0:154:34:test_warns_missing_args_sphinx:"""*args"" missing in parameter documentation":HIGH +inconsistent-return-statements:169:0:169:36:test_warns_missing_kwargs_sphinx:Either all return statements in a function should return an expression, or none of them should.:UNDEFINED +missing-param-doc:169:0:169:36:test_warns_missing_kwargs_sphinx:"""**kwargs"" missing in parameter documentation":HIGH +inconsistent-return-statements:184:0:184:39:test_finds_args_without_type_sphinx:Either all return statements in a function should return an expression, or none of them should.:UNDEFINED +missing-param-doc:184:0:184:39:test_finds_args_without_type_sphinx:"""*args"" missing in parameter documentation":HIGH +inconsistent-return-statements:201:0:201:41:test_finds_kwargs_without_type_sphinx:Either all return statements in a function should return an expression, or none of them should.:UNDEFINED +missing-param-doc:201:0:201:41:test_finds_kwargs_without_type_sphinx:"""**kwargs"" missing in parameter documentation":HIGH +inconsistent-return-statements:218:0:218:39:test_finds_args_without_type_sphinx:Either all return statements in a function should return an expression, or none of them should.:UNDEFINED +inconsistent-return-statements:237:0:237:41:test_finds_kwargs_without_type_sphinx:Either all return statements in a function should return an expression, or none of them should.:UNDEFINED +inconsistent-return-statements:256:0:256:39:test_finds_args_without_type_sphinx:Either all return statements in a function should return an expression, or none of them should.:UNDEFINED +inconsistent-return-statements:274:0:274:41:test_finds_kwargs_without_type_sphinx:Either all return statements in a function should return an expression, or none of them should.:UNDEFINED +missing-raises-doc:299:4:299:11:Foo.foo:"""AttributeError"" not documented as being raised":HIGH +unreachable:325:8:325:17:Foo.foo:Unreachable code:HIGH +missing-param-doc:328:4:328:11:Foo.foo:"""value"" missing in parameter documentation":HIGH +missing-raises-doc:328:4:328:11:Foo.foo:"""AttributeError"" not documented as being raised":HIGH +missing-type-doc:328:4:328:11:Foo.foo:"""value"" missing in parameter type documentation":HIGH +unreachable:364:8:364:17:Foo.foo:Unreachable code:HIGH +useless-param-doc:368:4:368:55:Foo.test_useless_docs_ignored_argument_names_sphinx:"""_, _ignored"" useless ignored parameter documentation":HIGH +useless-type-doc:368:4:368:55:Foo.test_useless_docs_ignored_argument_names_sphinx:"""_"" useless ignored parameter type documentation":HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_min_length.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_min_length.py new file mode 100644 index 0000000000000000000000000000000000000000..765bb2d6c84b2ca16091aa98fd4e5e09314f2baa --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_min_length.py @@ -0,0 +1,9 @@ +"""Tests for missing-param-doc and missing-type-doc for non-specified style docstrings +with accept-no-param-doc = no and docstring-min-length = 3 +""" +# pylint: disable=invalid-name, unused-argument + +# Example of a function that is less than 'docstring-min-length' config option +# No error message is emitted. +def test_skip_docstring_min_length(x, y): + """function is too short and is missing parameter documentation""" diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_min_length.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_min_length.rc new file mode 100644 index 0000000000000000000000000000000000000000..40f8c14b1c2622816a985ddde2666b82c3c7c26d --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_min_length.rc @@ -0,0 +1,7 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-param-doc=no +docstring-min-length=3 +no-docstring-rgx=^$ diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_check_init.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_check_init.py new file mode 100644 index 0000000000000000000000000000000000000000..1d6d2c70bcfaed9350c8864f73dd1a2ebf4bc23a --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_check_init.py @@ -0,0 +1,18 @@ +"""Tests for missing-param-doc and missing-type-doc for non-specified style docstrings +with accept-no-param-doc = no and no-docstring-rgx = ^(?!__init__$)_ +""" +# pylint: disable=invalid-name, unused-argument, too-few-public-methods, missing-class-docstring + + +# test_fail_docparams_check_init +# Check that __init__ is checked correctly, but other private methods aren't +class MyClass: + def __init__(self, my_param: int) -> None: # [missing-param-doc] + """ + My init docstring + """ + + def _private_method(self, my_param: int) -> None: + """ + My private method + """ diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_check_init.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_check_init.rc new file mode 100644 index 0000000000000000000000000000000000000000..a9e60fa73962629dd04ada1fb6e42911ee9ea988 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_check_init.rc @@ -0,0 +1,7 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-param-doc=no +docstring-min-length=-1 +no-docstring-rgx=^(?!__init__$)_ diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_check_init.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_check_init.txt new file mode 100644 index 0000000000000000000000000000000000000000..bc5000bd17f8272dd70f11cf619c6154006190bc --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_check_init.txt @@ -0,0 +1 @@ +missing-param-doc:10:4:10:16:MyClass.__init__:"""my_param"" missing in parameter documentation":HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_check_none.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_check_none.py new file mode 100644 index 0000000000000000000000000000000000000000..ca6eb2f7eade60c7e1d9d391e3e6835d6c2d90d6 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_check_none.py @@ -0,0 +1,16 @@ +"""Tests for missing-param-doc and missing-type-doc for non-specified style docstrings +with accept-no-param-doc = no and no-docstring-rgx = "" +""" +# pylint: disable=invalid-name, unused-argument, too-few-public-methods + + +class MyClass: + """test_no_docstring_rgx + Function that matches "check no functions" 'no-docstring-rgx' config option + No error message is emitted. + """ + + def __init__(self, my_param: int) -> None: + """ + My init docstring + """ diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_check_none.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_check_none.rc new file mode 100644 index 0000000000000000000000000000000000000000..f976c82119a4fccd9aa009c7a16d585040dae432 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_check_none.rc @@ -0,0 +1,7 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-param-doc=no +docstring-min-length=-1 +no-docstring-rgx= diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_default.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_default.py new file mode 100644 index 0000000000000000000000000000000000000000..1d2daa1a1b0ae3470fd3cbe360224c2bde3b7682 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_default.py @@ -0,0 +1,11 @@ +"""Tests for missing-param-doc and missing-type-doc for non-specified style docstrings +with accept-no-param-doc = no and the default value of no-docstring-rgx +""" +# pylint: disable=invalid-name, unused-argument + + +def _test_skip_no_docstring_rgx(x, y): + """Example of a function that matches the default 'no-docstring-rgx' config option + + No error message is emitted. + """ diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_default.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_default.rc new file mode 100644 index 0000000000000000000000000000000000000000..62c9395a772a8d6e32c6940ace688131f14b1098 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_default.rc @@ -0,0 +1,6 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-param-doc=no +docstring-min-length=-1 diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_test_all.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_test_all.py new file mode 100644 index 0000000000000000000000000000000000000000..829119a09a84bc4a917b89c3d8e4b6dea2f0ee18 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_test_all.py @@ -0,0 +1,28 @@ +"""Tests for missing-param-doc and missing-type-doc for non-specified style docstrings +with accept-no-param-doc = no and no-docstring-rgx = ^$ +""" +# pylint: disable=invalid-name, unused-argument, too-few-public-methods, function-redefined +# pylint: disable=missing-class-docstring + + +class MyClass: + """test_all_docstring_rgx + Function that matches "check all functions" 'no-docstring-rgx' config option + No error message is emitted. + """ + + def __init__(self, my_param: int) -> None: + """ + My init docstring + :param my_param: My first param + """ + + +# test_fail_empty_docstring_rgx +# Function that matches "check all functions" 'no-docstring-rgx' config option +# An error message is emitted. +class MyClass: + def __init__(self, my_param: int) -> None: # [missing-param-doc] + """ + My init docstring + """ diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_test_all.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_test_all.rc new file mode 100644 index 0000000000000000000000000000000000000000..505fa0440534f7d8b48fde951a4545a0487b321f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_test_all.rc @@ -0,0 +1,7 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-param-doc=no +docstring-min-length=-1 +no-docstring-rgx=^$ diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_test_all.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_test_all.txt new file mode 100644 index 0000000000000000000000000000000000000000..d845b5f17af19e761b07c002a8dfcc5dafa25679 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_test_all.txt @@ -0,0 +1 @@ +missing-param-doc:25:4:25:16:MyClass.__init__:"""my_param"" missing in parameter documentation":HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc.py new file mode 100644 index 0000000000000000000000000000000000000000..6ba112bd5f691b34b72d2e08dfdc1d3f850f9960 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc.py @@ -0,0 +1,108 @@ +"""Tests for missing-raises-doc and missing-raises-type-doc""" +# pylint: disable=function-redefined, invalid-name, undefined-variable, missing-function-docstring +# pylint: disable=unused-argument, import-error, unused-variable, no-member, try-except-raise +import collections + +from fake_package import BadError +from unknown import Unknown + + +def test_ignores_no_docstring(self): + raise RuntimeError("hi") + + +def test_ignores_unknown_style(self): + """This is a docstring.""" + raise RuntimeError("hi") + + +def test_ignores_raise_uninferable(self): + """This is a docstring. + + :raises NameError: Never + """ + raise Unknown("hi") + raise NameError("hi") # [unreachable] + + +def test_ignores_returns_from_inner_functions(self): # [missing-raises-doc] + """This is a docstring. + We do NOT expect a warning about the OSError in inner_func! + + :raises NameError: Never + """ + + def ex_func(val): + def inner_func(value): + return OSError(value) + + return RuntimeError(val) + + raise ex_func("hi") + raise NameError("hi") # [unreachable] + + +def test_ignores_returns_use_only_names(): + """This is a docstring + + :raises NameError: Never + """ + + def inner_func(): + return 42 + + raise inner_func() # [raising-bad-type] + + +def test_ignores_returns_use_only_exception_instances(): + """This is a docstring + + :raises MyException: Never + """ + + class MyException(Exception): + """A docstring""" + + def inner_func(): + return MyException + + raise inner_func() + + +def test_no_crash_when_inferring_handlers(): + """raises + + :raise U: pass + """ + try: + pass + except collections.U as exc: + raise + + +def test_no_crash_when_cant_find_exception(): + """raises + + :raise U: pass + """ + try: + pass + except U as exc: + raise + + +def test_no_error_notimplemented_documented(): + """ + Raises: + NotImplementedError: When called. + """ + raise NotImplementedError + + +def test_finds_short_name_exception(): + """Do something. + + Raises: + ~fake_package.exceptions.BadError: When something bad happened. + """ + raise BadError("A bad thing happened.") diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc.rc new file mode 100644 index 0000000000000000000000000000000000000000..4547f981174750f49bb673c8ad468fcff986a03f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins = pylint.extensions.docparams diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc.txt new file mode 100644 index 0000000000000000000000000000000000000000..d770776ef9c22ce5b51003520afc2a7794aeed15 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc.txt @@ -0,0 +1,4 @@ +unreachable:25:4:25:25:test_ignores_raise_uninferable:Unreachable code:HIGH +missing-raises-doc:28:0:28:45:test_ignores_returns_from_inner_functions:"""RuntimeError"" not documented as being raised":HIGH +unreachable:42:4:42:25:test_ignores_returns_from_inner_functions:Unreachable code:HIGH +raising-bad-type:54:4:54:22:test_ignores_returns_use_only_names:Raising int while only classes or instances are allowed:INFERENCE diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Google.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Google.py new file mode 100644 index 0000000000000000000000000000000000000000..22dbcadaa388c9307556cb74f068f2204b5c164c --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Google.py @@ -0,0 +1,192 @@ +"""Tests for missing-raises-doc and missing-raises-type-doc for Google style docstrings""" +# pylint: disable=function-redefined, invalid-name, undefined-variable, missing-function-docstring +# pylint: disable=unused-argument, import-outside-toplevel, import-error, try-except-raise, too-few-public-methods + + +def test_find_missing_google_raises(self): # [missing-raises-doc] + """This is a Google docstring. + + Raises: + NameError: Never + """ + raise RuntimeError("hi") + raise NameError("hi") # [unreachable] + + +def test_find_google_attr_raises_exact_exc(self): + """This is a google docstring. + + Raises: + re.error: Sometimes + """ + import re + + raise re.error("hi") + + +def test_find_google_attr_raises_substr_exc(self): + """This is a google docstring. + + Raises: + re.error: Sometimes + """ + from re import error + + raise error("hi") + + +def test_find_valid_missing_google_attr_raises(self): # [missing-raises-doc] + """This is a google docstring. + + Raises: + re.anothererror: Sometimes + """ + from re import error + + raise error("hi") + + +def test_find_invalid_missing_google_attr_raises(self): + """This is a google docstring. + pylint allows this to pass since the comparison between Raises and + raise are based on the class name, not the qualified name. + + Raises: + bogusmodule.error: Sometimes + """ + from re import error + + raise error("hi") + + +def test_google_raises_local_reference(self): + """This is a google docstring. + pylint allows this to pass since the comparison between Raises and + raise are based on the class name, not the qualified name. + + Raises: + .LocalException: Always + """ + from neighbor_module import LocalException + + raise LocalException("hi") + + +def test_find_all_google_raises(self): + """This is a Google docstring. + + Raises: + RuntimeError: Always + NameError: Never + """ + raise RuntimeError("hi") + raise NameError("hi") # [unreachable] + + +def test_find_multiple_google_raises(self): + """This is a Google docstring. + + Raises: + RuntimeError: Always + NameError, OSError, ValueError: Never + """ + raise RuntimeError("hi") + raise NameError("hi") # [unreachable] + raise OSError(2, "abort!") # [unreachable] + raise ValueError("foo") # [unreachable] + + +def test_find_rethrown_google_raises(self): # [missing-raises-doc] + """This is a Google docstring. + + Raises: + NameError: Sometimes + """ + try: + fake_func() + except RuntimeError: + raise + + raise NameError("hi") + + +def test_find_rethrown_google_multiple_raises(self): # [missing-raises-doc] + """This is a Google docstring. + + Raises: + NameError: Sometimes + """ + try: + fake_func() + except (RuntimeError, ValueError): + raise + + raise NameError("hi") + + +def test_ignores_caught_google_raises(self): + """This is a Google docstring. + + Raises: + NameError: Sometimes + """ + try: + raise RuntimeError("hi") + except RuntimeError: + pass + + raise NameError("hi") + + +class Foo: + """test_finds_missing_raises_from_setter_google + Example of a setter having missing raises documentation in + the Google style docstring of the property + """ + + @property + def foo_method(self): # [missing-raises-doc] + """int: docstring + + Include a "Raises" section so that this is identified + as a Google docstring and not a Numpy docstring. + + Raises: + RuntimeError: Always + """ + raise RuntimeError() + return 10 # [unreachable] + + @foo_method.setter + def foo_method(self, value): + print(self) + raise AttributeError() + + +class Foo: + """test_finds_missing_raises_from_setter_google_2 + Example of a setter having missing raises documentation in + its own Google style docstring of the property. + """ + + @property + def foo_method(self): + """int: docstring ... + + Raises: + RuntimeError: Always + """ + raise RuntimeError() + return 10 # [unreachable] + + @foo_method.setter + def foo_method(self, value): # [missing-raises-doc] + """setter docstring ... + + Raises: + RuntimeError: Never + """ + print(self) + if True: # [using-constant-test] + raise AttributeError() + raise RuntimeError() diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Google.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Google.rc new file mode 100644 index 0000000000000000000000000000000000000000..4547f981174750f49bb673c8ad468fcff986a03f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Google.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins = pylint.extensions.docparams diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Google.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Google.txt new file mode 100644 index 0000000000000000000000000000000000000000..f59d27176976b3bb333ff35a9905b28fbc7ca6d9 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Google.txt @@ -0,0 +1,14 @@ +missing-raises-doc:6:0:6:35:test_find_missing_google_raises:"""RuntimeError"" not documented as being raised":HIGH +unreachable:13:4:13:25:test_find_missing_google_raises:Unreachable code:HIGH +missing-raises-doc:38:0:38:46:test_find_valid_missing_google_attr_raises:"""error"" not documented as being raised":HIGH +unreachable:83:4:83:25:test_find_all_google_raises:Unreachable code:HIGH +unreachable:94:4:94:25:test_find_multiple_google_raises:Unreachable code:HIGH +unreachable:95:4:95:30:test_find_multiple_google_raises:Unreachable code:HIGH +unreachable:96:4:96:27:test_find_multiple_google_raises:Unreachable code:HIGH +missing-raises-doc:99:0:99:36:test_find_rethrown_google_raises:"""RuntimeError"" not documented as being raised":HIGH +missing-raises-doc:113:0:113:45:test_find_rethrown_google_multiple_raises:"""RuntimeError, ValueError"" not documented as being raised":HIGH +missing-raises-doc:148:4:148:18:Foo.foo_method:"""AttributeError"" not documented as being raised":HIGH +unreachable:158:8:158:17:Foo.foo_method:Unreachable code:HIGH +unreachable:180:8:180:17:Foo.foo_method:Unreachable code:HIGH +missing-raises-doc:183:4:183:18:Foo.foo_method:"""AttributeError"" not documented as being raised":HIGH +using-constant-test:190:11:190:15:Foo.foo_method:Using a conditional statement with a constant value:INFERENCE diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Numpy.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..8cf8e041f1d4afebaf1c49e87606af8b77d1445c --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Numpy.py @@ -0,0 +1,215 @@ +"""Tests for missing-raises-doc and missing-raises-type-doc for Numpy style docstrings + +Styleguide: +https://numpydoc.readthedocs.io/en/latest/format.html#docstring-standard +""" +# pylint: disable=function-redefined, invalid-name, undefined-variable, missing-function-docstring +# pylint: disable=unused-argument, try-except-raise, import-outside-toplevel +# pylint: disable=too-few-public-methods, disallowed-name, using-constant-test + + +def test_find_missing_numpy_raises(self): # [missing-raises-doc] + """This is a Numpy docstring. + + Raises + ------ + NameError + Never + """ + raise RuntimeError("hi") + raise NameError("hi") # [unreachable] + + +def test_find_all_numpy_raises(self): + """This is a Numpy docstring. + + Raises + ------ + RuntimeError + Always + NameError + Never + """ + raise RuntimeError("hi") + raise NameError("hi") # [unreachable] + + +def test_find_rethrown_numpy_raises(self): # [missing-raises-doc] + """This is a Numpy docstring. + + Raises + ------ + NameError + Sometimes + """ + try: + fake_func() + except RuntimeError: + raise + + raise NameError("hi") + + +def test_find_rethrown_numpy_multiple_raises(self): # [missing-raises-doc] + """This is a Numpy docstring. + + Raises + ------ + NameError + Sometimes + """ + try: + fake_func() + except (RuntimeError, ValueError): + raise + + raise NameError("hi") + + +def test_ignores_caught_numpy_raises(self): + """This is a numpy docstring. + + Raises + ------ + NameError + Sometimes + """ + try: + raise RuntimeError("hi") + except RuntimeError: + pass + + raise NameError("hi") + + +def test_find_numpy_attr_raises_exact_exc(self): + """This is a numpy docstring. + + Raises + ------ + re.error + Sometimes + """ + import re + + raise re.error("hi") + + +def test_find_numpy_attr_raises_substr_exc(self): + """This is a numpy docstring. + + Raises + ------ + re.error + Sometimes + """ + from re import error + + raise error("hi") + + +def test_find_valid_missing_numpy_attr_raises(self): # [missing-raises-doc] + """This is a numpy docstring. + + Raises + ------ + re.anothererror + Sometimes + """ + from re import error + + raise error("hi") + + +def test_find_invalid_missing_numpy_attr_raises(self): + """This is a numpy docstring. + pylint allows this to pass since the comparison between Raises and + raise are based on the class name, not the qualified name. + + Raises + ------ + bogusmodule.error + Sometimes + """ + from re import error + + raise error("hi") + + +class Foo: + """test_finds_missing_raises_from_setter_numpy + Example of a setter having missing raises documentation in + the Numpy style docstring of the property + """ + + @property + def foo(self): # [missing-raises-doc] + """int: docstring + + Include a "Raises" section so that this is identified + as a Numpy docstring and not a Google docstring. + + Raises + ------ + RuntimeError + Always + """ + raise RuntimeError() + return 10 # [unreachable] + + @foo.setter + def foo(self, value): + print(self) + raise AttributeError() + + +class Foo: + """test_finds_missing_raises_from_setter_numpy_2 + Example of a setter having missing raises documentation in + its own Numpy style docstring of the property + """ + + @property + def foo(self): + """int: docstring ... + + Raises + ------ + RuntimeError + Always + """ + raise RuntimeError() + return 10 # [unreachable] + + @foo.setter + def foo(self, value): # [missing-raises-doc] + """setter docstring ... + + Raises + ------ + RuntimeError + Never + """ + print(self) + if True: + raise AttributeError() + raise RuntimeError() + + +class Foo: + """test_finds_property_return_type_numpy + Example of a property having return documentation in + a numpy style docstring + """ + + @property + def foo(self): + """int: docstring ... + + Raises + ------ + RuntimeError + Always + """ + raise RuntimeError() + return 10 # [unreachable] diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Numpy.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Numpy.rc new file mode 100644 index 0000000000000000000000000000000000000000..4547f981174750f49bb673c8ad468fcff986a03f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Numpy.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins = pylint.extensions.docparams diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Numpy.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Numpy.txt new file mode 100644 index 0000000000000000000000000000000000000000..43c6ba89b95df24ce98c27c8c50345d6e194a8d4 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Numpy.txt @@ -0,0 +1,11 @@ +missing-raises-doc:11:0:11:34:test_find_missing_numpy_raises:"""RuntimeError"" not documented as being raised":HIGH +unreachable:20:4:20:25:test_find_missing_numpy_raises:Unreachable code:HIGH +unreachable:34:4:34:25:test_find_all_numpy_raises:Unreachable code:HIGH +missing-raises-doc:37:0:37:35:test_find_rethrown_numpy_raises:"""RuntimeError"" not documented as being raised":HIGH +missing-raises-doc:53:0:53:44:test_find_rethrown_numpy_multiple_raises:"""RuntimeError, ValueError"" not documented as being raised":HIGH +missing-raises-doc:111:0:111:45:test_find_valid_missing_numpy_attr_raises:"""error"" not documented as being raised":HIGH +missing-raises-doc:146:4:146:11:Foo.foo:"""AttributeError"" not documented as being raised":HIGH +unreachable:158:8:158:17:Foo.foo:Unreachable code:HIGH +unreachable:182:8:182:17:Foo.foo:Unreachable code:HIGH +missing-raises-doc:185:4:185:11:Foo.foo:"""AttributeError"" not documented as being raised":HIGH +unreachable:215:8:215:17:Foo.foo:Unreachable code:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Sphinx.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Sphinx.py new file mode 100644 index 0000000000000000000000000000000000000000..91a603b7115b53be254c4500e2b339598b21e28b --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Sphinx.py @@ -0,0 +1,162 @@ +"""Tests for missing-raises-doc and missing-raises-type-doc for Sphinx style docstrings""" +# pylint: disable=function-redefined, invalid-name, undefined-variable, missing-function-docstring +# pylint: disable=unused-argument, try-except-raise, import-outside-toplevel +# pylint: disable=missing-class-docstring, too-few-public-methods + + +def test_find_missing_sphinx_raises(self): # [missing-raises-doc] + """This is a Sphinx docstring. + + :raises NameError: Never + """ + raise RuntimeError("hi") + raise NameError("hi") # [unreachable] + + +def test_ignore_spurious_sphinx_raises(self): + """This is a Sphinx docstring. + + :raises RuntimeError: Always + :except NameError: Never + :raise OSError: Never + :exception ValueError: Never + """ + raise RuntimeError("Blah") + + +def test_find_all_sphinx_raises(self): + """This is a Sphinx docstring. + + :raises RuntimeError: Always + :except NameError: Never + :raise OSError: Never + :exception ValueError: Never + """ + raise RuntimeError("hi") + raise NameError("hi") # [unreachable] + raise OSError(2, "abort!") # [unreachable] + raise ValueError("foo") # [unreachable] + + +def test_find_multiple_sphinx_raises(self): + """This is a Sphinx docstring. + + :raises RuntimeError: Always + :raises NameError, OSError, ValueError: Never + """ + raise RuntimeError("hi") + raise NameError("hi") # [unreachable] + + +def test_finds_rethrown_sphinx_raises(self): # [missing-raises-doc] + """This is a Sphinx docstring. + + :raises NameError: Sometimes + """ + try: + fake_func() + except RuntimeError: + raise + + raise NameError("hi") + + +def test_finds_rethrown_sphinx_multiple_raises(self): # [missing-raises-doc] + """This is a Sphinx docstring. + + :raises NameError: Sometimes + """ + try: + fake_func() + except (RuntimeError, ValueError): + raise + + raise NameError("hi") + + +def test_ignores_caught_sphinx_raises(self): + """This is a Sphinx docstring. + + :raises NameError: Sometimes + """ + try: + raise RuntimeError("hi") + except RuntimeError: + pass + + raise NameError("hi") + + +def test_find_missing_sphinx_raises_infer_from_instance(self): # [missing-raises-doc] + """This is a Sphinx docstring. + + :raises NameError: Never + """ + my_exception = RuntimeError("hi") + raise my_exception + raise NameError("hi") # [unreachable] + + +def test_find_missing_sphinx_raises_infer_from_function(self): # [missing-raises-doc] + """This is a Sphinx docstring. + + :raises NameError: Never + """ + + def ex_func(val): + return RuntimeError(val) + + raise ex_func("hi") + raise NameError("hi") # [unreachable] + + +def test_find_sphinx_attr_raises_exact_exc(self): + """This is a sphinx docstring. + + :raises re.error: Sometimes + """ + import re + + raise re.error("hi") + + +def test_find_sphinx_attr_raises_substr_exc(self): + """This is a sphinx docstring. + + :raises re.error: Sometimes + """ + from re import error + + raise error("hi") + + +def test_find_valid_missing_sphinx_attr_raises(self): # [missing-raises-doc] + """This is a sphinx docstring. + + :raises re.anothererror: Sometimes + """ + from re import error + + raise error("hi") + + +def test_find_invalid_missing_sphinx_attr_raises(self): + """This is a sphinx docstring. + pylint allows this to pass since the comparison between Raises and + raise are based on the class name, not the qualified name. + + :raises bogusmodule.error: Sometimes + """ + from re import error + + raise error("hi") + + +class Foo: + def test_ignores_raise_notimplementederror_sphinx(self, arg): + """docstring ... + + :param arg: An argument. + :type arg: int + """ + raise NotImplementedError() diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Sphinx.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Sphinx.rc new file mode 100644 index 0000000000000000000000000000000000000000..4547f981174750f49bb673c8ad468fcff986a03f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Sphinx.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins = pylint.extensions.docparams diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Sphinx.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Sphinx.txt new file mode 100644 index 0000000000000000000000000000000000000000..599c8beda34237434a4a920fb6e1db70cabae8c8 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_Sphinx.txt @@ -0,0 +1,13 @@ +missing-raises-doc:7:0:7:35:test_find_missing_sphinx_raises:"""RuntimeError"" not documented as being raised":HIGH +unreachable:13:4:13:25:test_find_missing_sphinx_raises:Unreachable code:HIGH +unreachable:36:4:36:25:test_find_all_sphinx_raises:Unreachable code:HIGH +unreachable:37:4:37:30:test_find_all_sphinx_raises:Unreachable code:HIGH +unreachable:38:4:38:27:test_find_all_sphinx_raises:Unreachable code:HIGH +unreachable:48:4:48:25:test_find_multiple_sphinx_raises:Unreachable code:HIGH +missing-raises-doc:51:0:51:37:test_finds_rethrown_sphinx_raises:"""RuntimeError"" not documented as being raised":HIGH +missing-raises-doc:64:0:64:46:test_finds_rethrown_sphinx_multiple_raises:"""RuntimeError, ValueError"" not documented as being raised":HIGH +missing-raises-doc:90:0:90:55:test_find_missing_sphinx_raises_infer_from_instance:"""RuntimeError"" not documented as being raised":HIGH +unreachable:97:4:97:25:test_find_missing_sphinx_raises_infer_from_instance:Unreachable code:HIGH +missing-raises-doc:100:0:100:55:test_find_missing_sphinx_raises_infer_from_function:"""RuntimeError"" not documented as being raised":HIGH +unreachable:110:4:110:25:test_find_missing_sphinx_raises_infer_from_function:Unreachable code:HIGH +missing-raises-doc:133:0:133:46:test_find_valid_missing_sphinx_attr_raises:"""error"" not documented as being raised":HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_options.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_options.py new file mode 100644 index 0000000000000000000000000000000000000000..eb3cd3ac32df6a9b18dd5f3f6bbc0c758f7fd6c5 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_options.py @@ -0,0 +1,15 @@ +"""Minimal example where a W9006 message is displayed even if the +accept-no-raise-doc option is set to True. + +Requires at least one matching section (`Docstring.matching_sections`). + +Taken from https://github.com/PyCQA/pylint/issues/7208 +""" + + +def w9006issue(dummy: int): + """Sample function. + + :param dummy: Unused + """ + raise AssertionError() diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_options.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_options.rc new file mode 100644 index 0000000000000000000000000000000000000000..b36bb87a3064cc0be400b3d9da8984e9cea4eb28 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_options.rc @@ -0,0 +1,5 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-raise-doc = yes diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required.py new file mode 100644 index 0000000000000000000000000000000000000000..96f2297a28729b3eb3f240a77ae7f98d8c102e33 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required.py @@ -0,0 +1,15 @@ +"""Tests for missing-raises-doc and missing-raises-type-doc with accept-no-raise-doc = no""" +# pylint: disable=function-redefined, invalid-name, undefined-variable, missing-function-docstring +# pylint: disable=unused-argument + + +def test_warns_unknown_style(self): # [missing-raises-doc] + """This is a docstring.""" + raise RuntimeError("hi") + + +# This function doesn't require a docstring, because its name starts +# with an '_' (no-docstring-rgx): +def _function(some_arg: int): + """This is a docstring.""" + raise ValueError diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required.rc new file mode 100644 index 0000000000000000000000000000000000000000..40c032f0da9ec334f2388accfa88b9e8b64af030 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required.rc @@ -0,0 +1,5 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-raise-doc=no diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required.txt new file mode 100644 index 0000000000000000000000000000000000000000..6b4c70dc5df0433e650a71040d4e9a38eebd98c2 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required.txt @@ -0,0 +1 @@ +missing-raises-doc:6:0:6:28:test_warns_unknown_style:"""RuntimeError"" not documented as being raised":HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_Google.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_Google.py new file mode 100644 index 0000000000000000000000000000000000000000..f5985347bdd14d456bf572eaccb24b603406a5fc --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_Google.py @@ -0,0 +1,26 @@ +"""Tests for missing-raises-doc and missing-raises-type-doc for Google style docstrings +with accept-no-raise-doc = no""" +# pylint: disable=function-redefined, invalid-name, undefined-variable, missing-function-docstring +# pylint: disable=unused-argument, import-outside-toplevel + + +def test_google_raises_with_prefix_one(self): + """This is a google docstring. + + Raises: + ~re.error: Sometimes + """ + import re + + raise re.error("hi") + + +def test_google_raises_with_prefix_two(self): + """This is a google docstring. + + Raises: + !re.error: Sometimes + """ + import re + + raise re.error("hi") diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_Google.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_Google.rc new file mode 100644 index 0000000000000000000000000000000000000000..40c032f0da9ec334f2388accfa88b9e8b64af030 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_Google.rc @@ -0,0 +1,5 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-raise-doc=no diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_Numpy.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_Numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..1577f96f38175bb31bb2bc7ed90cde35a1612fa5 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_Numpy.py @@ -0,0 +1,30 @@ +"""Tests for missing-raises-doc and missing-raises-type-doc for Numpy style docstrings +with accept-no-raise-doc = no""" +# pylint: disable=function-redefined, invalid-name, undefined-variable, missing-function-docstring +# pylint: disable=unused-argument, import-outside-toplevel + + +def test_numpy_raises_with_prefix_one(self): + """This is a numpy docstring. + + Raises + ------ + ~re.error + Sometimes + """ + import re + + raise re.error("hi") + + +def test_numpy_raises_with_prefix_two(self): + """This is a numpy docstring. + + Raises + ------ + !re.error + Sometimes + """ + import re + + raise re.error("hi") diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_Numpy.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_Numpy.rc new file mode 100644 index 0000000000000000000000000000000000000000..40c032f0da9ec334f2388accfa88b9e8b64af030 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_Numpy.rc @@ -0,0 +1,5 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-raise-doc=no diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_Sphinx.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_Sphinx.py new file mode 100644 index 0000000000000000000000000000000000000000..eee8786808bd5a5a6414497d1cc34d48f70c43f2 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_Sphinx.py @@ -0,0 +1,24 @@ +"""Tests for missing-raises-doc and missing-raises-type-doc for Sphinx style docstrings +with accept-no-raise-doc = no""" +# pylint: disable=function-redefined, invalid-name, undefined-variable, missing-function-docstring +# pylint: disable=unused-argument, import-outside-toplevel + + +def test_sphinx_raises_with_prefix_one(self): + """This is a sphinx docstring. + + :raises ~re.error: Sometimes + """ + import re + + raise re.error("hi") + + +def test_sphinx_raises_with_prefix_two(self): + """This is a sphinx docstring. + + :raises !re.error: Sometimes + """ + import re + + raise re.error("hi") diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_Sphinx.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_Sphinx.rc new file mode 100644 index 0000000000000000000000000000000000000000..40c032f0da9ec334f2388accfa88b9e8b64af030 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_Sphinx.rc @@ -0,0 +1,5 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-raise-doc=no diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_exc_inheritance.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_exc_inheritance.py new file mode 100644 index 0000000000000000000000000000000000000000..16334818d5a7f6c7627e83e574768925f6fb2f45 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_exc_inheritance.py @@ -0,0 +1,45 @@ +"""Tests for missing-raises-doc for exception class inheritance.""" +# pylint: disable=missing-class-docstring + +class CustomError(NameError): + pass + + +class CustomChildError(CustomError): + pass + + +def test_find_missing_raise_for_parent(): # [missing-raises-doc] + """This is a docstring. + + Raises: + CustomError: Never + """ + raise NameError("hi") + + +def test_no_missing_raise_for_child_builtin(): + """This is a docstring. + + Raises: + Exception: Never + """ + raise ValueError("hi") + + +def test_no_missing_raise_for_child_custom(): + """This is a docstring. + + Raises: + NameError: Never + """ + raise CustomError("hi") + + +def test_no_missing_raise_for_child_custom_nested(): + """This is a docstring. + + Raises: + NameError: Never + """ + raise CustomChildError("hi") diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_exc_inheritance.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_exc_inheritance.rc new file mode 100644 index 0000000000000000000000000000000000000000..40c032f0da9ec334f2388accfa88b9e8b64af030 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_exc_inheritance.rc @@ -0,0 +1,5 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-raise-doc=no diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_exc_inheritance.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_exc_inheritance.txt new file mode 100644 index 0000000000000000000000000000000000000000..eceeb438c343262ddbcb4a90b00fe9f40d059134 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/raise/missing_raises_doc_required_exc_inheritance.txt @@ -0,0 +1 @@ +missing-raises-doc:12:0:12:38:test_find_missing_raise_for_parent:"""NameError"" not documented as being raised":HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc.py new file mode 100644 index 0000000000000000000000000000000000000000..f376b808790a41a08154ee76a169bd38ac23079d --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc.py @@ -0,0 +1,12 @@ +"""Tests for missing-return-doc and missing-return-type-doc""" +# pylint: disable=function-redefined, invalid-name, undefined-variable, missing-function-docstring +# pylint: disable=unused-argument + + +def ignores_no_docstring(self): + return False + + +def ignores_unknown_style(self): + """This is a docstring.""" + return False diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc.rc new file mode 100644 index 0000000000000000000000000000000000000000..4547f981174750f49bb673c8ad468fcff986a03f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins = pylint.extensions.docparams diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Google.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Google.py new file mode 100644 index 0000000000000000000000000000000000000000..498dbf1190becabdf808ebe351cf06fc6e43bf5f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Google.py @@ -0,0 +1,175 @@ +"""Tests for missing-return-doc and missing-return-type-doc for Google style docstrings""" +# pylint: disable=function-redefined, invalid-name, undefined-variable, missing-function-docstring +# pylint: disable=unused-argument, too-few-public-methods, unnecessary-pass +import abc + + +def my_func(self): + """find_google_returns + + Returns: + bool: Always False + """ + return False + + +def my_func(self, doc_type): + """ignores_google_return_none + + Args: + doc_type (str): Google + """ + return + + +def my_func(self): + """finds_google_return_custom_class + + Returns: + mymodule.Class: An object + """ + return mymodule.Class() + + +def my_func(self): + """finds_google_return_list_of_custom_class + + Returns: + list(:class:`mymodule.Class`): An object + """ + return [mymodule.Class()] + + +def my_func(self): # [redundant-returns-doc] + """warns_google_redundant_return_doc + + Returns: + One + """ + return None + + +def my_func(self): # [redundant-returns-doc] + """warns_google_redundant_rtype_doc + + Returns: + int: + """ + return None + + +def my_func(self): # [redundant-returns-doc] + """warns_google_redundant_return_doc_yield + + Returns: + int: One + """ + yield 1 + + +def my_func(self): + """ignores_google_redundant_return_doc_multiple_returns + + Returns: + int or None: One, or sometimes None. + """ + if a_func(): + return None + return 1 + + +class Foo: + """test_finds_property_return_type_google + Example of a property having return documentation in + a Google style docstring + """ + + @property + def foo_method(self): + """int: docstring ... + + Raises: + RuntimeError: Always + """ + raise RuntimeError() + return 10 # [unreachable] + + +class Foo: + """test_finds_annotation_property_return_type_google + Example of a property having return documentation in + a Google style docstring + """ + + @property + def foo_method(self) -> int: + """docstring ... + + Raises: + RuntimeError: Always + """ + raise RuntimeError() + return 10 # [unreachable] + + +class Foo: + """test_ignores_return_in_abstract_method_google + Example of an abstract method documenting the return type that an + implementation should return. + """ + + @abc.abstractmethod + def foo_method(self): + """docstring ... + + Returns: + int: Ten + """ + return 10 + + +class Foo: + """test_ignores_return_in_abstract_method_google_2 + Example of a method documenting the return type that an + implementation should return. + """ + + def foo_method(self, arg): + """docstring ... + + Args: + arg (int): An argument. + """ + raise NotImplementedError() + + +class Foo: + """test_ignores_ignored_argument_names_google + Example of a method documenting the return type that an + implementation should return. + """ + + def foo_method(self, arg, _): + """docstring ... + + Args: + arg (int): An argument. + """ + pass + + +class Foo: + """test_useless_docs_ignored_argument_names_google + Example of a method documenting the return type that an + implementation should return. + """ + + def foo_method(self, arg, _, _ignored): # [useless-type-doc, useless-param-doc] + """docstring ... + + Args: + arg (int): An argument. + _ (float): Another argument. + _ignored: Ignored argument. + """ + pass diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Google.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Google.rc new file mode 100644 index 0000000000000000000000000000000000000000..4547f981174750f49bb673c8ad468fcff986a03f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Google.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins = pylint.extensions.docparams diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Google.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Google.txt new file mode 100644 index 0000000000000000000000000000000000000000..3009696a2dc231f80f462f002d87c77587e14583 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Google.txt @@ -0,0 +1,7 @@ +redundant-returns-doc:43:0:43:11:my_func:Redundant returns documentation:HIGH +redundant-returns-doc:52:0:52:11:my_func:Redundant returns documentation:HIGH +redundant-returns-doc:61:0:61:11:my_func:Redundant returns documentation:HIGH +unreachable:95:8:95:17:Foo.foo_method:Unreachable code:HIGH +unreachable:112:8:112:17:Foo.foo_method:Unreachable code:HIGH +useless-param-doc:167:4:167:18:Foo.foo_method:"""_, _ignored"" useless ignored parameter documentation":HIGH +useless-type-doc:167:4:167:18:Foo.foo_method:"""_"" useless ignored parameter type documentation":HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Numpy.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..47f6f4ae07e2e6d89828bec903765bb8f3b85b18 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Numpy.py @@ -0,0 +1,177 @@ +"""Tests for missing-return-doc and missing-return-type-doc for Numpy style docstrings""" +# pylint: disable=function-redefined, invalid-name, undefined-variable, missing-function-docstring +# pylint: disable=unused-argument, too-few-public-methods, disallowed-name +import abc + + +def my_func(self): + """find_numpy_returns + + Returns + ------- + bool + Always False + """ + return False + + +def my_func(self): + """find_numpy_returns_with_of + + Returns + ------- + :obj:`list` of :obj:`str` + List of strings + """ + return ["hi", "bye"] + + +def my_func(self, doc_type): + """ignores_numpy_return_none + + Arguments + --------- + doc_type : str + Numpy + """ + return + + +def my_func(self): + """finds_numpy_return_custom_class + + Returns + ------- + mymodule.Class + An object + """ + return mymodule.Class() + + +def my_func(self): + """finds_numpy_return_list_of_custom_class + + Returns + ------- + list(:class:`mymodule.Class`) + An object + """ + return [mymodule.Class()] + + +def my_func(self): # [redundant-returns-doc] + """warns_numpy_redundant_return_doc + + Returns + ------- + int + One + """ + return None + + +def my_func(self): # [redundant-returns-doc] + """warns_numpy_redundant_rtype_doc + + Returns + ------- + int + """ + return None + + +def my_func(self): + """ignores_numpy_redundant_return_doc_multiple_returns + + Returns + ------- + int + One + None + Sometimes + """ + if a_func(): + return None + return 1 + + +def my_func(self): # [redundant-returns-doc] + """warns_numpy_redundant_return_doc_yield + + Returns + ------- + int + One + """ + yield 1 + + +class Foo: + """test_ignores_return_in_abstract_method_numpy + Example of an abstract method documenting the return type that an + implementation should return.""" + + @abc.abstractmethod + def foo(self): + """docstring ... + + Returns + ------- + int + Ten + """ + return 10 + + +class Foo: + """test_ignores_return_in_abstract_method_numpy_2 + Example of a method documenting the return type that an + implementation should return.""" + + def foo(self, arg): + """docstring ... + + Parameters + ---------- + arg : int + An argument. + """ + raise NotImplementedError() + + +class Foo: + """test_ignores_ignored_argument_names_numpy + Example of a method documenting the return type that an + implementation should return. + """ + + def foo(self, arg, _): + """docstring ... + + Parameters + ---------- + arg : int + An argument. + """ + + +class Foo: + """test_useless_docs_ignored_argument_names_numpy + Example of a method documenting the return type that an + implementation should return. + """ + + def foo(self, arg, _, _ignored): # [useless-type-doc, useless-param-doc] + """docstring ... + + Parameters + ---------- + arg : int + An argument. + + _ : float + Another argument. + + _ignored : + Ignored Argument + """ diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Numpy.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Numpy.rc new file mode 100644 index 0000000000000000000000000000000000000000..4547f981174750f49bb673c8ad468fcff986a03f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Numpy.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins = pylint.extensions.docparams diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Numpy.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Numpy.txt new file mode 100644 index 0000000000000000000000000000000000000000..975d7e5028907a4aceb831c44c7c4ecf3acf9861 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Numpy.txt @@ -0,0 +1,5 @@ +redundant-returns-doc:62:0:62:11:my_func:Redundant returns documentation:HIGH +redundant-returns-doc:73:0:73:11:my_func:Redundant returns documentation:HIGH +redundant-returns-doc:98:0:98:11:my_func:Redundant returns documentation:HIGH +useless-param-doc:164:4:164:11:Foo.foo:"""_, _ignored"" useless ignored parameter documentation":HIGH +useless-type-doc:164:4:164:11:Foo.foo:"""_"" useless ignored parameter type documentation":HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Sphinx.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Sphinx.py new file mode 100644 index 0000000000000000000000000000000000000000..41b0ce1ae5f855b0d29161ffad5919b6d3f61fad --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Sphinx.py @@ -0,0 +1,109 @@ +"""Tests for missing-return-doc and missing-return-type-doc for Sphinx style docstrings""" +# pylint: disable=function-redefined, invalid-name, undefined-variable, missing-function-docstring +# pylint: disable=unused-argument, disallowed-name, too-few-public-methods, missing-class-docstring +# pylint: disable=unnecessary-pass +import abc + + +def my_func(self): + """find_sphinx_returns + + :return: Always False + :rtype: bool + """ + return False + + +def my_func(self, doc_type): + """ignores_sphinx_return_none + + :param doc_type: Sphinx + :type doc_type: str + """ + return + + +def my_func(self): + """finds_sphinx_return_custom_class + + :returns: An object + :rtype: :class:`mymodule.Class` + """ + return mymodule.Class() + + +def my_func(self): + """finds_sphinx_return_list_of_custom_class + + :returns: An object + :rtype: list(:class:`mymodule.Class`) + """ + return [mymodule.Class()] + + +def my_func(self): # [redundant-returns-doc] + """warns_sphinx_redundant_return_doc + + :returns: One + """ + return None + + +def my_func(self): # [redundant-returns-doc] + """warns_sphinx_redundant_rtype_doc + + :rtype: int + """ + return None + + +def my_func(self): + """ignores_sphinx_redundant_return_doc_multiple_returns + + :returns: One + :rtype: int + + :returns: None sometimes + :rtype: None + """ + if a_func(): + return None + return 1 + + +def my_func_with_yield(self): + """ignore_sphinx_redundant_return_doc_yield + + :returns: One + :rtype: generator + """ + for value in range(3): + yield value + + +class Foo: + """test_ignores_return_in_abstract_method_sphinx + Example of an abstract method documenting the return type that an + implementation should return. + """ + + @abc.abstractmethod + def foo(self): + """docstring ... + + :returns: Ten + :rtype: int + """ + return 10 + + +class Foo: + def test_ignores_ignored_argument_names_sphinx(self, arg, _): + """Example of a method documenting the return type that an + implementation should return. + + + :param arg: An argument. + :type arg: int + """ + pass diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Sphinx.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Sphinx.rc new file mode 100644 index 0000000000000000000000000000000000000000..4547f981174750f49bb673c8ad468fcff986a03f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Sphinx.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins = pylint.extensions.docparams diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Sphinx.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Sphinx.txt new file mode 100644 index 0000000000000000000000000000000000000000..30e1817fd8ae536e0fe714d9dc156b6972d0419e --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_Sphinx.txt @@ -0,0 +1,2 @@ +redundant-returns-doc:44:0:44:11:my_func:Redundant returns documentation:HIGH +redundant-returns-doc:52:0:52:11:my_func:Redundant returns documentation:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required.py new file mode 100644 index 0000000000000000000000000000000000000000..bd56e7e070005b2aee928b1c02333d5441c30123 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required.py @@ -0,0 +1,14 @@ +"""Tests for missing-return-doc and missing-return-type-doc with accept-no-returns-doc = no""" +# pylint: disable=function-redefined, invalid-name, undefined-variable, missing-function-docstring +# pylint: disable=unused-argument + + +def warns_no_docstring(self): # [missing-return-doc, missing-return-type-doc] + return False + + +# this function doesn't require a docstring, because its name starts +# with an '_' (no-docstring-rgx): +def _function(some_arg: int) -> int: + _ = some_arg + return 0 diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required.rc new file mode 100644 index 0000000000000000000000000000000000000000..460cbb3df3e498e427119660a489d482f1340394 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required.rc @@ -0,0 +1,5 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-return-doc=no diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required.txt new file mode 100644 index 0000000000000000000000000000000000000000..871628b1db488d14c79495386d9e2fffcb0974d1 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required.txt @@ -0,0 +1,2 @@ +missing-return-doc:6:0:6:22:warns_no_docstring:Missing return documentation:HIGH +missing-return-type-doc:6:0:6:22:warns_no_docstring:Missing return type documentation:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Google.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Google.py new file mode 100644 index 0000000000000000000000000000000000000000..37546b34f9809d96e80f8b37f16e478ac9fb97be --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Google.py @@ -0,0 +1,74 @@ +"""Tests for missing-return-doc and missing-return-type-doc for Google style docstrings +with accept-no-returns-doc = no""" +# pylint: disable=function-redefined, invalid-name, undefined-variable, missing-function-docstring +# pylint: disable=unused-argument, too-few-public-methods + + +def my_func(self): # [missing-return-type-doc] + """Warn partial google returns + + Returns: + Always False + """ + return False + + +def my_func(self): # [missing-return-doc] + """warn_partial_google_returns_type + + Returns: + bool: + """ + return False + + +def my_func(self, doc_type): # [missing-return-doc, missing-return-type-doc] + """warn_missing_google_returns + + Parameters: + doc_type (str): Google + """ + return False + + +def my_func(self): # [missing-return-doc] + """warns_google_return_list_of_custom_class_without_description + + Returns: + list(:class:`mymodule.Class`): + """ + return [mymodule.Class()] + + +class Foo: + """test_finds_missing_property_return_type_google + Example of a property having return documentation in + a Google style docstring + """ + + @property + def foo_method(self): # [missing-return-type-doc] + """docstring ... + + Raises: + RuntimeError: Always + """ + raise RuntimeError() + return 10 # [unreachable] + + +class Foo: + """test_ignores_non_property_return_type_google + Example of a class function trying to use `type` as return + documentation in a Google style docstring + """ + + def foo_method(self): # [missing-return-doc, missing-return-type-doc] + """int: docstring ... + + Raises: + RuntimeError: Always + """ + print(self) + raise RuntimeError() + return 10 # [unreachable] diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Google.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Google.rc new file mode 100644 index 0000000000000000000000000000000000000000..460cbb3df3e498e427119660a489d482f1340394 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Google.rc @@ -0,0 +1,5 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-return-doc=no diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Google.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Google.txt new file mode 100644 index 0000000000000000000000000000000000000000..eea513b3f506175262e4e3b4e1ed6abf92915172 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Google.txt @@ -0,0 +1,10 @@ +missing-return-type-doc:7:0:7:11:my_func:Missing return type documentation:HIGH +missing-return-doc:16:0:16:11:my_func:Missing return documentation:HIGH +missing-return-doc:25:0:25:11:my_func:Missing return documentation:HIGH +missing-return-type-doc:25:0:25:11:my_func:Missing return type documentation:HIGH +missing-return-doc:34:0:34:11:my_func:Missing return documentation:HIGH +missing-return-type-doc:50:4:50:18:Foo.foo_method:Missing return type documentation:HIGH +unreachable:57:8:57:17:Foo.foo_method:Unreachable code:HIGH +missing-return-doc:66:4:66:18:Foo.foo_method:Missing return documentation:HIGH +missing-return-type-doc:66:4:66:18:Foo.foo_method:Missing return type documentation:HIGH +unreachable:74:8:74:17:Foo.foo_method:Unreachable code:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Numpy.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..8cc59f0ac11c86fada2a25553b45b79bf9fb182c --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Numpy.py @@ -0,0 +1,97 @@ +"""Tests for missing-return-doc and missing-return-type-doc for Numpy style docstrings +with accept-no-returns-doc = no""" +# pylint: disable=function-redefined, invalid-name, undefined-variable, missing-function-docstring +# pylint: disable=unused-argument, too-few-public-methods + + +def my_func(self, doc_type): # [missing-return-doc] + """warn_partial_numpy_returns_type + + Arguments + --------- + doc_type : str + Numpy + + Returns + ------- + bool + """ + return False + + +def my_func(self, doc_type): # [missing-return-doc, missing-return-type-doc] + """warn_missing_numpy_returns + + Arguments + --------- + doc_type : str + Numpy + """ + return False + + +def my_func(self): # [missing-return-doc] + """warns_numpy_return_list_of_custom_class_without_description + + Returns + ------- + list(:class:`mymodule.Class`) + """ + return [mymodule.Class()] + + +class Foo: + """test_finds_missing_property_return_type_numpy + Example of a property having return documentation in + a numpy style docstring + """ + + @property + def foo_prop(self): # [missing-return-type-doc] + """docstring ... + + Raises + ------ + RuntimeError + Always + """ + raise RuntimeError() + return 10 # [unreachable] + + +class Foo: + """test_ignores_non_property_return_type_numpy + Example of a class function trying to use `type` as return + documentation in a numpy style docstring + """ + + def foo_method(self): # [missing-return-doc, missing-return-type-doc] + """int: docstring ... + + Raises + ------ + RuntimeError + Always + """ + print(self) + raise RuntimeError() + return 10 # [unreachable] + + +class Foo: + """test_non_property_annotation_return_type_numpy + Example of a class function trying to use `type` as return + documentation in a numpy style docstring + """ + + def foo_method(self) -> int: # [missing-return-doc] + """int: docstring ... + + Raises + ------ + RuntimeError + Always + """ + print(self) + raise RuntimeError() + return 10 # [unreachable] diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Numpy.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Numpy.rc new file mode 100644 index 0000000000000000000000000000000000000000..460cbb3df3e498e427119660a489d482f1340394 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Numpy.rc @@ -0,0 +1,5 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-return-doc=no diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Numpy.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Numpy.txt new file mode 100644 index 0000000000000000000000000000000000000000..5be8a6009f0b1f033c8737c7142c3b702af6c777 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Numpy.txt @@ -0,0 +1,11 @@ +missing-return-doc:7:0:7:11:my_func:Missing return documentation:HIGH +missing-return-doc:22:0:22:11:my_func:Missing return documentation:HIGH +missing-return-type-doc:22:0:22:11:my_func:Missing return type documentation:HIGH +missing-return-doc:33:0:33:11:my_func:Missing return documentation:HIGH +missing-return-type-doc:50:4:50:16:Foo.foo_prop:Missing return type documentation:HIGH +unreachable:59:8:59:17:Foo.foo_prop:Unreachable code:HIGH +missing-return-doc:68:4:68:18:Foo.foo_method:Missing return documentation:HIGH +missing-return-type-doc:68:4:68:18:Foo.foo_method:Missing return type documentation:HIGH +unreachable:78:8:78:17:Foo.foo_method:Unreachable code:HIGH +missing-return-doc:87:4:87:18:Foo.foo_method:Missing return documentation:HIGH +unreachable:97:8:97:17:Foo.foo_method:Unreachable code:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Sphinx.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Sphinx.py new file mode 100644 index 0000000000000000000000000000000000000000..8f3d3333bcaed7fbf71d17c375bcf27150f0270e --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Sphinx.py @@ -0,0 +1,79 @@ +"""Tests for missing-return-doc and missing-return-type-doc for Sphinx style docstrings +with accept-no-returns-doc = no""" +# pylint: disable=function-redefined, invalid-name, undefined-variable, missing-function-docstring +# pylint: disable=unused-argument, disallowed-name, too-few-public-methods +# pylint: disable=line-too-long + + +def my_func(self): # [missing-return-type-doc] + """Warn partial sphinx returns + + :returns: Always False + """ + return False + + +def my_func(self) -> bool: + """Sphinx missing return type with annotations + + :returns: Always False + """ + return False + + +def my_func(self): # [missing-return-doc] + """Warn partial sphinx returns type + + :rtype: bool + """ + return False + + +def warn_missing_sphinx_returns( # [missing-return-type-doc, missing-return-doc] + self, doc_type +): + """This is a docstring. + + :param doc_type: Sphinx + :type doc_type: str + """ + return False + + +def my_func(self): # [missing-return-doc] + """warns_sphinx_return_list_of_custom_class_without_description + + :rtype: list(:class:`mymodule.Class`) + """ + return [mymodule.Class()] + + +class Foo: + """test_finds_missing_property_return_type_sphinx + Example of a property having missing return documentation in + a Sphinx style docstring + """ + + @property + def foo(self): # [missing-return-type-doc] + """docstring ... + + :raises RuntimeError: Always + """ + raise RuntimeError() + return 10 # [unreachable] + + +class Foo: + """Example of a class function trying to use `type` as return + documentation in a Sphinx style docstring + """ + + def test_ignores_non_property_return_type_sphinx( # [missing-return-doc, missing-return-type-doc] + self, + ): + """docstring ... + + :type: int + """ + return 10 diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Sphinx.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Sphinx.rc new file mode 100644 index 0000000000000000000000000000000000000000..460cbb3df3e498e427119660a489d482f1340394 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Sphinx.rc @@ -0,0 +1,5 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-return-doc=no diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Sphinx.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Sphinx.txt new file mode 100644 index 0000000000000000000000000000000000000000..216c8643f94f52032ea2053efb2cba66ded28ca4 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/return/missing_return_doc_required_Sphinx.txt @@ -0,0 +1,9 @@ +missing-return-type-doc:8:0:8:11:my_func:Missing return type documentation:HIGH +missing-return-doc:24:0:24:11:my_func:Missing return documentation:HIGH +missing-return-doc:32:0:32:31:warn_missing_sphinx_returns:Missing return documentation:HIGH +missing-return-type-doc:32:0:32:31:warn_missing_sphinx_returns:Missing return type documentation:HIGH +missing-return-doc:43:0:43:11:my_func:Missing return documentation:HIGH +missing-return-type-doc:58:4:58:11:Foo.foo:Missing return type documentation:HIGH +unreachable:64:8:64:17:Foo.foo:Unreachable code:HIGH +missing-return-doc:72:4:72:52:Foo.test_ignores_non_property_return_type_sphinx:Missing return documentation:HIGH +missing-return-type-doc:72:4:72:52:Foo.test_ignores_non_property_return_type_sphinx:Missing return type documentation:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/useless_type_doc.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/useless_type_doc.py new file mode 100644 index 0000000000000000000000000000000000000000..110a7a5f582cb3bd6142fe1a13833e38a24615a7 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/useless_type_doc.py @@ -0,0 +1,73 @@ +#pylint: disable = missing-any-param-doc +"""demonstrate FP with useless-type-doc""" + + +def function(public_param: int, _some_private_param: bool = False) -> None: + """does things + + Args: + public_param: an ordinary parameter + """ + for _ in range(public_param): + ... + if _some_private_param: + ... + else: + ... + + +def smart_function(public_param: int, _some_private_param: bool = False) -> None: + """We're speaking about _some_private_param without really documenting it. + + Args: + public_param: an ordinary parameter + """ + for _ in range(public_param): + ... + if _some_private_param: + ... + else: + ... + + +# +1: [useless-type-doc,useless-param-doc] +def function_useless_doc(public_param: int, _some_private_param: bool = False) -> None: + """does things + + Args: + public_param: an ordinary parameter + _some_private_param (bool): private param + + """ + for _ in range(public_param): + ... + if _some_private_param: + ... + else: + ... + + +def test(_new: str) -> str: + """foobar + + :return: comment + """ + return "" + + +def smarter_test(_new: str) -> str: + """We're speaking about _new without really documenting it. + + :return: comment + """ + return "" + + +# +1: [useless-type-doc,useless-param-doc] +def test_two(_new: str) -> str: + """foobar + + :param str _new: + :return: comment + """ + return "" diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/useless_type_doc.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/useless_type_doc.rc new file mode 100644 index 0000000000000000000000000000000000000000..2e63824f632a0f09eb3e9e7a2a84c2a3bd670ec2 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/useless_type_doc.rc @@ -0,0 +1,8 @@ +[MAIN] +load-plugins=pylint.extensions.docparams, + +[PARAMETER_DOCUMENTATION] +accept-no-param-doc=no +accept-no-raise-doc=no +accept-no-return-doc=no +accept-no-yields-doc=no diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/useless_type_doc.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/useless_type_doc.txt new file mode 100644 index 0000000000000000000000000000000000000000..cc6b7148d6019238aa7afe215a908b2c9527cbfc --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/useless_type_doc.txt @@ -0,0 +1,4 @@ +useless-param-doc:34:0:34:24:function_useless_doc:"""_some_private_param"" useless ignored parameter documentation":HIGH +useless-type-doc:34:0:34:24:function_useless_doc:"""_some_private_param"" useless ignored parameter type documentation":HIGH +useless-param-doc:67:0:67:12:test_two:"""_new"" useless ignored parameter documentation":HIGH +useless-type-doc:67:0:67:12:test_two:"""_new"" useless ignored parameter type documentation":HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc.py new file mode 100644 index 0000000000000000000000000000000000000000..331b7f9bf50f98309fb488f77dd3a0b4db14fd22 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc.py @@ -0,0 +1,12 @@ +"""Tests for missing-yield-doc and missing-yield-type-doc""" +# pylint: disable=missing-function-docstring, unused-argument, function-redefined + +# Ignore no docstring +def my_func(self): + yield False + + +# Ignore unrecognized style docstring +def my_func(self): + """This is a docstring.""" + yield False diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc.rc new file mode 100644 index 0000000000000000000000000000000000000000..4547f981174750f49bb673c8ad468fcff986a03f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins = pylint.extensions.docparams diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Google.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Google.py new file mode 100644 index 0000000000000000000000000000000000000000..9ebfbb30b070c5aa6378b57741fb2f31a7a384dd --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Google.py @@ -0,0 +1,35 @@ +"""Tests for missing-yield-doc and missing-yield-type-doc for Google style docstrings""" +# pylint: disable=missing-function-docstring, unused-argument, function-redefined +# pylint: disable=invalid-name, undefined-variable +import typing + + +# Test redundant yields docstring variants +def my_func(self): + """This is a docstring. + + Yields: + int or None: One, or sometimes None. + """ + if a_func(): + yield None + yield 1 + + +def my_func(self): # [redundant-yields-doc] + """This is a docstring. + + Yields: + int: One + """ + return 1 + + +# Test missing yields typing docstring +def generator() -> typing.Iterator[int]: + """A simple function for checking type hints. + + Yields: + The number 0 + """ + yield 0 diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Google.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Google.rc new file mode 100644 index 0000000000000000000000000000000000000000..4547f981174750f49bb673c8ad468fcff986a03f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Google.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins = pylint.extensions.docparams diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Google.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Google.txt new file mode 100644 index 0000000000000000000000000000000000000000..8315f89bbc1117810ef08aee0236d54b9c6df31c --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Google.txt @@ -0,0 +1 @@ +redundant-yields-doc:19:0:19:11:my_func:Redundant yields documentation:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Numpy.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..ed827550b3fe7e4ee1af9d5098edffa679946c62 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Numpy.py @@ -0,0 +1,30 @@ +"""Tests for missing-yield-doc and missing-yield-type-doc for Numpy style docstrings""" +# pylint: disable=missing-function-docstring, unused-argument, function-redefined +# pylint: disable=invalid-name, undefined-variable + + +# Test redundant yields docstring variants +def my_func(self): + """This is a docstring. + + Yields + ------- + int + One + None + Sometimes + """ + if a_func(): + yield None + yield 1 + + +def my_func(self): # [redundant-yields-doc] + """This is a docstring. + + Yields + ------- + int + One + """ + return 1 diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Numpy.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Numpy.rc new file mode 100644 index 0000000000000000000000000000000000000000..4547f981174750f49bb673c8ad468fcff986a03f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Numpy.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins = pylint.extensions.docparams diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Numpy.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Numpy.txt new file mode 100644 index 0000000000000000000000000000000000000000..1324cb5dc70c5d241eda0f35c9ba6e8a283478ae --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Numpy.txt @@ -0,0 +1 @@ +redundant-yields-doc:22:0:22:11:my_func:Redundant yields documentation:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Sphinx.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Sphinx.py new file mode 100644 index 0000000000000000000000000000000000000000..850c8b128029d718d1d8efec7cce7f3e9b765870 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Sphinx.py @@ -0,0 +1,13 @@ +"""Tests for missing-yield-doc and missing-yield-type-doc for Sphinx style docstrings""" +# pylint: disable=missing-function-docstring, unused-argument, function-redefined +# pylint: disable=invalid-name, undefined-variable +import typing + + +# Test missing yields typing docstring +def generator() -> typing.Iterator[int]: + """A simple function for checking type hints. + + :returns: The number 0 + """ + yield 0 diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Sphinx.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Sphinx.rc new file mode 100644 index 0000000000000000000000000000000000000000..4547f981174750f49bb673c8ad468fcff986a03f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_Sphinx.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins = pylint.extensions.docparams diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required.py new file mode 100644 index 0000000000000000000000000000000000000000..bfaae4f03cec0bbb14fccb78fc2ee6c7c6d41050 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required.py @@ -0,0 +1,15 @@ +"""Tests for missing-yield-doc and missing-yield-type-doc with accept-no-yields-doc = no""" +# pylint: disable=missing-function-docstring, unused-argument, function-redefined + +from typing import Iterator + + +# Test missing docstring +def my_func(self): # [missing-yield-doc, missing-yield-type-doc] + yield False + + +# This function doesn't require a docstring, because its name starts +# with an '_' (no-docstring-rgx): +def _function(some_arg: int) -> Iterator[int]: + yield some_arg diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required.rc new file mode 100644 index 0000000000000000000000000000000000000000..0c0b547953c7c8ee8ea6db839462a67badd47b27 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required.rc @@ -0,0 +1,5 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-yields-doc=no diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required.txt new file mode 100644 index 0000000000000000000000000000000000000000..c7bd4b0333596de5dccb0a084d00794b603d589d --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required.txt @@ -0,0 +1,2 @@ +missing-yield-doc:8:0:8:11:my_func:Missing yield documentation:HIGH +missing-yield-type-doc:8:0:8:11:my_func:Missing yield type documentation:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Google.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Google.py new file mode 100644 index 0000000000000000000000000000000000000000..b9a16d1c6ed5851ff9895d460d07dbecdb03838d --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Google.py @@ -0,0 +1,67 @@ +"""Tests for missing-yield-doc and missing-yield-type-doc for Google style docstrings +with accept-no-yields-doc = no""" +# pylint: disable=missing-function-docstring, unused-argument, function-redefined +# pylint: disable=invalid-name, undefined-variable + + +def my_func(self): + """This is a docstring. + + Yields: + bool: Always False + """ + yield False + + +def my_func(self): + """This is a docstring. + + Yields: + mymodule.Class: An object + """ + yield mymodule.Class() + + +def my_func(self): + """This is a docstring. + + Yields: + list(:class:`mymodule.Class`): An object + """ + yield [mymodule.Class()] + + +def my_func(self): # [missing-yield-doc] + """This is a docstring. + + Yields: + list(:class:`mymodule.Class`): + """ + yield [mymodule.Class()] + + +def my_func(self): # [missing-yield-type-doc] + """This is a docstring. + + Yields: + Always False + """ + yield False + + +def my_func(self): # [missing-yield-doc] + """This is a docstring. + + Yields: + bool: + """ + yield False + + +def my_func(self, doc_type): # [missing-yield-doc, missing-yield-type-doc] + """This is a docstring. + + Parameters: + doc_type (str): Google + """ + yield False diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Google.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Google.rc new file mode 100644 index 0000000000000000000000000000000000000000..0c0b547953c7c8ee8ea6db839462a67badd47b27 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Google.rc @@ -0,0 +1,5 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-yields-doc=no diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Google.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Google.txt new file mode 100644 index 0000000000000000000000000000000000000000..a08ffd329d61fcee5c245315d048e9905452ec14 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Google.txt @@ -0,0 +1,5 @@ +missing-yield-doc:34:0:34:11:my_func:Missing yield documentation:HIGH +missing-yield-type-doc:43:0:43:11:my_func:Missing yield type documentation:HIGH +missing-yield-doc:52:0:52:11:my_func:Missing yield documentation:HIGH +missing-yield-doc:61:0:61:11:my_func:Missing yield documentation:HIGH +missing-yield-type-doc:61:0:61:11:my_func:Missing yield type documentation:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Numpy.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..8b5472a484b3432081a426e9fc770c175b81efc3 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Numpy.py @@ -0,0 +1,58 @@ +"""Tests for missing-yield-doc and missing-yield-type-doc for Numpy style docstrings +with accept-no-yields-doc = no""" +# pylint: disable=missing-function-docstring, unused-argument, function-redefined +# pylint: disable=invalid-name, undefined-variable + + +def my_func(self): + """This is a docstring. + + Yields + ------- + bool + Always False + """ + yield False + + +def my_func(self): + """This is a docstring. + + Yields + ------- + mymodule.Class + An object + """ + yield mymodule.Class() + + +def my_func(self): + """This is a docstring. + + Yields + ------- + list(:class:`mymodule.Class`) + An object + """ + yield [mymodule.Class()] + + +def my_func(self): # [missing-yield-doc] + """This is a docstring. + + Yields + ------- + list(:class:`mymodule.Class`) + """ + yield [mymodule.Class()] + + +def my_func(self, doc_type): # [missing-yield-doc, missing-yield-type-doc] + """This is a docstring. + + Arguments + --------- + doc_type : str + Numpy + """ + yield False diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Numpy.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Numpy.rc new file mode 100644 index 0000000000000000000000000000000000000000..0c0b547953c7c8ee8ea6db839462a67badd47b27 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Numpy.rc @@ -0,0 +1,5 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-yields-doc=no diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Numpy.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Numpy.txt new file mode 100644 index 0000000000000000000000000000000000000000..683dd9912960b517661c0a908aa047e002ddc4dc --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Numpy.txt @@ -0,0 +1,3 @@ +missing-yield-doc:40:0:40:11:my_func:Missing yield documentation:HIGH +missing-yield-doc:50:0:50:11:my_func:Missing yield documentation:HIGH +missing-yield-type-doc:50:0:50:11:my_func:Missing yield type documentation:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Sphinx.py b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Sphinx.py new file mode 100644 index 0000000000000000000000000000000000000000..9378482f4a74578ab811fe137822492c62b8ab14 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Sphinx.py @@ -0,0 +1,65 @@ +"""Tests for missing-yield-doc and missing-yield-type-doc for Sphinx style docstrings +with accept-no-yields-doc = no""" +# pylint: disable=missing-function-docstring, unused-argument, function-redefined +# pylint: disable=invalid-name, undefined-variable + + +# Test Sphinx docstring +def my_func(self): + """This is a docstring. + + :return: Always False + :rtype: bool + """ + yield False + + +def my_func(self): + """This is a docstring. + + :returns: An object + :rtype: :class:`mymodule.Class` + """ + yield mymodule.Class() + + +def my_func(self): + """This is a docstring. + + :returns: An object + :rtype: list(:class:`mymodule.Class`) + """ + yield [mymodule.Class()] + + +def my_func(self): # [missing-yield-doc] + """This is a docstring. + + :rtype: list(:class:`mymodule.Class`) + """ + yield [mymodule.Class()] + + +def my_func(self): # [missing-yield-type-doc] + """This is a docstring. + + :returns: Always False + """ + yield False + + +def my_func(self): # [missing-yield-doc] + """This is a docstring. + + :rtype: bool + """ + yield False + + +def my_func(self, doc_type): # [missing-yield-doc, missing-yield-type-doc] + """This is a docstring. + + :param doc_type: Sphinx + :type doc_type: str + """ + yield False diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Sphinx.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Sphinx.rc new file mode 100644 index 0000000000000000000000000000000000000000..0c0b547953c7c8ee8ea6db839462a67badd47b27 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Sphinx.rc @@ -0,0 +1,5 @@ +[MAIN] +load-plugins = pylint.extensions.docparams + +[BASIC] +accept-no-yields-doc=no diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Sphinx.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Sphinx.txt new file mode 100644 index 0000000000000000000000000000000000000000..f6467a9c199798135964541b187760ab9039c578 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docparams/yield/missing_yield_doc_required_Sphinx.txt @@ -0,0 +1,5 @@ +missing-yield-doc:35:0:35:11:my_func:Missing yield documentation:HIGH +missing-yield-type-doc:43:0:43:11:my_func:Missing yield type documentation:HIGH +missing-yield-doc:51:0:51:11:my_func:Missing yield documentation:HIGH +missing-yield-doc:59:0:59:11:my_func:Missing yield documentation:HIGH +missing-yield-type-doc:59:0:59:11:my_func:Missing yield type documentation:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docstyle/docstyle_first_line_empty.py b/testbed/pylint-dev__pylint/tests/functional/ext/docstyle/docstyle_first_line_empty.py new file mode 100644 index 0000000000000000000000000000000000000000..92d7a5b7fef3dd9357e0a21d376ad65db907a7ee --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docstyle/docstyle_first_line_empty.py @@ -0,0 +1,22 @@ +"""Checks of Dosctrings 'docstring-first-line-empty'""" +# pylint: disable=too-few-public-methods,bad-docstring-quotes + +def check_messages(*messages): # [docstring-first-line-empty] + """ + docstring""" + return messages + + +def function2(): + """Test Ok""" + + +class FFFF: # [docstring-first-line-empty] + """ + Test Docstring First Line Empty + """ + + def method1(self): # [docstring-first-line-empty] + ''' + Test Triple Single Quotes docstring + ''' diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docstyle/docstyle_first_line_empty.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docstyle/docstyle_first_line_empty.rc new file mode 100644 index 0000000000000000000000000000000000000000..9b4edb6214ea21b13733d40fcb26ffc90feef475 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docstyle/docstyle_first_line_empty.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins=pylint.extensions.docstyle, diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docstyle/docstyle_first_line_empty.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docstyle/docstyle_first_line_empty.txt new file mode 100644 index 0000000000000000000000000000000000000000..6113fffaa72b829f02e69d47d9f01aba05da4908 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docstyle/docstyle_first_line_empty.txt @@ -0,0 +1,3 @@ +docstring-first-line-empty:4:0:4:18:check_messages:First line empty in function docstring:HIGH +docstring-first-line-empty:14:0:14:10:FFFF:First line empty in class docstring:HIGH +docstring-first-line-empty:19:4:19:15:FFFF.method1:First line empty in method docstring:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docstyle/docstyle_quotes.rc b/testbed/pylint-dev__pylint/tests/functional/ext/docstyle/docstyle_quotes.rc new file mode 100644 index 0000000000000000000000000000000000000000..9b4edb6214ea21b13733d40fcb26ffc90feef475 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docstyle/docstyle_quotes.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins=pylint.extensions.docstyle, diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/docstyle/docstyle_quotes.txt b/testbed/pylint-dev__pylint/tests/functional/ext/docstyle/docstyle_quotes.txt new file mode 100644 index 0000000000000000000000000000000000000000..a83c3ab282ae61b939097eb80e5ac5bfeb7dec29 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/docstyle/docstyle_quotes.txt @@ -0,0 +1,4 @@ +bad-docstring-quotes:6:4:6:15:FFFF.method1:"Bad docstring quotes in method, expected """""", given '''":HIGH +bad-docstring-quotes:11:4:11:15:FFFF.method2:"Bad docstring quotes in method, expected """""", given """:HIGH +bad-docstring-quotes:14:4:14:15:FFFF.method3:"Bad docstring quotes in method, expected """""", given '":HIGH +bad-docstring-quotes:17:4:17:15:FFFF.method4:"Bad docstring quotes in method, expected """""", given '":HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/empty_comment/empty_comment.py b/testbed/pylint-dev__pylint/tests/functional/ext/empty_comment/empty_comment.py new file mode 100644 index 0000000000000000000000000000000000000000..6adaa4fc15491afc888fd4a4f99a606c9d6b5f75 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/empty_comment/empty_comment.py @@ -0,0 +1,13 @@ +"""empty-comment test-case""" +# +1:[empty-comment] +A = 5 # +# +1:[empty-comment] +# +A = '#' + '1' +# +1:[empty-comment] +print(A) # +print("A=", A) # should not be an error# +# +1:[empty-comment] +A = "#pe\0ace#love#" # +A = "peace#love" # \0 peace'#'''' love#peace'''-'#love'-"peace#love"# +####### diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/empty_comment/empty_comment.rc b/testbed/pylint-dev__pylint/tests/functional/ext/empty_comment/empty_comment.rc new file mode 100644 index 0000000000000000000000000000000000000000..053552640a230ac47d9d3afcd0acccefc9caca14 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/empty_comment/empty_comment.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins=pylint.extensions.empty_comment, diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/empty_comment/empty_comment.txt b/testbed/pylint-dev__pylint/tests/functional/ext/empty_comment/empty_comment.txt new file mode 100644 index 0000000000000000000000000000000000000000..fe5695639ec8d1afdd8acc4a5d1a47d6f8924609 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/empty_comment/empty_comment.txt @@ -0,0 +1,4 @@ +empty-comment:3:0:None:None::Line with empty comment:UNDEFINED +empty-comment:5:0:None:None::Line with empty comment:UNDEFINED +empty-comment:8:0:None:None::Line with empty comment:UNDEFINED +empty-comment:11:0:None:None::Line with empty comment:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/eq_without_hash/eq_without_hash.py b/testbed/pylint-dev__pylint/tests/functional/ext/eq_without_hash/eq_without_hash.py new file mode 100644 index 0000000000000000000000000000000000000000..a28afc97bb2ccb62dd4bb1886f4d55c0653bb0e6 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/eq_without_hash/eq_without_hash.py @@ -0,0 +1,11 @@ +"""Regression test for #5025""" + +# pylint: disable=invalid-name, missing-docstring, too-few-public-methods + + +class AClass: # [eq-without-hash] + def __init__(self) -> None: + self.x = 5 + + def __eq__(self, other: object) -> bool: + return isinstance(other, AClass) and other.x == self.x diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/eq_without_hash/eq_without_hash.rc b/testbed/pylint-dev__pylint/tests/functional/ext/eq_without_hash/eq_without_hash.rc new file mode 100644 index 0000000000000000000000000000000000000000..6e2e015a492a7e2066b613e50b5e80aeb5aee712 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/eq_without_hash/eq_without_hash.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins=pylint.extensions.eq_without_hash, diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/for_any_all/for_any_all.rc b/testbed/pylint-dev__pylint/tests/functional/ext/for_any_all/for_any_all.rc new file mode 100644 index 0000000000000000000000000000000000000000..2fc82079352e4114c0539ee09d5b42c2aba210aa --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/for_any_all/for_any_all.rc @@ -0,0 +1,2 @@ +[MAIN] +load-plugins=pylint.extensions.for_any_all diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/redefined_variable_type/redefined_variable_type.py b/testbed/pylint-dev__pylint/tests/functional/ext/redefined_variable_type/redefined_variable_type.py new file mode 100644 index 0000000000000000000000000000000000000000..1d31bc96832b026436c77fdfec61ffd503012d71 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/redefined_variable_type/redefined_variable_type.py @@ -0,0 +1,110 @@ +"""Checks variable types aren't redefined within a method or a function""" + +# pylint: disable=too-few-public-methods,missing-docstring,unused-variable,invalid-name + +_OK = True + +class MyClass: + + class Klass: + def __init__(self): + self.var2 = 'var' + + def __init__(self): + self.var = True + self.var1 = 2 + self.var2 = 1. + self.var1 = 2. # [redefined-variable-type] + self.a_str = "hello" + a_str = False + (a_str, b_str) = (1, 2) # no support for inference on tuple assignment + a_str = 2.0 if self.var else 1.0 # [redefined-variable-type] + + def _getter(self): + return self.a_str + def _setter(self, val): + self.a_str = val + var2 = property(_getter, _setter) + + def some_method(self): + def func(): + var = 1 + test = 'bar' + var = 'baz' # [redefined-variable-type] + self.var = 1 # the rule checks for redefinitions in the scope of a function or method + test = 'foo' + myint = 2 + myint = False # [redefined-variable-type] + +_OK = "This is OK" # [redefined-variable-type] + +if _OK: + SOME_FLOAT = 1. + +def dummy_function(): + return 2 + +def other_function(): + instance = MyClass() + instance = True # [redefined-variable-type] + +SOME_FLOAT = dummy_function() # [redefined-variable-type] + +A_GLOB = None +A_GLOB = [1, 2, 3] + +def func2(x): + if x: + var = 'foo' + else: + var = True + + if x: + var2 = 'foo' + elif not x: + var2 = 2 + else: + pass + + if x: + var3 = 'foo' + var3 = 2 # [redefined-variable-type] + else: + pass + + var = 2 # [redefined-variable-type] + + if x: + pass + elif not x: + var4 = True + elif _OK: + pass + else: + var4 = 2. + var4 = 'baz' # [redefined-variable-type] + + +# Test that ``redefined-variable-type`` is not emitted +# https://github.com/PyCQA/pylint/issues/8120 + +async def test_a(): + data = [ + {'test': 1}, + {'test': 2}, + ] + return data + +async def test_b(): + data = {'test': 1} + return data + + +class AsyncFunctions: + async def funtion1(self): + potato = 1 + print(potato) + + async def funtion2(self): + potato = {} + print(potato) diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/redundant_typehint_argument.py b/testbed/pylint-dev__pylint/tests/functional/ext/typing/redundant_typehint_argument.py new file mode 100644 index 0000000000000000000000000000000000000000..fe2cc4a2ec96e0dd34aa9f39554be71eb10a880f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/redundant_typehint_argument.py @@ -0,0 +1,34 @@ +"""Checks for redundant Union typehints in assignments""" +# pylint: disable=deprecated-typing-alias,consider-alternative-union-syntax,consider-using-alias,invalid-name,unused-argument,missing-function-docstring + +from __future__ import annotations +from typing import Union, Optional, Sequence + +# +1: [redundant-typehint-argument, redundant-typehint-argument] +ANSWER_0: Union[int, int, str, bool, float, str] = 0 +ANSWER_1: Optional[int] = 1 +ANSWER_2: Sequence[int] = [2] +ANSWER_3: Union[list[int], str, int, bool, list[int]] = 3 # [redundant-typehint-argument] +ANSWER_4: Optional[None] = None # [redundant-typehint-argument] +ANSWER_5: Optional[list[int]] = None +ANSWER_6: Union[None, None] = None # [redundant-typehint-argument] +# +1: [redundant-typehint-argument] +ANSWER_7: Union[list[int], dict[int], dict[list[int]], list[str], list[str]] = [7] +ANSWER_8: int | int = 8 # [redundant-typehint-argument] +ANSWER_9: str | int | None | int | bool = 9 # [redundant-typehint-argument] +ANSWER_10: dict | list[int] | float | str | int | bool = 10 +# +1: [redundant-typehint-argument] +ANSWER_11: list[int] | dict[int] | dict[list[int]] | list[str] | list[str] = ['string'] + +# Multiple warnings for the same repeated type +# +1: [redundant-typehint-argument, redundant-typehint-argument, redundant-typehint-argument] +x: int | int | int | int + +# No warning for redundant types in compound type (yet !) +z: dict[int | int, str | str] + +# +1: [redundant-typehint-argument] +zz: dict[int | int, str | str] | dict[int | int, str | str] + +# No warnings for redundant types in function signature (yet !) +def f(p: int | int) -> str | str: ... diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/redundant_typehint_argument.rc b/testbed/pylint-dev__pylint/tests/functional/ext/typing/redundant_typehint_argument.rc new file mode 100644 index 0000000000000000000000000000000000000000..7ffc1704bb1f2a23bb2757265cd4fc38f5845d41 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/redundant_typehint_argument.rc @@ -0,0 +1,8 @@ +[main] +load-plugins=pylint.extensions.typing + +[testoptions] +min_pyver=3.7 + +[TYPING] +runtime-typing=no diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/redundant_typehint_argument.txt b/testbed/pylint-dev__pylint/tests/functional/ext/typing/redundant_typehint_argument.txt new file mode 100644 index 0000000000000000000000000000000000000000..cf4bb78c2161006283b29b597ad4f4925533c04d --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/redundant_typehint_argument.txt @@ -0,0 +1,13 @@ +redundant-typehint-argument:8:0:8:52::Type `int` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:8:0:8:52::Type `str` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:11:0:11:57::Type `list[int]` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:12:10:12:24::Type `None` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:14:0:14:34::Type `None` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:16:0:16:82::Type `list[str]` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:17:0:17:23::Type `int` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:18:0:18:43::Type `int` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:21:0:21:87::Type `list[str]` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:25:0:25:24::Type `int` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:25:0:25:24::Type `int` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:25:0:25:24::Type `int` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:31:0:31:59::Type `dict[int | int, str | str]` is used more than once in union type annotation. Remove redundant typehints.:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/redundant_typehint_argument_py310.py b/testbed/pylint-dev__pylint/tests/functional/ext/typing/redundant_typehint_argument_py310.py new file mode 100644 index 0000000000000000000000000000000000000000..72a4cc8366352b108b58ad1dfc373c67f44bea50 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/redundant_typehint_argument_py310.py @@ -0,0 +1,40 @@ +"""Checks for redundant Union typehints in assignments""" +# pylint: disable=deprecated-typing-alias,consider-alternative-union-syntax,consider-using-alias,invalid-name,unused-argument,missing-function-docstring + +from __future__ import annotations +from typing import Union, Optional, Sequence + +# +1: [redundant-typehint-argument, redundant-typehint-argument] +ANSWER_0: Union[int, int, str, bool, float, str] = 0 +ANSWER_1: Optional[int] = 1 +ANSWER_2: Sequence[int] = [2] +ANSWER_3: Union[list[int], str, int, bool, list[int]] = 3 # [redundant-typehint-argument] +ANSWER_4: Optional[None] = None # [redundant-typehint-argument] +ANSWER_5: Optional[list[int]] = None +ANSWER_6: Union[None, None] = None # [redundant-typehint-argument] +# +1: [redundant-typehint-argument] +ANSWER_7: Union[list[int], dict[int], dict[list[int]], list[str], list[str]] = [7] +ANSWER_8: int | int = 8 # [redundant-typehint-argument] +ANSWER_9: str | int | None | int | bool = 9 # [redundant-typehint-argument] +ANSWER_10: dict | list[int] | float | str | int | bool = 10 +# +1: [redundant-typehint-argument] +ANSWER_11: list[int] | dict[int] | dict[list[int]] | list[str] | list[str] = ['string'] + +# Multiple warnings for the same repeated type +# +1: [redundant-typehint-argument, redundant-typehint-argument, redundant-typehint-argument] +x: int | int | int | int + +# No warning for type alias (yet !) +Q = int | int +QQ = Q | Q + +q: Q | Q # [redundant-typehint-argument] + +# No warning for redundant types in compound type (yet !) +z: dict[int | int, str | str] + +# +1: [redundant-typehint-argument] +zz: dict[int | int, str | str] | dict[int | int, str | str] + +# No warnings for redundant types in function signature (yet !) +def f(p: int | int) -> str | str: ... diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/redundant_typehint_argument_py310.rc b/testbed/pylint-dev__pylint/tests/functional/ext/typing/redundant_typehint_argument_py310.rc new file mode 100644 index 0000000000000000000000000000000000000000..3c06fa4330a5b87058a37080ff41ee4eb5c23b87 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/redundant_typehint_argument_py310.rc @@ -0,0 +1,6 @@ +[main] +py-version=3.10 +load-plugins=pylint.extensions.typing + +[testoptions] +min_pyver=3.10 diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/redundant_typehint_argument_py310.txt b/testbed/pylint-dev__pylint/tests/functional/ext/typing/redundant_typehint_argument_py310.txt new file mode 100644 index 0000000000000000000000000000000000000000..39e5c3591496e54634dc1201709c7a1c12be8b0b --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/redundant_typehint_argument_py310.txt @@ -0,0 +1,14 @@ +redundant-typehint-argument:8:0:8:52::Type `int` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:8:0:8:52::Type `str` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:11:0:11:57::Type `list[int]` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:12:10:12:24::Type `None` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:14:0:14:34::Type `None` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:16:0:16:82::Type `list[str]` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:17:0:17:23::Type `int` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:18:0:18:43::Type `int` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:21:0:21:87::Type `list[str]` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:25:0:25:24::Type `int` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:25:0:25:24::Type `int` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:25:0:25:24::Type `int` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:31:0:31:8::Type `Q` is used more than once in union type annotation. Remove redundant typehints.:HIGH +redundant-typehint-argument:37:0:37:59::Type `dict[int | int, str | str]` is used more than once in union type annotation. Remove redundant typehints.:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable.py b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable.py new file mode 100644 index 0000000000000000000000000000000000000000..0713e17c87ffb0be255ed81ee24225c75ac1cea0 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable.py @@ -0,0 +1,32 @@ +""" +'collections.abc.Callable' is broken inside Optional and Union types for Python 3.9.0 +https://bugs.python.org/issue42965 + +Use 'typing.Callable' instead. +""" +# pylint: disable=missing-docstring,unsubscriptable-object +import collections.abc +from collections.abc import Callable +from typing import TYPE_CHECKING, Optional, Union + +Alias1 = Optional[Callable[[int], None]] # [broken-collections-callable] +Alias2 = Union[Callable[[int], None], None] # [broken-collections-callable] + +Alias3 = Optional[Callable[..., None]] +Alias4 = Union[Callable[..., None], None] +Alias5 = list[Callable[..., None]] +Alias6 = Callable[[int], None] + +if TYPE_CHECKING: + # ok inside TYPE_CHECKING block + Alias7 = Optional[Callable[[int], None]] + + +def func1() -> Optional[Callable[[int], None]]: # [broken-collections-callable] + ... + +def func2() -> Optional["Callable[[int], None]"]: + ... + +def func3() -> Union[collections.abc.Callable[[int], None], None]: # [broken-collections-callable] + ... diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable.rc b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable.rc new file mode 100644 index 0000000000000000000000000000000000000000..5841196f242629513183641c5dac4b2ce4111525 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable.rc @@ -0,0 +1,6 @@ +[main] +py-version=3.9 +load-plugins=pylint.extensions.typing + +[testoptions] +min_pyver=3.7 diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable.txt b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable.txt new file mode 100644 index 0000000000000000000000000000000000000000..6edcf211b26373493feea493d6106968caada3b0 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable.txt @@ -0,0 +1,4 @@ +broken-collections-callable:12:18:12:26::'collections.abc.Callable' inside Optional and Union is broken in 3.9.0 / 3.9.1 (use 'typing.Callable' instead):INFERENCE +broken-collections-callable:13:15:13:23::'collections.abc.Callable' inside Optional and Union is broken in 3.9.0 / 3.9.1 (use 'typing.Callable' instead):INFERENCE +broken-collections-callable:25:24:25:32:func1:'collections.abc.Callable' inside Optional and Union is broken in 3.9.0 / 3.9.1 (use 'typing.Callable' instead):INFERENCE +broken-collections-callable:31:21:31:45:func3:'collections.abc.Callable' inside Optional and Union is broken in 3.9.0 / 3.9.1 (use 'typing.Callable' instead):INFERENCE diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable_deprecated_alias.py b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable_deprecated_alias.py new file mode 100644 index 0000000000000000000000000000000000000000..f01592a59a4b0e453b348717389cb5ab1cbe0821 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable_deprecated_alias.py @@ -0,0 +1,26 @@ +""" +'collections.abc.Callable' is broken inside Optional and Union types for Python 3.9.0 +https://bugs.python.org/issue42965 + +Use 'typing.Callable' instead. + +Don't emit 'deprecated-typing-alias' for 'Callable' if at least one replacement +would create broken instances. +""" +# pylint: disable=missing-docstring,unsubscriptable-object +from typing import Callable, Optional, Union + +Alias1 = Optional[Callable[[int], None]] +Alias2 = Union[Callable[[int], None], None] + +Alias3 = Optional[Callable[..., None]] +Alias4 = Union[Callable[..., None], None] +Alias5 = list[Callable[[int], None]] +Alias6 = Callable[[int], None] + + +def func1() -> Optional[Callable[[int], None]]: + ... + +def func2() -> Optional["Callable[[int], None]"]: + ... diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable_deprecated_alias.rc b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable_deprecated_alias.rc new file mode 100644 index 0000000000000000000000000000000000000000..5841196f242629513183641c5dac4b2ce4111525 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable_deprecated_alias.rc @@ -0,0 +1,6 @@ +[main] +py-version=3.9 +load-plugins=pylint.extensions.typing + +[testoptions] +min_pyver=3.7 diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable_future_import.py b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable_future_import.py new file mode 100644 index 0000000000000000000000000000000000000000..947e060b98649ee3dd2eac0272cd58f7705e4e12 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable_future_import.py @@ -0,0 +1,30 @@ +""" +'collections.abc.Callable' is broken inside Optional and Union types for Python 3.9.0 +https://bugs.python.org/issue42965 + +Use 'typing.Callable' instead. +""" +# pylint: disable=missing-docstring,unsubscriptable-object +from __future__ import annotations + +import collections.abc +from collections.abc import Callable +from typing import Optional, Union + +Alias1 = Optional[Callable[[int], None]] # [broken-collections-callable] +Alias2 = Union[Callable[[int], None], None] # [broken-collections-callable] + +Alias3 = Optional[Callable[..., None]] +Alias4 = Union[Callable[..., None], None] +Alias5 = list[Callable[[int], None]] +Alias6 = Callable[[int], None] + + +def func1() -> Optional[Callable[[int], None]]: + ... + +def func2() -> Optional["Callable[[int], None]"]: + ... + +def func3() -> Union[collections.abc.Callable[[int], None], None]: + ... diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable_future_import.rc b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable_future_import.rc new file mode 100644 index 0000000000000000000000000000000000000000..5841196f242629513183641c5dac4b2ce4111525 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable_future_import.rc @@ -0,0 +1,6 @@ +[main] +py-version=3.9 +load-plugins=pylint.extensions.typing + +[testoptions] +min_pyver=3.7 diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable_future_import.txt b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable_future_import.txt new file mode 100644 index 0000000000000000000000000000000000000000..a3f3553f6a39d828fa63f15a96b08abb0785469c --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_callable_future_import.txt @@ -0,0 +1,2 @@ +broken-collections-callable:14:18:14:26::'collections.abc.Callable' inside Optional and Union is broken in 3.9.0 / 3.9.1 (use 'typing.Callable' instead):INFERENCE +broken-collections-callable:15:15:15:23::'collections.abc.Callable' inside Optional and Union is broken in 3.9.0 / 3.9.1 (use 'typing.Callable' instead):INFERENCE diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn.py b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn.py new file mode 100644 index 0000000000000000000000000000000000000000..e7b5643ae035f80fcf0c49b3fada89970523289c --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn.py @@ -0,0 +1,36 @@ +""" +'typing.NoReturn' is broken inside compound types for Python 3.7.0 +https://bugs.python.org/issue34921 + +If no runtime introspection is required, use string annotations instead. +""" +# pylint: disable=missing-docstring, broad-exception-raised +import typing +from typing import TYPE_CHECKING, Callable, NoReturn, Union + +import typing_extensions + + +def func1() -> NoReturn: + raise Exception + +def func2() -> Union[None, NoReturn]: # [broken-noreturn] + pass + +def func3() -> Union[None, "NoReturn"]: + pass + +def func4() -> Union[None, typing.NoReturn]: # [broken-noreturn] + pass + +def func5() -> Union[None, typing_extensions.NoReturn]: # [broken-noreturn] + pass + + +Alias1 = NoReturn +Alias2 = Callable[..., NoReturn] # [broken-noreturn] +Alias3 = Callable[..., "NoReturn"] + +if TYPE_CHECKING: + # ok inside TYPE_CHECKING block + Alias4 = Callable[..., NoReturn] diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn.rc b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn.rc new file mode 100644 index 0000000000000000000000000000000000000000..eb28fc75b92be3132654e29606fd449d6569ea5a --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn.rc @@ -0,0 +1,3 @@ +[main] +py-version=3.7 +load-plugins=pylint.extensions.typing diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn.txt b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn.txt new file mode 100644 index 0000000000000000000000000000000000000000..ce4503341ff77a4cc426b9b56e04525ea5d7b856 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn.txt @@ -0,0 +1,4 @@ +broken-noreturn:17:27:17:35:func2:'NoReturn' inside compound types is broken in 3.7.0 / 3.7.1:INFERENCE +broken-noreturn:23:27:23:42:func4:'NoReturn' inside compound types is broken in 3.7.0 / 3.7.1:INFERENCE +broken-noreturn:26:27:26:53:func5:'NoReturn' inside compound types is broken in 3.7.0 / 3.7.1:INFERENCE +broken-noreturn:31:23:31:31::'NoReturn' inside compound types is broken in 3.7.0 / 3.7.1:INFERENCE diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn_future_import.py b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn_future_import.py new file mode 100644 index 0000000000000000000000000000000000000000..e0ea7761ba7bace5e3b5f405bf564eee00a15a26 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn_future_import.py @@ -0,0 +1,41 @@ +""" +'typing.NoReturn' is broken inside compond types for Python 3.7.0 +https://bugs.python.org/issue34921 + +If no runtime introspection is required, use string annotations instead. + +With 'from __future__ import annotations', only emit errors for nodes +not in a type annotation context. +""" +# pylint: disable=missing-docstring, broad-exception-raised +from __future__ import annotations + +import typing +from typing import TYPE_CHECKING, Callable, NoReturn, Union + +import typing_extensions + + +def func1() -> NoReturn: + raise Exception + +def func2() -> Union[None, NoReturn]: + pass + +def func3() -> Union[None, "NoReturn"]: + pass + +def func4() -> Union[None, typing.NoReturn]: + pass + +def func5() -> Union[None, typing_extensions.NoReturn]: + pass + + +Alias1 = NoReturn +Alias2 = Callable[..., NoReturn] # [broken-noreturn] +Alias3 = Callable[..., "NoReturn"] + +if TYPE_CHECKING: + # ok inside TYPE_CHECKING block + Alias4 = Callable[..., NoReturn] diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn_future_import.rc b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn_future_import.rc new file mode 100644 index 0000000000000000000000000000000000000000..282a65d62e6ba2a258577d26c2797e9bd67b70ca --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn_future_import.rc @@ -0,0 +1,6 @@ +[main] +py-version=3.7 +load-plugins=pylint.extensions.typing + +[testoptions] +min_pyver=3.7 diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn_future_import.txt b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn_future_import.txt new file mode 100644 index 0000000000000000000000000000000000000000..891a3a4d8b85ce8bbc7ba4b1567c207f76f8153e --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn_future_import.txt @@ -0,0 +1 @@ +broken-noreturn:36:23:36:31::'NoReturn' inside compound types is broken in 3.7.0 / 3.7.1:INFERENCE diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn_py372.py b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn_py372.py new file mode 100644 index 0000000000000000000000000000000000000000..6bd31f0695174264eab9019d179caa4272d4d0c1 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn_py372.py @@ -0,0 +1,38 @@ +""" +'typing.NoReturn' is broken inside compond types for Python 3.7.0 +https://bugs.python.org/issue34921 + +If no runtime introspection is required, use string annotations instead. + +Don't emit errors if py-version set to >= 3.7.2. +""" +# pylint: disable=missing-docstring, broad-exception-raised +import typing +from typing import TYPE_CHECKING, Callable, NoReturn, Union + +import typing_extensions + + +def func1() -> NoReturn: + raise Exception + +def func2() -> Union[None, NoReturn]: + pass + +def func3() -> Union[None, "NoReturn"]: + pass + +def func4() -> Union[None, typing.NoReturn]: + pass + +def func5() -> Union[None, typing_extensions.NoReturn]: + pass + + +Alias1 = NoReturn +Alias2 = Callable[..., NoReturn] +Alias3 = Callable[..., "NoReturn"] + +if TYPE_CHECKING: + # ok inside TYPE_CHECKING block + Alias4 = Callable[..., NoReturn] diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn_py372.rc b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn_py372.rc new file mode 100644 index 0000000000000000000000000000000000000000..236c2fbc7a4f44fdfc9773b2795b29c8dde498c3 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_broken_noreturn_py372.rc @@ -0,0 +1,3 @@ +[main] +py-version=3.7.2 +load-plugins=pylint.extensions.typing diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_alias.py b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_alias.py new file mode 100644 index 0000000000000000000000000000000000000000..8fe3b591868fe921a61502734e0b1acd752d967b --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_alias.py @@ -0,0 +1,75 @@ +"""Test pylint.extension.typing - consider-using-alias + +'py-version' needs to be set to '3.7' or '3.8' and 'runtime-typing=no'. +With 'from __future__ import annotations' present. +""" + +# pylint: disable=missing-docstring,invalid-name,unused-argument,line-too-long,unnecessary-direct-lambda-call + +# Disabled because of a bug with pypy 3.8 see +# https://github.com/PyCQA/pylint/pull/7918#issuecomment-1352737369 +# pylint: disable=multiple-statements + +from __future__ import annotations + +import collections +import collections.abc +import typing +from collections.abc import Awaitable +from dataclasses import dataclass +from typing import Dict, List, Set, Union, TypedDict, Callable, Tuple, Type + +var1: typing.Dict[str, int] # [consider-using-alias] +var2: List[int] # [consider-using-alias] +var3: collections.abc.Iterable[int] +var4: typing.OrderedDict[str, int] # [consider-using-alias] +var5: typing.Awaitable[None] # [consider-using-alias] +var6: typing.Iterable[int] # [consider-using-alias] +var7: typing.Hashable # [consider-using-alias] +var8: typing.ContextManager[str] # [consider-using-alias] +var9: typing.Pattern[str] # [consider-using-alias] +var10: typing.re.Match[str] # [consider-using-alias] +var11: list[int] +var12: collections.abc +var13: Awaitable[None] +var14: collections.defaultdict[str, str] + +Alias1 = Set[int] +Alias2 = Dict[int, List[int]] +Alias3 = Union[int, typing.List[str]] +Alias4 = List # [consider-using-alias] + +var21: Type[object] # [consider-using-alias] +var22: Tuple[str] # [consider-using-alias] +var23: Callable[..., str] # [consider-using-alias] +var31: type[object] +var32: tuple[str] +var33: collections.abc.Callable[..., str] + + +def func1(arg1: List[int], /, *args: List[int], arg2: set[int], **kwargs: Dict[str, int]) -> typing.Tuple[int]: + # -1:[consider-using-alias,consider-using-alias,consider-using-alias,consider-using-alias] + pass + +def func2(arg1: list[int]) -> tuple[int, int]: + pass + +class CustomIntList(typing.List[int]): + pass + +cast_variable = [1, 2, 3] +cast_variable = typing.cast(List[int], cast_variable) + +(lambda x: 2)(List[int]) + +class CustomNamedTuple(typing.NamedTuple): + my_var: List[int] # [consider-using-alias] + +CustomTypedDict1 = TypedDict("CustomTypedDict1", my_var=List[int]) + +class CustomTypedDict2(TypedDict): + my_var: List[int] # [consider-using-alias] + +@dataclass +class CustomDataClass: + my_var: List[int] # [consider-using-alias] diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_alias.rc b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_alias.rc new file mode 100644 index 0000000000000000000000000000000000000000..4e5e75f5d8a07bafd669b4f33da746840f39f7d1 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_alias.rc @@ -0,0 +1,9 @@ +[main] +py-version=3.8 +load-plugins=pylint.extensions.typing + +[testoptions] +min_pyver=3.8 + +[typing] +runtime-typing=no diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_alias.txt b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_alias.txt new file mode 100644 index 0000000000000000000000000000000000000000..2cd299d9043c6acb8090a9735a2a391ce3b48f39 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_alias.txt @@ -0,0 +1,20 @@ +consider-using-alias:22:6:22:17::'typing.Dict' will be deprecated with PY39, consider using 'dict' instead:INFERENCE +consider-using-alias:23:6:23:10::'typing.List' will be deprecated with PY39, consider using 'list' instead:INFERENCE +consider-using-alias:25:6:25:24::'typing.OrderedDict' will be deprecated with PY39, consider using 'collections.OrderedDict' instead:INFERENCE +consider-using-alias:26:6:26:22::'typing.Awaitable' will be deprecated with PY39, consider using 'collections.abc.Awaitable' instead:INFERENCE +consider-using-alias:27:6:27:21::'typing.Iterable' will be deprecated with PY39, consider using 'collections.abc.Iterable' instead:INFERENCE +consider-using-alias:28:6:28:21::'typing.Hashable' will be deprecated with PY39, consider using 'collections.abc.Hashable' instead:INFERENCE +consider-using-alias:29:6:29:27::'typing.ContextManager' will be deprecated with PY39, consider using 'contextlib.AbstractContextManager' instead:INFERENCE +consider-using-alias:30:6:30:20::'typing.Pattern' will be deprecated with PY39, consider using 're.Pattern' instead:INFERENCE +consider-using-alias:31:7:31:22::'typing.Match' will be deprecated with PY39, consider using 're.Match' instead:INFERENCE +consider-using-alias:40:9:40:13::'typing.List' will be deprecated with PY39, consider using 'list' instead:INFERENCE +consider-using-alias:42:7:42:11::'typing.Type' will be deprecated with PY39, consider using 'type' instead:INFERENCE +consider-using-alias:43:7:43:12::'typing.Tuple' will be deprecated with PY39, consider using 'tuple' instead:INFERENCE +consider-using-alias:44:7:44:15::'typing.Callable' will be deprecated with PY39, consider using 'collections.abc.Callable' instead:INFERENCE +consider-using-alias:50:74:50:78:func1:'typing.Dict' will be deprecated with PY39, consider using 'dict' instead:INFERENCE +consider-using-alias:50:16:50:20:func1:'typing.List' will be deprecated with PY39, consider using 'list' instead:INFERENCE +consider-using-alias:50:37:50:41:func1:'typing.List' will be deprecated with PY39, consider using 'list' instead:INFERENCE +consider-using-alias:50:93:50:105:func1:'typing.Tuple' will be deprecated with PY39, consider using 'tuple' instead:INFERENCE +consider-using-alias:66:12:66:16:CustomNamedTuple:'typing.List' will be deprecated with PY39, consider using 'list' instead:INFERENCE +consider-using-alias:71:12:71:16:CustomTypedDict2:'typing.List' will be deprecated with PY39, consider using 'list' instead:INFERENCE +consider-using-alias:75:12:75:16:CustomDataClass:'typing.List' will be deprecated with PY39, consider using 'list' instead:INFERENCE diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_alias_without_future.py b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_alias_without_future.py new file mode 100644 index 0000000000000000000000000000000000000000..943a16188789f48436b213c82c64cc07ee0c5d1c --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_alias_without_future.py @@ -0,0 +1,73 @@ +"""Test pylint.extension.typing - consider-using-alias + +'py-version' needs to be set to '3.7' or '3.8' and 'runtime-typing=no'. +""" + +# pylint: disable=missing-docstring,invalid-name,unused-argument,line-too-long,unsubscriptable-object +# pylint: disable=unnecessary-direct-lambda-call + +# Disabled because of a bug with pypy 3.8 see +# https://github.com/PyCQA/pylint/pull/7918#issuecomment-1352737369 +# pylint: disable=multiple-statements + +import collections +import collections.abc +import typing +from collections.abc import Awaitable +from dataclasses import dataclass +from typing import Dict, List, Set, Union, TypedDict, Callable, Tuple, Type + +var1: typing.Dict[str, int] # [consider-using-alias] +var2: List[int] # [consider-using-alias] +var3: collections.abc.Iterable[int] +var4: typing.OrderedDict[str, int] # [consider-using-alias] +var5: typing.Awaitable[None] # [consider-using-alias] +var6: typing.Iterable[int] # [consider-using-alias] +var7: typing.Hashable # [consider-using-alias] +var8: typing.ContextManager[str] # [consider-using-alias] +var9: typing.Pattern[str] # [consider-using-alias] +var10: typing.re.Match[str] # [consider-using-alias] +var11: list[int] +var12: collections.abc +var13: Awaitable[None] +var14: collections.defaultdict[str, str] + +Alias1 = Set[int] +Alias2 = Dict[int, List[int]] +Alias3 = Union[int, typing.List[str]] +Alias4 = List # [consider-using-alias] + +var21: Type[object] # [consider-using-alias] +var22: Tuple[str] # [consider-using-alias] +var23: Callable[..., str] # [consider-using-alias] +var31: type[object] +var32: tuple[str] +var33: collections.abc.Callable[..., str] + + +def func1(arg1: List[int], /, *args: List[int], arg2: set[int], **kwargs: Dict[str, int]) -> typing.Tuple[int]: + # -1:[consider-using-alias,consider-using-alias,consider-using-alias,consider-using-alias] + pass + +def func2(arg1: list[int]) -> tuple[int, int]: + pass + +class CustomIntList(typing.List[int]): + pass + +cast_variable = [1, 2, 3] +cast_variable = typing.cast(List[int], cast_variable) + +(lambda x: 2)(List[int]) + +class CustomNamedTuple(typing.NamedTuple): + my_var: List[int] # [consider-using-alias] + +CustomTypedDict1 = TypedDict("CustomTypedDict1", my_var=List[int]) + +class CustomTypedDict2(TypedDict): + my_var: List[int] # [consider-using-alias] + +@dataclass +class CustomDataClass: + my_var: List[int] # [consider-using-alias] diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_alias_without_future.rc b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_alias_without_future.rc new file mode 100644 index 0000000000000000000000000000000000000000..4e5e75f5d8a07bafd669b4f33da746840f39f7d1 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_alias_without_future.rc @@ -0,0 +1,9 @@ +[main] +py-version=3.8 +load-plugins=pylint.extensions.typing + +[testoptions] +min_pyver=3.8 + +[typing] +runtime-typing=no diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_alias_without_future.txt b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_alias_without_future.txt new file mode 100644 index 0000000000000000000000000000000000000000..7cf15a63c806587c1183eefa690fec393e3b63d6 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_alias_without_future.txt @@ -0,0 +1,20 @@ +consider-using-alias:20:6:20:17::'typing.Dict' will be deprecated with PY39, consider using 'dict' instead. Add 'from __future__ import annotations' as well:INFERENCE +consider-using-alias:21:6:21:10::'typing.List' will be deprecated with PY39, consider using 'list' instead. Add 'from __future__ import annotations' as well:INFERENCE +consider-using-alias:23:6:23:24::'typing.OrderedDict' will be deprecated with PY39, consider using 'collections.OrderedDict' instead. Add 'from __future__ import annotations' as well:INFERENCE +consider-using-alias:24:6:24:22::'typing.Awaitable' will be deprecated with PY39, consider using 'collections.abc.Awaitable' instead. Add 'from __future__ import annotations' as well:INFERENCE +consider-using-alias:25:6:25:21::'typing.Iterable' will be deprecated with PY39, consider using 'collections.abc.Iterable' instead. Add 'from __future__ import annotations' as well:INFERENCE +consider-using-alias:26:6:26:21::'typing.Hashable' will be deprecated with PY39, consider using 'collections.abc.Hashable' instead:INFERENCE +consider-using-alias:27:6:27:27::'typing.ContextManager' will be deprecated with PY39, consider using 'contextlib.AbstractContextManager' instead. Add 'from __future__ import annotations' as well:INFERENCE +consider-using-alias:28:6:28:20::'typing.Pattern' will be deprecated with PY39, consider using 're.Pattern' instead. Add 'from __future__ import annotations' as well:INFERENCE +consider-using-alias:29:7:29:22::'typing.Match' will be deprecated with PY39, consider using 're.Match' instead. Add 'from __future__ import annotations' as well:INFERENCE +consider-using-alias:38:9:38:13::'typing.List' will be deprecated with PY39, consider using 'list' instead:INFERENCE +consider-using-alias:40:7:40:11::'typing.Type' will be deprecated with PY39, consider using 'type' instead. Add 'from __future__ import annotations' as well:INFERENCE +consider-using-alias:41:7:41:12::'typing.Tuple' will be deprecated with PY39, consider using 'tuple' instead. Add 'from __future__ import annotations' as well:INFERENCE +consider-using-alias:42:7:42:15::'typing.Callable' will be deprecated with PY39, consider using 'collections.abc.Callable' instead. Add 'from __future__ import annotations' as well:INFERENCE +consider-using-alias:48:74:48:78:func1:'typing.Dict' will be deprecated with PY39, consider using 'dict' instead. Add 'from __future__ import annotations' as well:INFERENCE +consider-using-alias:48:16:48:20:func1:'typing.List' will be deprecated with PY39, consider using 'list' instead. Add 'from __future__ import annotations' as well:INFERENCE +consider-using-alias:48:37:48:41:func1:'typing.List' will be deprecated with PY39, consider using 'list' instead. Add 'from __future__ import annotations' as well:INFERENCE +consider-using-alias:48:93:48:105:func1:'typing.Tuple' will be deprecated with PY39, consider using 'tuple' instead. Add 'from __future__ import annotations' as well:INFERENCE +consider-using-alias:64:12:64:16:CustomNamedTuple:'typing.List' will be deprecated with PY39, consider using 'list' instead. Add 'from __future__ import annotations' as well:INFERENCE +consider-using-alias:69:12:69:16:CustomTypedDict2:'typing.List' will be deprecated with PY39, consider using 'list' instead. Add 'from __future__ import annotations' as well:INFERENCE +consider-using-alias:73:12:73:16:CustomDataClass:'typing.List' will be deprecated with PY39, consider using 'list' instead. Add 'from __future__ import annotations' as well:INFERENCE diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union.py b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union.py new file mode 100644 index 0000000000000000000000000000000000000000..780a9610001118bd1152719734746cb3dbe6b409 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union.py @@ -0,0 +1,53 @@ +"""Test pylint.extension.typing - consider-alternative-union-syntax + +'py-version' needs to be set to >= '3.7' and 'runtime-typing=no'. +With 'from __future__ import annotations' present. +""" + +# pylint: disable=missing-docstring,invalid-name,unused-argument,line-too-long +# pylint: disable=consider-using-alias,unnecessary-direct-lambda-call + +# Disabled because of a bug with pypy 3.8 see +# https://github.com/PyCQA/pylint/pull/7918#issuecomment-1352737369 +# pylint: disable=multiple-statements + +from __future__ import annotations +from dataclasses import dataclass +import typing +from typing import Dict, List, Optional, Union, TypedDict + +var1: Union[int, str] # [consider-alternative-union-syntax] +var2: List[Union[int, None]] # [consider-alternative-union-syntax] +var3: Dict[str, typing.Union[int, str]] # [consider-alternative-union-syntax] +var4: Optional[int] # [consider-alternative-union-syntax] + +Alias1 = Union[int, str] +Alias2 = List[Union[int, None]] +Alias3 = Dict[str, typing.Union[int, str]] +Alias4 = Optional[int] + +def func1( + arg1: Optional[int], # [consider-alternative-union-syntax] + **kwargs: Dict[str, Union[int, str]] # [consider-alternative-union-syntax] +) -> Union[str, None]: # [consider-alternative-union-syntax] + pass + +class Custom1(List[Union[str, int]]): + pass + +cast_variable = [1, 2, 3] +cast_variable = typing.cast(Union[List[int], None], cast_variable) + +(lambda x: 2)(Optional[int]) + +class CustomNamedTuple(typing.NamedTuple): + my_var: Union[int, str] # [consider-alternative-union-syntax] + +CustomTypedDict1 = TypedDict("CustomTypedDict1", my_var=Optional[int]) + +class CustomTypedDict2(TypedDict): + my_var: Dict[str, List[Union[str, int]]] # [consider-alternative-union-syntax] + +@dataclass +class CustomDataClass: + my_var: Optional[int] # [consider-alternative-union-syntax] diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union.rc b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union.rc new file mode 100644 index 0000000000000000000000000000000000000000..4e5e75f5d8a07bafd669b4f33da746840f39f7d1 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union.rc @@ -0,0 +1,9 @@ +[main] +py-version=3.8 +load-plugins=pylint.extensions.typing + +[testoptions] +min_pyver=3.8 + +[typing] +runtime-typing=no diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union.txt b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union.txt new file mode 100644 index 0000000000000000000000000000000000000000..5f2746815f56f61fa3c909f57382fff5651a203d --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union.txt @@ -0,0 +1,10 @@ +consider-alternative-union-syntax:19:6:19:11::Consider using alternative Union syntax instead of 'Union':INFERENCE +consider-alternative-union-syntax:20:11:20:16::Consider using alternative Union syntax instead of 'Union':INFERENCE +consider-alternative-union-syntax:21:16:21:28::Consider using alternative Union syntax instead of 'Union':INFERENCE +consider-alternative-union-syntax:22:6:22:14::Consider using alternative Union syntax instead of 'Optional':INFERENCE +consider-alternative-union-syntax:30:10:30:18:func1:Consider using alternative Union syntax instead of 'Optional':INFERENCE +consider-alternative-union-syntax:31:24:31:29:func1:Consider using alternative Union syntax instead of 'Union':INFERENCE +consider-alternative-union-syntax:32:5:32:10:func1:Consider using alternative Union syntax instead of 'Union':INFERENCE +consider-alternative-union-syntax:44:12:44:17:CustomNamedTuple:Consider using alternative Union syntax instead of 'Union':INFERENCE +consider-alternative-union-syntax:49:27:49:32:CustomTypedDict2:Consider using alternative Union syntax instead of 'Union':INFERENCE +consider-alternative-union-syntax:53:12:53:20:CustomDataClass:Consider using alternative Union syntax instead of 'Optional':INFERENCE diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union_py310.py b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union_py310.py new file mode 100644 index 0000000000000000000000000000000000000000..2c661f152c2043c482febeab4029a3ca38915dd7 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union_py310.py @@ -0,0 +1,45 @@ +"""Test pylint.extension.typing - consider-alternative-union-syntax + +'py-version' needs to be set to >= '3.10'. +""" +# pylint: disable=missing-docstring,invalid-name,unused-argument,line-too-long +# pylint: disable=deprecated-typing-alias,unnecessary-direct-lambda-call +from dataclasses import dataclass +import typing +from typing import Dict, List, Optional, Union, TypedDict + +var1: Union[int, str] # [consider-alternative-union-syntax] +var2: List[Union[int, None]] # [consider-alternative-union-syntax] +var3: Dict[str, typing.Union[int, str]] # [consider-alternative-union-syntax] +var4: Optional[int] # [consider-alternative-union-syntax] + +Alias1 = Union[int, str] # [consider-alternative-union-syntax] +Alias2 = List[Union[int, None]] # [consider-alternative-union-syntax] +Alias3 = Dict[str, typing.Union[int, str]] # [consider-alternative-union-syntax] +Alias4 = Optional[int] # [consider-alternative-union-syntax] + +def func1( + arg1: Optional[int], # [consider-alternative-union-syntax] + **kwargs: Dict[str, Union[int, str]] # [consider-alternative-union-syntax] +) -> Union[str, None]: # [consider-alternative-union-syntax] + pass + +class Custom1(List[Union[str, int]]): # [consider-alternative-union-syntax] + pass + +cast_variable = [1, 2, 3] +cast_variable = typing.cast(Union[List[int], None], cast_variable) # [consider-alternative-union-syntax] + +(lambda x: 2)(Optional[int]) # [consider-alternative-union-syntax] + +class CustomNamedTuple(typing.NamedTuple): + my_var: Union[int, str] # [consider-alternative-union-syntax] + +CustomTypedDict1 = TypedDict("CustomTypedDict1", my_var=Optional[int]) # [consider-alternative-union-syntax] + +class CustomTypedDict2(TypedDict): + my_var: Dict[str, List[Union[str, int]]] # [consider-alternative-union-syntax] + +@dataclass +class CustomDataClass: + my_var: Optional[int] # [consider-alternative-union-syntax] diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union_py310.rc b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union_py310.rc new file mode 100644 index 0000000000000000000000000000000000000000..a35db157734b3323378cc71e92191dd5dc5a5c19 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union_py310.rc @@ -0,0 +1,8 @@ +[main] +py-version=3.10 +load-plugins=pylint.extensions.typing + +[testoptions] +min_pyver=3.10 + +[typing] diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union_py310.txt b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union_py310.txt new file mode 100644 index 0000000000000000000000000000000000000000..fde1d7e2b2639afaeb47eed8e05408b94c082589 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union_py310.txt @@ -0,0 +1,18 @@ +consider-alternative-union-syntax:11:6:11:11::Consider using alternative Union syntax instead of 'Union':INFERENCE +consider-alternative-union-syntax:12:11:12:16::Consider using alternative Union syntax instead of 'Union':INFERENCE +consider-alternative-union-syntax:13:16:13:28::Consider using alternative Union syntax instead of 'Union':INFERENCE +consider-alternative-union-syntax:14:6:14:14::Consider using alternative Union syntax instead of 'Optional':INFERENCE +consider-alternative-union-syntax:16:9:16:14::Consider using alternative Union syntax instead of 'Union':INFERENCE +consider-alternative-union-syntax:17:14:17:19::Consider using alternative Union syntax instead of 'Union':INFERENCE +consider-alternative-union-syntax:18:19:18:31::Consider using alternative Union syntax instead of 'Union':INFERENCE +consider-alternative-union-syntax:19:9:19:17::Consider using alternative Union syntax instead of 'Optional':INFERENCE +consider-alternative-union-syntax:22:10:22:18:func1:Consider using alternative Union syntax instead of 'Optional':INFERENCE +consider-alternative-union-syntax:23:24:23:29:func1:Consider using alternative Union syntax instead of 'Union':INFERENCE +consider-alternative-union-syntax:24:5:24:10:func1:Consider using alternative Union syntax instead of 'Union':INFERENCE +consider-alternative-union-syntax:27:19:27:24:Custom1:Consider using alternative Union syntax instead of 'Union':INFERENCE +consider-alternative-union-syntax:31:28:31:33::Consider using alternative Union syntax instead of 'Union':INFERENCE +consider-alternative-union-syntax:33:14:33:22::Consider using alternative Union syntax instead of 'Optional':INFERENCE +consider-alternative-union-syntax:36:12:36:17:CustomNamedTuple:Consider using alternative Union syntax instead of 'Union':INFERENCE +consider-alternative-union-syntax:38:56:38:64::Consider using alternative Union syntax instead of 'Optional':INFERENCE +consider-alternative-union-syntax:41:27:41:32:CustomTypedDict2:Consider using alternative Union syntax instead of 'Union':INFERENCE +consider-alternative-union-syntax:45:12:45:20:CustomDataClass:Consider using alternative Union syntax instead of 'Optional':INFERENCE diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union_without_future.py b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union_without_future.py new file mode 100644 index 0000000000000000000000000000000000000000..d29ba306e9324a4979722281d929ce1b92cc5c7a --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union_without_future.py @@ -0,0 +1,51 @@ +"""Test pylint.extension.typing - consider-alternative-union-syntax + +'py-version' needs to be set to >= '3.7' and 'runtime-typing=no'. +""" + +# pylint: disable=missing-docstring,invalid-name,unused-argument,line-too-long,unnecessary-direct-lambda-call +# pylint: disable=consider-using-alias + +# Disabled because of a bug with pypy 3.8 see +# https://github.com/PyCQA/pylint/pull/7918#issuecomment-1352737369 +# pylint: disable=multiple-statements + +from dataclasses import dataclass +import typing +from typing import Dict, List, Optional, Union, TypedDict + +var1: Union[int, str] # [consider-alternative-union-syntax] +var2: List[Union[int, None]] # [consider-alternative-union-syntax] +var3: Dict[str, typing.Union[int, str]] # [consider-alternative-union-syntax] +var4: Optional[int] # [consider-alternative-union-syntax] + +Alias1 = Union[int, str] +Alias2 = List[Union[int, None]] +Alias3 = Dict[str, typing.Union[int, str]] +Alias4 = Optional[int] + +def func1( + arg1: Optional[int], # [consider-alternative-union-syntax] + **kwargs: Dict[str, Union[int, str]] # [consider-alternative-union-syntax] +) -> Union[str, None]: # [consider-alternative-union-syntax] + pass + +class Custom1(List[Union[str, int]]): + pass + +cast_variable = [1, 2, 3] +cast_variable = typing.cast(Union[List[int], None], cast_variable) + +(lambda x: 2)(Optional[int]) + +class CustomNamedTuple(typing.NamedTuple): + my_var: Union[int, str] # [consider-alternative-union-syntax] + +CustomTypedDict1 = TypedDict("CustomTypedDict1", my_var=Optional[int]) + +class CustomTypedDict2(TypedDict): + my_var: Dict[str, List[Union[str, int]]] # [consider-alternative-union-syntax] + +@dataclass +class CustomDataClass: + my_var: Optional[int] # [consider-alternative-union-syntax] diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union_without_future.rc b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union_without_future.rc new file mode 100644 index 0000000000000000000000000000000000000000..4e5e75f5d8a07bafd669b4f33da746840f39f7d1 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union_without_future.rc @@ -0,0 +1,9 @@ +[main] +py-version=3.8 +load-plugins=pylint.extensions.typing + +[testoptions] +min_pyver=3.8 + +[typing] +runtime-typing=no diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union_without_future.txt b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union_without_future.txt new file mode 100644 index 0000000000000000000000000000000000000000..5d48e9afcad6ae0bf65f9665adb17e65e787cdfc --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_consider_using_union_without_future.txt @@ -0,0 +1,10 @@ +consider-alternative-union-syntax:17:6:17:11::Consider using alternative Union syntax instead of 'Union'. Add 'from __future__ import annotations' as well:INFERENCE +consider-alternative-union-syntax:18:11:18:16::Consider using alternative Union syntax instead of 'Union'. Add 'from __future__ import annotations' as well:INFERENCE +consider-alternative-union-syntax:19:16:19:28::Consider using alternative Union syntax instead of 'Union'. Add 'from __future__ import annotations' as well:INFERENCE +consider-alternative-union-syntax:20:6:20:14::Consider using alternative Union syntax instead of 'Optional'. Add 'from __future__ import annotations' as well:INFERENCE +consider-alternative-union-syntax:28:10:28:18:func1:Consider using alternative Union syntax instead of 'Optional'. Add 'from __future__ import annotations' as well:INFERENCE +consider-alternative-union-syntax:29:24:29:29:func1:Consider using alternative Union syntax instead of 'Union'. Add 'from __future__ import annotations' as well:INFERENCE +consider-alternative-union-syntax:30:5:30:10:func1:Consider using alternative Union syntax instead of 'Union'. Add 'from __future__ import annotations' as well:INFERENCE +consider-alternative-union-syntax:42:12:42:17:CustomNamedTuple:Consider using alternative Union syntax instead of 'Union'. Add 'from __future__ import annotations' as well:INFERENCE +consider-alternative-union-syntax:47:27:47:32:CustomTypedDict2:Consider using alternative Union syntax instead of 'Union'. Add 'from __future__ import annotations' as well:INFERENCE +consider-alternative-union-syntax:51:12:51:20:CustomDataClass:Consider using alternative Union syntax instead of 'Optional'. Add 'from __future__ import annotations' as well:INFERENCE diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_deprecated_alias.py b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_deprecated_alias.py new file mode 100644 index 0000000000000000000000000000000000000000..80c132ebd9015b706ba4bbf89ff250038b11a5b3 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_deprecated_alias.py @@ -0,0 +1,66 @@ +"""Test pylint.extension.typing - deprecated-typing-alias + +'py-version' needs to be set to >= '3.9'. +""" +# pylint: disable=missing-docstring,invalid-name,unused-argument,line-too-long,unsubscriptable-object,unnecessary-direct-lambda-call +import collections +import collections.abc +import typing +from collections.abc import Awaitable +from dataclasses import dataclass +from typing import Dict, List, Set, Union, TypedDict, Callable, Tuple, Type + +var1: typing.Dict[str, int] # [deprecated-typing-alias] +var2: List[int] # [deprecated-typing-alias] +var3: collections.abc.Iterable[int] +var4: typing.OrderedDict[str, int] # [deprecated-typing-alias] +var5: typing.Awaitable[None] # [deprecated-typing-alias] +var6: typing.Iterable[int] # [deprecated-typing-alias] +var7: typing.Hashable # [deprecated-typing-alias] +var8: typing.ContextManager[str] # [deprecated-typing-alias] +var9: typing.Pattern[str] # [deprecated-typing-alias] +var10: typing.re.Match[str] # [deprecated-typing-alias] +var11: list[int] +var12: collections.abc +var13: Awaitable[None] +var14: collections.defaultdict[str, str] + +Alias1 = Set[int] # [deprecated-typing-alias] +Alias2 = Dict[int, List[int]] # [deprecated-typing-alias,deprecated-typing-alias] +Alias3 = Union[int, typing.List[str]] # [deprecated-typing-alias] +Alias4 = List # [deprecated-typing-alias] + +var21: Type[object] # [deprecated-typing-alias] +var22: Tuple[str] # [deprecated-typing-alias] +var23: Callable[..., str] # [deprecated-typing-alias] +var31: type[object] +var32: tuple[str] +var33: collections.abc.Callable[..., str] + + +def func1(arg1: List[int], /, *args: List[int], arg2: set[int], **kwargs: Dict[str, int]) -> typing.Tuple[int]: + # -1:[deprecated-typing-alias,deprecated-typing-alias,deprecated-typing-alias,deprecated-typing-alias] + pass + +def func2(arg1: list[int]) -> tuple[int, int]: + pass + +class CustomIntList(typing.List[int]): # [deprecated-typing-alias] + pass + +cast_variable = [1, 2, 3] +cast_variable = typing.cast(List[int], cast_variable) # [deprecated-typing-alias] + +(lambda x: 2)(List[int]) # [deprecated-typing-alias] + +class CustomNamedTuple(typing.NamedTuple): + my_var: List[int] # [deprecated-typing-alias] + +CustomTypedDict1 = TypedDict("CustomTypedDict1", my_var=List[int]) # [deprecated-typing-alias] + +class CustomTypedDict2(TypedDict): + my_var: List[int] # [deprecated-typing-alias] + +@dataclass +class CustomDataClass: + my_var: List[int] # [deprecated-typing-alias] diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_deprecated_alias.rc b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_deprecated_alias.rc new file mode 100644 index 0000000000000000000000000000000000000000..a4a4c9022cc225e20feb960ff2eae865446f11bd --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_deprecated_alias.rc @@ -0,0 +1,8 @@ +[main] +py-version=3.9 +load-plugins=pylint.extensions.typing + +[testoptions] +min_pyver=3.9 + +[typing] diff --git a/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_deprecated_alias.txt b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_deprecated_alias.txt new file mode 100644 index 0000000000000000000000000000000000000000..62cf9902ad798ecf4934fb2fc45768f452b2642a --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/ext/typing/typing_deprecated_alias.txt @@ -0,0 +1,28 @@ +deprecated-typing-alias:13:6:13:17::'typing.Dict' is deprecated, use 'dict' instead:INFERENCE +deprecated-typing-alias:14:6:14:10::'typing.List' is deprecated, use 'list' instead:INFERENCE +deprecated-typing-alias:16:6:16:24::'typing.OrderedDict' is deprecated, use 'collections.OrderedDict' instead:INFERENCE +deprecated-typing-alias:17:6:17:22::'typing.Awaitable' is deprecated, use 'collections.abc.Awaitable' instead:INFERENCE +deprecated-typing-alias:18:6:18:21::'typing.Iterable' is deprecated, use 'collections.abc.Iterable' instead:INFERENCE +deprecated-typing-alias:19:6:19:21::'typing.Hashable' is deprecated, use 'collections.abc.Hashable' instead:INFERENCE +deprecated-typing-alias:20:6:20:27::'typing.ContextManager' is deprecated, use 'contextlib.AbstractContextManager' instead:INFERENCE +deprecated-typing-alias:21:6:21:20::'typing.Pattern' is deprecated, use 're.Pattern' instead:INFERENCE +deprecated-typing-alias:22:7:22:22::'typing.Match' is deprecated, use 're.Match' instead:INFERENCE +deprecated-typing-alias:28:9:28:12::'typing.Set' is deprecated, use 'set' instead:INFERENCE +deprecated-typing-alias:29:9:29:13::'typing.Dict' is deprecated, use 'dict' instead:INFERENCE +deprecated-typing-alias:29:19:29:23::'typing.List' is deprecated, use 'list' instead:INFERENCE +deprecated-typing-alias:30:20:30:31::'typing.List' is deprecated, use 'list' instead:INFERENCE +deprecated-typing-alias:31:9:31:13::'typing.List' is deprecated, use 'list' instead:INFERENCE +deprecated-typing-alias:33:7:33:11::'typing.Type' is deprecated, use 'type' instead:INFERENCE +deprecated-typing-alias:34:7:34:12::'typing.Tuple' is deprecated, use 'tuple' instead:INFERENCE +deprecated-typing-alias:35:7:35:15::'typing.Callable' is deprecated, use 'collections.abc.Callable' instead:INFERENCE +deprecated-typing-alias:41:74:41:78:func1:'typing.Dict' is deprecated, use 'dict' instead:INFERENCE +deprecated-typing-alias:41:16:41:20:func1:'typing.List' is deprecated, use 'list' instead:INFERENCE +deprecated-typing-alias:41:37:41:41:func1:'typing.List' is deprecated, use 'list' instead:INFERENCE +deprecated-typing-alias:41:93:41:105:func1:'typing.Tuple' is deprecated, use 'tuple' instead:INFERENCE +deprecated-typing-alias:48:20:48:31:CustomIntList:'typing.List' is deprecated, use 'list' instead:INFERENCE +deprecated-typing-alias:52:28:52:32::'typing.List' is deprecated, use 'list' instead:INFERENCE +deprecated-typing-alias:54:14:54:18::'typing.List' is deprecated, use 'list' instead:INFERENCE +deprecated-typing-alias:57:12:57:16:CustomNamedTuple:'typing.List' is deprecated, use 'list' instead:INFERENCE +deprecated-typing-alias:59:56:59:60::'typing.List' is deprecated, use 'list' instead:INFERENCE +deprecated-typing-alias:62:12:62:16:CustomTypedDict2:'typing.List' is deprecated, use 'list' instead:INFERENCE +deprecated-typing-alias:66:12:66:16:CustomDataClass:'typing.List' is deprecated, use 'list' instead:INFERENCE diff --git a/testbed/pylint-dev__pylint/tests/functional/u/__init__.py b/testbed/pylint-dev__pylint/tests/functional/u/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unbalanced_dict_unpacking.py b/testbed/pylint-dev__pylint/tests/functional/u/unbalanced_dict_unpacking.py new file mode 100644 index 0000000000000000000000000000000000000000..2c4d3b10317e1dfd219cf7412bbf3a404f977c38 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unbalanced_dict_unpacking.py @@ -0,0 +1,91 @@ +"""Check possible unbalanced dict unpacking """ +# pylint: disable=missing-function-docstring, invalid-name +# pylint: disable=unused-variable, redefined-outer-name, line-too-long + +def dict_vals(): + a, b, c, d, e, f, g = {1: 2}.values() # [unbalanced-dict-unpacking] + return a, b + +def dict_keys(): + a, b, c, d, e, f, g = {1: 2, "hi": 20}.keys() # [unbalanced-dict-unpacking] + return a, b + + +def dict_items(): + tupe_one, tuple_two = {1: 2, "boo": 3}.items() + tupe_one, tuple_two, tuple_three = {1: 2, "boo": 3}.items() # [unbalanced-dict-unpacking] + return tuple_three + +def all_dict(): + a, b, c, d, e, f, g = {1: 2, 3: 4} # [unbalanced-dict-unpacking] + return a + +for a, b, c, d, e, f, g in {1: 2}.items(): # [unbalanced-dict-unpacking] + pass + +for key, value in {1: 2}: # [unbalanced-dict-unpacking] + pass + +for key, value in {1: 2}.keys(): # [unbalanced-dict-unpacking, consider-iterating-dictionary] + pass + +for key, value in {1: 2}.values(): # [unbalanced-dict-unpacking] + pass + +empty = {} + +# this should not raise unbalanced-dict because it is valid code using `items()` +for key, value in empty.items(): + print(key) + print(value) + +for key, val in {1: 2}.items(): + print(key) + +populated = {2: 1} +for key, val in populated.items(): + print(key) + +key, val = populated.items() # [unbalanced-dict-unpacking] + +for key, val in {1: 2, 3: 4, 5: 6}.items(): + print(key) + +key, val = {1: 2, 3: 4, 5: 6}.items() # [unbalanced-dict-unpacking] + +a, b, c = {} # [unbalanced-dict-unpacking] + +for k in {'key': 'value', 1: 2}.items(): + print(k) + +for k, _ in {'key': 'value'}.items(): + print(k) + +for _, _ in {'key': 'value'}.items(): + print(_) + +for _, val in {'key': 'value'}.values(): # [unbalanced-dict-unpacking] + print(val) + +for key, *val in {'key': 'value', 1: 2}.items(): + print(key) + +for *key, val in {'key': 'value', 1: 2}.items(): + print(key) + + +for key, *val in {'key': 'value', 1: 2, 20: 21}.values(): # [unbalanced-dict-unpacking] + print(key) + +for *key, val in {'key': 'value', 1: 2, 20: 21}.values(): # [unbalanced-dict-unpacking] + print(key) + +one, *others = {1: 2, 3: 4, 5: 6}.items() +one, *others, last = {1: 2, 3: 4, 5: 6}.items() + +one, *others = {1: 2, 3: 4, 5: 6}.values() +one, *others, last = {1: 2, 3: 4, 5: 6}.values() + +_, *others = {1: 2, 3: 4, 5: 6}.items() +_, *others = {1: 2, 3: 4, 5: 6}.values() +_, others = {1: 2, 3: 4, 5: 6}.values() # [unbalanced-dict-unpacking] diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unbalanced_dict_unpacking.txt b/testbed/pylint-dev__pylint/tests/functional/u/unbalanced_dict_unpacking.txt new file mode 100644 index 0000000000000000000000000000000000000000..b31d89b4011e2172ca17b8028e0a3eb412fd47dc --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unbalanced_dict_unpacking.txt @@ -0,0 +1,16 @@ +unbalanced-dict-unpacking:6:4:6:41:dict_vals:"Possible unbalanced dict unpacking with {1: 2}.values(): left side has 7 labels, right side has 1 value":INFERENCE +unbalanced-dict-unpacking:10:4:10:49:dict_keys:"Possible unbalanced dict unpacking with {1: 2, 'hi': 20}.keys(): left side has 7 labels, right side has 2 values":INFERENCE +unbalanced-dict-unpacking:16:4:16:63:dict_items:"Possible unbalanced dict unpacking with {1: 2, 'boo': 3}.items(): left side has 3 labels, right side has 2 values":INFERENCE +unbalanced-dict-unpacking:20:4:20:38:all_dict:"Possible unbalanced dict unpacking with {1: 2, 3: 4}: left side has 7 labels, right side has 2 values":INFERENCE +unbalanced-dict-unpacking:23:0:24:8::"Possible unbalanced dict unpacking with {1: 2}.items(): left side has 7 labels, right side has 1 value":INFERENCE +unbalanced-dict-unpacking:26:0:27:8::"Possible unbalanced dict unpacking with {1: 2}: left side has 2 labels, right side has 1 value":INFERENCE +consider-iterating-dictionary:29:18:29:31::Consider iterating the dictionary directly instead of calling .keys():INFERENCE +unbalanced-dict-unpacking:29:0:30:8::"Possible unbalanced dict unpacking with {1: 2}.keys(): left side has 2 labels, right side has 1 value":INFERENCE +unbalanced-dict-unpacking:32:0:33:8::"Possible unbalanced dict unpacking with {1: 2}.values(): left side has 2 labels, right side has 1 value":INFERENCE +unbalanced-dict-unpacking:49:0:49:28::"Possible unbalanced dict unpacking with populated.items(): left side has 2 labels, right side has 1 value":INFERENCE +unbalanced-dict-unpacking:54:0:54:37::"Possible unbalanced dict unpacking with {1: 2, 3: 4, 5: 6}.items(): left side has 2 labels, right side has 3 values":INFERENCE +unbalanced-dict-unpacking:56:0:56:12::"Possible unbalanced dict unpacking with {}: left side has 3 labels, right side has 0 values":INFERENCE +unbalanced-dict-unpacking:67:0:68:14::"Possible unbalanced dict unpacking with {'key': 'value'}.values(): left side has 2 labels, right side has 1 value":INFERENCE +unbalanced-dict-unpacking:77:0:78:14::"Possible unbalanced dict unpacking with {'key': 'value', 1: 2, 20: 21}.values(): left side has 2 labels, right side has 3 values":INFERENCE +unbalanced-dict-unpacking:80:0:81:14::"Possible unbalanced dict unpacking with {'key': 'value', 1: 2, 20: 21}.values(): left side has 2 labels, right side has 3 values":INFERENCE +unbalanced-dict-unpacking:91:0:91:39::"Possible unbalanced dict unpacking with {1: 2, 3: 4, 5: 6}.values(): left side has 2 labels, right side has 3 values":INFERENCE diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unbalanced_tuple_unpacking.py b/testbed/pylint-dev__pylint/tests/functional/u/unbalanced_tuple_unpacking.py new file mode 100644 index 0000000000000000000000000000000000000000..2267489339883d253c696f26a8b7e15c80b05c2a --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unbalanced_tuple_unpacking.py @@ -0,0 +1,162 @@ +"""Check possible unbalanced tuple unpacking """ +from __future__ import absolute_import +from typing import NamedTuple +from functional.u.unpacking.unpacking import unpack + +# pylint: disable=missing-class-docstring, missing-function-docstring, using-constant-test, import-outside-toplevel + + +def do_stuff(): + """This is not right.""" + first, second = 1, 2, 3 # [unbalanced-tuple-unpacking] + return first + second + + +def do_stuff1(): + """This is not right.""" + first, second = [1, 2, 3] # [unbalanced-tuple-unpacking] + return first + second + + +def do_stuff2(): + """This is not right.""" + (first, second) = 1, 2, 3 # [unbalanced-tuple-unpacking] + return first + second + + +def do_stuff3(): + """This is not right.""" + first, second = range(100) + return first + second + + +def do_stuff4(): + """This is right""" + first, second = 1, 2 + return first + second + + +def do_stuff5(): + """This is also right""" + first, second = (1, 2) + return first + second + + +def do_stuff6(): + """This is right""" + (first, second) = (1, 2) + return first + second + + +def temp(): + """This is not weird""" + if True: + return [1, 2] + return [2, 3, 4] + + +def do_stuff7(): + """This is not right, but we're not sure""" + first, second = temp() + return first + second + + +def temp2(): + """This is weird, but correct""" + if True: + return (1, 2) + + if True: + return (2, 3) + return (4, 5) + + +def do_stuff8(): + """This is correct""" + first, second = temp2() + return first + second + + +def do_stuff9(): + """This is not correct""" + first, second = unpack() # [unbalanced-tuple-unpacking] + return first + second + + +class UnbalancedUnpacking: + """Test unbalanced tuple unpacking in instance attributes.""" + + # pylint: disable=attribute-defined-outside-init, invalid-name, too-few-public-methods + def test(self): + """unpacking in instance attributes""" + # we're not sure if temp() returns two or three values + # so we shouldn't emit an error + self.a, self.b = temp() + self.a, self.b = temp2() + self.a, self.b = unpack() # [unbalanced-tuple-unpacking] + + +def issue329(*args): + """Don't emit unbalanced tuple unpacking if the + rhs of the assignment is a variable-length argument, + because we don't know the actual length of the tuple. + """ + first, second, third = args + return first, second, third + + +def test_decimal(): + """Test a false positive with decimal.Decimal.as_tuple + + See astroid https://bitbucket.org/logilab/astroid/issues/92/ + """ + from decimal import Decimal + + dec = Decimal(2) + first, second, third = dec.as_tuple() + return first, second, third + + +def test_issue_559(): + """Test that we don't have a false positive wrt to issue #559.""" + from ctypes import c_int + + root_x, root_y, win_x, win_y = [c_int()] * 4 + return root_x, root_y, win_x, win_y + + +class MyClass(NamedTuple): + first: float + second: float + third: float = 1.0 + + def my_sum(self): + """Unpack 3 variables""" + first, second, third = self + return first + second + third + + def sum_unpack_3_into_4(self): + """Attempt to unpack 3 variables into 4""" + first, second, third, fourth = self # [unbalanced-tuple-unpacking] + return first + second + third + fourth + + def sum_unpack_3_into_2(self): + """Attempt to unpack 3 variables into 2""" + first, second = self # [unbalanced-tuple-unpacking] + return first + second + + +def my_function(mystring): + """The number of items on the right-hand-side of the assignment to this function is not known""" + mylist = [] + for item in mystring: + mylist.append(item) + return mylist + + +a, b = my_function("12") # [unbalanced-tuple-unpacking] +c = my_function("12") +d, *_ = my_function("12") + +# https://github.com/PyCQA/pylint/issues/5998 +x, y, z = (1, 2) # [unbalanced-tuple-unpacking] diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unbalanced_tuple_unpacking.txt b/testbed/pylint-dev__pylint/tests/functional/u/unbalanced_tuple_unpacking.txt new file mode 100644 index 0000000000000000000000000000000000000000..651e09840330da8eee2d7a275f6da1e11287bd6c --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unbalanced_tuple_unpacking.txt @@ -0,0 +1,9 @@ +unbalanced-tuple-unpacking:11:4:11:27:do_stuff:"Possible unbalanced tuple unpacking with sequence '(1, 2, 3)': left side has 2 labels, right side has 3 values":INFERENCE +unbalanced-tuple-unpacking:17:4:17:29:do_stuff1:"Possible unbalanced tuple unpacking with sequence '[1, 2, 3]': left side has 2 labels, right side has 3 values":INFERENCE +unbalanced-tuple-unpacking:23:4:23:29:do_stuff2:"Possible unbalanced tuple unpacking with sequence '(1, 2, 3)': left side has 2 labels, right side has 3 values":INFERENCE +unbalanced-tuple-unpacking:82:4:82:28:do_stuff9:"Possible unbalanced tuple unpacking with sequence defined at line 7 of functional.u.unpacking.unpacking: left side has 2 labels, right side has 3 values":INFERENCE +unbalanced-tuple-unpacking:96:8:96:33:UnbalancedUnpacking.test:"Possible unbalanced tuple unpacking with sequence defined at line 7 of functional.u.unpacking.unpacking: left side has 2 labels, right side has 3 values":INFERENCE +unbalanced-tuple-unpacking:140:8:140:43:MyClass.sum_unpack_3_into_4:"Possible unbalanced tuple unpacking with sequence defined at line 128: left side has 4 labels, right side has 3 values":INFERENCE +unbalanced-tuple-unpacking:145:8:145:28:MyClass.sum_unpack_3_into_2:"Possible unbalanced tuple unpacking with sequence defined at line 128: left side has 2 labels, right side has 3 values":INFERENCE +unbalanced-tuple-unpacking:157:0:157:24::"Possible unbalanced tuple unpacking with sequence defined at line 151: left side has 2 labels, right side has 0 values":INFERENCE +unbalanced-tuple-unpacking:162:0:162:16::"Possible unbalanced tuple unpacking with sequence '(1, 2)': left side has 3 labels, right side has 2 values":INFERENCE diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unbalanced_tuple_unpacking_py30.py b/testbed/pylint-dev__pylint/tests/functional/u/unbalanced_tuple_unpacking_py30.py new file mode 100644 index 0000000000000000000000000000000000000000..c45cccdd1d052d90963c0cd2500da88e0326d229 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unbalanced_tuple_unpacking_py30.py @@ -0,0 +1,11 @@ +""" Test that using starred nodes in unpacking +does not trigger a false positive on Python 3. +""" +# pylint: disable=unused-variable + +def test(): + """ Test that starred expressions don't give false positives. """ + first, second, *last = (1, 2, 3, 4) + one, two, three, *four = (1, 2, 3, 4) + *last, = (1, 2) + return (first, second, last) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unexpected_keyword_arg.py b/testbed/pylint-dev__pylint/tests/functional/u/unexpected_keyword_arg.py new file mode 100644 index 0000000000000000000000000000000000000000..e7b648899e31eb873721578098d1ba41e43e0d79 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unexpected_keyword_arg.py @@ -0,0 +1,118 @@ +"""Tests for unexpected-keyword-arg""" +# pylint: disable=undefined-variable, too-few-public-methods, missing-function-docstring, missing-class-docstring + + +def non_param_decorator(func): + """Decorator without a parameter""" + + def new_func(): + func() + + return new_func + + +def param_decorator(func): + """Decorator with a parameter""" + + def new_func(internal_arg=3): + func(junk=internal_arg) + + return new_func + + +def kwargs_decorator(func): + """Decorator with kwargs. + The if ... else makes the double decoration with param_decorator valid. + """ + + def new_func(**kwargs): + if "internal_arg" in kwargs: + func(junk=kwargs["internal_arg"]) + else: + func(junk=kwargs["junk"]) + + return new_func + + +@non_param_decorator +def do_something(junk=None): + """A decorated function. This should not be passed a keyword argument""" + print(junk) + + +do_something(internal_arg=2) # [unexpected-keyword-arg] + + +@param_decorator +def do_something_decorated(junk=None): + """A decorated function. This should be passed a keyword argument""" + print(junk) + + +do_something_decorated(internal_arg=2) + + +@kwargs_decorator +def do_something_decorated_too(junk=None): + """A decorated function. This should be passed a keyword argument""" + print(junk) + + +do_something_decorated_too(internal_arg=2) + + +@non_param_decorator +@kwargs_decorator +def do_something_double_decorated(junk=None): + """A decorated function. This should not be passed a keyword argument. + non_param_decorator will raise an exception if a keyword argument is passed. + """ + print(junk) + + +do_something_double_decorated(internal_arg=2) # [unexpected-keyword-arg] + + +@param_decorator +@kwargs_decorator +def do_something_double_decorated_correct(junk=None): + """A decorated function. This should be passed a keyword argument""" + print(junk) + + +do_something_double_decorated_correct(internal_arg=2) + + +# Test that we don't crash on Class decoration +class DecoratorClass: + pass + + +@DecoratorClass +def crash_test(): + pass + + +crash_test(internal_arg=2) # [unexpected-keyword-arg] + + +# Test that we don't emit a false positive for uninferable decorators +@unknown_decorator +def crash_test_two(): + pass + + +crash_test_two(internal_arg=2) + + +# Test that we don't crash on decorators that don't return anything +def no_return_decorator(func): + print(func) + + +@no_return_decorator +def test_no_return(): + pass + + +test_no_return(internal_arg=2) # [unexpected-keyword-arg] diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unexpected_keyword_arg.txt b/testbed/pylint-dev__pylint/tests/functional/u/unexpected_keyword_arg.txt new file mode 100644 index 0000000000000000000000000000000000000000..3cc968e88304a588dfa4d677392d1e79b42d3c2b --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unexpected_keyword_arg.txt @@ -0,0 +1,4 @@ +unexpected-keyword-arg:43:0:43:28::Unexpected keyword argument 'internal_arg' in function call:UNDEFINED +unexpected-keyword-arg:73:0:73:45::Unexpected keyword argument 'internal_arg' in function call:UNDEFINED +unexpected-keyword-arg:96:0:96:26::Unexpected keyword argument 'internal_arg' in function call:UNDEFINED +unexpected-keyword-arg:118:0:118:30::Unexpected keyword argument 'internal_arg' in function call:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unexpected_special_method_signature.py b/testbed/pylint-dev__pylint/tests/functional/u/unexpected_special_method_signature.py new file mode 100644 index 0000000000000000000000000000000000000000..e2ae33857363c2f4c3ff1c22374b050c6b1d9b37 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unexpected_special_method_signature.py @@ -0,0 +1,138 @@ +"""Test for special methods implemented incorrectly.""" + +# pylint: disable=missing-docstring, unused-argument, too-few-public-methods +# pylint: disable=invalid-name,too-many-arguments,bad-staticmethod-argument + +class Invalid: + + def __enter__(self, other): # [unexpected-special-method-signature] + pass + + def __del__(self, other): # [unexpected-special-method-signature] + pass + + def __format__(self, other, other2): # [unexpected-special-method-signature] + pass + + def __setattr__(self): # [unexpected-special-method-signature] + pass + + def __round__(self, invalid, args): # [unexpected-special-method-signature] + pass + + def __deepcopy__(self, memo, other): # [unexpected-special-method-signature] + pass + + def __iter__(): # [no-method-argument] + pass + + @staticmethod + def __getattr__(self, nanana): # [unexpected-special-method-signature] + pass + + def __subclasses__(self, blabla): # [unexpected-special-method-signature] + pass + + +class FirstBadContextManager: + def __enter__(self): + return self + def __exit__(self, exc_type): # [unexpected-special-method-signature] + pass + +class SecondBadContextManager: + def __enter__(self): + return self + def __exit__(self, exc_type, value, tb, stack): # [unexpected-special-method-signature] + pass + +class ThirdBadContextManager: + def __enter__(self): + return self + + # +1: [unexpected-special-method-signature] + def __exit__(self, exc_type, value, tb, stack, *args): + pass + + +class Async: + + def __aiter__(self, extra): # [unexpected-special-method-signature] + pass + def __anext__(self, extra, argument): # [unexpected-special-method-signature] + pass + def __await__(self, param): # [unexpected-special-method-signature] + pass + def __aenter__(self, first): # [unexpected-special-method-signature] + pass + def __aexit__(self): # [unexpected-special-method-signature] + pass + + +class Valid: + + def __new__(cls, test, multiple, args): + pass + + def __init__(self, this, can, have, multiple, args, as_well): + pass + + def __call__(self, also, trv, for_this): + pass + + def __round__(self, n): + pass + + def __index__(self, n=42): + """Expects 0 args, but we are taking in account arguments with defaults.""" + + def __deepcopy__(self, memo): + pass + + def __format__(self, format_specification=''): + pass + + def __copy__(self, this=None, is_not=None, necessary=None): + pass + + @staticmethod + def __enter__(): + pass + + @staticmethod + def __getitem__(index): + pass + + @classmethod + def __init_subclass__(cls, blabla): + pass + + +class FirstGoodContextManager: + def __enter__(self): + return self + def __exit__(self, exc_type, value, tb): + pass + +class SecondGoodContextManager: + def __enter__(self): + return self + def __exit__(self, exc_type=None, value=None, tb=None): + pass + +class ThirdGoodContextManager: + def __enter__(self): + return self + def __exit__(self, exc_type, *args): + pass + + +# unexpected-special-method-signature +# https://github.com/PyCQA/pylint/issues/6644 +class Philosopher: + def __init_subclass__(cls, default_name, **kwargs): + super().__init_subclass__(**kwargs) + cls.default_name = default_name + +class AustralianPhilosopher(Philosopher, default_name="Bruce"): + pass diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unexpected_special_method_signature.txt b/testbed/pylint-dev__pylint/tests/functional/u/unexpected_special_method_signature.txt new file mode 100644 index 0000000000000000000000000000000000000000..9a4c6e6ff61df937edd48761114fa3f1a6dffb3d --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unexpected_special_method_signature.txt @@ -0,0 +1,17 @@ +unexpected-special-method-signature:8:4:8:17:Invalid.__enter__:The special method '__enter__' expects 0 param(s), 1 was given:UNDEFINED +unexpected-special-method-signature:11:4:11:15:Invalid.__del__:The special method '__del__' expects 0 param(s), 1 was given:UNDEFINED +unexpected-special-method-signature:14:4:14:18:Invalid.__format__:The special method '__format__' expects 1 param(s), 2 were given:UNDEFINED +unexpected-special-method-signature:17:4:17:19:Invalid.__setattr__:The special method '__setattr__' expects 2 param(s), 0 was given:UNDEFINED +unexpected-special-method-signature:20:4:20:17:Invalid.__round__:The special method '__round__' expects between 0 or 1 param(s), 2 were given:UNDEFINED +unexpected-special-method-signature:23:4:23:20:Invalid.__deepcopy__:The special method '__deepcopy__' expects 1 param(s), 2 were given:UNDEFINED +no-method-argument:26:4:26:16:Invalid.__iter__:Method '__iter__' has no argument:UNDEFINED +unexpected-special-method-signature:30:4:30:19:Invalid.__getattr__:The special method '__getattr__' expects 1 param(s), 2 were given:UNDEFINED +unexpected-special-method-signature:33:4:33:22:Invalid.__subclasses__:The special method '__subclasses__' expects 0 param(s), 1 was given:UNDEFINED +unexpected-special-method-signature:40:4:40:16:FirstBadContextManager.__exit__:The special method '__exit__' expects 3 param(s), 1 was given:UNDEFINED +unexpected-special-method-signature:46:4:46:16:SecondBadContextManager.__exit__:The special method '__exit__' expects 3 param(s), 4 were given:UNDEFINED +unexpected-special-method-signature:54:4:54:16:ThirdBadContextManager.__exit__:The special method '__exit__' expects 3 param(s), 4 were given:UNDEFINED +unexpected-special-method-signature:60:4:60:17:Async.__aiter__:The special method '__aiter__' expects 0 param(s), 1 was given:UNDEFINED +unexpected-special-method-signature:62:4:62:17:Async.__anext__:The special method '__anext__' expects 0 param(s), 2 were given:UNDEFINED +unexpected-special-method-signature:64:4:64:17:Async.__await__:The special method '__await__' expects 0 param(s), 1 was given:UNDEFINED +unexpected-special-method-signature:66:4:66:18:Async.__aenter__:The special method '__aenter__' expects 0 param(s), 1 was given:UNDEFINED +unexpected-special-method-signature:68:4:68:17:Async.__aexit__:The special method '__aexit__' expects 3 param(s), 0 was given:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/ungrouped_imports.py b/testbed/pylint-dev__pylint/tests/functional/u/ungrouped_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..ace3a8e3f19b337d468e70c8957cfe562baeb0af --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/ungrouped_imports.py @@ -0,0 +1,34 @@ +"""Checks import order rule""" +# pylint: disable=unused-import,wrong-import-position,wrong-import-order,using-constant-test +# pylint: disable=import-error +import six +import logging.config +import os.path +from astroid import are_exclusive +import logging # [ungrouped-imports] +import unused_import +try: + import os # [ungrouped-imports] +except ImportError: + pass +from os import pardir +import scipy +from os import sep +from astroid import exceptions # [ungrouped-imports] +if True: + import logging.handlers # [ungrouped-imports] +from os.path import join # [ungrouped-imports] +# Test related to compatibility with isort: +# We check that we do not create error with the old way pylint was handling it +import subprocess +import unittest +from unittest import TestCase +from unittest.mock import MagicMock + + +# https://github.com/PyCQA/pylint/issues/3382 +# Imports in a `if TYPE_CHECKING` block should not trigger `ungrouped-imports` +from typing import TYPE_CHECKING +if TYPE_CHECKING: + import re + from typing import List diff --git a/testbed/pylint-dev__pylint/tests/functional/u/ungrouped_imports.txt b/testbed/pylint-dev__pylint/tests/functional/u/ungrouped_imports.txt new file mode 100644 index 0000000000000000000000000000000000000000..b7d9a2494a5efa37bec96c8fb9f6f1c1ee45b3ca --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/ungrouped_imports.txt @@ -0,0 +1,5 @@ +ungrouped-imports:8:0:8:14::Imports from package logging are not grouped:UNDEFINED +ungrouped-imports:11:4:11:13::Imports from package os are not grouped:UNDEFINED +ungrouped-imports:17:0:17:30::Imports from package astroid are not grouped:UNDEFINED +ungrouped-imports:19:4:19:27::Imports from package logging are not grouped:UNDEFINED +ungrouped-imports:20:0:20:24::Imports from package os are not grouped:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/ungrouped_imports_isort_compatible.py b/testbed/pylint-dev__pylint/tests/functional/u/ungrouped_imports_isort_compatible.py new file mode 100644 index 0000000000000000000000000000000000000000..2e64ed402a55e723ab0f65893b46254eea99da6e --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/ungrouped_imports_isort_compatible.py @@ -0,0 +1,6 @@ +"""Checks import order rule with imports that isort could generate""" +# pylint: disable=unused-import +import astroid +import isort +from astroid import are_exclusive, decorators +from astroid.modutils import get_module_part, is_standard_module diff --git a/testbed/pylint-dev__pylint/tests/functional/u/ungrouped_imports_suppression.py b/testbed/pylint-dev__pylint/tests/functional/u/ungrouped_imports_suppression.py new file mode 100644 index 0000000000000000000000000000000000000000..9b482b355a3fb6636efe2df98e5b274815550c71 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/ungrouped_imports_suppression.py @@ -0,0 +1,15 @@ +"""Check ungrouped import and interaction with useless-suppression. + +Previously disabling ungrouped-imports would always lead to useless-suppression. +""" +# pylint: enable=useless-suppression +# pylint: disable=unused-import, wrong-import-order + +import logging.config +import os.path +from astroid import are_exclusive # pylint: disable=ungrouped-imports # [useless-suppression] +import logging.handlers # pylint: disable=ungrouped-imports # This should not raise useless-suppression +try: + import os # [ungrouped-imports] +except ImportError: + pass diff --git a/testbed/pylint-dev__pylint/tests/functional/u/ungrouped_imports_suppression.rc b/testbed/pylint-dev__pylint/tests/functional/u/ungrouped_imports_suppression.rc new file mode 100644 index 0000000000000000000000000000000000000000..10388685f17a12ca151ef56d4459425d6587de48 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/ungrouped_imports_suppression.rc @@ -0,0 +1,2 @@ +[testoptions] +exclude_from_minimal_messages_config=true diff --git a/testbed/pylint-dev__pylint/tests/functional/u/ungrouped_imports_suppression.txt b/testbed/pylint-dev__pylint/tests/functional/u/ungrouped_imports_suppression.txt new file mode 100644 index 0000000000000000000000000000000000000000..3ba8b0ea0f0d810f74f4c5cc024ee3af212aac22 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/ungrouped_imports_suppression.txt @@ -0,0 +1,2 @@ +useless-suppression:10:0:None:None::Useless suppression of 'ungrouped-imports':UNDEFINED +ungrouped-imports:13:4:13:13::Imports from package os are not grouped:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unhashable_member.py b/testbed/pylint-dev__pylint/tests/functional/u/unhashable_member.py new file mode 100644 index 0000000000000000000000000000000000000000..c788668c479e0c54bed873f24f7c822fdf24a39a --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unhashable_member.py @@ -0,0 +1,30 @@ +# pylint: disable=missing-docstring,expression-not-assigned,too-few-public-methods,pointless-statement + + +class Unhashable: + __hash__ = list.__hash__ + +# Subscripts +{}[[1, 2, 3]] # [unhashable-member] +{}[{}] # [unhashable-member] +{}[Unhashable()] # [unhashable-member] +{}[1:2] # [unhashable-member] +{'foo': 'bar'}['foo'] +{'foo': 'bar'}[42] + +# Keys +{[1, 2, 3]: "tomato"} # [unhashable-member] +{ + [1, 2, 3]: "tomato", # [unhashable-member] + [4, 5, 6]: "celeriac", # [unhashable-member] +} +{[1, 2, 3]} # [unhashable-member] +{"tomato": "tomahto"} +{dict: {}} +{lambda x: x: "tomato"} # pylint: disable=unnecessary-lambda + + +class FromDict(dict): + ... + +{FromDict: 1} diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unhashable_member.txt b/testbed/pylint-dev__pylint/tests/functional/u/unhashable_member.txt new file mode 100644 index 0000000000000000000000000000000000000000..cbde3f8d67e682c24efc7eef5ce159d0e041ee50 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unhashable_member.txt @@ -0,0 +1,8 @@ +unhashable-member:8:0:8:2::'[1, 2, 3]' is unhashable and can't be used as a key in a dict:INFERENCE +unhashable-member:9:0:9:2::'{}' is unhashable and can't be used as a key in a dict:INFERENCE +unhashable-member:10:0:10:2::'Unhashable()' is unhashable and can't be used as a key in a dict:INFERENCE +unhashable-member:11:0:11:2::"'1:2' is unhashable and can't be used as a key in a dict":INFERENCE +unhashable-member:16:1:16:10::'[1, 2, 3]' is unhashable and can't be used as a key in a dict:INFERENCE +unhashable-member:18:4:18:13::'[1, 2, 3]' is unhashable and can't be used as a key in a dict:INFERENCE +unhashable-member:19:4:19:13::'[4, 5, 6]' is unhashable and can't be used as a key in a dict:INFERENCE +unhashable-member:21:1:21:10::'[1, 2, 3]' is unhashable and can't be used as a member in a set:INFERENCE diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unicode/unicode_bidi_commenting_out.py b/testbed/pylint-dev__pylint/tests/functional/u/unicode/unicode_bidi_commenting_out.py new file mode 100644 index 0000000000000000000000000000000000000000..f5a1275fd9b2ab9f956535e831ec27f9a61ad59d --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unicode/unicode_bidi_commenting_out.py @@ -0,0 +1,12 @@ +""" +Example #1 of trojan unicode, see https://trojansource.codes/ +Taken from https://github.com/nickboucher/trojan-source/tree/main/Python +""" + + +def a_function(): + """A simple function""" + access_level = "user" + # +1: [bidirectional-unicode] + if access_level != "none‮⁦": # Check if admin ⁩⁦' and access_level != 'user + print("You are an admin.") diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unicode/unicode_bidi_commenting_out.txt b/testbed/pylint-dev__pylint/tests/functional/u/unicode/unicode_bidi_commenting_out.txt new file mode 100644 index 0000000000000000000000000000000000000000..7c1d4f4289b0f66333b30b3046d4639239c01e92 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unicode/unicode_bidi_commenting_out.txt @@ -0,0 +1 @@ +bidirectional-unicode:11:0:11:80::Contains control characters that can permit obfuscated code executed differently than displayed:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unicode/unicode_bidi_early_return.py b/testbed/pylint-dev__pylint/tests/functional/u/unicode/unicode_bidi_early_return.py new file mode 100644 index 0000000000000000000000000000000000000000..1de7a50406b7c3573dcf12805641cb3cbb708d32 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unicode/unicode_bidi_early_return.py @@ -0,0 +1,19 @@ +""" +Example #2 of trojan unicode, see https://trojansource.codes/ +Taken from https://github.com/nickboucher/trojan-source/tree/main/Python +""" +# pylint: disable=unreachable + +bank = {"alice": 100} + +# +4: [bidirectional-unicode] + + +def subtract_funds(account: str, amount: int): + """Subtract funds from bank account then ⁧""" + return + bank[account] -= amount + return + + +subtract_funds("alice", 50) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unicode/unicode_bidi_early_return.txt b/testbed/pylint-dev__pylint/tests/functional/u/unicode/unicode_bidi_early_return.txt new file mode 100644 index 0000000000000000000000000000000000000000..576edc887fb73e2fdfafc1782527955c1ef7c882 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unicode/unicode_bidi_early_return.txt @@ -0,0 +1 @@ +bidirectional-unicode:13:0:13:49::Contains control characters that can permit obfuscated code executed differently than displayed:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unicode/unicode_bidi_pep672.py b/testbed/pylint-dev__pylint/tests/functional/u/unicode/unicode_bidi_pep672.py new file mode 100644 index 0000000000000000000000000000000000000000..710167c093a926524d8ae15dc78961da6563ee6d --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unicode/unicode_bidi_pep672.py @@ -0,0 +1,8 @@ +""" +Example of trojan unicode, see https://trojansource.codes/ +This example was taken from PEP672 +""" +# pylint: disable=invalid-name + +# +1: [bidirectional-unicode] +example = "x‏" * 100 # "‏x" is assigned diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unicode/unicode_bidi_pep672.txt b/testbed/pylint-dev__pylint/tests/functional/u/unicode/unicode_bidi_pep672.txt new file mode 100644 index 0000000000000000000000000000000000000000..c4d3dcf5c9f9806a07ca0f1c29ef627fbc53061f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unicode/unicode_bidi_pep672.txt @@ -0,0 +1 @@ +bidirectional-unicode:8:0:8:43::Contains control characters that can permit obfuscated code executed differently than displayed:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unidiomatic_typecheck.py b/testbed/pylint-dev__pylint/tests/functional/u/unidiomatic_typecheck.py new file mode 100644 index 0000000000000000000000000000000000000000..2a1957d75e715c5fe7963b23cdc705fb42c6dae5 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unidiomatic_typecheck.py @@ -0,0 +1,70 @@ +"""Warnings for using type(x) == Y or type(x) is Y instead of isinstance(x, Y).""" +# pylint: disable=missing-docstring,expression-not-assigned,redefined-builtin,invalid-name,unnecessary-lambda-assignment,use-dict-literal + +def simple_positives(): + type(42) is int # [unidiomatic-typecheck] + type(42) is not int # [unidiomatic-typecheck] + type(42) == int # [unidiomatic-typecheck] + type(42) != int # [unidiomatic-typecheck] + +def simple_inference_positives(): + alias = type + alias(42) is int # [unidiomatic-typecheck] + alias(42) is not int # [unidiomatic-typecheck] + alias(42) == int # [unidiomatic-typecheck] + alias(42) != int # [unidiomatic-typecheck] + +def type_creation_negatives(): + type('Q', (object,), dict(a=1)) is int + type('Q', (object,), dict(a=1)) is not int + type('Q', (object,), dict(a=1)) == int + type('Q', (object,), dict(a=1)) != int + +def invalid_type_call_negatives(**kwargs): + type(bad=7) is int + type(bad=7) is not int + type(bad=7) == int + type(bad=7) != int + type(bad=7) in [int] + type(bad=7) not in [int] + type('bad', 7) is int + type('bad', 7) is not int + type('bad', 7) == int + type('bad', 7) != int + type('bad', 7) in [int] + type('bad', 7) not in [int] + type(**kwargs) is int + type(**kwargs) is not int + type(**kwargs) == int + type(**kwargs) != int + type(**kwargs) in [int] + type(**kwargs) not in [int] + +def local_var_shadowing_inference_negatives(): + type = lambda dummy: 7 + type(42) is int + type(42) is not int + type(42) == int + type(42) != int + type(42) in [int] + type(42) not in [int] + +def parameter_shadowing_inference_negatives(type): + type(42) is int + type(42) is not int + type(42) == int + type(42) != int + type(42) in [int] + type(42) not in [int] + +def deliberate_subclass_check_negatives(b): + type(42) is type(b) + type(42) is not type(b) + +def type_of_literals_positives(a): + type(a) is type([]) # [unidiomatic-typecheck] + type(a) is not type([]) # [unidiomatic-typecheck] + type(a) is type({}) # [unidiomatic-typecheck] + type(a) is not type({}) # [unidiomatic-typecheck] + type(a) is type("") # [unidiomatic-typecheck] + type(a) is not type("") # [unidiomatic-typecheck] diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unidiomatic_typecheck.txt b/testbed/pylint-dev__pylint/tests/functional/u/unidiomatic_typecheck.txt new file mode 100644 index 0000000000000000000000000000000000000000..84f5021d96c0ceb15bba4b15a1b3a7c2a9665fb5 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unidiomatic_typecheck.txt @@ -0,0 +1,14 @@ +unidiomatic-typecheck:5:4:5:19:simple_positives:Use isinstance() rather than type() for a typecheck.:UNDEFINED +unidiomatic-typecheck:6:4:6:23:simple_positives:Use isinstance() rather than type() for a typecheck.:UNDEFINED +unidiomatic-typecheck:7:4:7:19:simple_positives:Use isinstance() rather than type() for a typecheck.:UNDEFINED +unidiomatic-typecheck:8:4:8:19:simple_positives:Use isinstance() rather than type() for a typecheck.:UNDEFINED +unidiomatic-typecheck:12:4:12:20:simple_inference_positives:Use isinstance() rather than type() for a typecheck.:UNDEFINED +unidiomatic-typecheck:13:4:13:24:simple_inference_positives:Use isinstance() rather than type() for a typecheck.:UNDEFINED +unidiomatic-typecheck:14:4:14:20:simple_inference_positives:Use isinstance() rather than type() for a typecheck.:UNDEFINED +unidiomatic-typecheck:15:4:15:20:simple_inference_positives:Use isinstance() rather than type() for a typecheck.:UNDEFINED +unidiomatic-typecheck:65:4:65:23:type_of_literals_positives:Use isinstance() rather than type() for a typecheck.:UNDEFINED +unidiomatic-typecheck:66:4:66:27:type_of_literals_positives:Use isinstance() rather than type() for a typecheck.:UNDEFINED +unidiomatic-typecheck:67:4:67:23:type_of_literals_positives:Use isinstance() rather than type() for a typecheck.:UNDEFINED +unidiomatic-typecheck:68:4:68:27:type_of_literals_positives:Use isinstance() rather than type() for a typecheck.:UNDEFINED +unidiomatic-typecheck:69:4:69:23:type_of_literals_positives:Use isinstance() rather than type() for a typecheck.:UNDEFINED +unidiomatic-typecheck:70:4:70:27:type_of_literals_positives:Use isinstance() rather than type() for a typecheck.:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/uninferable_all_object.py b/testbed/pylint-dev__pylint/tests/functional/u/uninferable_all_object.py new file mode 100644 index 0000000000000000000000000000000000000000..3e565f9ebf9e75ed476f1cbd4115a1d858761e12 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/uninferable_all_object.py @@ -0,0 +1,9 @@ +"""Test that non-inferable __all__ variables do not make Pylint crash.""" + +__all__ = sorted([ + 'Dummy', + 'NonExistant', + 'path', + 'func', + 'inner', + 'InnerKlass']) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unknown_encoding_jython.py b/testbed/pylint-dev__pylint/tests/functional/u/unknown_encoding_jython.py new file mode 100644 index 0000000000000000000000000000000000000000..9863285124532cc408775585ecc6cc6d0d9a1313 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unknown_encoding_jython.py @@ -0,0 +1,6 @@ +# [syntax-error] +# -*- coding: IBO-8859-1 -*- +""" check correct unknown encoding declaration +""" + +__revision__ = 'יייי' diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unknown_encoding_jython.rc b/testbed/pylint-dev__pylint/tests/functional/u/unknown_encoding_jython.rc new file mode 100644 index 0000000000000000000000000000000000000000..ed0c011c82846ea7579cd45f5a0de85b26bb6ddf --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unknown_encoding_jython.rc @@ -0,0 +1,2 @@ +[testoptions] +except_implementations=PyPy,CPython,IronPython diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unknown_encoding_jython.txt b/testbed/pylint-dev__pylint/tests/functional/u/unknown_encoding_jython.txt new file mode 100644 index 0000000000000000000000000000000000000000..b7ff720d3c43744c78515dd1596ef468ceda2620 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unknown_encoding_jython.txt @@ -0,0 +1 @@ +syntax-error:1::"Unknown encoding: IBO-8859-1" diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unpacking/unpacking.py b/testbed/pylint-dev__pylint/tests/functional/u/unpacking/unpacking.py new file mode 100644 index 0000000000000000000000000000000000000000..59d9abbe41f0b99d623f702179c1bf6b9c463529 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unpacking/unpacking.py @@ -0,0 +1,11 @@ +""" Code for checking the display of the module +for unbalanced-tuple-unpacking and unpacking-non-sequence +""" + +def unpack(): + """ Return something""" + return (1, 2, 3) + +def nonseq(): + """ Return non sequence """ + return 1 diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unpacking/unpacking_generalizations.py b/testbed/pylint-dev__pylint/tests/functional/u/unpacking/unpacking_generalizations.py new file mode 100644 index 0000000000000000000000000000000000000000..1c5fb16b815011eadf99de3ffcb7b38dbe76a061 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unpacking/unpacking_generalizations.py @@ -0,0 +1,29 @@ +"""Various tests for unpacking generalizations added in Python 3.5""" + +# pylint: disable=missing-docstring, invalid-name + +def func_variadic_args(*args): + return args + + +def func_variadic_positional_args(a, b, *args): + return a, b, args + +def func_positional_args(a, b, c, d): + return a, b, c, d + + +func_variadic_args(*(2, 3), *(3, 4), *(4, 5)) +func_variadic_args(1, 2, *(2, 3), 2, 3, *(4, 5)) +func_variadic_positional_args(1, 2, *(4, 5), *(5, 6)) +func_variadic_positional_args(*(2, 3), *(4, 5), *(5, 6)) +func_variadic_positional_args(*(2, 3)) +func_variadic_positional_args(*(2, 3, 4)) +func_variadic_positional_args(1, 2, 3, *(3, 4)) + +func_positional_args(*(2, 3, 4), *(2, 3)) # [too-many-function-args] +func_positional_args(*(1, 2), 3) # [no-value-for-parameter] +func_positional_args(1, *(2, ), 3, *(4, 5)) # [too-many-function-args] +func_positional_args(1, 2, c=24, d=32, **{'d': 32}) # [repeated-keyword] +# +1: [repeated-keyword,repeated-keyword] +func_positional_args(1, 2, c=24, **{'c': 34, 'd': 33}, **{'d': 24}) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unpacking/unpacking_generalizations.txt b/testbed/pylint-dev__pylint/tests/functional/u/unpacking/unpacking_generalizations.txt new file mode 100644 index 0000000000000000000000000000000000000000..caecb193eaa60bfcbf4157af56230444d0466c40 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unpacking/unpacking_generalizations.txt @@ -0,0 +1,6 @@ +too-many-function-args:24:0:24:41::Too many positional arguments for function call:UNDEFINED +no-value-for-parameter:25:0:25:32::No value for argument 'd' in function call:UNDEFINED +too-many-function-args:26:0:26:43::Too many positional arguments for function call:UNDEFINED +repeated-keyword:27:0:27:51::Got multiple values for keyword argument 'd' in function call:UNDEFINED +repeated-keyword:29:0:29:67::Got multiple values for keyword argument 'c' in function call:UNDEFINED +repeated-keyword:29:0:29:67::Got multiple values for keyword argument 'd' in function call:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unpacking/unpacking_non_sequence.py b/testbed/pylint-dev__pylint/tests/functional/u/unpacking/unpacking_non_sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..feb465ecbec44a519aec6fd1df11cdbd2f844df5 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unpacking/unpacking_non_sequence.py @@ -0,0 +1,148 @@ +"""Check unpacking non-sequences in assignments. """ + +# pylint: disable=too-few-public-methods, invalid-name, attribute-defined-outside-init, unused-variable +# pylint: disable=using-constant-test, missing-docstring, wrong-import-order,wrong-import-position,no-else-return +from os import rename as nonseq_func +from functional.u.unpacking.unpacking import nonseq +from typing import NamedTuple + + +# Working + +class Seq: + """ sequence """ + def __init__(self): + self.items = range(2) + + def __getitem__(self, item): + return self.items[item] + + def __len__(self): + return len(self.items) + +class Iter: + """ Iterator """ + def __iter__(self): + for number in range(2): + yield number + +def good_unpacking(): + """ returns should be unpackable """ + if True: + return [1, 2] + else: + return (3, 4) + +def good_unpacking2(): + """ returns should be unpackable """ + return good_unpacking() + +class MetaIter(type): + "metaclass that makes classes that use it iterables" + def __iter__(cls): + return iter((1, 2)) + +class IterClass(metaclass=MetaIter): + "class that is iterable (and unpackable)" + +class AbstrClass: + "abstract class" + pair = None + + def setup_pair(self): + "abstract method" + raise NotImplementedError + + def __init__(self): + "error should not be emitted because setup_pair is abstract" + self.setup_pair() + x, y = self.pair + +a, b = [1, 2] +a, b = (1, 2) +a, b = set([1, 2]) +a, b = {1: 2, 2: 3} +a, b = "xy" +a, b = Seq() +a, b = Iter() +a, b = (number for number in range(2)) +a, b = good_unpacking() +a, b = good_unpacking2() +a, b = IterClass + +# Not working +class NonSeq: + """ does nothing """ + +a, b = NonSeq() # [unpacking-non-sequence] +a, b = ValueError # [unpacking-non-sequence] +a, b = None # [unpacking-non-sequence] +a, b = 1 # [unpacking-non-sequence] +a, b = nonseq # [unpacking-non-sequence] +a, b = nonseq() # [unpacking-non-sequence] +a, b = nonseq_func # [unpacking-non-sequence] + +class ClassUnpacking: + """ Check unpacking as instance attributes. """ + + def test(self): + """ test unpacking in instance attributes. """ + + self.a, self.b = 1, 2 + self.a, self.b = {1: 2, 2: 3} + self.a, self.b = "xy" + self.a, c = "xy" + c, self.a = good_unpacking() + self.a, self.b = Iter() + + self.a, self.b = NonSeq() # [unpacking-non-sequence] + self.a, self.b = ValueError # [unpacking-non-sequence] + self.a, c = nonseq_func # [unpacking-non-sequence] + +class TestBase: + 'base class with `test` method implementation' + @staticmethod + def test(data): + 'default implementation' + return data + +class Test(TestBase): + 'child class that overrides `test` method' + def __init__(self): + # no error should be emitted here as `test` is overridden in this class + (self.aaa, self.bbb, self.ccc) = self.test(None) + + @staticmethod + def test(data): + 'overridden implementation' + return (1, 2, 3) + + +import platform + + +def flow_control_false_positive(): + # This used to trigger an unpacking-non-sequence error. The problem was + # partially related to the fact that pylint does not understand flow control, + # but now it does not emit anymore, for this example, due to skipping it when + # determining an inference of multiple potential values. + # In any case, it is good having this repro as a test. + system, node, release, version, machine, processor = platform.uname() + # The previous line raises W0633 + return system, node, release, version, machine, processor + + +def flow_control_unpacking(var=None): + if var is not None: + var0, var1 = var + return var0, var1 + return None + + +class MyClass(NamedTuple): + x: float + y: float + + def sum(self): + x, y = self + return x + y diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unpacking/unpacking_non_sequence.txt b/testbed/pylint-dev__pylint/tests/functional/u/unpacking/unpacking_non_sequence.txt new file mode 100644 index 0000000000000000000000000000000000000000..473acde6f99a2271f7a81b7304f99ff622f08aa0 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unpacking/unpacking_non_sequence.txt @@ -0,0 +1,10 @@ +unpacking-non-sequence:77:0:77:15::Attempting to unpack a non-sequence defined at line 74:UNDEFINED +unpacking-non-sequence:78:0:78:17::Attempting to unpack a non-sequence:UNDEFINED +unpacking-non-sequence:79:0:79:11::Attempting to unpack a non-sequence 'None':UNDEFINED +unpacking-non-sequence:80:0:80:8::Attempting to unpack a non-sequence '1':UNDEFINED +unpacking-non-sequence:81:0:81:13::Attempting to unpack a non-sequence defined at line 9 of functional.u.unpacking.unpacking:UNDEFINED +unpacking-non-sequence:82:0:82:15::Attempting to unpack a non-sequence defined at line 11 of functional.u.unpacking.unpacking:UNDEFINED +unpacking-non-sequence:83:0:83:18::Attempting to unpack a non-sequence:UNDEFINED +unpacking-non-sequence:98:8:98:33:ClassUnpacking.test:Attempting to unpack a non-sequence defined at line 74:UNDEFINED +unpacking-non-sequence:99:8:99:35:ClassUnpacking.test:Attempting to unpack a non-sequence:UNDEFINED +unpacking-non-sequence:100:8:100:31:ClassUnpacking.test:Attempting to unpack a non-sequence:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unpacking/unpacking_non_sequence_py37.py b/testbed/pylint-dev__pylint/tests/functional/u/unpacking/unpacking_non_sequence_py37.py new file mode 100644 index 0000000000000000000000000000000000000000..13ab35b9a9b8b99ae83f3a108921bb43b767cafc --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unpacking/unpacking_non_sequence_py37.py @@ -0,0 +1,22 @@ +""" +https://github.com/PyCQA/pylint/issues/4895 +""" + +# pylint: disable=missing-docstring + +# Disabled because of a bug with pypy 3.8 see +# https://github.com/PyCQA/pylint/pull/7918#issuecomment-1352737369 +# pylint: disable=multiple-statements + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass + + +@dataclass +class Metric: + function: Callable[..., tuple[int, int]] + + def update(self): + _, _ = self.function() diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unpacking/unpacking_non_sequence_py37.rc b/testbed/pylint-dev__pylint/tests/functional/u/unpacking/unpacking_non_sequence_py37.rc new file mode 100644 index 0000000000000000000000000000000000000000..a17bb22dafb99eb4cf76db1ac0f83de586947860 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unpacking/unpacking_non_sequence_py37.rc @@ -0,0 +1,2 @@ +[testoptions] +min_pyver=3.7 diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unreachable.py b/testbed/pylint-dev__pylint/tests/functional/u/unreachable.py new file mode 100644 index 0000000000000000000000000000000000000000..0211a61366ee680b22f4cb762d646af31cb81298 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unreachable.py @@ -0,0 +1,81 @@ +# pylint: disable=missing-docstring, broad-exception-raised, too-few-public-methods, redefined-outer-name +# pylint: disable=consider-using-sys-exit, protected-access + +import os +import signal +import sys + +def func1(): + return 1 + print('unreachable') # [unreachable] + +def func2(): + while 1: + break + print('unreachable') # [unreachable] + +def func3(): + for i in (1, 2, 3): + print(i) + continue + print('unreachable') # [unreachable] + +def func4(): + raise Exception + return 1 / 0 # [unreachable] + + +# https://github.com/PyCQA/pylint/issues/4698 +def func5(): + """Empty generator functions should be allowed.""" + return + yield + +def func6(): + """Add 'unreachable' if yield is followed by another node.""" + return + yield + print("unreachable") # [unreachable] + +def func7(): + sys.exit(1) + var = 2 + 2 # [unreachable] + print(var) + +def func8(): + signal.signal(signal.SIGTERM, lambda *args: sys.exit(0)) + try: + print(1) + except KeyboardInterrupt: + pass + +class FalseExit: + def exit(self, number): + print(f"False positive this is not sys.exit({number})") + +def func_false_exit(): + sys = FalseExit() + sys.exit(1) + var = 2 + 2 + print(var) + +def func9(): + os._exit() + var = 2 + 2 # [unreachable] + print(var) + +def func10(): + exit() + var = 2 + 2 # [unreachable] + print(var) + +def func11(): + quit() + var = 2 + 2 # [unreachable] + print(var) + +incognito_function = sys.exit +def func12(): + incognito_function() + var = 2 + 2 # [unreachable] + print(var) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unreachable.txt b/testbed/pylint-dev__pylint/tests/functional/u/unreachable.txt new file mode 100644 index 0000000000000000000000000000000000000000..82f9797aa1d78598d6a69bb4664d56f0cbb53929 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unreachable.txt @@ -0,0 +1,10 @@ +unreachable:10:4:10:24:func1:Unreachable code:HIGH +unreachable:15:8:15:28:func2:Unreachable code:HIGH +unreachable:21:8:21:28:func3:Unreachable code:HIGH +unreachable:25:4:25:16:func4:Unreachable code:HIGH +unreachable:38:4:38:24:func6:Unreachable code:HIGH +unreachable:42:4:42:15:func7:Unreachable code:INFERENCE +unreachable:64:4:64:15:func9:Unreachable code:INFERENCE +unreachable:69:4:69:15:func10:Unreachable code:INFERENCE +unreachable:74:4:74:15:func11:Unreachable code:INFERENCE +unreachable:80:4:80:15:func12:Unreachable code:INFERENCE diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unrecognized_inline_option.py b/testbed/pylint-dev__pylint/tests/functional/u/unrecognized_inline_option.py new file mode 100644 index 0000000000000000000000000000000000000000..3163b1ea6e3bbe2788f9b30088543eff61d00f6b --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unrecognized_inline_option.py @@ -0,0 +1,3 @@ +# +1: [unrecognized-inline-option] +# pylint:bouboule=1 +"""Check unknown option""" diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unrecognized_inline_option.txt b/testbed/pylint-dev__pylint/tests/functional/u/unrecognized_inline_option.txt new file mode 100644 index 0000000000000000000000000000000000000000..45ac6f114a0b42d06a9813cb00094e94716bd244 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unrecognized_inline_option.txt @@ -0,0 +1 @@ +unrecognized-inline-option:2:0:None:None::Unrecognized file option 'bouboule':UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unspecified_encoding_py38.py b/testbed/pylint-dev__pylint/tests/functional/u/unspecified_encoding_py38.py new file mode 100644 index 0000000000000000000000000000000000000000..66b8523f4c7ce899ef943081919e65caa1faa499 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unspecified_encoding_py38.py @@ -0,0 +1,164 @@ +"""Warnings for using open() without specifying an encoding""" +# pylint: disable=consider-using-with, too-few-public-methods +import dataclasses +import io +import locale +from pathlib import Path +from typing import Optional + +FILENAME = "foo.bar" +open(FILENAME, "w", encoding="utf-8") +open(FILENAME, "wb") +open(FILENAME, "w+b") +open(FILENAME) # [unspecified-encoding] +open(FILENAME, "wt") # [unspecified-encoding] +open(FILENAME, "w+") # [unspecified-encoding] +open(FILENAME, "w", encoding=None) # [unspecified-encoding] +open(FILENAME, "r") # [unspecified-encoding] + +with open(FILENAME, encoding="utf8", errors="surrogateescape") as f: + pass + +LOCALE_ENCODING = locale.getlocale()[1] +with open(FILENAME, encoding=LOCALE_ENCODING) as f: + pass + +with open(FILENAME) as f: # [unspecified-encoding] + pass + +with open(FILENAME, encoding=None) as f: # [unspecified-encoding] + pass + +LOCALE_ENCODING = None +with open(FILENAME, encoding=LOCALE_ENCODING) as f: # [unspecified-encoding] + pass + +io.open(FILENAME, "w+b") +io.open_code(FILENAME) +io.open(FILENAME) # [unspecified-encoding] +io.open(FILENAME, "wt") # [unspecified-encoding] +io.open(FILENAME, "w+") # [unspecified-encoding] +io.open(FILENAME, "w", encoding=None) # [unspecified-encoding] + +with io.open(FILENAME, encoding="utf8", errors="surrogateescape") as f: + pass + +LOCALE_ENCODING = locale.getlocale()[1] +with io.open(FILENAME, encoding=LOCALE_ENCODING) as f: + pass + +with io.open(FILENAME) as f: # [unspecified-encoding] + pass + +with io.open(FILENAME, encoding=None) as f: # [unspecified-encoding] + pass + +LOCALE_ENCODING = None +with io.open(FILENAME, encoding=LOCALE_ENCODING) as f: # [unspecified-encoding] + pass + +LOCALE_ENCODING = locale.getlocale()[1] +Path(FILENAME).read_text(encoding=LOCALE_ENCODING) +Path(FILENAME).read_text(encoding="utf8") +Path(FILENAME).read_text("utf8") + +LOCALE_ENCODING = None +Path(FILENAME).read_text() # [unspecified-encoding] +Path(FILENAME).read_text(encoding=None) # [unspecified-encoding] +Path(FILENAME).read_text(encoding=LOCALE_ENCODING) # [unspecified-encoding] + +LOCALE_ENCODING = locale.getlocale()[1] +Path(FILENAME).write_text("string", encoding=LOCALE_ENCODING) +Path(FILENAME).write_text("string", encoding="utf8") + +LOCALE_ENCODING = None +Path(FILENAME).write_text("string") # [unspecified-encoding] +Path(FILENAME).write_text("string", encoding=None) # [unspecified-encoding] +Path(FILENAME).write_text("string", encoding=LOCALE_ENCODING) # [unspecified-encoding] + +LOCALE_ENCODING = locale.getlocale()[1] +Path(FILENAME).open("w+b") +Path(FILENAME).open() # [unspecified-encoding] +Path(FILENAME).open("wt") # [unspecified-encoding] +Path(FILENAME).open("w+") # [unspecified-encoding] +Path(FILENAME).open("w", encoding=None) # [unspecified-encoding] +Path(FILENAME).open("w", encoding=LOCALE_ENCODING) + + +# Tests for storing data about open calls. +# Most of these are regression tests for a crash +# reported in https://github.com/PyCQA/pylint/issues/5321 + +# -- Constants +MODE = "wb" +open(FILENAME, mode=MODE) + + +# -- Functions +def return_mode_function(): + """Return a mode for open call""" + return "wb" + +open(FILENAME, mode=return_mode_function()) + + +# -- Classes +class IOData: + """Class that returns mode strings""" + + mode = "wb" + + def __init__(self): + self.my_mode = "wb" + + @staticmethod + def my_mode_method(): + """Returns a pre-defined mode""" + return "wb" + + @staticmethod + def my_mode_method_returner(mode: str) -> str: + """Returns the supplied mode""" + return mode + + +open(FILENAME, mode=IOData.mode) +open(FILENAME, mode=IOData().my_mode) +open(FILENAME, mode=IOData().my_mode_method()) +open(FILENAME, mode=IOData().my_mode_method_returner("wb")) +# Invalid value but shouldn't crash, reported in https://github.com/PyCQA/pylint/issues/5321 +open(FILENAME, mode=IOData) + + +# -- Dataclasses +@dataclasses.dataclass +class IOArgs: + """Dataclass storing information about how to open a file""" + + encoding: Optional[str] + mode: str + + +args_good_one = IOArgs(encoding=None, mode="wb") + +# Test for crash reported in https://github.com/PyCQA/pylint/issues/5321 +open(FILENAME, args_good_one.mode, encoding=args_good_one.encoding) + +# Positional arguments +open(FILENAME, "w", -1, "utf-8") +open(FILENAME, "w", -1) # [unspecified-encoding] + +Path(FILENAME).open("w", -1, "utf-8") +Path(FILENAME).open("w", -1) # [unspecified-encoding] + +Path(FILENAME).read_text("utf-8") +Path(FILENAME).read_text() # [unspecified-encoding] + +Path(FILENAME).write_text("string", "utf-8") +Path(FILENAME).write_text("string") # [unspecified-encoding] + +# Test for crash reported in https://github.com/PyCQA/pylint/issues/5731 +open(FILENAME, mode=None) # [bad-open-mode, unspecified-encoding] + +# Test for crash reported in https://github.com/PyCQA/pylint/issues/6414 +open('foo', mode=2) # [bad-open-mode, unspecified-encoding] diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unspecified_encoding_py38.rc b/testbed/pylint-dev__pylint/tests/functional/u/unspecified_encoding_py38.rc new file mode 100644 index 0000000000000000000000000000000000000000..85fc502b372ea64005d4e09627da9827c325d447 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unspecified_encoding_py38.rc @@ -0,0 +1,2 @@ +[testoptions] +min_pyver=3.8 diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unspecified_encoding_py38.txt b/testbed/pylint-dev__pylint/tests/functional/u/unspecified_encoding_py38.txt new file mode 100644 index 0000000000000000000000000000000000000000..8cf19dee45e05bb4565e87f3a32faef5b2b59771 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unspecified_encoding_py38.txt @@ -0,0 +1,33 @@ +unspecified-encoding:13:0:13:14::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:14:0:14:20::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:15:0:15:20::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:16:0:16:34::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:17:0:17:19::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:26:5:26:19::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:29:5:29:34::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:33:5:33:45::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:38:0:38:17::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:39:0:39:23::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:40:0:40:23::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:41:0:41:37::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:50:5:50:22::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:53:5:53:37::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:57:5:57:48::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:66:0:66:26::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:67:0:67:39::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:68:0:68:50::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:75:0:75:35::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:76:0:76:50::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:77:0:77:61::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:81:0:81:21::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:82:0:82:25::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:83:0:83:25::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:84:0:84:39::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:149:0:149:23::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:152:0:152:28::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:155:0:155:26::Using open without explicitly specifying an encoding:UNDEFINED +unspecified-encoding:158:0:158:35::Using open without explicitly specifying an encoding:UNDEFINED +bad-open-mode:161:0:161:25::"""None"" is not a valid mode for open.":UNDEFINED +unspecified-encoding:161:0:161:25::Using open without explicitly specifying an encoding:UNDEFINED +bad-open-mode:164:0:164:19::"""2"" is not a valid mode for open.":UNDEFINED +unspecified-encoding:164:0:164:19::Using open without explicitly specifying an encoding:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unsubscriptable_object.py b/testbed/pylint-dev__pylint/tests/functional/u/unsubscriptable_object.py new file mode 100644 index 0000000000000000000000000000000000000000..0b7da78b3877f64ef68e1c9b60291d8d1c422bda --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unsubscriptable_object.py @@ -0,0 +1,7 @@ +"""Tests for unscubscriptable-object""" + +# Test for typing.NamedTuple +# See: https://github.com/PyCQA/pylint/issues/1295 +import typing + +MyType = typing.Tuple[str, str] diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unsubscriptable_value.py b/testbed/pylint-dev__pylint/tests/functional/u/unsubscriptable_value.py new file mode 100644 index 0000000000000000000000000000000000000000..79e17903b713d2b092ebf9a3bc3223f96f1ef2e2 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unsubscriptable_value.py @@ -0,0 +1,127 @@ +""" +Checks that value used in a subscript supports subscription +(i.e. defines __getitem__ method). +""" +# pylint: disable=missing-docstring,pointless-statement,expression-not-assigned,wrong-import-position, unnecessary-comprehension +# pylint: disable=too-few-public-methods,import-error,invalid-name,wrong-import-order, redundant-u-string-prefix +# pylint: disable=use-dict-literal + +# primitives +numbers = [1, 2, 3] +numbers[0] +"123"[0] +u"123"[0] +b"123"[0] +bytearray(b"123")[0] +dict(a=1, b=2)['a'] +(1, 2, 3)[0] + +# list/dict comprehensions are fine +[x for x in range(10)][0] +{x: 10 - x for x in range(10)}[0] + + +# instances +class NonSubscriptable: + pass + +class Subscriptable: + def __getitem__(self, key): + return key + key + +NonSubscriptable()[0] # [unsubscriptable-object] +NonSubscriptable[0] # [unsubscriptable-object] +Subscriptable()[0] +Subscriptable[0] # [unsubscriptable-object] + +# generators are not subscriptable +def powers_of_two(): + k = 0 + while k < 10: + yield 2 ** k + k += 1 + +powers_of_two()[0] # [unsubscriptable-object] +powers_of_two[0] # [unsubscriptable-object] + + +# check that primitive non subscriptable types are caught +True[0] # [unsubscriptable-object] +None[0] # [unsubscriptable-object] +8.5[0] # [unsubscriptable-object] +10[0] # [unsubscriptable-object] + +# sets are not subscriptable +{x ** 2 for x in range(10)}[0] # [unsubscriptable-object] +set(numbers)[0] # [unsubscriptable-object] +frozenset(numbers)[0] # [unsubscriptable-object] + +# skip instances with unknown base classes +from some_missing_module import LibSubscriptable + +class MaybeSubscriptable(LibSubscriptable): + pass + +MaybeSubscriptable()[0] + +# subscriptable classes (through metaclasses) + +class MetaSubscriptable(type): + def __getitem__(cls, key): + return key + key + +class SubscriptableClass(metaclass=MetaSubscriptable): + pass + +SubscriptableClass[0] +SubscriptableClass()[0] # [unsubscriptable-object] + +# functions are not subscriptable +def test(*args, **kwargs): + return args, kwargs + +test()[0] +test[0] # [unsubscriptable-object] + +# deque +from collections import deque +deq = deque(maxlen=10) +deq.append(42) +deq[0] + + +class AbstractClass: + + def __init__(self): + self.ala = {i for i in range(10)} + self.bala = [i for i in range(10)] + self.portocala = None + + def test_unsubscriptable(self): + self.bala[0] + self.portocala[0] + + +class ClassMixin: + + def __init__(self): + self.ala = {i for i in range(10)} + self.bala = [i for i in range(10)] + self.portocala = None + + def test_unsubscriptable(self): + self.bala[0] + self.portocala[0] + + +def return_an_int(param): + """Returns an int""" + if param == 0: + return 1 + return 0 + + +def test_one(param): + """Should complain about var_one[0], but doesn't""" + var_one = return_an_int(param) + return var_one[0] # [unsubscriptable-object] diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unsubscriptable_value.rc b/testbed/pylint-dev__pylint/tests/functional/u/unsubscriptable_value.rc new file mode 100644 index 0000000000000000000000000000000000000000..6a8ee96cae403ae9ee5b8e1ab7fba0008491922a --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unsubscriptable_value.rc @@ -0,0 +1,2 @@ +[testoptions] +requires = six diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unsubscriptable_value.txt b/testbed/pylint-dev__pylint/tests/functional/u/unsubscriptable_value.txt new file mode 100644 index 0000000000000000000000000000000000000000..d0833b600b239e8f527f7049f7ac9898184656d1 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unsubscriptable_value.txt @@ -0,0 +1,15 @@ +unsubscriptable-object:32:0:32:18::Value 'NonSubscriptable()' is unsubscriptable:UNDEFINED +unsubscriptable-object:33:0:33:16::Value 'NonSubscriptable' is unsubscriptable:UNDEFINED +unsubscriptable-object:35:0:35:13::Value 'Subscriptable' is unsubscriptable:UNDEFINED +unsubscriptable-object:44:0:44:15::Value 'powers_of_two()' is unsubscriptable:UNDEFINED +unsubscriptable-object:45:0:45:13::Value 'powers_of_two' is unsubscriptable:UNDEFINED +unsubscriptable-object:49:0:49:4::Value 'True' is unsubscriptable:UNDEFINED +unsubscriptable-object:50:0:50:4::Value 'None' is unsubscriptable:UNDEFINED +unsubscriptable-object:51:0:51:3::Value '8.5' is unsubscriptable:UNDEFINED +unsubscriptable-object:52:0:52:2::Value '10' is unsubscriptable:UNDEFINED +unsubscriptable-object:55:0:55:27::Value '{x**2 for x in range(10)}' is unsubscriptable:UNDEFINED +unsubscriptable-object:56:0:56:12::Value 'set(numbers)' is unsubscriptable:UNDEFINED +unsubscriptable-object:57:0:57:18::Value 'frozenset(numbers)' is unsubscriptable:UNDEFINED +unsubscriptable-object:77:0:77:20::Value 'SubscriptableClass()' is unsubscriptable:UNDEFINED +unsubscriptable-object:84:0:84:4::Value 'test' is unsubscriptable:UNDEFINED +unsubscriptable-object:127:11:127:18:test_one:Value 'var_one' is unsubscriptable:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unsubscriptable_value_py37.py b/testbed/pylint-dev__pylint/tests/functional/u/unsubscriptable_value_py37.py new file mode 100644 index 0000000000000000000000000000000000000000..acbbe6bdd8cb4d746c9f6ab3dad75d19be4813d7 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unsubscriptable_value_py37.py @@ -0,0 +1,17 @@ +# pylint: disable=missing-class-docstring,too-few-public-methods,pointless-statement,expression-not-assigned +""" +Checks that class used in a subscript supports subscription +(i.e. defines __class_getitem__ method). +""" +import typing + + +class Subscriptable: + + def __class_getitem__(cls, params): + pass + +Subscriptable[0] +Subscriptable()[0] # [unsubscriptable-object] + +a: typing.List[int] diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unsubscriptable_value_py37.rc b/testbed/pylint-dev__pylint/tests/functional/u/unsubscriptable_value_py37.rc new file mode 100644 index 0000000000000000000000000000000000000000..a17bb22dafb99eb4cf76db1ac0f83de586947860 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unsubscriptable_value_py37.rc @@ -0,0 +1,2 @@ +[testoptions] +min_pyver=3.7 diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unsubscriptable_value_py37.txt b/testbed/pylint-dev__pylint/tests/functional/u/unsubscriptable_value_py37.txt new file mode 100644 index 0000000000000000000000000000000000000000..3e3e5544408c8518ba365f4c7ae710f51072ae23 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unsubscriptable_value_py37.txt @@ -0,0 +1 @@ +unsubscriptable-object:15:0:15:15::Value 'Subscriptable()' is unsubscriptable:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_argument.py b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_argument.py new file mode 100644 index 0000000000000000000000000000000000000000..b46c1e4d75f017d6f6dd1f825d122a5b8b727749 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_argument.py @@ -0,0 +1,109 @@ +# pylint: disable=missing-docstring,too-few-public-methods + +def test_unused(first, second, _not_used): # [unused-argument, unused-argument] + pass + + +def test_prefixed_with_ignored(first, ignored_second): + first() + + +def test_prefixed_with_unused(first, unused_second): + first() + +# for Sub.inherited, only the warning for "aay" is desired. +# The warnings for "aab" and "aac" are most likely false positives though, +# because there could be another subclass that overrides the same method and does +# use the arguments (e.g. Sub2) + + +class Base: + "parent" + def inherited(self, aaa, aab, aac): + "abstract method" + raise NotImplementedError + +class Sub(Base): + "child 1" + def inherited(self, aaa, aab, aac): + "overridden method, though don't use every argument" + return aaa + + def newmethod(self, aax, aay): # [unused-argument] + "another method, warning for aay desired" + return self, aax + +class Sub2(Base): + "child 1" + + def inherited(self, aaa, aab, aac): + "overridden method, use every argument" + return aaa + aab + aac + +def metadata_from_dict(key): + """ + Should not raise unused-argument message because key is + used inside comprehension dict + """ + return {key: str(value) for key, value in key.items()} + + +def metadata_from_dict_2(key): + """Similar, but with more nesting""" + return {key: (a, b) for key, (a, b) in key.items()} + + +# pylint: disable=too-few-public-methods, wrong-import-position + + +def function(arg=1): # [unused-argument] + """ignore arg""" + + +class AAAA: + """dummy class""" + + def method(self, arg): # [unused-argument] + """dummy method""" + print(self) + def __init__(self, *unused_args, **unused_kwargs): + pass + + @classmethod + def selected(cls, *args, **kwargs): # [unused-argument, unused-argument] + """called by the registry when the vobject has been selected. + """ + return cls + + def using_inner_function(self, etype, size=1): + """return a fake result set for a particular entity type""" + rset = AAAA([('A',)]*size, f'{etype} X', + description=[(etype,)]*size) + def inner(row, col=0, etype=etype, req=self, rset=rset): + """inner using all its argument""" + # pylint: disable=maybe-no-member + return req.vreg.etype_class(etype)(req, rset, row, col) + # pylint: disable = attribute-defined-outside-init + rset.get_entity = inner + +class BBBB: + """dummy class""" + + def __init__(self, arg): # [unused-argument] + """Constructor with an extra parameter. Should raise a warning""" + self.spam = 1 + + +# Regression test for https://github.com/PyCQA/pylint/issues/5771 +# involving keyword-only arguments +class Ancestor: + def __init__(self): + self.thing = None + + def set_thing(self, thing, *, other=None): # [unused-argument] + self.thing = thing + +class Descendant(Ancestor): + def set_thing(self, thing, *, other=None): + """Subclass does not raise unused-argument""" + self.thing = thing diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_global_variable4.txt b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_global_variable4.txt new file mode 100644 index 0000000000000000000000000000000000000000..a90f8f6ff98f899ad3cf9554fcdce43a66fa4c62 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_global_variable4.txt @@ -0,0 +1,2 @@ +unused-variable:2:0:2:3::Unused variable 'VAR':UNDEFINED +unused-variable:3:0:3:3::Unused variable 'VAR':UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import.py b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import.py new file mode 100644 index 0000000000000000000000000000000000000000..3534cd0cf387d746e64f27d31a61679a6f8ca1cf --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import.py @@ -0,0 +1,112 @@ +"""unused import""" +# pylint: disable=undefined-all-variable, import-error, too-few-public-methods, missing-docstring,wrong-import-position, multiple-imports +import xml.etree # [unused-import] +import xml.sax # [unused-import] +import os.path as test # [unused-import] +from abc import ABCMeta +from sys import argv as test2 # [unused-import] +from sys import flags # [unused-import] + +# +1:[unused-import,unused-import] +from collections import deque, OrderedDict, Counter +import re, html.parser # [unused-import] + +DATA = Counter() +# pylint: disable=self-assigning-variable +from fake import SomeName, SomeOtherName # [unused-import] + + +class SomeClass: + SomeName = SomeName # https://bitbucket.org/logilab/pylint/issue/475 + SomeOtherName = 1 + SomeOtherName = SomeOtherName + + +from never import __all__ + +# pylint: disable=wrong-import-order,ungrouped-imports,reimported +import typing +from typing import TYPE_CHECKING +import typing as t + + +if typing.TYPE_CHECKING: + import collections +if TYPE_CHECKING: + import itertools +if t.TYPE_CHECKING: + import xml + + +def get_ordered_dict() -> "collections.OrderedDict": + return [] + + +def get_itertools_obj() -> "itertools.count": + return [] + + +def use_html_parser() -> "html.parser.HTMLParser": + return html.parser.HTMLParser + + +import os # [unused-import] +import sys + + +class NonRegr: + """???""" + + def __init__(self): + print("initialized") + + def sys(self): + """should not get sys from there...""" + print(self, sys) + + def dummy(self, truc): + """yo""" + return self, truc + + def blop(self): + """yo""" + print(self, "blip") + + +if TYPE_CHECKING: + if sys.version_info >= (3, 6, 2): + from typing import NoReturn + +# Pathological cases +from io import TYPE_CHECKING # pylint: disable=no-name-in-module +import trace as t +import astroid as typing # pylint: disable=shadowed-import + +TYPE_CHECKING = "red herring" + +if TYPE_CHECKING: + import unittest # [unused-import] +if t.TYPE_CHECKING: # pylint: disable=no-member + import uuid # [unused-import] +if typing.TYPE_CHECKING: # pylint: disable=no-member + import warnings # [unused-import] +if typing.TYPE_CHECKING_WITH_MAGIC: # pylint: disable=no-member + import compileall # [unused-import] + +TYPE_CHECKING = False +if TYPE_CHECKING: + import zoneinfo + + +class WithMetaclass(metaclass=ABCMeta): + pass + + +# Regression test for https://github.com/PyCQA/pylint/issues/3765 +# `unused-import` should not be emitted when a type annotation uses quotation marks +from typing import List + + +class Bee: + def get_all_classes(self) -> "List[Bee]": + pass diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import.txt b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import.txt new file mode 100644 index 0000000000000000000000000000000000000000..f242bcb23d522835f37d38d38ed5f97c658273de --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import.txt @@ -0,0 +1,14 @@ +unused-import:3:0:3:16::Unused import xml.etree:UNDEFINED +unused-import:4:0:4:14::Unused import xml.sax:UNDEFINED +unused-import:5:0:5:22::Unused os.path imported as test:UNDEFINED +unused-import:7:0:7:29::Unused argv imported from sys as test2:UNDEFINED +unused-import:8:0:8:21::Unused flags imported from sys:UNDEFINED +unused-import:11:0:11:51::Unused OrderedDict imported from collections:UNDEFINED +unused-import:11:0:11:51::Unused deque imported from collections:UNDEFINED +unused-import:12:0:12:22::Unused import re:UNDEFINED +unused-import:16:0:16:40::Unused SomeOtherName imported from fake:UNDEFINED +unused-import:53:0:53:9::Unused import os:UNDEFINED +unused-import:88:4:88:19::Unused import unittest:UNDEFINED +unused-import:90:4:90:15::Unused import uuid:UNDEFINED +unused-import:92:4:92:19::Unused import warnings:UNDEFINED +unused-import:94:4:94:21::Unused import compileall:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_class_def_keyword.py b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_class_def_keyword.py new file mode 100644 index 0000000000000000000000000000000000000000..0d6b5998736b6b4b627732a4a69dc3e157230900 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_class_def_keyword.py @@ -0,0 +1,38 @@ +""" +Test false-positive for unused-import on class keyword arguments + + https://github.com/PyCQA/pylint/issues/3202 +""" +# pylint: disable=missing-docstring,too-few-public-methods,invalid-name,import-error + +# Imports don't exist! Only check `unused-import` +from const import DOMAIN +from const import DOMAIN_2 +from const import DOMAIN_3 + + +class Child: + def __init_subclass__(cls, **kwargs): + pass + +class Parent(Child, domain=DOMAIN): + pass + + +# Alternative 1 +class Parent_2(Child, domain=DOMAIN_2): + DOMAIN_2 = DOMAIN_2 + + +# Alternative 2 +class A: + def __init__(self, arg): + pass + +class B: + CONF = "Hello World" + SCHEMA = A(arg=CONF) + + +# Test normal instantiation +A(arg=DOMAIN_3) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_everything_disabled.py b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_everything_disabled.py new file mode 100644 index 0000000000000000000000000000000000000000..381cd012fd2eb51580c55101036ddb0f7c6e851c --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_everything_disabled.py @@ -0,0 +1,17 @@ +"""Test that unused-import is not emitted here when everything else is disabled + +https://github.com/PyCQA/pylint/issues/3445 +https://github.com/PyCQA/pylint/issues/6089 +""" +from math import e, pi +from os import environ + +for k, v in environ.items(): + print(k, v) + + +class MyClass: + """For the bug reported in #6089 it is important to use the same names for the class attributes as in the imports.""" + + e = float(e) + pi = pi diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_positional_only_py38.py b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_positional_only_py38.py new file mode 100644 index 0000000000000000000000000000000000000000..693a377d9b34bea0b813ee5a913dad13e2b8d28b --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_positional_only_py38.py @@ -0,0 +1,10 @@ +"""Test that positional only argument annotations are properly marked as consumed + +https://github.com/PyCQA/pylint/issues/3462 +""" +from typing import AnyStr, Set + + +def func(arg: AnyStr, /, arg2: Set[str]): + """Uses positional only arguments""" + return arg, arg2 diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_positional_only_py38.rc b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_positional_only_py38.rc new file mode 100644 index 0000000000000000000000000000000000000000..85fc502b372ea64005d4e09627da9827c325d447 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_positional_only_py38.rc @@ -0,0 +1,2 @@ +[testoptions] +min_pyver=3.8 diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_py30.py b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_py30.py new file mode 100644 index 0000000000000000000000000000000000000000..2e79b5795634f29c452c09f7b3031d86b3c4ddea --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_py30.py @@ -0,0 +1,19 @@ +"""check unused import for metaclasses""" +# pylint: disable=too-few-public-methods,wrong-import-position,ungrouped-imports + +import abc +import sys +from abc import ABCMeta +from abc import ABCMeta as SomethingElse # [reimported] + +class Meta(metaclass=abc.ABCMeta): + """ Test """ + def __init__(self): + self.data = sys.executable + self.test = abc + +class Meta2(metaclass=ABCMeta): + """ Test """ + +class Meta3(metaclass=SomethingElse): + """ test """ diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_py30.txt b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_py30.txt new file mode 100644 index 0000000000000000000000000000000000000000..69c2e293db982fb2367192b45da9362fe9717290 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_py30.txt @@ -0,0 +1 @@ +reimported:7:0:7:40::Reimport 'ABCMeta' (imported line 6):HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_py39.py b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_py39.py new file mode 100644 index 0000000000000000000000000000000000000000..2a897b1741dc08f979d8b4b99b35bc51dfb9a19a --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_py39.py @@ -0,0 +1,10 @@ +""" +Test that a constant parameter of `typing.Annotated` does not emit `unused-import`. +`typing.Annotated` was introduced in Python version 3.9 +""" + +from pathlib import Path # [unused-import] +import typing as t + + +example: t.Annotated[str, "Path"] = "/foo/bar" diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_py39.rc b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_py39.rc new file mode 100644 index 0000000000000000000000000000000000000000..16b75eea755adb7d72c2126ffcbd214ca81ea0c3 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_py39.rc @@ -0,0 +1,2 @@ +[testoptions] +min_pyver=3.9 diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_py39.txt b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_py39.txt new file mode 100644 index 0000000000000000000000000000000000000000..50e5ad5a96f5082aa6dc44e3e00f1fbe97fb581f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_import_py39.txt @@ -0,0 +1 @@ +unused-import:6:0:6:24::Unused Path imported from pathlib:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_name_in_string_literal_type_annotation.py b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_name_in_string_literal_type_annotation.py new file mode 100644 index 0000000000000000000000000000000000000000..400e7725e0456abd47d385fa5f15926c8832dbd3 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_name_in_string_literal_type_annotation.py @@ -0,0 +1,31 @@ +"""Test if pylint sees names inside string literal type annotations. #3299""" +# pylint: disable=too-few-public-methods + +from argparse import ArgumentParser, Namespace +import os +from os import PathLike +from pathlib import Path +from typing import NoReturn, Set + +# unused-import shouldn't be emitted for Path +example1: Set["Path"] = set() + +def example2(_: "ArgumentParser") -> "NoReturn": + """unused-import shouldn't be emitted for ArgumentParser or NoReturn.""" + while True: + pass + +def example3(_: "os.PathLike[str]") -> None: + """unused-import shouldn't be emitted for os.""" + +def example4(_: "PathLike[str]") -> None: + """unused-import shouldn't be emitted for PathLike.""" + +# pylint shouldn't crash with the following strings in a type annotation context +example5: Set[""] +example6: Set[" "] +example7: Set["?"] + +class Class: + """unused-import shouldn't be emitted for Namespace""" + cls: "Namespace" diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_name_in_string_literal_type_annotation_py310.py b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_name_in_string_literal_type_annotation_py310.py new file mode 100644 index 0000000000000000000000000000000000000000..00bf5799fcbfbe73ce6f4e40d7a96828423136e8 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_name_in_string_literal_type_annotation_py310.py @@ -0,0 +1,9 @@ +# pylint: disable=missing-docstring + +from typing import TypeAlias + +def unused_variable_should_not_be_emitted(): + """unused-variable shouldn't be emitted for Example.""" + Example: TypeAlias = int + result: set["Example"] = set() + return result diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_name_in_string_literal_type_annotation_py310.rc b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_name_in_string_literal_type_annotation_py310.rc new file mode 100644 index 0000000000000000000000000000000000000000..68a8c8ef157980e74dc55bae272edcd141052de0 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_name_in_string_literal_type_annotation_py310.rc @@ -0,0 +1,2 @@ +[testoptions] +min_pyver=3.10 diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_name_in_string_literal_type_annotation_py38.py b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_name_in_string_literal_type_annotation_py38.py new file mode 100644 index 0000000000000000000000000000000000000000..96658ae369fc8b96d11da61a8708d4de6a3bd492 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_name_in_string_literal_type_annotation_py38.py @@ -0,0 +1,27 @@ +# pylint: disable=missing-docstring + +from argparse import ArgumentParser # [unused-import] +from argparse import Namespace # [unused-import] +import http # [unused-import] +from http import HTTPStatus +import typing as t +from typing import Literal as Lit + +# str inside Literal shouldn't be treated as names +example1: t.Literal["ArgumentParser", Lit["Namespace", "ArgumentParser"]] + + +def unused_variable_example(): + hello = "hello" # [unused-variable] + world = "world" # [unused-variable] + example2: Lit["hello", "world"] = "hello" + return example2 + + +# pylint shouldn't crash with the following strings in a type annotation context +example3: Lit["", " ", "?"] = "?" + + +# See https://peps.python.org/pep-0586/#literals-enums-and-forward-references +example4: t.Literal["http.HTTPStatus.OK", "http.HTTPStatus.NOT_FOUND"] +example5: "t.Literal[HTTPStatus.OK, HTTPStatus.NOT_FOUND]" diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_name_in_string_literal_type_annotation_py38.rc b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_name_in_string_literal_type_annotation_py38.rc new file mode 100644 index 0000000000000000000000000000000000000000..85fc502b372ea64005d4e09627da9827c325d447 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_name_in_string_literal_type_annotation_py38.rc @@ -0,0 +1,2 @@ +[testoptions] +min_pyver=3.8 diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_name_in_string_literal_type_annotation_py39.py b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_name_in_string_literal_type_annotation_py39.py new file mode 100644 index 0000000000000000000000000000000000000000..1258844cd2ba5e1f4b6c63357bda2c4a06ed75fd --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_name_in_string_literal_type_annotation_py39.py @@ -0,0 +1,11 @@ +# pylint: disable=missing-docstring + +import graphlib +from graphlib import TopologicalSorter + +def example( + sorter1: "graphlib.TopologicalSorter[int]", + sorter2: "TopologicalSorter[str]", +) -> None: + """unused-import shouldn't be emitted for graphlib or TopologicalSorter.""" + print(sorter1, sorter2) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_name_in_string_literal_type_annotation_py39.rc b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_name_in_string_literal_type_annotation_py39.rc new file mode 100644 index 0000000000000000000000000000000000000000..16b75eea755adb7d72c2126ffcbd214ca81ea0c3 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_name_in_string_literal_type_annotation_py39.rc @@ -0,0 +1,2 @@ +[testoptions] +min_pyver=3.9 diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_typing_imports.py b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_typing_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..7de4e411bf4e4e8e820635285a92476a5540b76d --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_typing_imports.py @@ -0,0 +1,85 @@ +# pylint: disable=missing-docstring +"""Regression test for https://github.com/PyCQA/pylint/issues/1168 + +The problem was that we weren't handling keyword-only arguments annotations, +which means we were never processing them. +""" + +import re +import typing +from collections import Counter as CollectionCounter +from collections import defaultdict +from datetime import datetime +from typing import ( + Any, + Callable, + Iterable, + List, + NamedTuple, + Optional, + Pattern, + Sequence, + Set, + Tuple, +) + + +def func1(arg: Optional[Callable]=None): + return arg + + +def func2(*, arg: Optional[Iterable]=None): + return arg + + +SOME_VALUE = [1] # type: List[Any] +for VALUE in [[1], [2], [3]]: # type: Tuple[Any] + print(VALUE) + + +class ContextManager: + def __enter__(self): + return {1} + + def __exit__(self, *_args): + pass + + +with ContextManager() as SOME_DICT: # type: Set[int] + print(SOME_DICT) + + +def func_test_type_comment(param): + # type: (NamedTuple) -> Tuple[NamedTuple, Pattern] + return param, re.compile('good') + + +def typing_fully_qualified(): + variable = None # type: typing.Optional[str] + other_variable: 'typing.Optional[str]' = None + return variable, other_variable + + +def function(arg1, # type: Iterable + arg2 # type: List + ): + # type: (...) -> Sequence + """docstring""" + print(arg1, arg2) + + +def magic(alpha, beta, gamma): + # type: (str, Optional[str], Optional[datetime]) -> Any + """going strong""" + return alpha, beta, gamma + + +def unused_assignment_import(): + foo_or_bar = 42 # type: defaultdict + return foo_or_bar + + +def unused_reassigned_import(counter): + # type: (CollectionCounter) -> int + print(counter) + return 42 diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_typing_imports.rc b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_typing_imports.rc new file mode 100644 index 0000000000000000000000000000000000000000..c53d2813267ff261b7d143c947bf4569ac0fb766 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_typing_imports.rc @@ -0,0 +1,3 @@ +[testoptions] +# This was added as PyPy is only able to run this on 3.8 and above +min_pyver=3.8 diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_variable.py b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_variable.py new file mode 100644 index 0000000000000000000000000000000000000000..0058516c945b88efc26344b91cb3d6c7c0fca87a --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_variable.py @@ -0,0 +1,201 @@ +# pylint: disable=missing-docstring, invalid-name, too-few-public-methods, import-outside-toplevel, fixme, line-too-long, broad-exception-raised + +def test_regression_737(): + import xml # [unused-import] + +def test_regression_923(): + import unittest.case # [unused-import] + import xml as sql # [unused-import] + +def test_unused_with_prepended_underscore(): + _foo = 42 + _ = 24 + __a = 24 + dummy = 24 + _a_ = 42 # [unused-variable] + __a__ = 24 # [unused-variable] + __never_used = 42 + +def test_local_field_prefixed_with_unused_or_ignored(): + flagged_local_field = 42 # [unused-variable] + unused_local_field = 42 + ignored_local_field = 42 + + +class HasUnusedDunderClass: + + def test(self): + __class__ = 42 # [unused-variable] + + def best(self): + self.test() + + +def locals_example_defined_before(): + value = 42 # [possibly-unused-variable] + return locals() + + +def locals_example_defined_after(): + local_variables = locals() + value = 42 # [unused-variable] + return local_variables + + +def locals_does_not_account_for_subscopes(): + value = 42 # [unused-variable] + + def some_other_scope(): + return locals() + return some_other_scope + + +def unused_import_from(): + from functools import wraps as abc # [unused-import] + from collections import namedtuple # [unused-import] + + +def unused_import_in_function(value): + from string import digits, hexdigits # [unused-import] + return value if value in digits else "Nope" + + +def hello(arg): + my_var = 'something' # [unused-variable] + if arg: + return True + raise Exception + +# pylint: disable=wrong-import-position +PATH = OS = collections = deque = None + + +def function(matches): + """"yo""" + aaaa = 1 # [unused-variable] + index = -1 + for match in matches: + index += 1 + print(match) + +from astroid import nodes +def visit_if(self, node: nodes.If) -> None: + """increments the branches counter""" + branches = 1 + # don't double count If nodes coming from some 'elif' + if node.orelse and len(node.orelse) > 1: + branches += 1 + self.inc_branch(branches) + self.stmts += branches + + +def test_global(): + """ Test various assignments of global + variables through imports. + """ + # pylint: disable=redefined-outer-name + global PATH, OS, collections, deque # [global-statement] + from os import path as PATH + import os as OS + import collections + from collections import deque + # make sure that these triggers unused-variable + from sys import platform # [unused-import] + from sys import version as VERSION # [unused-import] + import this # [unused-import] + import re as RE # [unused-import] + +# test cases that include exceptions +def function2(): + unused = 1 # [unused-variable] + try: + 1 / 0 + except ZeroDivisionError as error: + try: + 1 / 0 + except ZeroDivisionError as error: # [redefined-outer-name] + raise Exception("") from error + +def func(): + try: + 1 / 0 + except ZeroDivisionError as error: + try: + 1 / 0 + except error: + print("error") + +def func2(): + try: + 1 / 0 + except ZeroDivisionError as error: + try: + 1 / 0 + except: + raise Exception("") from error + +def func3(): + try: + 1 / 0 + except ZeroDivisionError as error: + print(f"{error}") + try: + 1 / 2 + except TypeError as error: # [unused-variable, redefined-outer-name] + print("warning") + +def func4(): + try: + 1 / 0 + except ZeroDivisionError as error: # [unused-variable] + try: + 1 / 0 + except ZeroDivisionError as error: # [redefined-outer-name] + print("error") + + +def main(lst): + """https://github.com/PyCQA/astroid/pull/1111#issuecomment-890367609""" + try: + raise ValueError + except ValueError as e: # [unused-variable] + pass + + for e in lst: + pass + + # e will be undefined if lst is empty + print(e) # [undefined-loop-variable] + +main([]) + + +def func5(): + """No unused-variable for a container if iterated in comprehension""" + x = [] + # Test case requires homonym between "for x" and "in x" + assert [True for x in x] + + +def sibling_except_handlers(): + try: + pass + except ValueError as e: + print(e) + try: + pass + except ValueError as e: + print(e) + +def func6(): + a = 1 + + def nonlocal_writer(): + nonlocal a + + for a in range(10): + pass + + nonlocal_writer() + + assert a == 9, a diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_variable.txt b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_variable.txt new file mode 100644 index 0000000000000000000000000000000000000000..19983d53652d5045eccfc7d56d0d246ab211dc87 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_variable.txt @@ -0,0 +1,28 @@ +unused-import:4:4:4:14:test_regression_737:Unused import xml:UNDEFINED +unused-import:7:4:7:24:test_regression_923:Unused import unittest.case:UNDEFINED +unused-import:8:4:8:21:test_regression_923:Unused xml imported as sql:UNDEFINED +unused-variable:15:4:15:7:test_unused_with_prepended_underscore:Unused variable '_a_':UNDEFINED +unused-variable:16:4:16:9:test_unused_with_prepended_underscore:Unused variable '__a__':UNDEFINED +unused-variable:20:4:20:23:test_local_field_prefixed_with_unused_or_ignored:Unused variable 'flagged_local_field':UNDEFINED +unused-variable:28:8:28:17:HasUnusedDunderClass.test:Unused variable '__class__':UNDEFINED +possibly-unused-variable:35:4:35:9:locals_example_defined_before:Possibly unused variable 'value':UNDEFINED +unused-variable:41:4:41:9:locals_example_defined_after:Unused variable 'value':UNDEFINED +unused-variable:46:4:46:9:locals_does_not_account_for_subscopes:Unused variable 'value':UNDEFINED +unused-import:54:4:54:38:unused_import_from:Unused wraps imported from functools as abc:UNDEFINED +unused-import:55:4:55:38:unused_import_from:Unused namedtuple imported from collections:UNDEFINED +unused-import:59:4:59:40:unused_import_in_function:Unused hexdigits imported from string:UNDEFINED +unused-variable:64:4:64:10:hello:Unused variable 'my_var':UNDEFINED +unused-variable:75:4:75:8:function:Unused variable 'aaaa':UNDEFINED +global-statement:97:4:97:39:test_global:Using the global statement:HIGH +unused-import:103:4:103:28:test_global:Unused platform imported from sys:UNDEFINED +unused-import:104:4:104:38:test_global:Unused version imported from sys as VERSION:UNDEFINED +unused-import:105:4:105:15:test_global:Unused import this:UNDEFINED +unused-import:106:4:106:19:test_global:Unused re imported as RE:UNDEFINED +unused-variable:110:4:110:10:function2:Unused variable 'unused':UNDEFINED +redefined-outer-name:116:8:117:42:function2:Redefining name 'error' from outer scope (line 113):UNDEFINED +redefined-outer-name:144:8:145:28:func3:Redefining name 'error' from outer scope (line 140):UNDEFINED +unused-variable:144:8:145:28:func3:Unused variable 'error':UNDEFINED +unused-variable:150:4:154:26:func4:Unused variable 'error':UNDEFINED +redefined-outer-name:153:8:154:26:func4:Redefining name 'error' from outer scope (line 150):UNDEFINED +unused-variable:161:4:162:12:main:Unused variable 'e':UNDEFINED +undefined-loop-variable:168:10:168:11:main:Using possibly undefined loop variable 'e':UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_variable_after_inference.py b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_variable_after_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..569564dc921f1de56ead804291812a1d4f144928 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_variable_after_inference.py @@ -0,0 +1,7 @@ +"""Regression test for https://github.com/PyCQA/pylint/issues/6895""" +# pylint: disable=missing-class-docstring,too-few-public-methods +import argparse +class Cls: + def meth(self): + """Enable non-iterator-returned to produce the failure condition""" + return argparse.Namespace(debug=True) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_variable_after_inference.rc b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_variable_after_inference.rc new file mode 100644 index 0000000000000000000000000000000000000000..c3b20ca24734478dac26c73adc7f3098cd1fbec3 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_variable_after_inference.rc @@ -0,0 +1,2 @@ +[Messages Control] +enable=non-iterator-returned diff --git a/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_variable_py38.rc b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_variable_py38.rc new file mode 100644 index 0000000000000000000000000000000000000000..25a81a70fae6191f70ca404b9929b390d3890ee1 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/unused/unused_variable_py38.rc @@ -0,0 +1,5 @@ +[testoptions] +min_pyver=3.8 + +[variables] +allow-global-unused-variables=no diff --git a/testbed/pylint-dev__pylint/tests/functional/u/use/use_a_generator.py b/testbed/pylint-dev__pylint/tests/functional/u/use/use_a_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..279deb46ffbc51a9d227ab9c56a34236ab11983d --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/use/use_a_generator.py @@ -0,0 +1,11 @@ +# pylint: disable=missing-docstring, invalid-name +# https://github.com/PyCQA/pylint/issues/3165 + +any([]) +all([]) + +any([0 for x in list(range(10))]) # [use-a-generator] +all([0 for y in list(range(10))]) # [use-a-generator] + +any(0 for x in list(range(10))) +all(0 for y in list(range(10))) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/use/use_a_generator.txt b/testbed/pylint-dev__pylint/tests/functional/u/use/use_a_generator.txt new file mode 100644 index 0000000000000000000000000000000000000000..7ab70dc6883dfbd202bec3c14693245b6239222b --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/use/use_a_generator.txt @@ -0,0 +1,2 @@ +use-a-generator:7:0:7:33::Use a generator instead 'any(0 for x in list(range(10)))':UNDEFINED +use-a-generator:8:0:8:33::Use a generator instead 'all(0 for y in list(range(10)))':UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/use/use_implicit_booleaness_not_comparison.py b/testbed/pylint-dev__pylint/tests/functional/u/use/use_implicit_booleaness_not_comparison.py new file mode 100644 index 0000000000000000000000000000000000000000..681ee0607aad78b8bc875b1062a7fbc6f0794817 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/use/use_implicit_booleaness_not_comparison.py @@ -0,0 +1,239 @@ +# pylint: disable=missing-docstring, missing-module-docstring, invalid-name +# pylint: disable=too-few-public-methods, line-too-long, dangerous-default-value +# pylint: disable=wrong-import-order +# https://github.com/PyCQA/pylint/issues/4774 + +def github_issue_4774(): + # Test literals + # https://github.com/PyCQA/pylint/issues/4774 + good_list = [] + if not good_list: + pass + + bad_list = [] + if bad_list == []: # [use-implicit-booleaness-not-comparison] + pass + +# Testing for empty literals +empty_tuple = () +empty_list = [] +empty_dict = {} + +if empty_tuple == (): # [use-implicit-booleaness-not-comparison] + pass + +if empty_list == []: # [use-implicit-booleaness-not-comparison] + pass + +if empty_dict == {}: # [use-implicit-booleaness-not-comparison] + pass + +if () == empty_tuple: # [use-implicit-booleaness-not-comparison] + pass + +if [] == empty_list: # [use-implicit-booleaness-not-comparison] + pass + +if {} == empty_dict: # [use-implicit-booleaness-not-comparison] + pass + +def bad_tuple_return(): + t = (1, ) + return t == () # [use-implicit-booleaness-not-comparison] + +def bad_list_return(): + b = [1] + return b == [] # [use-implicit-booleaness-not-comparison] + +def bad_dict_return(): + c = {1: 1} + return c == {} # [use-implicit-booleaness-not-comparison] + +assert () == empty_tuple # [use-implicit-booleaness-not-comparison] +assert [] == empty_list # [use-implicit-booleaness-not-comparison] +assert {} != empty_dict # [use-implicit-booleaness-not-comparison] +assert () < empty_tuple # [use-implicit-booleaness-not-comparison] +assert [] <= empty_list # [use-implicit-booleaness-not-comparison] +assert () > empty_tuple # [use-implicit-booleaness-not-comparison] +assert [] >= empty_list # [use-implicit-booleaness-not-comparison] + +assert [] == [] +assert {} != {} +assert () == () + +d = {} + +if d in {}: + pass + +class NoBool: + def __init__(self): + self.a = 2 + +class YesBool: + def __init__(self): + self.a = True + + def __bool__(self): + return self.a + + +# Should be triggered +a = NoBool() +if [] == a: # [use-implicit-booleaness-not-comparison] + pass + +a = YesBool() +if a == []: + pass + +# compound test cases + +e = [] +f = {} + +if e == [] and f == {}: # [use-implicit-booleaness-not-comparison, use-implicit-booleaness-not-comparison] + pass + + +named_fields = [0, "", "42", "forty two"] +empty = any(field == "" for field in named_fields) + +something_else = NoBool() +empty_literals = [[], {}, ()] +is_empty = any(field == something_else for field in empty_literals) + +h, i, j = 1, None, [1,2,3] + +def test(k): + print(k == {}) + +def test_with_default(k={}): + print(k == {}) + print(k == 1) + +test(h) +test(i) +test(j) + +test_with_default(h) +test_with_default(i) +test_with_default(j) + + +class A: + lst = [] + + @staticmethod + def test(b=1): + print(b) + return [] + + +if A.lst == []: # [use-implicit-booleaness-not-comparison] + pass + + +if [] == A.lst: # [use-implicit-booleaness-not-comparison] + pass + + +if A.test("b") == []: # [use-implicit-booleaness-not-comparison] + pass + + +def test_function(): + return [] + + +if test_function() == []: # [use-implicit-booleaness-not-comparison] + pass + +# pylint: disable=import-outside-toplevel, wrong-import-position, import-error +# Numpy has its own implementation of __bool__, but base class has list, that's why the comparison check is happening +import numpy +numpy_array = numpy.array([0]) +if numpy_array == []: # [use-implicit-booleaness-not-comparison] + print('numpy_array') +if numpy_array != []: # [use-implicit-booleaness-not-comparison] + print('numpy_array') +if numpy_array >= (): # [use-implicit-booleaness-not-comparison] + print('b') + +# pandas has its own implementations of __bool__ and is not subclass of list, dict, or tuple; that's why comparison check is not happening +import pandas as pd +pandas_df = pd.DataFrame() +if pandas_df == []: + pass +if pandas_df != (): + pass +if pandas_df <= []: + print("don't emit warning if variable can't safely be inferred") + +from typing import Union +from random import random + +var: Union[dict, bool, None] = {} +if random() > 0.5: + var = True + +if var == {}: + pass + +data = {} + +if data == {}: # [use-implicit-booleaness-not-comparison] + print("This will be printed") +if data != {}: # [use-implicit-booleaness-not-comparison] + print("This will also be printed") + +if data or not data: + print("This however won't be") + +# literal string check +long_test = {} +if long_test == { }: # [use-implicit-booleaness-not-comparison] + pass + + +# Check for properties and uninferable class methods +# See https://github.com/PyCQA/pylint/issues/5646 +from xyz import AnotherClassWithProperty + + +class ParentWithProperty: + + @classmethod + @property + def parent_function(cls): + return {} + + +class MyClassWithProxy(ParentWithProperty): + + attribute = True + + @property + @classmethod + def my_property(cls): + return {} + + @property + @classmethod + def my_difficult_property(cls): + if cls.attribute: + return {} + return MyClassWithProxy() + + + +def test_func(): + """Some assertions against empty dicts.""" + my_class = MyClassWithProxy() + assert my_class.parent_function == {} # [use-implicit-booleaness-not-comparison] + assert my_class.my_property == {} # [use-implicit-booleaness-not-comparison] + + # If the return value is not always implicit boolean, don't raise + assert my_class.my_difficult_property == {} + # Uninferable does not raise + assert AnotherClassWithProperty().my_property == {} diff --git a/testbed/pylint-dev__pylint/tests/functional/u/use/use_implicit_booleaness_not_comparison.txt b/testbed/pylint-dev__pylint/tests/functional/u/use/use_implicit_booleaness_not_comparison.txt new file mode 100644 index 0000000000000000000000000000000000000000..2ace15d7e2839c09547c7f3b87c159202dabe692 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/use/use_implicit_booleaness_not_comparison.txt @@ -0,0 +1,32 @@ +use-implicit-booleaness-not-comparison:14:7:14:21:github_issue_4774:'bad_list == []' can be simplified to 'not bad_list' as an empty list is falsey:HIGH +use-implicit-booleaness-not-comparison:22:3:22:20::'empty_tuple == ()' can be simplified to 'not empty_tuple' as an empty tuple is falsey:HIGH +use-implicit-booleaness-not-comparison:25:3:25:19::'empty_list == []' can be simplified to 'not empty_list' as an empty list is falsey:HIGH +use-implicit-booleaness-not-comparison:28:3:28:19::'empty_dict == {}' can be simplified to 'not empty_dict' as an empty dict is falsey:HIGH +use-implicit-booleaness-not-comparison:31:3:31:20::'empty_tuple == ()' can be simplified to 'not empty_tuple' as an empty tuple is falsey:HIGH +use-implicit-booleaness-not-comparison:34:3:34:19::'empty_list == []' can be simplified to 'not empty_list' as an empty list is falsey:HIGH +use-implicit-booleaness-not-comparison:37:3:37:19::'empty_dict == {}' can be simplified to 'not empty_dict' as an empty dict is falsey:HIGH +use-implicit-booleaness-not-comparison:42:11:42:18:bad_tuple_return:'t == ()' can be simplified to 'not t' as an empty tuple is falsey:HIGH +use-implicit-booleaness-not-comparison:46:11:46:18:bad_list_return:'b == []' can be simplified to 'not b' as an empty list is falsey:HIGH +use-implicit-booleaness-not-comparison:50:11:50:18:bad_dict_return:'c == {}' can be simplified to 'not c' as an empty dict is falsey:HIGH +use-implicit-booleaness-not-comparison:52:7:52:24::'empty_tuple == ()' can be simplified to 'not empty_tuple' as an empty tuple is falsey:HIGH +use-implicit-booleaness-not-comparison:53:7:53:23::'empty_list == []' can be simplified to 'not empty_list' as an empty list is falsey:HIGH +use-implicit-booleaness-not-comparison:54:7:54:23::'empty_dict != {}' can be simplified to 'empty_dict' as an empty dict is falsey:HIGH +use-implicit-booleaness-not-comparison:55:7:55:23::'empty_tuple < ()' can be simplified to 'not empty_tuple' as an empty tuple is falsey:HIGH +use-implicit-booleaness-not-comparison:56:7:56:23::'empty_list <= []' can be simplified to 'not empty_list' as an empty list is falsey:HIGH +use-implicit-booleaness-not-comparison:57:7:57:23::'empty_tuple > ()' can be simplified to 'not empty_tuple' as an empty tuple is falsey:HIGH +use-implicit-booleaness-not-comparison:58:7:58:23::'empty_list >= []' can be simplified to 'not empty_list' as an empty list is falsey:HIGH +use-implicit-booleaness-not-comparison:83:3:83:10::'a == []' can be simplified to 'not a' as an empty list is falsey:HIGH +use-implicit-booleaness-not-comparison:95:3:95:10::'e == []' can be simplified to 'not e' as an empty list is falsey:HIGH +use-implicit-booleaness-not-comparison:95:15:95:22::'f == {}' can be simplified to 'not f' as an empty dict is falsey:HIGH +use-implicit-booleaness-not-comparison:133:3:133:14::'A.lst == []' can be simplified to 'not A.lst' as an empty list is falsey:HIGH +use-implicit-booleaness-not-comparison:137:3:137:14::'A.lst == []' can be simplified to 'not A.lst' as an empty list is falsey:HIGH +use-implicit-booleaness-not-comparison:141:3:141:20::'A.test(...) == []' can be simplified to 'not A.test(...)' as an empty list is falsey:HIGH +use-implicit-booleaness-not-comparison:149:3:149:24::'test_function(...) == []' can be simplified to 'not test_function(...)' as an empty list is falsey:HIGH +use-implicit-booleaness-not-comparison:156:3:156:20::'numpy_array == []' can be simplified to 'not numpy_array' as an empty list is falsey:HIGH +use-implicit-booleaness-not-comparison:158:3:158:20::'numpy_array != []' can be simplified to 'numpy_array' as an empty list is falsey:HIGH +use-implicit-booleaness-not-comparison:160:3:160:20::'numpy_array >= ()' can be simplified to 'not numpy_array' as an empty tuple is falsey:HIGH +use-implicit-booleaness-not-comparison:185:3:185:13::'data == {}' can be simplified to 'not data' as an empty dict is falsey:HIGH +use-implicit-booleaness-not-comparison:187:3:187:13::'data != {}' can be simplified to 'data' as an empty dict is falsey:HIGH +use-implicit-booleaness-not-comparison:195:3:195:26::'long_test == {}' can be simplified to 'not long_test' as an empty dict is falsey:HIGH +use-implicit-booleaness-not-comparison:233:11:233:41:test_func:'my_class.parent_function == {}' can be simplified to 'not my_class.parent_function' as an empty dict is falsey:HIGH +use-implicit-booleaness-not-comparison:234:11:234:37:test_func:'my_class.my_property == {}' can be simplified to 'not my_class.my_property' as an empty dict is falsey:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/u/use/use_implicit_booleaness_not_len.py b/testbed/pylint-dev__pylint/tests/functional/u/use/use_implicit_booleaness_not_len.py new file mode 100644 index 0000000000000000000000000000000000000000..4002a6ddaf8993afddd47a0febb9c55795758f53 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/use/use_implicit_booleaness_not_len.py @@ -0,0 +1,191 @@ +# pylint: disable=too-few-public-methods,import-error, missing-docstring +# pylint: disable=useless-super-delegation,wrong-import-position,invalid-name, wrong-import-order, condition-evals-to-constant + +if len('TEST'): # [use-implicit-booleaness-not-len] + pass + +if not len('TEST'): # [use-implicit-booleaness-not-len] + pass + +z = [] +if z and len(['T', 'E', 'S', 'T']): # [use-implicit-booleaness-not-len] + pass + +if True or len('TEST'): # [use-implicit-booleaness-not-len] + pass + +if len('TEST') == 0: # Should be fine + pass + +if len('TEST') < 1: # Should be fine + pass + +if len('TEST') <= 0: # Should be fine + pass + +if 1 > len('TEST'): # Should be fine + pass + +if 0 >= len('TEST'): # Should be fine + pass + +if z and len('TEST') == 0: # Should be fine + pass + +if 0 == len('TEST') < 10: # Should be fine + pass + +# Should be fine +if 0 < 1 <= len('TEST') < 10: # [comparison-of-constants] + pass + +if 10 > len('TEST') != 0: # Should be fine + pass + +if 10 > len('TEST') > 1 > 0: # Should be fine + pass + +if 0 <= len('TEST') < 100: # Should be fine + pass + +if z or 10 > len('TEST') != 0: # Should be fine + pass + +if z: + pass +elif len('TEST'): # [use-implicit-booleaness-not-len] + pass + +if z: + pass +elif not len('TEST'): # [use-implicit-booleaness-not-len] + pass + +while len('TEST'): # [use-implicit-booleaness-not-len] + pass + +while not len('TEST'): # [use-implicit-booleaness-not-len] + pass + +while z and len('TEST'): # [use-implicit-booleaness-not-len] + pass + +while not len('TEST') and z: # [use-implicit-booleaness-not-len] + pass + +assert len('TEST') > 0 # Should be fine + +x = 1 if len('TEST') != 0 else 2 # Should be fine + +f_o_o = len('TEST') or 42 # Should be fine + +a = x and len(x) # Should be fine + +def some_func(): + return len('TEST') > 0 # Should be fine + +def github_issue_1325(): + l = [1, 2, 3] + length = len(l) if l else 0 # Should be fine + return length + +def github_issue_1331(*args): + assert False, len(args) # Should be fine + +def github_issue_1331_v2(*args): + assert len(args), args # [use-implicit-booleaness-not-len] + +def github_issue_1331_v3(*args): + assert len(args) or z, args # [use-implicit-booleaness-not-len] + +def github_issue_1331_v4(*args): + assert z and len(args), args # [use-implicit-booleaness-not-len] + +b = bool(len(z)) # [use-implicit-booleaness-not-len] +c = bool(len('TEST') or 42) # [use-implicit-booleaness-not-len] + +def github_issue_1879(): + + class ClassWithBool(list): + def __bool__(self): + return True + + class ClassWithoutBool(list): + pass + + class ChildClassWithBool(ClassWithBool): + pass + + class ChildClassWithoutBool(ClassWithoutBool): + pass + + assert len(ClassWithBool()) + assert len(ChildClassWithBool()) + assert len(ClassWithoutBool()) # [use-implicit-booleaness-not-len] + assert len(ChildClassWithoutBool()) # [use-implicit-booleaness-not-len] + assert len(range(0)) # [use-implicit-booleaness-not-len] + assert len([t + 1 for t in []]) # [use-implicit-booleaness-not-len] + assert len(u + 1 for u in []) # [use-implicit-booleaness-not-len] + assert len({"1":(v + 1) for v in {}}) # [use-implicit-booleaness-not-len] + assert len(set((w + 1) for w in set())) # [use-implicit-booleaness-not-len] + + # pylint: disable=import-outside-toplevel + import numpy + numpy_array = numpy.array([0]) + if len(numpy_array) > 0: + print('numpy_array') + if len(numpy_array): + print('numpy_array') + if numpy_array: + print('b') + + import pandas as pd + pandas_df = pd.DataFrame() + if len(pandas_df): + print("this works, but pylint tells me not to use len() without comparison") + if len(pandas_df) > 0: + print("this works and pylint likes it, but it's not the solution intended by PEP-8") + if pandas_df: + print("this does not work (truth value of dataframe is ambiguous)") + + def function_returning_list(r): + if r==1: + return [1] + return [2] + + def function_returning_int(r): + if r==1: + return 1 + return 2 + + # def function_returning_generator(r): + # for i in [r, 1, 2, 3]: + # yield i + + # def function_returning_comprehension(r): + # return [x+1 for x in [r, 1, 2, 3]] + + # def function_returning_function(r): + # return function_returning_generator(r) + + assert len(function_returning_list(z)) # [use-implicit-booleaness-not-len] + assert len(function_returning_int(z)) + # This should raise a use-implicit-booleaness-not-len once astroid can infer it + # See https://github.com/PyCQA/pylint/pull/3821#issuecomment-743771514 + # assert len(function_returning_generator(z)) + # assert len(function_returning_comprehension(z)) + # assert len(function_returning_function(z)) + + +def github_issue_4215(): + # Test undefined variables + # https://github.com/PyCQA/pylint/issues/4215 + if len(undefined_var): # [undefined-variable] + pass + if len(undefined_var2[0]): # [undefined-variable] + pass + +# pylint: disable=len-as-condition + +if len('TEST'): + pass diff --git a/testbed/pylint-dev__pylint/tests/functional/u/use/use_implicit_booleaness_not_len.txt b/testbed/pylint-dev__pylint/tests/functional/u/use/use_implicit_booleaness_not_len.txt new file mode 100644 index 0000000000000000000000000000000000000000..85917de828ac3b58a732f8958e890459bf8ae131 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/use/use_implicit_booleaness_not_len.txt @@ -0,0 +1,26 @@ +use-implicit-booleaness-not-len:4:3:4:14::Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:INFERENCE +use-implicit-booleaness-not-len:7:3:7:18::Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:HIGH +use-implicit-booleaness-not-len:11:9:11:34::Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:INFERENCE +use-implicit-booleaness-not-len:14:11:14:22::Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:INFERENCE +comparison-of-constants:39:3:39:28::"Comparison between constants: '0 < 1' has a constant value":HIGH +use-implicit-booleaness-not-len:56:5:56:16::Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:INFERENCE +use-implicit-booleaness-not-len:61:5:61:20::Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:HIGH +use-implicit-booleaness-not-len:64:6:64:17::Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:INFERENCE +use-implicit-booleaness-not-len:67:6:67:21::Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:HIGH +use-implicit-booleaness-not-len:70:12:70:23::Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:INFERENCE +use-implicit-booleaness-not-len:73:6:73:21::Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:HIGH +use-implicit-booleaness-not-len:96:11:96:20:github_issue_1331_v2:Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:INFERENCE +use-implicit-booleaness-not-len:99:11:99:20:github_issue_1331_v3:Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:INFERENCE +use-implicit-booleaness-not-len:102:17:102:26:github_issue_1331_v4:Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:INFERENCE +use-implicit-booleaness-not-len:104:9:104:15::Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:INFERENCE +use-implicit-booleaness-not-len:105:9:105:20::Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:INFERENCE +use-implicit-booleaness-not-len:124:11:124:34:github_issue_1879:Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:INFERENCE +use-implicit-booleaness-not-len:125:11:125:39:github_issue_1879:Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:INFERENCE +use-implicit-booleaness-not-len:126:11:126:24:github_issue_1879:Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:INFERENCE +use-implicit-booleaness-not-len:127:11:127:35:github_issue_1879:Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:HIGH +use-implicit-booleaness-not-len:128:11:128:33:github_issue_1879:Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:HIGH +use-implicit-booleaness-not-len:129:11:129:41:github_issue_1879:Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:HIGH +use-implicit-booleaness-not-len:130:11:130:43:github_issue_1879:Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:INFERENCE +use-implicit-booleaness-not-len:171:11:171:42:github_issue_1879:Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty:INFERENCE +undefined-variable:183:11:183:24:github_issue_4215:Undefined variable 'undefined_var':UNDEFINED +undefined-variable:185:11:185:25:github_issue_4215:Undefined variable 'undefined_var2':UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/use/use_literal_dict.py b/testbed/pylint-dev__pylint/tests/functional/u/use/use_literal_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..598b382bdfa9486034f2ceb566cd536657378488 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/use/use_literal_dict.py @@ -0,0 +1,46 @@ +# pylint: disable=missing-docstring, invalid-name, disallowed-name, unused-argument, too-few-public-methods + +x = dict() # [use-dict-literal] +x = dict(a="1", b=None, c=3) # [use-dict-literal] +x = dict(zip(["a", "b", "c"], [1, 2, 3])) +x = {} +x = {"a": 1, "b": 2, "c": 3} +x = dict(**x) # [use-dict-literal] + +def bar(boo: bool = False): + return 1 + +x = dict(foo=bar()) # [use-dict-literal] + +baz = {"e": 9, "f": 1} + +dict( # [use-dict-literal] + **baz, + suggestions=list( + bar( + boo=True, + ) + ), +) + +class SomeClass: + prop: dict = {"a": 1} + +inst = SomeClass() + +dict( # [use-dict-literal] + url="/foo", + **inst.prop, +) + +dict( # [use-dict-literal] + Lorem="ipsum", + dolor="sit", + amet="consectetur", + adipiscing="elit", + sed="do", + eiusmod="tempor", + incididunt="ut", + labore="et", + dolore="magna", +) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/use/use_literal_dict.txt b/testbed/pylint-dev__pylint/tests/functional/u/use/use_literal_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..14576647968a4c3aa8e77475d1fb2baac9913e30 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/use/use_literal_dict.txt @@ -0,0 +1,7 @@ +use-dict-literal:3:4:3:10::Consider using '{}' instead of a call to 'dict'.:INFERENCE +use-dict-literal:4:4:4:28::"Consider using '{""a"": '1', ""b"": None, ""c"": 3}' instead of a call to 'dict'.":INFERENCE +use-dict-literal:8:4:8:13::Consider using '{**x}' instead of a call to 'dict'.:INFERENCE +use-dict-literal:13:4:13:19::"Consider using '{""foo"": bar()}' instead of a call to 'dict'.":INFERENCE +use-dict-literal:17:0:24:1::"Consider using '{""suggestions"": list(bar(boo=True)), **baz}' instead of a call to 'dict'.":INFERENCE +use-dict-literal:31:0:34:1::"Consider using '{""url"": '/foo', **inst.prop}' instead of a call to 'dict'.":INFERENCE +use-dict-literal:36:0:46:1::"Consider using '{""Lorem"": 'ipsum', ""dolor"": 'sit', ""amet"": 'consectetur', ""adipiscing"": 'elit', ... }' instead of a call to 'dict'.":INFERENCE diff --git a/testbed/pylint-dev__pylint/tests/functional/u/use/use_literal_list.py b/testbed/pylint-dev__pylint/tests/functional/u/use/use_literal_list.py new file mode 100644 index 0000000000000000000000000000000000000000..78614a49dda3ae9740d9d4ec4ef2c956668ed25d --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/use/use_literal_list.py @@ -0,0 +1,9 @@ +# pylint: disable=missing-docstring, invalid-name + +x = list() # [use-list-literal] +x = list("string") +x = list(range(3)) +x = [] +x = ["string"] +x = [1, 2, 3] +x = [range(3)] diff --git a/testbed/pylint-dev__pylint/tests/functional/u/use/use_literal_list.txt b/testbed/pylint-dev__pylint/tests/functional/u/use/use_literal_list.txt new file mode 100644 index 0000000000000000000000000000000000000000..897e139a15ccb32785d90ffe384fe7d9a300d743 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/use/use_literal_list.txt @@ -0,0 +1 @@ +use-list-literal:3:4:3:10::Consider using [] instead of list():UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/use/use_maxsplit_arg.py b/testbed/pylint-dev__pylint/tests/functional/u/use/use_maxsplit_arg.py new file mode 100644 index 0000000000000000000000000000000000000000..449457a0c38d50605b0ef3add9c23253a3f78feb --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/use/use_maxsplit_arg.py @@ -0,0 +1,104 @@ +"""Emit a message for accessing first/last element of string.split""" +# pylint: disable=line-too-long,missing-docstring,unsubscriptable-object,too-few-public-methods,invalid-name,redefined-builtin + +# Test subscripting .split() +get_first = '1,2,3'.split(',')[0] # [use-maxsplit-arg] +get_last = '1,2,3'[::-1].split(',')[0] # [use-maxsplit-arg] + +SEQ = '1,2,3' +get_first = SEQ.split(',')[0] # [use-maxsplit-arg] +get_last = SEQ.split(',')[-1] # [use-maxsplit-arg] +get_first = SEQ.rsplit(',')[0] # [use-maxsplit-arg] +get_last = SEQ.rsplit(',')[-1] # [use-maxsplit-arg] + +# Don't suggest maxsplit=1 if not accessing the first or last element +get_mid = SEQ.split(',')[1] +get_mid = SEQ.split(',')[-2] + + +# Test varying maxsplit argument -- all these will be okay +# ## str.split() tests +good_split = '1,2,3'.split(sep=',', maxsplit=1)[-1] +good_split = '1,2,3'.split(sep=',', maxsplit=1)[0] +good_split = '1,2,3'.split(sep=',', maxsplit=2)[-1] +good_split = '1,2,3'.split(sep=',', maxsplit=2)[0] +good_split = '1,2,3'.split(sep=',', maxsplit=2)[1] + +# ## str.rsplit() tests +good_split = '1,2,3'.rsplit(sep=',', maxsplit=1)[-1] +good_split = '1,2,3'.rsplit(sep=',', maxsplit=1)[0] +good_split = '1,2,3'.rsplit(sep=',', maxsplit=2)[-1] +good_split = '1,2,3'.rsplit(sep=',', maxsplit=2)[0] +good_split = '1,2,3'.rsplit(sep=',', maxsplit=2)[1] + + +# Tests on class attributes +class Foo(): + class_str = '1,2,3' + def __init__(self): + self.my_str = '1,2,3' + + def get_string(self) -> str: + return self.my_str + +# Class attributes +get_first = Foo.class_str.split(',')[0] # [use-maxsplit-arg] +get_last = Foo.class_str.split(',')[-1] # [use-maxsplit-arg] +get_first = Foo.class_str.rsplit(',')[0] # [use-maxsplit-arg] +get_last = Foo.class_str.rsplit(',')[-1] # [use-maxsplit-arg] + +get_mid = Foo.class_str.split(',')[1] +get_mid = Foo.class_str.split(',')[-2] + + +# Test with accessors +test = Foo() +get_first = test.get_string().split(',')[0] # [use-maxsplit-arg] +get_last = test.get_string().split(',')[-1] # [use-maxsplit-arg] + +get_mid = test.get_string().split(',')[1] +get_mid = test.get_string().split(',')[-2] + + +# Test with iterating over strings +list_of_strs = ["a", "b", "c", "d", "e", "f"] +for s in list_of_strs: + print(s.split(" ")[0]) # [use-maxsplit-arg] + print(s.split(" ")[-1]) # [use-maxsplit-arg] + print(s.split(" ")[-2]) + + +# Test warning messages (matching and replacing .split / .rsplit) +class Bar(): + split = '1,2,3' + +# Error message should show Bar.split.split(',', maxsplit=1) or Bar.split.rsplit(',', maxsplit=1) +print(Bar.split.split(",")[0]) # [use-maxsplit-arg] +print(Bar.split.split(",")[-1]) # [use-maxsplit-arg] +print(Bar.split.rsplit(",")[0]) # [use-maxsplit-arg] +print(Bar.split.rsplit(",")[-1]) # [use-maxsplit-arg] + +# Special cases +a = "1,2,3".split('\n')[0] # [use-maxsplit-arg] +a = "1,2,3".split('split')[-1] # [use-maxsplit-arg] +a = "1,2,3".rsplit('rsplit')[0] # [use-maxsplit-arg] + +# Test cases for false-positive reported in #4664 +# https://github.com/PyCQA/pylint/issues/4664 +source = 'A.B.C.D.E.F.G' +i = 0 +for j in range(5): + print(source.split('.')[i]) + i = i + 1 + +# Test for crash when sep is given by keyword +# https://github.com/PyCQA/pylint/issues/5737 +get_last = SEQ.split(sep=None)[-1] # [use-maxsplit-arg] + + +class FalsePositive4857: + def split(self, point): + return point + +obj = FalsePositive4857() +obj = obj.split((0, 0))[0] diff --git a/testbed/pylint-dev__pylint/tests/functional/u/use/use_maxsplit_arg.txt b/testbed/pylint-dev__pylint/tests/functional/u/use/use_maxsplit_arg.txt new file mode 100644 index 0000000000000000000000000000000000000000..b8f254004b5490fe4c265fd5565c52a8751f6e09 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/use/use_maxsplit_arg.txt @@ -0,0 +1,22 @@ +use-maxsplit-arg:5:12:5:30::Use '1,2,3'.split(',', maxsplit=1)[0] instead:UNDEFINED +use-maxsplit-arg:6:11:6:35::"Use '1,2,3'[::-1].split(',', maxsplit=1)[0] instead":UNDEFINED +use-maxsplit-arg:9:12:9:26::Use SEQ.split(',', maxsplit=1)[0] instead:UNDEFINED +use-maxsplit-arg:10:11:10:25::Use SEQ.rsplit(',', maxsplit=1)[-1] instead:UNDEFINED +use-maxsplit-arg:11:12:11:27::Use SEQ.split(',', maxsplit=1)[0] instead:UNDEFINED +use-maxsplit-arg:12:11:12:26::Use SEQ.rsplit(',', maxsplit=1)[-1] instead:UNDEFINED +use-maxsplit-arg:45:12:45:36::Use Foo.class_str.split(',', maxsplit=1)[0] instead:UNDEFINED +use-maxsplit-arg:46:11:46:35::Use Foo.class_str.rsplit(',', maxsplit=1)[-1] instead:UNDEFINED +use-maxsplit-arg:47:12:47:37::Use Foo.class_str.split(',', maxsplit=1)[0] instead:UNDEFINED +use-maxsplit-arg:48:11:48:36::Use Foo.class_str.rsplit(',', maxsplit=1)[-1] instead:UNDEFINED +use-maxsplit-arg:56:12:56:40::Use test.get_string().split(',', maxsplit=1)[0] instead:UNDEFINED +use-maxsplit-arg:57:11:57:39::Use test.get_string().rsplit(',', maxsplit=1)[-1] instead:UNDEFINED +use-maxsplit-arg:66:10:66:22::Use s.split(' ', maxsplit=1)[0] instead:UNDEFINED +use-maxsplit-arg:67:10:67:22::Use s.rsplit(' ', maxsplit=1)[-1] instead:UNDEFINED +use-maxsplit-arg:76:6:76:26::Use Bar.split.split(',', maxsplit=1)[0] instead:UNDEFINED +use-maxsplit-arg:77:6:77:26::Use Bar.split.rsplit(',', maxsplit=1)[-1] instead:UNDEFINED +use-maxsplit-arg:78:6:78:27::Use Bar.split.split(',', maxsplit=1)[0] instead:UNDEFINED +use-maxsplit-arg:79:6:79:27::Use Bar.split.rsplit(',', maxsplit=1)[-1] instead:UNDEFINED +use-maxsplit-arg:82:4:82:23::Use '1,2,3'.split('\n', maxsplit=1)[0] instead:UNDEFINED +use-maxsplit-arg:83:4:83:26::Use '1,2,3'.rsplit('split', maxsplit=1)[-1] instead:UNDEFINED +use-maxsplit-arg:84:4:84:28::Use '1,2,3'.split('rsplit', maxsplit=1)[0] instead:UNDEFINED +use-maxsplit-arg:96:11:96:30::Use SEQ.rsplit(None, maxsplit=1)[-1] instead:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/use/use_sequence_for_iteration.py b/testbed/pylint-dev__pylint/tests/functional/u/use/use_sequence_for_iteration.py new file mode 100644 index 0000000000000000000000000000000000000000..264e6e7b9dfc79183137c055bbd021ca997512e8 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/use/use_sequence_for_iteration.py @@ -0,0 +1,28 @@ +# pylint: disable=missing-docstring,pointless-statement,unnecessary-comprehension + +var = {1, 2, 3} + +for x in var: + pass +for x in {1, 2, 3}: # [use-sequence-for-iteration] + pass + +(x for x in var) +(x for x in {1, 2, 3}) # [use-sequence-for-iteration] + +[x for x in var] +[x for x in {1, 2, 3}] # [use-sequence-for-iteration] + +[x for x in {*var, 4}] + +def deduplicate(list_in): + for thing in {*list_in}: + print(thing) + +def deduplicate_two_lists(input1, input2): + for thing in {*input1, *input2}: + print(thing) + +def deduplicate_nested_sets(input1, input2, input3, input4): + for thing in {{*input1, *input2}, {*input3, *input4}}: + print(thing) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/use/use_sequence_for_iteration.txt b/testbed/pylint-dev__pylint/tests/functional/u/use/use_sequence_for_iteration.txt new file mode 100644 index 0000000000000000000000000000000000000000..3787b7a0eb4b9b601b633a29ea90c781966f6b7b --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/use/use_sequence_for_iteration.txt @@ -0,0 +1,3 @@ +use-sequence-for-iteration:7:9:7:18::Use a sequence type when iterating over values:HIGH +use-sequence-for-iteration:11:12:11:21::Use a sequence type when iterating over values:HIGH +use-sequence-for-iteration:14:12:14:21::Use a sequence type when iterating over values:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/u/use/use_symbolic_message_instead.py b/testbed/pylint-dev__pylint/tests/functional/u/use/use_symbolic_message_instead.py new file mode 100644 index 0000000000000000000000000000000000000000..ea984e3144bccf862e846b4c820bd9e4dce0ede9 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/use/use_symbolic_message_instead.py @@ -0,0 +1,25 @@ +# pylint: disable=C0111,R0903,T1234 # [unknown-option-value,use-symbolic-message-instead,use-symbolic-message-instead] +# pylint: enable=c0111,w0223 # [use-symbolic-message-instead,use-symbolic-message-instead] + +def my_function(arg): # [missing-function-docstring] + return arg or True + +# pylint: disable=C0111 # [use-symbolic-message-instead] +# pylint: enable=R0903 # [use-symbolic-message-instead] +# pylint: disable=R0903 # [use-symbolic-message-instead] + + +def foo(): # pylint: disable=C0102 # [use-symbolic-message-instead] + return 1 + + +def toto(): # pylint: disable=C0102,R1711 # [use-symbolic-message-instead,use-symbolic-message-instead] + return + + +def test_enabled_by_id_msg(): # pylint: enable=C0111 # [use-symbolic-message-instead,missing-function-docstring] + pass + + +def baz(): # pylint: disable=blacklisted-name + return 1 diff --git a/testbed/pylint-dev__pylint/tests/functional/u/use/use_symbolic_message_instead.txt b/testbed/pylint-dev__pylint/tests/functional/u/use/use_symbolic_message_instead.txt new file mode 100644 index 0000000000000000000000000000000000000000..7d10c7fa78d31953a6ea967722d36ad8d6bef312 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/use/use_symbolic_message_instead.txt @@ -0,0 +1,14 @@ +unknown-option-value:1:0:None:None::Unknown option value for 'disable', expected a valid pylint message and got 'T1234':HIGH +use-symbolic-message-instead:1:0:None:None::"'C0111' is cryptic: use '# pylint: disable=missing-docstring' instead":UNDEFINED +use-symbolic-message-instead:1:0:None:None::"'R0903' is cryptic: use '# pylint: disable=too-few-public-methods' instead":UNDEFINED +use-symbolic-message-instead:2:0:None:None::"'c0111' is cryptic: use '# pylint: enable=missing-docstring' instead":UNDEFINED +use-symbolic-message-instead:2:0:None:None::"'w0223' is cryptic: use '# pylint: enable=abstract-method' instead":UNDEFINED +missing-function-docstring:4:0:4:15:my_function:Missing function or method docstring:HIGH +use-symbolic-message-instead:7:0:None:None::"'C0111' is cryptic: use '# pylint: disable=missing-docstring' instead":UNDEFINED +use-symbolic-message-instead:8:0:None:None::"'R0903' is cryptic: use '# pylint: enable=too-few-public-methods' instead":UNDEFINED +use-symbolic-message-instead:9:0:None:None::"'R0903' is cryptic: use '# pylint: disable=too-few-public-methods' instead":UNDEFINED +use-symbolic-message-instead:12:0:None:None::"'C0102' is cryptic: use '# pylint: disable=blacklisted-name' instead":UNDEFINED +use-symbolic-message-instead:16:0:None:None::"'C0102' is cryptic: use '# pylint: disable=blacklisted-name' instead":UNDEFINED +use-symbolic-message-instead:16:0:None:None::"'R1711' is cryptic: use '# pylint: disable=useless-return' instead":UNDEFINED +missing-function-docstring:20:0:20:26:test_enabled_by_id_msg:Missing function or method docstring:HIGH +use-symbolic-message-instead:20:0:None:None::"'C0111' is cryptic: use '# pylint: enable=missing-docstring' instead":UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/use/used_before_assignment_except_handler_for_try_with_return_py38.py b/testbed/pylint-dev__pylint/tests/functional/u/use/used_before_assignment_except_handler_for_try_with_return_py38.py new file mode 100644 index 0000000000000000000000000000000000000000..a43a89aa1014f17b98223adaf426338ccbde079f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/use/used_before_assignment_except_handler_for_try_with_return_py38.py @@ -0,0 +1,46 @@ +"""Tests for used-before-assignment with assignments in except handlers after +try blocks with return statements. +See: https://github.com/PyCQA/pylint/issues/5500. +""" +# pylint: disable=inconsistent-return-statements + + +# Named expressions +def func_ok_namedexpr_1(var): + """'msg' is defined in one handler with a named expression under an if.""" + try: + return 1 / var.some_other_func() + except AttributeError: + if (msg := var.get_msg()): + pass + except ZeroDivisionError: + msg = "Division by 0" + print(msg) + + +def func_ok_namedexpr_2(var): + """'msg' is defined in one handler with a named expression occurring + in a call used in an if test. + """ + try: + return 1 / var.some_other_func() + except AttributeError: + if print(msg := var.get_msg()): + pass + except ZeroDivisionError: + msg = "Division by 0" + print(msg) + + +def func_ok_namedexpr_3(var): + """'msg' is defined in one handler with a named expression occurring + as a keyword in a call used in an if test. + """ + try: + return 1 / var.some_other_func() + except AttributeError: + if print("zero!", "here", sep=(msg := var.get_sep())): + pass + except ZeroDivisionError: + msg = "Division by 0" + print(msg) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/use/used_before_assignment_except_handler_for_try_with_return_py38.rc b/testbed/pylint-dev__pylint/tests/functional/u/use/used_before_assignment_except_handler_for_try_with_return_py38.rc new file mode 100644 index 0000000000000000000000000000000000000000..85fc502b372ea64005d4e09627da9827c325d447 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/use/used_before_assignment_except_handler_for_try_with_return_py38.rc @@ -0,0 +1,2 @@ +[testoptions] +min_pyver=3.8 diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment.py b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment.py new file mode 100644 index 0000000000000000000000000000000000000000..d36b2fd8d5296e340bfa5a9eba48c7fb66ef6f1c --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment.py @@ -0,0 +1,118 @@ +"""Miscellaneous used-before-assignment cases""" +# pylint: disable=consider-using-f-string, missing-function-docstring + + +MSG = "hello %s" % MSG # [used-before-assignment] + +MSG2 = "hello %s" % MSG2 # [used-before-assignment] + +def outer(): + inner() # [used-before-assignment] + def inner(): + pass + +outer() + + +# pylint: disable=unused-import, wrong-import-position, import-outside-toplevel, reimported, redefined-outer-name, global-statement +import time +def redefine_time_import(): + print(time.time()) # [used-before-assignment] + import time + + +def redefine_time_import_with_global(): + global time # pylint: disable=invalid-name + print(time.time()) + import time + + +# Control flow cases +FALSE = False +if FALSE: + VAR2 = True +if VAR2: # [used-before-assignment] + pass + +if FALSE: # pylint: disable=simplifiable-if-statement + VAR3 = True +elif VAR2: + VAR3 = True +else: + VAR3 = False +if VAR3: + pass + +if FALSE: + VAR4 = True +elif VAR2: + pass +else: + VAR4 = False +if VAR4: # [used-before-assignment] + pass + +if FALSE: + VAR5 = True +elif VAR2: + if FALSE: # pylint: disable=simplifiable-if-statement + VAR5 = True + else: + VAR5 = True +if VAR5: + pass + +if FALSE: + VAR6 = False +if VAR6: # [used-before-assignment] + pass + + +# Nested try +if FALSE: + try: + VAR7 = True + except ValueError: + pass +else: + VAR7 = False +if VAR7: + pass + +if FALSE: + try: + VAR8 = True + except ValueError as ve: + print(ve) + raise +else: + VAR8 = False +if VAR8: + pass + +if FALSE: + for i in range(5): + VAR9 = i + break +print(VAR9) + +if FALSE: + with open(__name__, encoding='utf-8') as f: + VAR10 = __name__ +print(VAR10) # [used-before-assignment] + +for num in [0, 1]: + VAR11 = num + if VAR11: + VAR12 = False +print(VAR12) + +def turn_on2(**kwargs): + """https://github.com/PyCQA/pylint/issues/7873""" + if "brightness" in kwargs: + brightness = kwargs["brightness"] + var, *args = (1, "set_dimmer_state", brightness) + else: + var, *args = (1, "restore_dimmer_state") + + print(var, *args) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment.txt b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment.txt new file mode 100644 index 0000000000000000000000000000000000000000..70153f39ac0181bc850e3dbc83508825ddd5fb4f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment.txt @@ -0,0 +1,8 @@ +used-before-assignment:5:19:5:22::Using variable 'MSG' before assignment:HIGH +used-before-assignment:7:20:7:24::Using variable 'MSG2' before assignment:HIGH +used-before-assignment:10:4:10:9:outer:Using variable 'inner' before assignment:HIGH +used-before-assignment:20:10:20:14:redefine_time_import:Using variable 'time' before assignment:HIGH +used-before-assignment:34:3:34:7::Using variable 'VAR2' before assignment:CONTROL_FLOW +used-before-assignment:52:3:52:7::Using variable 'VAR4' before assignment:CONTROL_FLOW +used-before-assignment:67:3:67:7::Using variable 'VAR6' before assignment:CONTROL_FLOW +used-before-assignment:102:6:102:11::Using variable 'VAR10' before assignment:CONTROL_FLOW diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_488.py b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_488.py new file mode 100644 index 0000000000000000000000000000000000000000..efc133c2b0171e502c2e3ebdd7aa6a4057955f97 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_488.py @@ -0,0 +1,9 @@ +# pylint: disable=missing-docstring +def func(): + """Test that a variable defined in a finally clause does not trigger a false positive""" + try: + variable = 1 + yield variable + finally: + variable = 2 + yield variable diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_class_nested_under_function.py b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_class_nested_under_function.py new file mode 100644 index 0000000000000000000000000000000000000000..3627ae1e19b67b0e723e52cf9bc71bb162840cbe --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_class_nested_under_function.py @@ -0,0 +1,13 @@ +"""https://github.com/PyCQA/pylint/issues/4590""" +# pylint: disable=too-few-public-methods + + +def conditional_class_factory(): + """Define a nested class""" + class ConditionalClass(ModuleClass): + """Subclasses a name from the module scope""" + return ConditionalClass + + +class ModuleClass: + """Module-level class""" diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_comprehension_homonyms.py b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_comprehension_homonyms.py new file mode 100644 index 0000000000000000000000000000000000000000..2321afed74bb9a96f689aeb58e0595f6527f6233 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_comprehension_homonyms.py @@ -0,0 +1,96 @@ +"""Homonym between filtered comprehension and assignment in except block.""" +# pylint: disable=broad-exception-raised + +def func(): + """https://github.com/PyCQA/pylint/issues/5586""" + try: + print(value for value in range(1 / 0) if isinstance(value, int)) + except ZeroDivisionError: + value = 1 + print(value) + + +def func2(): + """Same, but with attribute access.""" + try: + print(value for value in range(1 / 0) if isinstance(value.num, int)) + except ZeroDivisionError: + value = 1 + print(value) + + +def func3(): + """Same, but with no call.""" + try: + print(value for value in range(1 / 0) if value) + except ZeroDivisionError: + value = 1 + print(value) + + +def func4(): + """https://github.com/PyCQA/pylint/issues/6035""" + assets = [asset for asset in range(3) if asset.name == "filename"] + + try: + raise ValueError + except ValueError: + asset = assets[0] + print(asset) + + +def func5(): + """Similar, but with subscript notation""" + results = {} + # pylint: disable-next=consider-using-dict-items + filtered = [k for k in results if isinstance(results[k], dict)] + + try: + 1 / 0 + except ZeroDivisionError: + k = None + print(k, filtered) + + +def func6(data, keys): + """Similar, but with a subscript in a key-value pair rather than the test + See https://github.com/PyCQA/pylint/issues/6069""" + try: + results = {key: data[key] for key in keys} + except KeyError as exc: + key, *_ = exc.args + raise Exception(f"{key} not found") from exc + + return results + + +def func7(): + """Similar, but with a comparison""" + bools = [str(i) == i for i in range(3)] + + try: + 1 / 0 + except ZeroDivisionError: + i = None + print(i, bools) + + +def func8(): + """Similar, but with a container""" + pairs = [(i, i) for i in range(3)] + + try: + 1 / 0 + except ZeroDivisionError: + i = None + print(i, pairs) + + +# Module level cases + +module_ints = [j | j for j in range(3)] +try: + 1 / 0 +except ZeroDivisionError: + j = None + print(j, module_ints) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_conditional.py b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_conditional.py new file mode 100644 index 0000000000000000000000000000000000000000..b024d28982f22a38711132642df4755c5c932fef --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_conditional.py @@ -0,0 +1,7 @@ +"""used-before-assignment cases involving IF conditions""" + +if 1 + 1 == 2: + x = x + 1 # [used-before-assignment] + +if y: # [used-before-assignment] + y = y + 1 diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_conditional.txt b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_conditional.txt new file mode 100644 index 0000000000000000000000000000000000000000..a65f9f7387c10e935a81c0621df66b21d0906da9 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_conditional.txt @@ -0,0 +1,2 @@ +used-before-assignment:4:8:4:9::Using variable 'x' before assignment:HIGH +used-before-assignment:6:3:6:4::Using variable 'y' before assignment:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_else_return.py b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_else_return.py new file mode 100644 index 0000000000000000000000000000000000000000..a7e58bb61f63cf42341b75f1f0dc1fca7535174d --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_else_return.py @@ -0,0 +1,74 @@ +"""If the else block returns, it is generally safe to rely on assignments in the except.""" +# pylint: disable=missing-function-docstring, invalid-name +import sys + +def valid(): + """https://github.com/PyCQA/pylint/issues/6790""" + try: + pass + except ValueError: + error = True + else: + return + + print(error) + + +def invalid(): + """The finally will execute before the else returns.""" + try: + pass + except ValueError: + error = None + else: + return + finally: + print(error) # [used-before-assignment] + + +def invalid_2(): + """The else does not return in every branch.""" + try: + pass + except ValueError: + error = None + else: + if range(0): + return + finally: + print(error) # [used-before-assignment] + + +def invalid_3(): + """Not every except defines the name.""" + try: + pass + except ValueError: + error = None + except KeyError: + pass + finally: + print(error) # [used-before-assignment] + + +def invalid_4(): + """Should not rely on the name in the else even if it returns.""" + try: + pass + except ValueError: + error = True + else: + print(error) # [used-before-assignment] + return + +def valid_exit(): + try: + pass + except SystemExit as e: + lint_result = e.code + else: + sys.exit("Bad") + if lint_result != 0: + sys.exit("Error is 0.") + + print(lint_result) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_else_return.txt b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_else_return.txt new file mode 100644 index 0000000000000000000000000000000000000000..5ef28cfd68df72e4e21f5f402cf3abaa115475d2 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_else_return.txt @@ -0,0 +1,4 @@ +used-before-assignment:26:14:26:19:invalid:Using variable 'error' before assignment:CONTROL_FLOW +used-before-assignment:39:14:39:19:invalid_2:Using variable 'error' before assignment:CONTROL_FLOW +used-before-assignment:51:14:51:19:invalid_3:Using variable 'error' before assignment:CONTROL_FLOW +used-before-assignment:61:14:61:19:invalid_4:Using variable 'error' before assignment:CONTROL_FLOW diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_except_handler_for_try_with_return.py b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_except_handler_for_try_with_return.py new file mode 100644 index 0000000000000000000000000000000000000000..c83a48473988b629651a0b22ab2350e14d1a46b2 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_except_handler_for_try_with_return.py @@ -0,0 +1,187 @@ +"""Tests for used-before-assignment with assignments in except handlers after +try blocks with return statements. +See: https://github.com/PyCQA/pylint/issues/5500. +""" +# pylint: disable=inconsistent-return-statements,broad-exception-raised + + +def function(): + """Assume except blocks execute if the try block returns.""" + try: + success_message = "success message" + return success_message + except ValueError: + failure_message = "failure message" + finally: + print(failure_message) # [used-before-assignment] + + return failure_message + + +def func_ok(var): + """'msg' is defined in all ExceptHandlers.""" + try: + return 1 / var.some_other_func() + except AttributeError: + msg = "Attribute not defined" + except ZeroDivisionError: + msg = "Division by 0" + print(msg) + + +def func_ok2(var): + """'msg' is defined in all ExceptHandlers that don't raise an Exception.""" + try: + return 1 / var.some_other_func() + except AttributeError as ex: + raise Exception from ex + except ZeroDivisionError: + msg = "Division by 0" + print(msg) + + +def func_ok3(var): + """'msg' is defined in all ExceptHandlers that don't return.""" + try: + return 1 / var.some_other_func() + except AttributeError: + return + except ZeroDivisionError: + msg = "Division by 0" + print(msg) + + +def func_ok4(var): + """Define "msg" with a chained assignment.""" + try: + return 1 / var.some_other_func() + except AttributeError: + msg2 = msg = "Division by 0" + print(msg2) + except ZeroDivisionError: + msg = "Division by 0" + print(msg) + + +def func_ok5(var): + """Define 'msg' via unpacked iterable.""" + try: + return 1 / var.some_other_func() + except AttributeError: + msg, msg2 = ["Division by 0", "Division by 0"] + print(msg2) + except ZeroDivisionError: + msg = "Division by 0" + print(msg) + + +def func_ok6(var): + """Define 'msg' in one handler nested under if block.""" + err_message = "Division by 0" + try: + return 1 / var.some_other_func() + except ZeroDivisionError: + if err_message: + msg = "Division by 0" + else: + msg = None + print(msg) + + +def func_ok7(var): + """Define 'msg' in one handler nested under with statement.""" + try: + return 1 / var.some_other_func() + except ZeroDivisionError: + with open(__file__, encoding='utf-8') as my_file: + msg = "Division by 0" + my_file.write(msg) + print(msg) + + +def func_ok8(var): + """Define 'msg' in one handler via type annotation.""" + try: + return 1 / var.some_other_func() + except ZeroDivisionError: + # See func_invalid2() for mere annotation without value + msg: str = "Division by 0" + print(msg) + + +def func_invalid1(var): + """'msg' is not defined in one handler.""" + try: + return 1 / var.some_other_func() + except AttributeError: + pass + except ZeroDivisionError: + msg = "Division by 0" + print(msg) # [used-before-assignment] + + +def func_invalid2(var): + """'msg' is not defined in one handler.""" + try: + return 1 / var.some_other_func() + except AttributeError: + msg: str + except ZeroDivisionError: + msg = "Division by 0" + print(msg) # [used-before-assignment] + + +def func_invalid3(var): + """'msg' is not defined in one handler, but is defined in another + nested under an if. Nesting under an if tests that the implementation + does not assume direct parentage between `msg=` and `except`, and + the prior except is necessary to raise the message. + """ + err_message = False + try: + return 1 / var.some_other_func() + except AttributeError: + pass + except ZeroDivisionError: + if err_message: + msg = "Division by 0" + else: + msg = None + print(msg) # [used-before-assignment] + + +def func_invalid4(var): + """Define 'msg' in one handler nested under with statement.""" + try: + return 1 / var.some_other_func() + except AttributeError: + pass + except ZeroDivisionError: + with open(__file__, encoding='utf-8') as my_file: + msg = "Division by 0" + my_file.write("****") + print(msg) # [used-before-assignment] + + +def func_invalid5(var): + """Define 'msg' in one handler only via chained assignment.""" + try: + return 1 / var.some_other_func() + except AttributeError: + pass + except ZeroDivisionError: + msg2 = msg = "Division by 0" + print(msg2) + print(msg) # [used-before-assignment] + + +def func_invalid6(var): + """Define 'msg' in one handler only via unpacked iterable.""" + try: + return 1 / var.some_other_func() + except AttributeError: + pass + except ZeroDivisionError: + msg, msg2 = ["Division by 0"] * 2 + print(msg2) + print(msg) # [used-before-assignment] diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_except_handler_for_try_with_return.txt b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_except_handler_for_try_with_return.txt new file mode 100644 index 0000000000000000000000000000000000000000..5f2be351ddc3a40f933d3c9f05ec27065066f336 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_except_handler_for_try_with_return.txt @@ -0,0 +1,7 @@ +used-before-assignment:16:14:16:29:function:Using variable 'failure_message' before assignment:CONTROL_FLOW +used-before-assignment:120:10:120:13:func_invalid1:Using variable 'msg' before assignment:CONTROL_FLOW +used-before-assignment:131:10:131:13:func_invalid2:Using variable 'msg' before assignment:CONTROL_FLOW +used-before-assignment:150:10:150:13:func_invalid3:Using variable 'msg' before assignment:CONTROL_FLOW +used-before-assignment:163:10:163:13:func_invalid4:Using variable 'msg' before assignment:CONTROL_FLOW +used-before-assignment:175:10:175:13:func_invalid5:Using variable 'msg' before assignment:CONTROL_FLOW +used-before-assignment:187:10:187:13:func_invalid6:Using variable 'msg' before assignment:CONTROL_FLOW diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue1081.py b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue1081.py new file mode 100644 index 0000000000000000000000000000000000000000..d478bdeecc74871e1600be9e3a8dd82a17caebe3 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue1081.py @@ -0,0 +1,40 @@ +# pylint: disable=missing-docstring,invalid-name,too-few-public-methods + +x = 24 + + +def used_before_assignment_1(a): + if x == a: # [used-before-assignment] + for x in [1, 2]: # [redefined-outer-name] + pass + + +def used_before_assignment_2(a): + if x == a: # [used-before-assignment] + pass + x = 2 # [redefined-outer-name] + + +def used_before_assignment_3(a): + if x == a: # [used-before-assignment] + if x > 3: + x = 2 # [redefined-outer-name] + + +def not_used_before_assignment(a): + if x == a: + pass + + +def not_used_before_assignment_2(a): + x = 3 # [redefined-outer-name] + if x == a: + pass + + +def func(something): + return something ** 3 + + +class FalsePositive: + x = func(x) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue1081.txt b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue1081.txt new file mode 100644 index 0000000000000000000000000000000000000000..857c4826bafdc02b9db70ac21703f62c696a3910 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue1081.txt @@ -0,0 +1,7 @@ +used-before-assignment:7:7:7:8:used_before_assignment_1:Using variable 'x' before assignment:HIGH +redefined-outer-name:8:12:8:13:used_before_assignment_1:Redefining name 'x' from outer scope (line 3):UNDEFINED +used-before-assignment:13:7:13:8:used_before_assignment_2:Using variable 'x' before assignment:HIGH +redefined-outer-name:15:4:15:5:used_before_assignment_2:Redefining name 'x' from outer scope (line 3):UNDEFINED +used-before-assignment:19:7:19:8:used_before_assignment_3:Using variable 'x' before assignment:HIGH +redefined-outer-name:21:12:21:13:used_before_assignment_3:Redefining name 'x' from outer scope (line 3):UNDEFINED +redefined-outer-name:30:4:30:5:not_used_before_assignment_2:Redefining name 'x' from outer scope (line 3):UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue2615.py b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue2615.py new file mode 100644 index 0000000000000000000000000000000000000000..bce073bf3c114be6ff4c441bc96e6a51f029e493 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue2615.py @@ -0,0 +1,60 @@ +"""https://github.com/PyCQA/pylint/issues/2615""" +def main(): + """When evaluating except blocks, assume try statements fail.""" + try: + res = 1 / 0 + res = 42 + if main(): + res = None + with open(__file__, encoding="utf-8") as opened_file: + res = opened_file.readlines() + except ZeroDivisionError: + print(res) # [used-before-assignment] + print(res) + + +def nested_except_blocks(): + """Assignments in an except are tested against possibly failing + assignments in try blocks at two different nesting levels.""" + try: + res = 1 / 0 + res = 42 + if main(): + res = None + with open(__file__, encoding="utf-8") as opened_file: + res = opened_file.readlines() + except ZeroDivisionError: + try: + more_bad_division = 1 / 0 + except ZeroDivisionError: + print(more_bad_division) # [used-before-assignment] + print(res) # [used-before-assignment] + print(res) + + +def consecutive_except_blocks(): + """An assignment assumed to execute in one TryExcept should continue to be + assumed to execute in a consecutive TryExcept. + """ + try: + res = 100 + except ZeroDivisionError: + pass + try: + pass + except ValueError: + print(res) + + +def name_earlier_in_except_block(): + """Permit the name that might not have been assigned during the try block + to be defined inside a conditional inside the except block. + """ + try: + res = 1 / 0 + except ZeroDivisionError: + if main(): + res = 10 + else: + res = 11 + print(res) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue2615.txt b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue2615.txt new file mode 100644 index 0000000000000000000000000000000000000000..567f5623051f4c0103774b87e7f58c956ea489c8 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue2615.txt @@ -0,0 +1,3 @@ +used-before-assignment:12:14:12:17:main:Using variable 'res' before assignment:CONTROL_FLOW +used-before-assignment:30:18:30:35:nested_except_blocks:Using variable 'more_bad_division' before assignment:CONTROL_FLOW +used-before-assignment:31:18:31:21:nested_except_blocks:Using variable 'res' before assignment:CONTROL_FLOW diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue4761.py b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue4761.py new file mode 100644 index 0000000000000000000000000000000000000000..6f8e048e4c86fdb4ec81823bc919da39e7371e50 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue4761.py @@ -0,0 +1,206 @@ +"""used-before-assignment (E0601)""" +def function(): + """Consider that except blocks may not execute.""" + try: + pass + except ValueError: + some_message = 'some message' + + if not some_message: # [used-before-assignment] + return 1 + + return some_message + + +def uses_nonlocal(): + """https://github.com/PyCQA/pylint/issues/5965""" + count = 0 + def inner(): + nonlocal count + try: + print(count) + except ValueError: + count +=1 + + return inner() + + +def uses_unrelated_nonlocal(): + """Unrelated nonlocals still let messages emit""" + count = 0 + unrelated = 0 + def inner(): + nonlocal unrelated + try: + print(count) # [used-before-assignment] + except ValueError: + count += 1 + + print(count) + return inner() + + +# Cases related to a specific control flow where +# the `else` of a loop can depend on a name only defined +# in a single except handler because that except handler is the +# only non-break exit branch. + +def valid_only_non_break_exit_from_loop_is_except_handler(): + """https://github.com/PyCQA/pylint/issues/5683""" + for _ in range(3): + try: + function() # not an exit branch because of `else` below + except ValueError as verr: + error = verr # < exit branch where error is defined + else: + break # < exit condition where error is *not* defined + # will skip else: raise error + print("retrying...") + else: + # This usage is valid because there is only one exit branch + raise error + + +def invalid_no_outer_else(): + """The reliance on the name is not guarded by else.""" + for _ in range(3): + try: + function() + except ValueError as verr: + error = verr + else: + break + print("retrying...") + raise error # [used-before-assignment] + + +def invalid_no_outer_else_2(): + """Same, but the raise is inside a loop.""" + for _ in range(3): + try: + function() + except ValueError as verr: + error = verr + else: + break + raise error # [used-before-assignment] + + +def invalid_no_inner_else(): + """No inner else statement.""" + for _ in range(3): + try: + function() + except ValueError as verr: + error = verr + print("retrying...") + if function(): + break + else: + raise error # [used-before-assignment] + + +def invalid_wrong_break_location(): + """The break is in the wrong location.""" + for _ in range(3): + try: + function() + break + except ValueError as verr: + error = verr + print("I give up") + else: + raise error # [used-before-assignment] + + +def invalid_no_break(): + """No break.""" + for _ in range(3): + try: + function() + except ValueError as verr: + error = verr + else: + pass + else: # pylint: disable=useless-else-on-loop + raise error # [used-before-assignment] + + +def invalid_other_non_break_exit_from_loop_besides_except_handler(): + """The continue creates another exit branch.""" + while function(): + if function(): + continue + try: + pass + except ValueError as verr: + error = verr + else: + break + else: + raise error # [used-before-assignment] + + +def valid_continue_does_not_matter(): + """This continue doesn't matter: still just one exit branch.""" + while function(): + try: + for _ in range(3): + if function(): + continue + print(1 / 0) + except ZeroDivisionError as zde: + error = zde + else: + break + else: + raise error + + +def invalid_conditional_continue_after_break(): + """The continue is another exit branch""" + while function(): + try: + if function(): + break + if not function(): + continue + except ValueError as verr: + error = verr + else: + break + else: + raise error # [used-before-assignment] + + +def invalid_unrelated_loops(): + """The loop else in question is not related to the try/except/else.""" + for _ in range(3): + try: + function() + except ValueError as verr: + error = verr + else: + break + while function(): + print('The time is:') + break + else: + raise error # [used-before-assignment] + + +def valid_nested_loops(): + """The name `error` is still available in a nested else.""" + for _ in range(3): + try: + function() + except ValueError as verr: + error = verr + else: + break + else: + while function(): + print('The time is:') + break + else: + raise error diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue4761.txt b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue4761.txt new file mode 100644 index 0000000000000000000000000000000000000000..833e0bf18543b2e8de8d3d45418c9aba4e556fc9 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue4761.txt @@ -0,0 +1,10 @@ +used-before-assignment:9:11:9:23:function:Using variable 'some_message' before assignment:CONTROL_FLOW +used-before-assignment:35:18:35:23:uses_unrelated_nonlocal.inner:Using variable 'count' before assignment:CONTROL_FLOW +used-before-assignment:74:10:74:15:invalid_no_outer_else:Using variable 'error' before assignment:CONTROL_FLOW +used-before-assignment:86:14:86:19:invalid_no_outer_else_2:Using variable 'error' before assignment:CONTROL_FLOW +used-before-assignment:100:14:100:19:invalid_no_inner_else:Using variable 'error' before assignment:CONTROL_FLOW +used-before-assignment:113:14:113:19:invalid_wrong_break_location:Using variable 'error' before assignment:CONTROL_FLOW +used-before-assignment:126:14:126:19:invalid_no_break:Using variable 'error' before assignment:CONTROL_FLOW +used-before-assignment:141:14:141:19:invalid_other_non_break_exit_from_loop_besides_except_handler:Using variable 'error' before assignment:CONTROL_FLOW +used-before-assignment:173:14:173:19:invalid_conditional_continue_after_break:Using variable 'error' before assignment:CONTROL_FLOW +used-before-assignment:189:14:189:19:invalid_unrelated_loops:Using variable 'error' before assignment:CONTROL_FLOW diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue626.py b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue626.py new file mode 100644 index 0000000000000000000000000000000000000000..cb9fc100e6484dbd40380f966063f1d54bf82610 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue626.py @@ -0,0 +1,51 @@ +# pylint: disable=missing-docstring,invalid-name +def main1(): + try: + raise ValueError + except ValueError as e: # [unused-variable] + pass + + print(e) # [used-before-assignment] + + +def main2(): + try: + raise ValueError + except ValueError as e: + print(e) + + +def main3(): + try: + raise ValueError + except ValueError as e: # [unused-variable] + pass + + e = 10 + print(e) + + +def main4(): + try: + raise ValueError + except ValueError as e: # [unused-variable] + pass + + try: + raise ValueError + except ValueError as e: + pass + + try: + raise ValueError + except ValueError as e: + pass + + print(e) # [used-before-assignment] + + +def main5(): + try: + print([e for e in range(3) if e]) + except ValueError as e: + print(e) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue626.txt b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue626.txt new file mode 100644 index 0000000000000000000000000000000000000000..3d0e572463430d4dc7aeccd1d712d2274cfa55c1 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue626.txt @@ -0,0 +1,5 @@ +unused-variable:5:4:6:12:main1:Unused variable 'e':UNDEFINED +used-before-assignment:8:10:8:11:main1:Using variable 'e' before assignment:CONTROL_FLOW +unused-variable:21:4:22:12:main3:Unused variable 'e':UNDEFINED +unused-variable:31:4:32:12:main4:Unused variable 'e':UNDEFINED +used-before-assignment:44:10:44:11:main4:Using variable 'e' before assignment:CONTROL_FLOW diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue85.py b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue85.py new file mode 100644 index 0000000000000000000000000000000000000000..367af9dfa071cb40db9aa9adc3b51759754383e5 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue85.py @@ -0,0 +1,126 @@ +"""https://github.com/PyCQA/pylint/issues/85""" +def main(): + """When evaluating finally blocks, assume try statements fail.""" + try: + res = 1 / 0 + res = 42 + finally: + print(res) # [used-before-assignment] + print(res) + + +def try_except_finally(): + """When evaluating finally blocks, assume try statements fail.""" + try: + res = 1 / 0 + res = 42 + except ZeroDivisionError: + print() + finally: + print(res) # [used-before-assignment] + print(res) + + +def try_except_finally_assignment_in_final_block(): + """Assignment of the name in the final block does not warn.""" + try: + res = 1 / 0 + res = 42 + except ZeroDivisionError: + print() + finally: + res = 999 + print(res) + print(res) + + +def try_except_finally_nested_try_finally_in_try(): + """Don't confuse assignments in different finally statements where + one is nested inside a try. + """ + try: + try: + res = 1 / 0 + finally: + print(res) # [used-before-assignment] + print(1 / 0) + except ZeroDivisionError: + print() + finally: + res = 999 # this assignment could be confused for that above + print(res) + print(res) + + +def try_except_finally_nested_in_finally(): + """Until Pylint comes to a consensus on requiring all except handlers to + define a name, raise, or return (https://github.com/PyCQA/pylint/issues/5524), + Pylint assumes statements in try blocks succeed when accessed *after* + except or finally blocks and fail when accessed *in* except or finally + blocks.) + """ + try: + outer_times = 1 + finally: + try: + inner_times = 1 + except TypeError: + pass + finally: + print(outer_times) # [used-before-assignment] + print(inner_times) # see docstring: might emit in a future version + + +def try_except_finally_nested_in_finally_2(): + """Neither name is accessed after a finally block.""" + try: + outer_times = 1 + finally: + try: + inner_times = 1 + except TypeError: + pass + finally: + print(inner_times) # [used-before-assignment] + print(outer_times) # [used-before-assignment] + + +def try_except_finally_nested_in_finally_3(): + """One name is never accessed after a finally block, but just emit + once per name. + """ + try: + outer_times = 1 + finally: + try: + inner_times = 1 + except TypeError: + pass + finally: + print(inner_times) # [used-before-assignment] + print(outer_times) # [used-before-assignment] + print(inner_times) + # used-before-assignment is only raised once per name + print(outer_times) + + +def try_except_finally_nested_in_finally_4(): + """Triple nesting: don't assume direct parentages of outer try/finally + and inner try/finally. + """ + try: + outer_times = 1 + finally: + try: + pass + finally: + try: + inner_times = 1 + except TypeError: + pass + finally: + print(inner_times) # [used-before-assignment] + print(outer_times) # [used-before-assignment] + print(inner_times) + # used-before-assignment is only raised once per name + print(outer_times) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue85.txt b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue85.txt new file mode 100644 index 0000000000000000000000000000000000000000..9f405c2c5cae3d58972ee6737c93c4343f6ca6f0 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue85.txt @@ -0,0 +1,10 @@ +used-before-assignment:8:14:8:17:main:Using variable 'res' before assignment:CONTROL_FLOW +used-before-assignment:20:14:20:17:try_except_finally:Using variable 'res' before assignment:CONTROL_FLOW +used-before-assignment:45:18:45:21:try_except_finally_nested_try_finally_in_try:Using variable 'res' before assignment:HIGH +used-before-assignment:70:18:70:29:try_except_finally_nested_in_finally:Using variable 'outer_times' before assignment:CONTROL_FLOW +used-before-assignment:84:18:84:29:try_except_finally_nested_in_finally_2:Using variable 'inner_times' before assignment:CONTROL_FLOW +used-before-assignment:85:14:85:25:try_except_finally_nested_in_finally_2:Using variable 'outer_times' before assignment:CONTROL_FLOW +used-before-assignment:100:18:100:29:try_except_finally_nested_in_finally_3:Using variable 'inner_times' before assignment:CONTROL_FLOW +used-before-assignment:101:18:101:29:try_except_finally_nested_in_finally_3:Using variable 'outer_times' before assignment:CONTROL_FLOW +used-before-assignment:122:22:122:33:try_except_finally_nested_in_finally_4:Using variable 'inner_times' before assignment:CONTROL_FLOW +used-before-assignment:123:22:123:33:try_except_finally_nested_in_finally_4:Using variable 'outer_times' before assignment:CONTROL_FLOW diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue853.py b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue853.py new file mode 100644 index 0000000000000000000000000000000000000000..7da9fdd50c4b4846880e5fd7b15c59ecb0fa159d --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_issue853.py @@ -0,0 +1,23 @@ +# pylint: disable=missing-docstring,bare-except,pointless-statement,superfluous-parens, consider-using-f-string +def strangeproblem(): + try: + for _ in range(0, 4): + message = object() + print(type(message)) + finally: + message = object() + + +try: + MY_INT = 1 + print("MY_INT = %d" % MY_INT) +finally: + MY_INT = 2 + +try: + pass +except: + FALSE_POSITIVE = 1 + FALSE_POSITIVE # here pylint claims used-before-assignment +finally: + FALSE_POSITIVE = 2 # this line is needed to reproduce the issue diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_nonlocal.py b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_nonlocal.py new file mode 100644 index 0000000000000000000000000000000000000000..18e16177d01f8638f916790527068dd89822a62e --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_nonlocal.py @@ -0,0 +1,108 @@ +"""Check for nonlocal and used-before-assignment""" +# pylint: disable=missing-docstring, unused-variable, too-few-public-methods + + +def test_ok(): + """ uses nonlocal """ + cnt = 1 + def wrap(): + nonlocal cnt + cnt = cnt + 1 + wrap() + +def test_fail(): + """ doesn't use nonlocal """ + cnt = 1 + def wrap(): + cnt = cnt + 1 # [used-before-assignment] + wrap() + +def test_fail2(): + """ use nonlocal, but for other variable """ + cnt = 1 + count = 1 + def wrap(): + nonlocal count + cnt = cnt + 1 # [used-before-assignment] + wrap() + +def test_fail3(arg: test_fail4): # [used-before-assignment] + """ Depends on `test_fail4`, in argument annotation. """ + return arg +# +1: [used-before-assignment, used-before-assignment] +def test_fail4(*args: test_fail5, **kwargs: undefined): + """ Depends on `test_fail5` and `undefined` in + variable and named arguments annotations. + """ + return args, kwargs + +def test_fail5()->undefined1: # [used-before-assignment] + """ Depends on `undefined1` in function return annotation. """ + +def undefined(): + """ no op """ + +def undefined1(): + """ no op """ + + +def nonlocal_in_ifexp(): + """bar""" + bug2 = True + def on_click(event): + """on_click""" + if event: + nonlocal bug2 + bug2 = not bug2 + on_click(True) + +nonlocal_in_ifexp() + + +def type_annotation_only_gets_value_via_nonlocal(): + """https://github.com/PyCQA/pylint/issues/5394""" + some_num: int + def inner(): + nonlocal some_num + some_num = 5 + inner() + print(some_num) + + +def type_annotation_only_gets_value_via_nonlocal_nested(): + """Similar, with nesting""" + some_num: int + def inner(): + def inner2(): + nonlocal some_num + some_num = 5 + inner2() + inner() + print(some_num) + + +def type_annotation_never_gets_value_despite_nonlocal(): + """Type annotation lacks a value despite nonlocal declaration""" + some_num: int + def inner(): + nonlocal some_num + inner() + print(some_num) # [used-before-assignment] + + +def inner_function_lacks_access_to_outer_args(args): + """Check homonym between inner function and outer function names""" + def inner(): + print(args) # [used-before-assignment] + args = [] + inner() + print(args) + + +def inner_function_ok(args): + """Explicitly redefined homonym defined before is OK.""" + def inner(): + args = [] + print(args) + inner() + print(args) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_nonlocal.txt b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_nonlocal.txt new file mode 100644 index 0000000000000000000000000000000000000000..2bdbf2fe1ea30b4299dbbadeb74b764622cf4624 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_nonlocal.txt @@ -0,0 +1,8 @@ +used-before-assignment:17:14:17:17:test_fail.wrap:Using variable 'cnt' before assignment:HIGH +used-before-assignment:26:14:26:17:test_fail2.wrap:Using variable 'cnt' before assignment:HIGH +used-before-assignment:29:20:29:30:test_fail3:Using variable 'test_fail4' before assignment:HIGH +used-before-assignment:33:22:33:32:test_fail4:Using variable 'test_fail5' before assignment:HIGH +used-before-assignment:33:44:33:53:test_fail4:Using variable 'undefined' before assignment:HIGH +used-before-assignment:39:18:39:28:test_fail5:Using variable 'undefined1' before assignment:HIGH +used-before-assignment:90:10:90:18:type_annotation_never_gets_value_despite_nonlocal:Using variable 'some_num' before assignment:HIGH +used-before-assignment:96:14:96:18:inner_function_lacks_access_to_outer_args.inner:Using variable 'args' before assignment:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_py310.py b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_py310.py new file mode 100644 index 0000000000000000000000000000000000000000..14f46b61e9fa8e67ea69f35d7866ccd04d259845 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_py310.py @@ -0,0 +1,7 @@ +"""Tests for used-before-assignment with python 3.10's pattern matching""" + +match ("example", "one"): + case (x, y) if x == "example": + print("x used to cause used-before-assignment!") + case _: + print("good thing it doesn't now!") diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_py310.rc b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_py310.rc new file mode 100644 index 0000000000000000000000000000000000000000..68a8c8ef157980e74dc55bae272edcd141052de0 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_py310.rc @@ -0,0 +1,2 @@ +[testoptions] +min_pyver=3.10 diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_py37.py b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_py37.py new file mode 100644 index 0000000000000000000000000000000000000000..c64bf7cf55e2df925af65a8577b573aed98cd910 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_py37.py @@ -0,0 +1,35 @@ +"""Tests for used-before-assignment with functions added in python 3.7""" +# pylint: disable=missing-function-docstring +from __future__ import annotations +from collections import namedtuple +from typing import List + + +class MyClass: + """With the future import only default values can't refer to the base class""" + + def correct_typing_method(self, other: MyClass) -> bool: + return self == other + + def second_correct_typing_method(self, other: List[MyClass]) -> bool: + return self == other[0] + + def incorrect_default_method( + self, other=MyClass() # [undefined-variable] + ) -> bool: + return self == other + + def correct_string_typing_method(self, other: "MyClass") -> bool: + return self == other + + def correct_inner_typing_method(self) -> bool: + def inner_method(self, other: MyClass) -> bool: + return self == other + + return inner_method(self, MyClass()) + + +class NamedTupleSubclass(namedtuple("NamedTupleSubclass", [])): + """Taken from https://github.com/PyCQA/pylint/issues/5982""" + def method(self) -> NamedTupleSubclass: + """Variables checker crashed when astroid did not supply a lineno""" diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_py37.rc b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_py37.rc new file mode 100644 index 0000000000000000000000000000000000000000..a17bb22dafb99eb4cf76db1ac0f83de586947860 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_py37.rc @@ -0,0 +1,2 @@ +[testoptions] +min_pyver=3.7 diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_py37.txt b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_py37.txt new file mode 100644 index 0000000000000000000000000000000000000000..fa0a0b77a05243641a1d0908cb6d8dc69bf32eea --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_py37.txt @@ -0,0 +1 @@ +undefined-variable:18:20:18:27:MyClass.incorrect_default_method:Undefined variable 'MyClass':UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_ternary.py b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_ternary.py new file mode 100644 index 0000000000000000000000000000000000000000..72012f4243f4de4fce8bc7376f5174ff336de049 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_ternary.py @@ -0,0 +1,54 @@ +"""Tests for used-before-assignment false positive from ternary expression with walrus operator""" +# pylint: disable=unnecessary-lambda-assignment, unused-variable, disallowed-name, invalid-name + +def invalid(): + """invalid cases that will trigger used-before-assignment""" + var = foo(a, '', '') # [used-before-assignment] + print(str(1 if (a:=-1) else 0)) + var = bar(b) # [used-before-assignment] + var = c*c # [used-before-assignment] + var = 1 if (b:=-1) else 0 + var = 1 if (c:=-1) else 0 + +def attribute_call_valid(): + """assignment with attribute calls""" + var = (a if (a:='a') else '').lower() + var = ('' if (b:='b') else b).lower() + var = (c if (c:='c') else c).upper().lower().replace('', '').strip() + var = ''.strip().replace('', '' + (e if (e:='e') else '').lower()) + +def function_call_arg_valid(): + """assignment as function call arguments""" + var = str(a if (a:='a') else '') + var = str('' if (b:='b') else b) + var = foo(1, c if (c:=1) else 0, 1) + print(foo('', '', foo('', str(int(d if (d:='1') else '')), ''))) + +def function_call_keyword_valid(): + """assignment as function call keywords""" + var = foo(x=a if (a:='1') else '', y='', z='') + var = foo(x='', y=foo(x='', y='', z=b if (b:='1') else ''), z='') + +def dictionary_items_valid(): + """assignment as dictionary keys/values""" + var = { + 0: w if (w:=input()) else "", + } + var = { + x if (x:=input()) else "": 0, + } + var = { + 0: y if (y:=input()) else "", + z if (z:=input()) else "": 0, + } + +def complex_valid(): + """assignment within complex call expression""" + var = str(bar(bar(a if (a:=1) else 0))).lower().upper() + print(foo(x=foo(''.replace('', str(b if (b:=1) else 0).upper()), '', z=''), y='', z='')) + +def foo(x, y, z): + """helper function for tests""" + return x+y+z + +bar = lambda x : x diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_ternary.rc b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_ternary.rc new file mode 100644 index 0000000000000000000000000000000000000000..85fc502b372ea64005d4e09627da9827c325d447 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_ternary.rc @@ -0,0 +1,2 @@ +[testoptions] +min_pyver=3.8 diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_ternary.txt b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_ternary.txt new file mode 100644 index 0000000000000000000000000000000000000000..d991970e4c1e1becf68c6f8c372e877a3c239d95 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_ternary.txt @@ -0,0 +1,3 @@ +used-before-assignment:6:14:6:15:invalid:Using variable 'a' before assignment:HIGH +used-before-assignment:8:14:8:15:invalid:Using variable 'b' before assignment:HIGH +used-before-assignment:9:10:9:11:invalid:Using variable 'c' before assignment:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_type_annotations.py b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_type_annotations.py new file mode 100644 index 0000000000000000000000000000000000000000..1a03050c34c49621ed8d414efb983fa2fb53c44b --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_type_annotations.py @@ -0,0 +1,90 @@ +"""Tests for annotation of variables and potential use before assignment""" +# pylint: disable=too-few-public-methods, global-variable-not-assigned +from collections import namedtuple +from typing import List + +def value_and_type_assignment(): + """The variable assigned a value and type""" + variable: int = 2 + print(variable) + + +def only_type_assignment(): + """The variable never gets assigned a value""" + variable: int + print(variable) # [used-before-assignment] + + +def both_type_and_value_assignment(): + """The variable first gets a type and subsequently a value""" + variable: int + variable = 1 + print(variable) + + +def value_assignment_after_access(): + """The variable gets a value after it has been accessed""" + variable: int + print(variable) # [used-before-assignment] + variable = 1 + + +def value_assignment_from_iterator(): + """The variables gets a value from an iterator""" + variable: int + for variable in (1, 2): + print(variable) + + +def assignment_in_comprehension(): + """A previously typed variables gets used in a comprehension. Don't crash!""" + some_list: List[int] + some_list = [1, 2, 3] + some_list = [i * 2 for i in some_list] + + +def decorator_returning_function(): + """A decorator that returns a wrapper function with decoupled typing""" + def wrapper_with_decoupled_typing(): + print(var) + + var: int + var = 2 + return wrapper_with_decoupled_typing + + +def decorator_returning_incorrect_function(): + """A decorator that returns a wrapper function with decoupled typing""" + def wrapper_with_type_and_no_value(): + # This emits NameError rather than UnboundLocalError, so + # undefined-variable is okay, even though the traceback refers + # to "free variable 'var' referenced before assignment" + print(var) # [undefined-variable] + + var: int + return wrapper_with_type_and_no_value + + +def typing_and_value_assignment_with_tuple_assignment(): + """The typed variables get assigned with a tuple assignment""" + var_one: int + var_two: int + var_one, var_two = 1, 1 + print(var_one) + print(var_two) + + +def nested_class_as_return_annotation(): + """A namedtuple as a class attribute is used as a return annotation + + Taken from https://github.com/PyCQA/pylint/issues/5568""" + class MyObject: + """namedtuple as class attribute""" + Coords = namedtuple('Point', ['x', 'y']) + + def my_method(self) -> Coords: + """Return annotation is valid""" + # pylint: disable=unnecessary-pass + pass + + print(MyObject) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_type_annotations.txt b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_type_annotations.txt new file mode 100644 index 0000000000000000000000000000000000000000..81e1646da884f084b55eebb989841925713f4a72 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_type_annotations.txt @@ -0,0 +1,3 @@ +used-before-assignment:15:10:15:18:only_type_assignment:Using variable 'variable' before assignment:HIGH +used-before-assignment:28:10:28:18:value_assignment_after_access:Using variable 'variable' before assignment:HIGH +undefined-variable:62:14:62:17:decorator_returning_incorrect_function.wrapper_with_type_and_no_value:Undefined variable 'var':HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_typing.py b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..a685bdabc89362b797c796d3cd35f4597a2c17dd --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_typing.py @@ -0,0 +1,197 @@ +"""Tests for used-before-assignment for typing related issues""" +# pylint: disable=missing-function-docstring,ungrouped-imports,invalid-name + + +from typing import List, Optional, TYPE_CHECKING + +if TYPE_CHECKING: + if True: # pylint: disable=using-constant-test + import math + from urllib.request import urlopen + import array + import base64 + import binascii + import bisect + import calendar + import collections + import copy + import datetime + import email + import heapq + import json + import mailbox + import mimetypes + import numbers + import pprint + import types + import zoneinfo +elif input(): + import calendar, bisect # pylint: disable=multiple-imports + if input() + 1: + import heapq + else: + import heapq +elif input(): + try: + numbers = None if input() else 1 + import array + except Exception as e: # pylint: disable=broad-exception-caught + import types + finally: + copy = None +elif input(): + for i in range(1,2): + email = None + else: # pylint: disable=useless-else-on-loop + json = None + while input(): + import mailbox + else: # pylint: disable=useless-else-on-loop + mimetypes = None +elif input(): + with input() as base64: + pass + with input() as temp: + import binascii +else: + from urllib.request import urlopen + zoneinfo: str = '' + def pprint(): + pass + class collections: # pylint: disable=too-few-public-methods,missing-class-docstring + pass + +class MyClass: + """Type annotation or default values for first level methods can't refer to their own class""" + + def incorrect_typing_method( + self, other: MyClass # [undefined-variable] + ) -> bool: + return self == other + + def incorrect_nested_typing_method( + self, other: List[MyClass] # [undefined-variable] + ) -> bool: + return self == other[0] + + def incorrect_default_method( + self, other=MyClass() # [undefined-variable] + ) -> bool: + return self == other + + def correct_string_typing_method(self, other: "MyClass") -> bool: + return self == other + + def correct_inner_typing_method(self) -> bool: + def inner_method(self, other: MyClass) -> bool: + return self == other + + return inner_method(self, MyClass()) + + +class MySecondClass: + """Class to test self referential variable typing. + This regressed, reported in: https://github.com/PyCQA/pylint/issues/5342 + """ + + def self_referential_optional_within_method(self) -> None: + variable: Optional[MySecondClass] = self + print(variable) + + def correct_inner_typing_method(self) -> bool: + def inner_method(self, other: MySecondClass) -> bool: + return self == other + + return inner_method(self, MySecondClass()) + + +class MyOtherClass: + """Class to test self referential variable typing, no regression.""" + + def correct_inner_typing_method(self) -> bool: + def inner_method(self, other: MyOtherClass) -> bool: + return self == other + + return inner_method(self, MyOtherClass()) + + def self_referential_optional_within_method(self) -> None: + variable: Optional[MyOtherClass] = self + print(variable) + + +class MyThirdClass: + """Class to test self referential variable typing within conditionals. + This regressed, reported in: https://github.com/PyCQA/pylint/issues/5499 + """ + + def function(self, var: int) -> None: + if var < 0.5: + _x: MyThirdClass = self + + def other_function(self) -> None: + _x: MyThirdClass = self + + +class MyFourthClass: # pylint: disable=too-few-public-methods + """Class to test conditional imports guarded by TYPE_CHECKING two levels + up then used in function annotation. See https://github.com/PyCQA/pylint/issues/7539""" + + def is_close(self, comparator: math.isclose, first, second): # [used-before-assignment] + """Conditional imports guarded are only valid for variable annotations.""" + comparator(first, second) + + +class VariableAnnotationsGuardedByTypeChecking: # pylint: disable=too-few-public-methods + """Class to test conditional imports guarded by TYPE_CHECKING then used in + local (function) variable annotations, which are not evaluated at runtime. + + See: https://github.com/PyCQA/pylint/issues/7609 + and https://github.com/PyCQA/pylint/issues/7882 + """ + + still_an_error: datetime.date # [used-before-assignment] + + def print_date(self, date) -> None: + date: datetime.date = date + print(date) + + import datetime # pylint: disable=import-outside-toplevel + + +class ConditionalImportGuardedWhenUsed: # pylint: disable=too-few-public-methods + """Conditional imports also guarded by TYPE_CHECKING when used.""" + if TYPE_CHECKING: + print(urlopen) + + +class TypeCheckingMultiBranch: # pylint: disable=too-few-public-methods,unused-variable + """Test for defines in TYPE_CHECKING if/elif/else branching""" + def defined_in_elif_branch(self) -> calendar.Calendar: + print(bisect) + return calendar.Calendar() + + def defined_in_else_branch(self) -> urlopen: + print(zoneinfo) + print(pprint()) + print(collections()) + return urlopen + + def defined_in_nested_if_else(self) -> heapq: + print(heapq) + return heapq + + def defined_in_try_except(self) -> array: + print(types) + print(copy) + print(numbers) + return array + + def defined_in_loops(self) -> json: + print(email) + print(mailbox) + print(mimetypes) + return json + + def defined_in_with(self) -> base64: + print(binascii) + return base64 diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_typing.txt b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_typing.txt new file mode 100644 index 0000000000000000000000000000000000000000..c0a31fae089d84ad656ab15b66a6a165449ddd0d --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_before_assignment_typing.txt @@ -0,0 +1,5 @@ +undefined-variable:68:21:68:28:MyClass.incorrect_typing_method:Undefined variable 'MyClass':UNDEFINED +undefined-variable:73:26:73:33:MyClass.incorrect_nested_typing_method:Undefined variable 'MyClass':UNDEFINED +undefined-variable:78:20:78:27:MyClass.incorrect_default_method:Undefined variable 'MyClass':UNDEFINED +used-before-assignment:139:35:139:39:MyFourthClass.is_close:Using variable 'math' before assignment:HIGH +used-before-assignment:152:20:152:28:VariableAnnotationsGuardedByTypeChecking:Using variable 'datetime' before assignment:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_prior_global_declaration.py b/testbed/pylint-dev__pylint/tests/functional/u/used/used_prior_global_declaration.py new file mode 100644 index 0000000000000000000000000000000000000000..079501022c642dbbd3f3966f16ca4ce9db84de54 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_prior_global_declaration.py @@ -0,0 +1,39 @@ +# pylint: disable=missing-docstring, pointless-statement, global-variable-not-assigned, global-statement + + +CONST = 1 + + +def test(): + CONST # [used-prior-global-declaration] + + global CONST + + +def other_test(): + CONST + + global SOMETHING + + +def other_test_1(): + global SOMETHING + + CONST + + +def other_test_2(): + CONST + + def inner(): + global CONST + + return inner + + +def other_test_3(): + def inner(): + return CONST + + global CONST + return inner diff --git a/testbed/pylint-dev__pylint/tests/functional/u/used/used_prior_global_declaration.txt b/testbed/pylint-dev__pylint/tests/functional/u/used/used_prior_global_declaration.txt new file mode 100644 index 0000000000000000000000000000000000000000..314d8523415cce1207f7a4aabde43352718bb03c --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/used/used_prior_global_declaration.txt @@ -0,0 +1 @@ +used-prior-global-declaration:8:4:8:9:test:Name 'CONST' is used prior to global declaration:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_else_on_loop.py b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_else_on_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..20354cad08d3982da371481ca7e12c590b70619c --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_else_on_loop.py @@ -0,0 +1,102 @@ +"""Check for else branches on loops with break and return only.""" + + +def test_return_for(): + """else + return is not acceptable.""" + for i in range(10): + if i % 2: + return i + else: # [useless-else-on-loop] + print('math is broken') + return None + +def test_return_while(): + """else + return is not acceptable.""" + while True: + return 1 + else: # [useless-else-on-loop] + print('math is broken') + return None + + +while True: + def short_fun(): + """A function with a loop.""" + for _ in range(10): + break +else: # [useless-else-on-loop] + print('or else!') + + +while True: + while False: + break +else: # [useless-else-on-loop] + print('or else!') + +for j in range(10): + pass +else: # [useless-else-on-loop] + print('fat chance') + for j in range(10): + break + + +def test_return_for2(): + """no false positive for break in else + + https://bitbucket.org/logilab/pylint/issue/117/useless-else-on-loop-false-positives + """ + for i in range(10): + for _ in range(i): + if i % 2: + break + else: + break + else: + print('great math') + + +def test_break_in_orelse_deep(): + """no false positive for break in else deeply nested + """ + for _ in range(10): + if 1 < 2: # pylint: disable=comparison-of-constants + for _ in range(3): + if 3 < 2: # pylint: disable=comparison-of-constants + break + else: + break + else: + return True + return False + + +def test_break_in_orelse_deep2(): + """should rise a useless-else-on-loop message, as the break statement is only + for the inner for loop + """ + for _ in range(10): + if 1 < 2: # pylint: disable=comparison-of-constants + for _ in range(3): + if 3 < 2: # pylint: disable=comparison-of-constants + break + else: + print("all right") + else: # [useless-else-on-loop] + return True + return False + + +def test_break_in_orelse_deep3(): + """no false positive for break deeply nested in else + """ + for _ in range(10): + for _ in range(3): + pass + else: + if 1 < 2: # pylint: disable=comparison-of-constants + break + else: + return True + return False diff --git a/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_else_on_loop.txt b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_else_on_loop.txt new file mode 100644 index 0000000000000000000000000000000000000000..067b6435d2ca5f060ed02e7708b694251b437b2e --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_else_on_loop.txt @@ -0,0 +1,6 @@ +useless-else-on-loop:9:4:10:31:test_return_for:Else clause on loop without a break statement, remove the else and de-indent all the code inside it:UNDEFINED +useless-else-on-loop:17:4:18:31:test_return_while:Else clause on loop without a break statement, remove the else and de-indent all the code inside it:UNDEFINED +useless-else-on-loop:27:0:28:21::Else clause on loop without a break statement, remove the else and de-indent all the code inside it:UNDEFINED +useless-else-on-loop:34:0:35:21::Else clause on loop without a break statement, remove the else and de-indent all the code inside it:UNDEFINED +useless-else-on-loop:39:0:42:13::Else clause on loop without a break statement, remove the else and de-indent all the code inside it:UNDEFINED +useless-else-on-loop:86:4:87:19:test_break_in_orelse_deep2:Else clause on loop without a break statement, remove the else and de-indent all the code inside it:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_object_inheritance.py b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_object_inheritance.py new file mode 100644 index 0000000000000000000000000000000000000000..5c23d2147e60469c2604f2e00c5949e6a44d9979 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_object_inheritance.py @@ -0,0 +1,27 @@ +"""Check if a class inherits from object. +In python3 every class implicitly inherits from object, therefore give refactoring message to + remove object from bases""" +# pylint: disable=invalid-name, missing-docstring, too-few-public-methods +# pylint: disable=inconsistent-mro +import abc + +class A(object): # [useless-object-inheritance] + pass + +class B: + pass + +class C(B, object): # [useless-object-inheritance] + pass + +class D(object, C, metaclass=abc.ABCMeta): # [useless-object-inheritance] + pass + +class E(D, C, object, metaclass=abc.ABCMeta): # [useless-object-inheritance] + pass + +class F(A): # positive test case + pass + +class G(B): # positive test case + pass diff --git a/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_object_inheritance.txt b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_object_inheritance.txt new file mode 100644 index 0000000000000000000000000000000000000000..67f48417f93a9f0e30262c5fe4f1b1fffaa4dee5 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_object_inheritance.txt @@ -0,0 +1,4 @@ +useless-object-inheritance:8:0:8:7:A:Class 'A' inherits from object, can be safely removed from bases in python3:UNDEFINED +useless-object-inheritance:14:0:14:7:C:Class 'C' inherits from object, can be safely removed from bases in python3:UNDEFINED +useless-object-inheritance:17:0:17:7:D:Class 'D' inherits from object, can be safely removed from bases in python3:UNDEFINED +useless-object-inheritance:20:0:20:7:E:Class 'E' inherits from object, can be safely removed from bases in python3:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_parent_delegation.py b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_parent_delegation.py new file mode 100644 index 0000000000000000000000000000000000000000..ce645e31f8561f139fa86cfacb8c7f19207a0b82 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_parent_delegation.py @@ -0,0 +1,432 @@ +# pylint: disable=missing-docstring, no-member, bad-super-call +# pylint: disable=too-few-public-methods, unused-argument, invalid-name, too-many-public-methods +# pylint: disable=line-too-long, arguments-out-of-order +# pylint: disable=super-with-arguments, dangerous-default-value +# pylint: disable=too-many-function-args, no-method-argument + +import random +from typing import Any, List + +default_var = 1 + + +def not_a_method(param, param2): + return super(None, None).not_a_method(param, param2) + + +class SuperBase: + def with_default_arg(self, first, default_arg="only_in_super_base"): + pass + + def with_default_arg_bis(self, first, default_arg="only_in_super_base"): + pass + + def with_default_arg_ter(self, first, default_arg="will_be_changed"): + pass + + def with_default_arg_quad(self, first, default_arg="will_be_changed"): + pass + + +class Base(SuperBase): + + fake_method = not_a_method + + def something(self): + pass + + def with_default_argument(self, first, default_arg="default"): + pass + + def with_default_argument_bis(self, first, default_arg="default"): + pass + + def without_default_argument(self, first, second): + pass + + def with_default_argument_none(self, first, default_arg=None): + pass + + def without_default_argument2(self, first, second): + pass + + def with_default_argument_int(self, first, default_arg=42): + pass + + def with_default_argument_tuple(self, first, default_arg=()): + pass + + def with_default_argument_dict(self, first, default_arg={}): + pass + + def with_default_argument_var(self, first, default_arg=default_var): + pass + + def with_default_arg_ter(self, first, default_arg="has_been_changed"): + super().with_default_arg_ter(first, default_arg) + + def with_default_arg_quad(self, first, default_arg="has_been_changed"): + super().with_default_arg_quad(first, default_arg) + + def with_default_unhandled(self, first, default_arg=lambda: True): + super().with_default_arg_quad(first, default_arg) + + +class NotUselessSuper(Base): + def multiple_statements(self): + first = 42 * 24 + return super().multiple_statements() + first + + def not_a_call(self): + return 1 + 2 + + def not_super_call(self): + return type(self).__class__ + + def not_super_attribute_access(self): + return super() + + def invalid_super_call(self): + return super(NotUselessSuper, 1).invalid_super_call() + + def other_invalid_super_call(self): + return super(2, 3, 4, 5).other_invalid_super_call() + + def different_name(self): + return super().something() + + def different_super_mro_pointer(self): + return super(Base, self).different_super_mro_pointer() + + def different_super_type(self): + return super(NotUselessSuper, NotUselessSuper).different_super_type() + + def other_different_super_type(self): + return super(NotUselessSuper, 1).other_different_super_type() + + def not_passing_param(self, first): + return super(NotUselessSuper, self).not_passing_param() + + def modifying_param(self, first): + return super(NotUselessSuper, self).modifying_param(first + 1) + + def transforming_param(self, first): + return super(NotUselessSuper, self).transforming_param(type(first)) + + def modifying_variadic(self, *args): + return super(NotUselessSuper, self).modifying_variadic(tuple(args)) + + def not_passing_keyword_variadics(self, *args, **kwargs): + return super(NotUselessSuper, self).not_passing_keyword_variadics(*args) + + def not_passing_default(self, first, second=None): + return super(NotUselessSuper, self).not_passing_default(first) + + def passing_only_a_handful(self, first, second, third, fourth): + return super(NotUselessSuper, self).passing_only_a_handful(first, second) + + def not_the_same_order(self, first, second, third): + return super(NotUselessSuper, self).not_the_same_order(third, first, second) + + def no_kwargs_in_signature(self, key=None): + values = {"key": "something"} + return super(NotUselessSuper, self).no_kwargs_in_signature(**values) + + def no_args_in_signature(self, first, second): + values = (first + 1, second + 2) + return super(NotUselessSuper, self).no_args_in_signature(*values) + + def variadics_with_multiple_keyword_arguments(self, **kwargs): + return super(NotUselessSuper, self).variadics_with_multiple_keyword_arguments( + first=None, second=None, **kwargs + ) + + def extraneous_keyword_params(self, none_ok=False): + super(NotUselessSuper, self).extraneous_keyword_params( + none_ok, valid_values=[23, 42] + ) + + def extraneous_positional_args(self, **args): + super(NotUselessSuper, self).extraneous_positional_args(1, 2, **args) + + def with_default_argument(self, first, default_arg="other"): + # Not useless because the default_arg is different from the one in the base class + super(NotUselessSuper, self).with_default_argument(first, default_arg) + + def without_default_argument(self, first, second=True): + # Not useless because in the base class there is not default value for second argument + super(NotUselessSuper, self).without_default_argument(first, second) + + def with_default_argument_none(self, first, default_arg="NotNone"): + # Not useless because the default_arg is different from the one in the base class + super(NotUselessSuper, self).with_default_argument_none(first, default_arg) + + def without_default_argument2(self, first, second=None): + # Not useless because in the base class there is not default value for second argument + super(NotUselessSuper, self).without_default_argument2(first, second) + + def with_default_argument_int(self, first, default_arg="42"): + # Not useless because the default_arg is a string whereas in the base class it's an int + super(NotUselessSuper, self).with_default_argument_int(first, default_arg) + + def with_default_argument_tuple(self, first, default_arg=("42", "a")): + # Not useless because the default_arg is different from the one in the base class + super(NotUselessSuper, self).with_default_argument_tuple(first, default_arg) + + def with_default_argument_dict(self, first, default_arg={"foo": "bar"}): + # Not useless because the default_arg is different from the one in the base class + super(NotUselessSuper, self).with_default_argument_dict(first, default_arg) + + default_var = 2 + + def with_default_argument_var(self, first, default_arg=default_var): + # Not useless because the default_arg refers to a different variable from the one in the base class + super(NotUselessSuper, self).with_default_argument_var(first, default_arg) + + def with_default_argument_bis(self, first, default_arg="default"): + # Although the default_arg is the same as in the base class, the call signature + # differs. Thus it is not useless. + super(NotUselessSuper, self).with_default_argument_bis( + default_arg + "_argument" + ) + + def fake_method(self, param2="other"): + super(NotUselessSuper, self).fake_method(param2) + + def with_default_arg(self, first, default_arg="only_in_super_base"): + # Not useless because the call of this method is different from the function signature + super(NotUselessSuper, self).with_default_arg(first, default_arg + "_and_here") + + def with_default_arg_bis(self, first, default_arg="default_changed"): + # Not useless because the default value is different from the SuperBase one + super(NotUselessSuper, self).with_default_arg_bis(first, default_arg) + + def with_default_arg_ter(self, first, default_arg="has_been_changed_again"): + # Not useless because the default value is different from the Base one + super(NotUselessSuper, self).with_default_arg_ter(first, default_arg) + + def with_default_arg_quad(self, first, default_arg="has_been_changed"): + # Not useless because the default value is the same as in the base but the + # call is different from the signature + super(NotUselessSuper, self).with_default_arg_quad( + first, default_arg + "_and_modified" + ) + + def with_default_unhandled(self, first, default_arg=lambda: True): + # Not useless because the default value type is not explicitly handled (Lambda), so assume they are different + super(NotUselessSuper, self).with_default_unhandled(first, default_arg) + + +class UselessSuper(Base): + def equivalent_params(self): # [useless-parent-delegation] + return super(UselessSuper, self).equivalent_params() + + def equivalent_params_1(self, first): # [useless-parent-delegation] + return super(UselessSuper, self).equivalent_params_1(first) + + def equivalent_params_2(self, *args): # [useless-parent-delegation] + return super(UselessSuper, self).equivalent_params_2(*args) + + def equivalent_params_3(self, *args, **kwargs): # [useless-parent-delegation] + return super(UselessSuper, self).equivalent_params_3(*args, **kwargs) + + def equivalent_params_4(self, first): # [useless-parent-delegation] + super(UselessSuper, self).equivalent_params_4(first) + + def equivalent_params_5(self, first, *args): # [useless-parent-delegation] + super(UselessSuper, self).equivalent_params_5(first, *args) + + def equivalent_params_6(self, first, *args, **kwargs): # [useless-parent-delegation] + return super(UselessSuper, self).equivalent_params_6(first, *args, **kwargs) + + def with_default_argument(self, first, default_arg="default"): # [useless-parent-delegation] + # useless because the default value here is the same as in the base class + return super(UselessSuper, self).with_default_argument(first, default_arg) + + def without_default_argument(self, first, second): # [useless-parent-delegation] + return super(UselessSuper, self).without_default_argument(first, second) + + def with_default_argument_none(self, first, default_arg=None): # [useless-parent-delegation] + # useless because the default value here is the same as in the base class + super(UselessSuper, self).with_default_argument_none(first, default_arg) + + def with_default_argument_int(self, first, default_arg=42): # [useless-parent-delegation] + super(UselessSuper, self).with_default_argument_int(first, default_arg) + + def with_default_argument_tuple(self, first, default_arg=()): # [useless-parent-delegation] + super(UselessSuper, self).with_default_argument_tuple(first, default_arg) + + def with_default_argument_dict(self, first, default_arg={}): # [useless-parent-delegation] + super(UselessSuper, self).with_default_argument_dict(first, default_arg) + + def with_default_argument_var(self, first, default_arg=default_var): # [useless-parent-delegation] + super(UselessSuper, self).with_default_argument_var(first, default_arg) + + def __init__(self): # [useless-parent-delegation] + super(UselessSuper, self).__init__() + + def with_default_arg(self, first, default_arg="only_in_super_base"): # [useless-parent-delegation] + super(UselessSuper, self).with_default_arg(first, default_arg) + + def with_default_arg_bis(self, first, default_arg="only_in_super_base"): # [useless-parent-delegation] + super(UselessSuper, self).with_default_arg_bis(first, default_arg) + + def with_default_arg_ter(self, first, default_arg="has_been_changed"): # [useless-parent-delegation] + super(UselessSuper, self).with_default_arg_ter(first, default_arg) + + def with_default_arg_quad(self, first, default_arg="has_been_changed"): # [useless-parent-delegation] + super(UselessSuper, self).with_default_arg_quad(first, default_arg) + + +def trigger_something(value_to_trigger): + pass + + +class NotUselessSuperDecorators(Base): + @trigger_something("value1") + def method_decorated(self): + super(NotUselessSuperDecorators, self).method_decorated() + + +class MyList(list): + def __eq__(self, other): + return len(self) == len(other) + + def __hash__(self): + return hash(len(self)) + + +class ExtendedList(MyList): + def __eq__(self, other): + return super().__eq__(other) and len(self) > 0 + + def __hash__(self): + return super().__hash__() + + +class DecoratedList(MyList): + def __str__(self): + return f"List -> {super().__str__()}" + + def __hash__(self): # [useless-parent-delegation] + return super().__hash__() + + +# Reported in https://github.com/PyCQA/pylint/issues/2270 +class Super: + def __init__(self, *args): + self.args = args + + +class Sub(Super): + def __init__(self, a, b): + super().__init__(a, b) + + +class SubTwo(Super): + def __init__(self, a, *args): + super().__init__(a, *args) + + +class SuperTwo: + def __init__(self, a, *args): + self.args = args + + +class SubTwoOne(SuperTwo): + def __init__(self, a, *args): # [useless-parent-delegation] + super().__init__(a, *args) + + +class SubTwoTwo(SuperTwo): + def __init__(self, a, b, *args): + super().__init__(a, b, *args) + + +class NotUselessSuperPy3: + def not_passing_keyword_only(self, first, *, second): + return super().not_passing_keyword_only(first) + + def passing_keyword_only_with_modifications(self, first, *, second): + return super().passing_keyword_only_with_modifications(first, second + 1) + + +class AlsoNotUselessSuperPy3(NotUselessSuperPy3): + def not_passing_keyword_only(self, first, *, second="second"): + return super().not_passing_keyword_only(first, second=second) + + +class UselessSuperPy3: + def useless(self, *, first): # [useless-parent-delegation] + super().useless(first=first) + + +class Egg(): + def __init__(self, thing: object) -> None: + pass + + +class Spam(Egg): + def __init__(self, thing: int) -> None: + super().__init__(thing) + + +class Ham(Egg): + def __init__(self, thing: object) -> None: # [useless-parent-delegation] + super().__init__(thing) + + +class Test: + def __init__(self, _arg: List[int]) -> None: + super().__init__() + + +class ReturnTypeAny: + choices = ["a", 1, (2, 3)] + + def draw(self) -> Any: + return random.choice(self.choices) + + +class ReturnTypeNarrowed(ReturnTypeAny): + choices = [1, 2, 3] + + def draw(self) -> int: + return super().draw() + + +class NoReturnType: + choices = ["a", 1, (2, 3)] + + def draw(self): + return random.choice(self.choices) + + +class ReturnTypeSpecified(NoReturnType): + choices = ["a", "b"] + + def draw(self) -> str: # [useless-parent-delegation] + return super().draw() + + +class ReturnTypeSame(ReturnTypeAny): + choices = ["a", "b"] + + def draw(self) -> Any: # [useless-parent-delegation] + return super().draw() + + +# Any number of positional arguments followed by one keyword argument with a default value +class Fruit: + def __init__(*, tastes_bitter=None): + ... + + +class Lemon(Fruit): + def __init__(*, tastes_bitter=True): + super().__init__(tastes_bitter=tastes_bitter) + + +class CustomError(Exception): + def __init__(self, message="default"): + super().__init__(message) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_parent_delegation.txt b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_parent_delegation.txt new file mode 100644 index 0000000000000000000000000000000000000000..0917021739e4705165045ce2e8480984dd204324 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_parent_delegation.txt @@ -0,0 +1,25 @@ +useless-parent-delegation:221:4:221:25:UselessSuper.equivalent_params:Useless parent or super() delegation in method 'equivalent_params':INFERENCE +useless-parent-delegation:224:4:224:27:UselessSuper.equivalent_params_1:Useless parent or super() delegation in method 'equivalent_params_1':INFERENCE +useless-parent-delegation:227:4:227:27:UselessSuper.equivalent_params_2:Useless parent or super() delegation in method 'equivalent_params_2':INFERENCE +useless-parent-delegation:230:4:230:27:UselessSuper.equivalent_params_3:Useless parent or super() delegation in method 'equivalent_params_3':INFERENCE +useless-parent-delegation:233:4:233:27:UselessSuper.equivalent_params_4:Useless parent or super() delegation in method 'equivalent_params_4':INFERENCE +useless-parent-delegation:236:4:236:27:UselessSuper.equivalent_params_5:Useless parent or super() delegation in method 'equivalent_params_5':INFERENCE +useless-parent-delegation:239:4:239:27:UselessSuper.equivalent_params_6:Useless parent or super() delegation in method 'equivalent_params_6':INFERENCE +useless-parent-delegation:242:4:242:29:UselessSuper.with_default_argument:Useless parent or super() delegation in method 'with_default_argument':INFERENCE +useless-parent-delegation:246:4:246:32:UselessSuper.without_default_argument:Useless parent or super() delegation in method 'without_default_argument':INFERENCE +useless-parent-delegation:249:4:249:34:UselessSuper.with_default_argument_none:Useless parent or super() delegation in method 'with_default_argument_none':INFERENCE +useless-parent-delegation:253:4:253:33:UselessSuper.with_default_argument_int:Useless parent or super() delegation in method 'with_default_argument_int':INFERENCE +useless-parent-delegation:256:4:256:35:UselessSuper.with_default_argument_tuple:Useless parent or super() delegation in method 'with_default_argument_tuple':INFERENCE +useless-parent-delegation:259:4:259:34:UselessSuper.with_default_argument_dict:Useless parent or super() delegation in method 'with_default_argument_dict':INFERENCE +useless-parent-delegation:262:4:262:33:UselessSuper.with_default_argument_var:Useless parent or super() delegation in method 'with_default_argument_var':INFERENCE +useless-parent-delegation:265:4:265:16:UselessSuper.__init__:Useless parent or super() delegation in method '__init__':INFERENCE +useless-parent-delegation:268:4:268:24:UselessSuper.with_default_arg:Useless parent or super() delegation in method 'with_default_arg':INFERENCE +useless-parent-delegation:271:4:271:28:UselessSuper.with_default_arg_bis:Useless parent or super() delegation in method 'with_default_arg_bis':INFERENCE +useless-parent-delegation:274:4:274:28:UselessSuper.with_default_arg_ter:Useless parent or super() delegation in method 'with_default_arg_ter':INFERENCE +useless-parent-delegation:277:4:277:29:UselessSuper.with_default_arg_quad:Useless parent or super() delegation in method 'with_default_arg_quad':INFERENCE +useless-parent-delegation:311:4:311:16:DecoratedList.__hash__:Useless parent or super() delegation in method '__hash__':INFERENCE +useless-parent-delegation:337:4:337:16:SubTwoOne.__init__:Useless parent or super() delegation in method '__init__':INFERENCE +useless-parent-delegation:360:4:360:15:UselessSuperPy3.useless:Useless parent or super() delegation in method 'useless':INFERENCE +useless-parent-delegation:375:4:375:16:Ham.__init__:Useless parent or super() delegation in method '__init__':INFERENCE +useless-parent-delegation:408:4:408:12:ReturnTypeSpecified.draw:Useless parent or super() delegation in method 'draw':INFERENCE +useless-parent-delegation:415:4:415:12:ReturnTypeSame.draw:Useless parent or super() delegation in method 'draw':INFERENCE diff --git a/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_parent_delegation_py38.py b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_parent_delegation_py38.py new file mode 100644 index 0000000000000000000000000000000000000000..dded3b2cb83f948e7094bbd5c2677161d8ae7049 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_parent_delegation_py38.py @@ -0,0 +1,17 @@ +# pylint: disable=missing-docstring,too-few-public-methods +from typing import Any + + +class Egg: + def __init__(self, first: Any, /, second: Any) -> None: + pass + + +class Spam(Egg): + def __init__(self, first: float, /, second: float) -> None: + super().__init__(first, second) + + +class Ham(Egg): + def __init__(self, first: Any, /, second: Any) -> None: # [useless-parent-delegation] + super().__init__(first, second) diff --git a/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_parent_delegation_py38.rc b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_parent_delegation_py38.rc new file mode 100644 index 0000000000000000000000000000000000000000..85fc502b372ea64005d4e09627da9827c325d447 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_parent_delegation_py38.rc @@ -0,0 +1,2 @@ +[testoptions] +min_pyver=3.8 diff --git a/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_parent_delegation_py38.txt b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_parent_delegation_py38.txt new file mode 100644 index 0000000000000000000000000000000000000000..a42a822149959351d5e87b3927ceff198896b152 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_parent_delegation_py38.txt @@ -0,0 +1 @@ +useless-parent-delegation:16:4:16:16:Ham.__init__:Useless parent or super() delegation in method '__init__':INFERENCE diff --git a/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_return.py b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_return.py new file mode 100644 index 0000000000000000000000000000000000000000..e7537353ef524846219f843097aee546a643f8b3 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_return.py @@ -0,0 +1,15 @@ +# pylint: disable=missing-docstring,too-few-public-methods,bad-option-value + + +def myfunc(): # [useless-return] + print('---- testing ---') + return + +class SomeClass: + def mymethod(self): # [useless-return] + print('---- testing ---') + return None + + # These are not emitted + def item_at(self): + return None diff --git a/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_return.txt b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_return.txt new file mode 100644 index 0000000000000000000000000000000000000000..035e951ab26e8533d6672071b6edb493f3cd7421 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_return.txt @@ -0,0 +1,2 @@ +useless-return:4:0:4:10:myfunc:Useless return at end of function or method:UNDEFINED +useless-return:9:4:9:16:SomeClass.mymethod:Useless return at end of function or method:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_suppression.py b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_suppression.py new file mode 100644 index 0000000000000000000000000000000000000000..b5c681eefe113000d288ab0d1af78fdb5e3db658 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_suppression.py @@ -0,0 +1,16 @@ +"""Tests for useless suppressions""" +# pylint: enable=useless-suppression, line-too-long +# pylint: disable=unused-import, wrong-import-order, wrong-import-position + +# False positive for wrong-import-order +# Reported in https://github.com/PyCQA/pylint/issues/2366 +from pylint import run_pylint +import astroid + +# False-positive for 'line-too-long' +# Reported in https://github.com/PyCQA/pylint/issues/4212 +VAR = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" # pylint: disable=line-too-long + +# False-positive for 'wrong-import-order' +# Reported in https://github.com/PyCQA/pylint/issues/5219 +import os diff --git a/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_suppression.rc b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_suppression.rc new file mode 100644 index 0000000000000000000000000000000000000000..10388685f17a12ca151ef56d4459425d6587de48 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_suppression.rc @@ -0,0 +1,2 @@ +[testoptions] +exclude_from_minimal_messages_config=true diff --git a/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_with_lock.py b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_with_lock.py new file mode 100644 index 0000000000000000000000000000000000000000..19d664084da98acac395a746ede453be4a73b26f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_with_lock.py @@ -0,0 +1,58 @@ +"""Tests for the useless-with-lock message""" +# pylint: disable=missing-docstring +import threading +from threading import Lock, RLock, Condition, Semaphore, BoundedSemaphore + + +with threading.Lock(): # [useless-with-lock] + ... + +with Lock(): # [useless-with-lock] + ... + +with threading.Lock() as this_shouldnt_matter: # [useless-with-lock] + ... + +with threading.RLock(): # [useless-with-lock] + ... + +with RLock(): # [useless-with-lock] + ... + +with threading.Condition(): # [useless-with-lock] + ... + +with Condition(): # [useless-with-lock] + ... + +with threading.Semaphore(): # [useless-with-lock] + ... + +with Semaphore(): # [useless-with-lock] + ... + +with threading.BoundedSemaphore(): # [useless-with-lock] + ... + +with BoundedSemaphore(): # [useless-with-lock] + ... + +lock = threading.Lock() +with lock: # this is ok + ... + +rlock = threading.RLock() +with rlock: # this is ok + ... + +cond = threading.Condition() +with cond: # this is ok + ... + +sem = threading.Semaphore() +with sem: # this is ok + ... + +b_sem = threading.BoundedSemaphore() +with b_sem: # this is ok + ... diff --git a/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_with_lock.txt b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_with_lock.txt new file mode 100644 index 0000000000000000000000000000000000000000..94a6cf1ece0ed6078f47dded3eccd35564198709 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/useless/useless_with_lock.txt @@ -0,0 +1,11 @@ +useless-with-lock:7:0:8:7::'threading.Lock()' directly created in 'with' has no effect:UNDEFINED +useless-with-lock:10:0:11:7::'threading.Lock()' directly created in 'with' has no effect:UNDEFINED +useless-with-lock:13:0:14:7::'threading.Lock()' directly created in 'with' has no effect:UNDEFINED +useless-with-lock:16:0:17:7::'threading.RLock()' directly created in 'with' has no effect:UNDEFINED +useless-with-lock:19:0:20:7::'threading.RLock()' directly created in 'with' has no effect:UNDEFINED +useless-with-lock:22:0:23:7::'threading.Condition()' directly created in 'with' has no effect:UNDEFINED +useless-with-lock:25:0:26:7::'threading.Condition()' directly created in 'with' has no effect:UNDEFINED +useless-with-lock:28:0:29:7::'threading.Semaphore()' directly created in 'with' has no effect:UNDEFINED +useless-with-lock:31:0:32:7::'threading.Semaphore()' directly created in 'with' has no effect:UNDEFINED +useless-with-lock:34:0:35:7::'threading.BoundedSemaphore()' directly created in 'with' has no effect:UNDEFINED +useless-with-lock:37:0:38:7::'threading.BoundedSemaphore()' directly created in 'with' has no effect:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/u/using_constant_test.py b/testbed/pylint-dev__pylint/tests/functional/u/using_constant_test.py new file mode 100644 index 0000000000000000000000000000000000000000..4586150b17c5fa618ec5a6bc0004a66cf3678099 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/using_constant_test.py @@ -0,0 +1,178 @@ +"""Verify if constant tests are used inside if statements.""" +# pylint: disable=invalid-name, missing-docstring,too-few-public-methods +# pylint: disable=expression-not-assigned +# pylint: disable=missing-parentheses-for-call-in-test, unnecessary-comprehension, condition-evals-to-constant +# pylint: disable=use-list-literal, use-dict-literal + +import collections + + +def function(): + yield + + +class Class: + + def method(self): + pass + + +instance = Class() + +if collections: # [using-constant-test] + pass + +# GenExpr +if (node for node in range(10)): # [using-constant-test] + pass + +if lambda: None: # [using-constant-test] + pass + +if function: # [using-constant-test] + pass + +if Class: # [using-constant-test] + pass + +if 2: # [using-constant-test] + pass + +if True: # [using-constant-test] + pass + +if '': # [using-constant-test] + pass + +if b'': # [using-constant-test] + pass + +if 2.0: # [using-constant-test] + pass + +if {}: # [using-constant-test] + pass + +if {1, 2, 3}: # [using-constant-test] + pass + +if (1, 2, 3): # [using-constant-test] + pass + +if (): # [using-constant-test] + pass + +if [1, 2, 3]: # [using-constant-test] + pass + +if []: # [using-constant-test] + pass + +# Generator +generator = function() +if generator: # [using-constant-test] + pass + +if 1 if 2 else 3: # [using-constant-test] + pass + +def test_comprehensions(): + [data for data in range(100) if abs] # [using-constant-test] + [data for data in range(100) if 1] # [using-constant-test] + (data for data in range(100) if abs) # [using-constant-test] + (data for data in range(100) if 1) # [using-constant-test] + {data for data in range(100) if abs} # [using-constant-test] + {data: 1 for data in range(100) if abs} # [using-constant-test] + + +# UnboundMethod / Function +if Class.method: # [using-constant-test] + pass + +# BoundMethod +if instance.method: # [using-constant-test] + pass + +# For these, we require to do inference, even though the result can be a +# constant value. For some of them, we could determine that the test +# is constant, such as 2 + 3, but the components of the BinOp +# can be anything else (2 + somefunccall). + +name = 42 +if name: + pass + +if 3 + 4: + pass + +if 3 and 4: + pass + +if not 3: + pass + +if instance.method(): + pass + +if 2 < 3: # [comparison-of-constants] + pass + +if tuple((1, 2, 3)): + pass + +if dict(): + pass + +if tuple(): + pass + +if list(): + pass + +if [1, 2, 3][:1]: + pass + +def test(*args): + if args: + return 42 + return None + +def test_good_comprehension_checks(): + [data for data in range(100)] + [data for data in range(100) if data] + [data for data in range(100) if abs(data)] + (data for data in range(100) if data) + (data for data in range(100) if abs(data)) + {data for data in range(100) if data} + {data for data in range(100) if abs(data)} + {data: 1 for data in range(100) if data} + {data: 1 for data in range(100)} + + +# Calls to functions returning generator expressions are always truthy +def get_generator(): + return (x for x in range(0)) + +if get_generator(): # [using-constant-test] + pass + +def maybe_get_generator(arg): + if arg: + return (x for x in range(0)) + return None + +if maybe_get_generator(None): + pass + +y = (a for a in range(10)) +if y: # [using-constant-test] + pass + +z = (a for a in range(10)) +z = "red herring" +if z: + pass + +gen = get_generator() +if gen: # [using-constant-test] + pass diff --git a/testbed/pylint-dev__pylint/tests/functional/u/using_constant_test.txt b/testbed/pylint-dev__pylint/tests/functional/u/using_constant_test.txt new file mode 100644 index 0000000000000000000000000000000000000000..033bad0b0ffea087fee8d601ffbdcc56bef20e31 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/u/using_constant_test.txt @@ -0,0 +1,30 @@ +using-constant-test:22:3:22:14::Using a conditional statement with a constant value:INFERENCE +using-constant-test:26:3:26:31::Using a conditional statement with a constant value:INFERENCE +using-constant-test:29:3:29:15::Using a conditional statement with a constant value:INFERENCE +using-constant-test:32:3:32:11::Using a conditional statement with a constant value:INFERENCE +using-constant-test:35:3:35:8::Using a conditional statement with a constant value:INFERENCE +using-constant-test:38:3:38:4::Using a conditional statement with a constant value:INFERENCE +using-constant-test:41:3:41:7::Using a conditional statement with a constant value:INFERENCE +using-constant-test:44:3:44:5::Using a conditional statement with a constant value:INFERENCE +using-constant-test:47:3:47:6::Using a conditional statement with a constant value:INFERENCE +using-constant-test:50:3:50:6::Using a conditional statement with a constant value:INFERENCE +using-constant-test:53:3:53:5::Using a conditional statement with a constant value:INFERENCE +using-constant-test:56:3:56:12::Using a conditional statement with a constant value:INFERENCE +using-constant-test:59:3:59:12::Using a conditional statement with a constant value:INFERENCE +using-constant-test:62:3:62:5::Using a conditional statement with a constant value:INFERENCE +using-constant-test:65:3:65:12::Using a conditional statement with a constant value:INFERENCE +using-constant-test:68:3:68:5::Using a conditional statement with a constant value:INFERENCE +using-constant-test:73:3:73:12::Using a conditional statement with a constant value:INFERENCE +using-constant-test:76:8:76:9::Using a conditional statement with a constant value:INFERENCE +using-constant-test:80:36:80:39:test_comprehensions:Using a conditional statement with a constant value:INFERENCE +using-constant-test:81:36:81:37:test_comprehensions:Using a conditional statement with a constant value:INFERENCE +using-constant-test:82:36:82:39:test_comprehensions:Using a conditional statement with a constant value:INFERENCE +using-constant-test:83:36:83:37:test_comprehensions:Using a conditional statement with a constant value:INFERENCE +using-constant-test:84:36:84:39:test_comprehensions:Using a conditional statement with a constant value:INFERENCE +using-constant-test:85:39:85:42:test_comprehensions:Using a conditional statement with a constant value:INFERENCE +using-constant-test:89:3:89:15::Using a conditional statement with a constant value:INFERENCE +using-constant-test:93:3:93:18::Using a conditional statement with a constant value:INFERENCE +comparison-of-constants:117:3:117:8::"Comparison between constants: '2 < 3' has a constant value":HIGH +using-constant-test:156:0:157:8::Using a conditional statement with a constant value:INFERENCE +using-constant-test:168:3:168:4::Using a conditional statement with a constant value:INFERENCE +using-constant-test:177:0:178:8::Using a conditional statement with a constant value:INFERENCE diff --git a/testbed/pylint-dev__pylint/tests/functional/w/__init__.py b/testbed/pylint-dev__pylint/tests/functional/w/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wildcard_import.py b/testbed/pylint-dev__pylint/tests/functional/w/wildcard_import.py new file mode 100644 index 0000000000000000000000000000000000000000..4034162e0f3215865f731a4c58fa36d3ce86417b --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wildcard_import.py @@ -0,0 +1,5 @@ +# pylint: disable=missing-docstring,import-error,unused-wildcard-import +from indirect1 import * # [wildcard-import] +# This is an unresolved import which still generates the wildcard-import +# warning. +from unknown.package import * # [wildcard-import] diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wildcard_import.txt b/testbed/pylint-dev__pylint/tests/functional/w/wildcard_import.txt new file mode 100644 index 0000000000000000000000000000000000000000..4e404d4ec05bcaa3af37754c421871f4acd2cea1 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wildcard_import.txt @@ -0,0 +1,2 @@ +wildcard-import:2:0:2:23::Wildcard import indirect1:UNDEFINED +wildcard-import:5:0:5:29::Wildcard import unknown.package:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wildcard_import_allowed.py b/testbed/pylint-dev__pylint/tests/functional/w/wildcard_import_allowed.py new file mode 100644 index 0000000000000000000000000000000000000000..21fea473816bc58a0d643b0dae544e77aaca7a67 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wildcard_import_allowed.py @@ -0,0 +1,4 @@ +# pylint: disable=missing-docstring,unused-wildcard-import,redefined-builtin,import-error +from csv import * +from abc import * # [wildcard-import] +from UNINFERABLE import * # [wildcard-import] diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wildcard_import_allowed.rc b/testbed/pylint-dev__pylint/tests/functional/w/wildcard_import_allowed.rc new file mode 100644 index 0000000000000000000000000000000000000000..c46d828f6da45068b9c63d31dfdee30684acd722 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wildcard_import_allowed.rc @@ -0,0 +1,2 @@ +[IMPORTS] +allow-wildcard-with-all=yes diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wildcard_import_allowed.txt b/testbed/pylint-dev__pylint/tests/functional/w/wildcard_import_allowed.txt new file mode 100644 index 0000000000000000000000000000000000000000..8f24a21a171b4865df05a9db0c8b2aec8e2893fc --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wildcard_import_allowed.txt @@ -0,0 +1,2 @@ +wildcard-import:3:0:3:17::Wildcard import abc:UNDEFINED +wildcard-import:4:0:4:25::Wildcard import UNINFERABLE:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/w/with_used_before_assign.py b/testbed/pylint-dev__pylint/tests/functional/w/with_used_before_assign.py new file mode 100644 index 0000000000000000000000000000000000000000..ebe7d3093c6e87e02007ea87e6cd57311ce7055e --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/with_used_before_assign.py @@ -0,0 +1,12 @@ +""" +Regression test for +https://bitbucket.org/logilab/pylint/issue/128/attributeerror-when-parsing +""" +from __future__ import with_statement + + +def do_nothing(): + """ empty """ + with open("", encoding="utf-8") as ctx.obj: # [undefined-variable] + context.do() # [used-before-assignment] + context = None diff --git a/testbed/pylint-dev__pylint/tests/functional/w/with_used_before_assign.txt b/testbed/pylint-dev__pylint/tests/functional/w/with_used_before_assign.txt new file mode 100644 index 0000000000000000000000000000000000000000..04620998867f0ff6f5870f547b818ffe91f42657 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/with_used_before_assign.txt @@ -0,0 +1,2 @@ +undefined-variable:10:39:10:42:do_nothing:Undefined variable 'ctx':UNDEFINED +used-before-assignment:11:8:11:15:do_nothing:Using variable 'context' before assignment:HIGH diff --git a/testbed/pylint-dev__pylint/tests/functional/w/with_using_generator.py b/testbed/pylint-dev__pylint/tests/functional/w/with_using_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..9f557363fe3949ba3e4abf6b0f5a59543d1170a6 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/with_using_generator.py @@ -0,0 +1,14 @@ +""" Testing with statements that use generators. This should not crash. """ + +class Base: + """ Base class. """ + val = 0 + + def gen(self): + """ A generator. """ + yield self.val + + def fun(self): + """ With statement using a generator. """ + with self.gen(): # [not-context-manager] + pass diff --git a/testbed/pylint-dev__pylint/tests/functional/w/with_using_generator.txt b/testbed/pylint-dev__pylint/tests/functional/w/with_using_generator.txt new file mode 100644 index 0000000000000000000000000000000000000000..12e3ad06afbd9b75265497652bf2c0e5947a97f3 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/with_using_generator.txt @@ -0,0 +1 @@ +not-context-manager:13:8:14:16:Base.fun:Context manager 'generator' doesn't implement __enter__ and __exit__.:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_exception_operation.py b/testbed/pylint-dev__pylint/tests/functional/w/wrong_exception_operation.py new file mode 100644 index 0000000000000000000000000000000000000000..8078573c4163796f7f5dd194f06274e1d632b894 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_exception_operation.py @@ -0,0 +1,18 @@ +# pylint: disable=missing-docstring, superfluous-parens + + +try: + 1/0 +except (ValueError | TypeError): # [catching-non-exception,wrong-exception-operation] + pass + +try: + 1/0 +except (ValueError + TypeError): # [wrong-exception-operation] + pass + + +try: + 1/0 +except (ValueError < TypeError): # [wrong-exception-operation] + pass diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_exception_operation.rc b/testbed/pylint-dev__pylint/tests/functional/w/wrong_exception_operation.rc new file mode 100644 index 0000000000000000000000000000000000000000..68a8c8ef157980e74dc55bae272edcd141052de0 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_exception_operation.rc @@ -0,0 +1,2 @@ +[testoptions] +min_pyver=3.10 diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_exception_operation.txt b/testbed/pylint-dev__pylint/tests/functional/w/wrong_exception_operation.txt new file mode 100644 index 0000000000000000000000000000000000000000..dc3c213462fa2216620533b232e1fa09bdc06eef --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_exception_operation.txt @@ -0,0 +1,4 @@ +catching-non-exception:6:8:6:30::"Catching an exception which doesn't inherit from Exception: ValueError | TypeError":UNDEFINED +wrong-exception-operation:6:8:6:30::Invalid exception operation. Did you mean '(ValueError, TypeError)' instead?:UNDEFINED +wrong-exception-operation:11:8:11:30::Invalid exception operation. Did you mean '(ValueError, TypeError)' instead?:UNDEFINED +wrong-exception-operation:17:8:17:30::Invalid exception operation. Did you mean '(ValueError, TypeError)' instead?:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_exception_operation_py37.py b/testbed/pylint-dev__pylint/tests/functional/w/wrong_exception_operation_py37.py new file mode 100644 index 0000000000000000000000000000000000000000..1c3c4e3803b9202adb0b6574ba964cbaae36a77b --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_exception_operation_py37.py @@ -0,0 +1,18 @@ +# pylint: disable=missing-docstring, superfluous-parens + + +try: + 1/0 +except (ValueError | TypeError): # [wrong-exception-operation] + pass + +try: + 1/0 +except (ValueError + TypeError): # [wrong-exception-operation] + pass + + +try: + 1/0 +except (ValueError < TypeError): # [wrong-exception-operation] + pass diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_exception_operation_py37.rc b/testbed/pylint-dev__pylint/tests/functional/w/wrong_exception_operation_py37.rc new file mode 100644 index 0000000000000000000000000000000000000000..dd83cc9536f4f4725cb3479162b69219b5256772 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_exception_operation_py37.rc @@ -0,0 +1,3 @@ +[testoptions] +min_pyver=3.7 +max_pyver=3.10 diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_exception_operation_py37.txt b/testbed/pylint-dev__pylint/tests/functional/w/wrong_exception_operation_py37.txt new file mode 100644 index 0000000000000000000000000000000000000000..c92fcc2a2b5973a5e6d7d6d8586238b716ca1f3e --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_exception_operation_py37.txt @@ -0,0 +1,3 @@ +wrong-exception-operation:6:8:6:30::Invalid exception operation. Did you mean '(ValueError, TypeError)' instead?:UNDEFINED +wrong-exception-operation:11:8:11:30::Invalid exception operation. Did you mean '(ValueError, TypeError)' instead?:UNDEFINED +wrong-exception-operation:17:8:17:30::Invalid exception operation. Did you mean '(ValueError, TypeError)' instead?:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_order.py b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_order.py new file mode 100644 index 0000000000000000000000000000000000000000..ed0615b0c09c294854c8638c20f1f82f91f73057 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_order.py @@ -0,0 +1,43 @@ +"""Checks import order rule""" +# pylint: disable=unused-import,ungrouped-imports,import-error,no-name-in-module,relative-beyond-top-level +from __future__ import absolute_import +try: + from six.moves import configparser +except ImportError: + import configparser + +import logging + +import six +import os.path # [wrong-import-order] +from astroid import are_exclusive +import sys # [wrong-import-order] +import datetime # [wrong-import-order] +import unused_import +from .package import Class +import totally_missing # [wrong-import-order] +from . import package +import astroid # [wrong-import-order] +from . import package2 +from .package2 import Class2 +from ..package3 import Class3 +from six.moves.urllib.parse import quote # [wrong-import-order] + + +LOGGER = logging.getLogger(__name__) + + +if LOGGER: + # imports nested skipped + from . import package4 + import pprint + from pprint import PrettyPrinter + + +try: + # imports nested skipped + from . import package4 + import random + from random import division +except ImportError: + LOGGER.info('A useful message here') diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_order.txt b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_order.txt new file mode 100644 index 0000000000000000000000000000000000000000..c0706a9d276f767bb15e77b4440b20344d5b5b2a --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_order.txt @@ -0,0 +1,6 @@ +wrong-import-order:12:0:12:14::"standard import ""import os.path"" should be placed before ""import six""":UNDEFINED +wrong-import-order:14:0:14:10::"standard import ""import sys"" should be placed before ""import six""":UNDEFINED +wrong-import-order:15:0:15:15::"standard import ""import datetime"" should be placed before ""import six""":UNDEFINED +wrong-import-order:18:0:18:22::"third party import ""import totally_missing"" should be placed before ""from .package import Class""":UNDEFINED +wrong-import-order:20:0:20:14::"third party import ""import astroid"" should be placed before ""from .package import Class""":UNDEFINED +wrong-import-order:24:0:24:40::"third party import ""from six.moves.urllib.parse import quote"" should be placed before ""from .package import Class""":UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_order2.py b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_order2.py new file mode 100644 index 0000000000000000000000000000000000000000..7157512ddcecd029591e6379ecf30fb59676db90 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_order2.py @@ -0,0 +1,16 @@ +"""Checks import order rule in a right case""" +# pylint: disable=unused-import,ungrouped-imports,import-error,no-name-in-module + + +# Standard imports +import os +from sys import argv + +# external imports +import isort + +from six import moves + +# local_imports +from . import my_package +from .my_package import myClass diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position.py b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position.py new file mode 100644 index 0000000000000000000000000000000000000000..7d1fddfa3bf520f4acf39233730a9e49106cadc7 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position.py @@ -0,0 +1,33 @@ +"""Checks import order rule""" +# pylint: disable=unused-import,ungrouped-imports,wrong-import-order +# pylint: disable=import-error, too-few-public-methods, missing-docstring,using-constant-test +import os.path + +if True: + from astroid import are_exclusive +try: + import sys +except ImportError: + class Myclass: + """docstring""" + +if sys.version_info[0] >= 3: + from collections import OrderedDict +else: + class OrderedDict: + """Nothing to see here.""" + def some_func(self): + pass + +import six # [wrong-import-position] + +CONSTANT = True + +import datetime # [wrong-import-position] + +VAR = 0 +for i in range(10): + VAR += i + +import scipy # [wrong-import-position] +import astroid # [wrong-import-position] diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position.txt b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position.txt new file mode 100644 index 0000000000000000000000000000000000000000..3de4d7c17fc10c47818790a6d06655ef1edc8512 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position.txt @@ -0,0 +1,4 @@ +wrong-import-position:22:0:22:10::"Import ""import six"" should be placed at the top of the module":UNDEFINED +wrong-import-position:26:0:26:15::"Import ""import datetime"" should be placed at the top of the module":UNDEFINED +wrong-import-position:32:0:32:12::"Import ""import scipy"" should be placed at the top of the module":UNDEFINED +wrong-import-position:33:0:33:14::"Import ""import astroid"" should be placed at the top of the module":UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position10.py b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position10.py new file mode 100644 index 0000000000000000000000000000000000000000..f4a8680390acab01535ccc67faf2a4b0faf66248 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position10.py @@ -0,0 +1,15 @@ +"""Checks import position rule""" +# pylint: disable=unused-import +import os + +try: + import ast +except ImportError: + def method(items): + """docstring""" + value = 0 + for item in items: + value += item + return value + +import sys diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position11.py b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position11.py new file mode 100644 index 0000000000000000000000000000000000000000..9af72c0e57a55b3af5a0550181ee298fa1717946 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position11.py @@ -0,0 +1,4 @@ +"""Checks import position rule""" +# pylint: disable=unused-import,pointless-string-statement +A = 1 +import os # [wrong-import-position] diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position11.txt b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position11.txt new file mode 100644 index 0000000000000000000000000000000000000000..2e7cae207426b6aeb79b709c1f9314c927a99e98 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position11.txt @@ -0,0 +1 @@ +wrong-import-position:4:0:4:9::"Import ""import os"" should be placed at the top of the module":UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position12.py b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position12.py new file mode 100644 index 0000000000000000000000000000000000000000..300968c401bf90812884651696a40739e2bf75b5 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position12.py @@ -0,0 +1,5 @@ +"""Checks import position rule""" +# pylint: disable=unused-import,pointless-string-statement +"Two string" + +import os # [wrong-import-position] diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position12.txt b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position12.txt new file mode 100644 index 0000000000000000000000000000000000000000..7ea2c2a3bff147daca8c8fd39c16173ab2cb8341 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position12.txt @@ -0,0 +1 @@ +wrong-import-position:5:0:5:9::"Import ""import os"" should be placed at the top of the module":UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position13.py b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position13.py new file mode 100644 index 0000000000000000000000000000000000000000..6b3d03463bfe56aa0cf2c6e7b8c9598d4086ae37 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position13.py @@ -0,0 +1,4 @@ +"""Checks import position rule""" +# pylint: disable=unused-import,no-name-in-module +A = 1 +from sys import x # [wrong-import-position] diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position13.txt b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position13.txt new file mode 100644 index 0000000000000000000000000000000000000000..b4c7b4a3d556f85aa7c4aafadf1760c034252a3d --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position13.txt @@ -0,0 +1 @@ +wrong-import-position:4:0:4:17::"Import ""from sys import x"" should be placed at the top of the module":UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position14.py b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position14.py new file mode 100644 index 0000000000000000000000000000000000000000..f5c9a03e58e842fddb836b5b80a9506694b004c7 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position14.py @@ -0,0 +1,5 @@ +"""Checks import position rule""" +# pylint: disable=unused-import,undefined-variable,import-error +if x: + import os +import y # [wrong-import-position] diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position14.txt b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position14.txt new file mode 100644 index 0000000000000000000000000000000000000000..a91a24fbcc9540e33bc41f12b58e60d0e31f434f --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position14.txt @@ -0,0 +1 @@ +wrong-import-position:5:0:5:8::"Import ""import y"" should be placed at the top of the module":UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position15.py b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position15.py new file mode 100644 index 0000000000000000000000000000000000000000..58a19b66c9fd91fb8c01375f2b0d546094be3685 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position15.py @@ -0,0 +1,9 @@ +"""Checks import position rule with pep-0008""" +# pylint: disable=unused-import + +__author__ = 'some author' +__email__ = 'some.author@some_email' +__copyright__ = 'Some copyright' + + +import sys diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position2.py b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position2.py new file mode 100644 index 0000000000000000000000000000000000000000..d7441b4658eacaaa2a697345d5ac3d166778bf51 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position2.py @@ -0,0 +1,10 @@ +"""Checks import order rule with nested non_import sentence""" +# pylint: disable=unused-import,ungrouped-imports,import-error,no-name-in-module,relative-beyond-top-level +try: + from sys import argv +except ImportError: + pass +else: + pass + +import os diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position3.py b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position3.py new file mode 100644 index 0000000000000000000000000000000000000000..a1808a8fd7554d4acb1b263825fa802723905f82 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position3.py @@ -0,0 +1,3 @@ +"""Checks import position rule""" +# pylint: disable=unused-import,ungrouped-imports,import-error,no-name-in-module,relative-beyond-top-level +import os diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position4.py b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position4.py new file mode 100644 index 0000000000000000000000000000000000000000..96f39ce8d1f5073599baf18a3f95b163fb99a736 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position4.py @@ -0,0 +1,5 @@ +"""Checks import position rule""" +# pylint: disable=unused-import,ungrouped-imports,import-error,no-name-in-module,relative-beyond-top-level,unused-variable,import-outside-toplevel +def method1(): + """Method 1""" + import x diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position5.py b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position5.py new file mode 100644 index 0000000000000000000000000000000000000000..ff9c28cd72a0100f75460a4f376fddabc62e2209 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position5.py @@ -0,0 +1,4 @@ +r"""Checks import position rule""" +# pylint: disable=unused-import,ungrouped-imports,import-error,no-name-in-module,relative-beyond-top-level + +import os diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position6.py b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position6.py new file mode 100644 index 0000000000000000000000000000000000000000..e719d2cb9ae05d74dfabe4610640667c7d612ac0 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position6.py @@ -0,0 +1,7 @@ +"""Checks import position rule""" +# pylint: disable=unused-import,ungrouped-imports,import-error,no-name-in-module,relative-beyond-top-level,undefined-variable + +import y + +if x: + import os diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position7.py b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position7.py new file mode 100644 index 0000000000000000000000000000000000000000..58a79b84bcbbfe1e489eb792b4fbd315394caddb --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position7.py @@ -0,0 +1,9 @@ +"""Checks import position rule""" +# pylint: disable=unused-import,ungrouped-imports,import-error,no-name-in-module,relative-beyond-top-level +try: + import x +except ImportError: + pass +finally: + pass +import y diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position8.py b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position8.py new file mode 100644 index 0000000000000000000000000000000000000000..531d9ca5f2df1565ec564fa7900e4be36d3b926c --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position8.py @@ -0,0 +1,4 @@ +"""Checks import position rule""" +# pylint: disable=unused-import,ungrouped-imports,import-error,no-name-in-module,relative-beyond-top-level,undefined-variable +if x: + import os diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position9.py b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position9.py new file mode 100644 index 0000000000000000000000000000000000000000..232c453ccb5d80d84902cee2d98de0ed75341beb --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position9.py @@ -0,0 +1,9 @@ +"""Checks import position rule""" +# pylint: disable=unused-import,ungrouped-imports,import-error,no-name-in-module,relative-beyond-top-level +import y +try: + import x +except ImportError: + pass +else: + pass diff --git a/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position_exclude_dunder_main.py b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position_exclude_dunder_main.py new file mode 100644 index 0000000000000000000000000000000000000000..05f680377a1219c102c459b640c2371055dd3821 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/w/wrong_import_position_exclude_dunder_main.py @@ -0,0 +1,12 @@ +# pylint: disable=import-error, unused-import, missing-docstring +CONS = 42 + +if __name__ == '__main__': + CONSTANT = True + VAR = 0 + for i in range(10): + VAR += i + + import six + import datetime + import astroid diff --git a/testbed/pylint-dev__pylint/tests/functional/y/__init__.py b/testbed/pylint-dev__pylint/tests/functional/y/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/pylint-dev__pylint/tests/functional/y/yield_assign.py b/testbed/pylint-dev__pylint/tests/functional/y/yield_assign.py new file mode 100644 index 0000000000000000000000000000000000000000..e7a938c6922ad3017f2fb82848d1a4037e023314 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/y/yield_assign.py @@ -0,0 +1,20 @@ +"""https://www.logilab.org/ticket/8771""" + + +def generator(): + """yield as assignment""" + yield 45 + xxxx = yield 123 + print(xxxx) + +def generator_fp1(seq): + """W0631 false positive""" + for val in seq: + pass + for val in seq: + yield val + +def generator_fp2(): + """E0601 false positive""" + xxxx = 12 + yield xxxx diff --git a/testbed/pylint-dev__pylint/tests/functional/y/yield_from_iterable.py b/testbed/pylint-dev__pylint/tests/functional/y/yield_from_iterable.py new file mode 100644 index 0000000000000000000000000000000000000000..7803936d5334854af0c64870adcd7f48c61b8602 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/y/yield_from_iterable.py @@ -0,0 +1,7 @@ +""" +Check that `yield from`-statement takes an iterable. +""" +# pylint: disable=missing-docstring + +def to_ten(): + yield from 10 # [not-an-iterable] diff --git a/testbed/pylint-dev__pylint/tests/functional/y/yield_from_iterable.txt b/testbed/pylint-dev__pylint/tests/functional/y/yield_from_iterable.txt new file mode 100644 index 0000000000000000000000000000000000000000..52b98e87ecf197f6389830b7867300e1ad476296 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/y/yield_from_iterable.txt @@ -0,0 +1 @@ +not-an-iterable:7:15:7:17:to_ten:Non-iterable value 10 is used in an iterating context:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/y/yield_from_outside_func.py b/testbed/pylint-dev__pylint/tests/functional/y/yield_from_outside_func.py new file mode 100644 index 0000000000000000000000000000000000000000..1c58af4295cbbfd9f89c64ba1f17e46973a2891c --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/y/yield_from_outside_func.py @@ -0,0 +1,6 @@ +"""This is grammatically correct, but it's still a SyntaxError""" +# pylint: disable=unnecessary-lambda-assignment + +yield from [1, 2] # [yield-outside-function] + +LAMBDA_WITH_YIELD = lambda: (yield from [1, 2]) diff --git a/testbed/pylint-dev__pylint/tests/functional/y/yield_from_outside_func.txt b/testbed/pylint-dev__pylint/tests/functional/y/yield_from_outside_func.txt new file mode 100644 index 0000000000000000000000000000000000000000..769cfc097b8b30acffe7c2b3b0d0fec2f4604740 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/y/yield_from_outside_func.txt @@ -0,0 +1 @@ +yield-outside-function:4:0:4:17::Yield outside function:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/y/yield_inside_async_function.py b/testbed/pylint-dev__pylint/tests/functional/y/yield_inside_async_function.py new file mode 100644 index 0000000000000000000000000000000000000000..9f293b47d323f037b04ac0e1001add83a2d54466 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/y/yield_inside_async_function.py @@ -0,0 +1,16 @@ +"""Test that `yield` or `yield from` can't be used inside an async function.""" +# pylint: disable=missing-docstring, unused-variable + +async def good(): + def _inner(): + yield 42 + yield from [1, 2, 3] + +async def good_two(): + # Starting from python 3.6 it's possible to yield inside async + # https://www.python.org/dev/peps/pep-0525/ + yield 42 + + +async def bad(): + yield from [1, 2, 3] # [yield-inside-async-function] diff --git a/testbed/pylint-dev__pylint/tests/functional/y/yield_inside_async_function.txt b/testbed/pylint-dev__pylint/tests/functional/y/yield_inside_async_function.txt new file mode 100644 index 0000000000000000000000000000000000000000..1c2674c0cff3cfdcfcb8d096ba181948c0dc0b5d --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/y/yield_inside_async_function.txt @@ -0,0 +1 @@ +yield-inside-async-function:16:4:16:24:bad:Yield inside async function:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/y/yield_outside_func.py b/testbed/pylint-dev__pylint/tests/functional/y/yield_outside_func.py new file mode 100644 index 0000000000000000000000000000000000000000..198a1033668816923057f9fe2c3f9ab5ec9458a8 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/y/yield_outside_func.py @@ -0,0 +1,6 @@ +"""This is grammatically correct, but it's still a SyntaxError""" +# pylint: disable=unnecessary-lambda-assignment + +yield 1 # [yield-outside-function] + +LAMBDA_WITH_YIELD = lambda: (yield) diff --git a/testbed/pylint-dev__pylint/tests/functional/y/yield_outside_func.txt b/testbed/pylint-dev__pylint/tests/functional/y/yield_outside_func.txt new file mode 100644 index 0000000000000000000000000000000000000000..42cd732375e41928ad479f111f1d340b4a055913 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/y/yield_outside_func.txt @@ -0,0 +1 @@ +yield-outside-function:4:0:4:7::Yield outside function:UNDEFINED diff --git a/testbed/pylint-dev__pylint/tests/functional/y/yield_return_mix.py b/testbed/pylint-dev__pylint/tests/functional/y/yield_return_mix.py new file mode 100644 index 0000000000000000000000000000000000000000..a69a669d6530db1a42194a85217368896cea2b05 --- /dev/null +++ b/testbed/pylint-dev__pylint/tests/functional/y/yield_return_mix.py @@ -0,0 +1,8 @@ +""" module doc """ +# pylint: disable=useless-return + + +def somegen(): + """this kind of mix is OK""" + yield 1 + return