Skip to content

Commit

Permalink
Add typing with PyAnnotate to ./tests (#4950)
Browse files Browse the repository at this point in the history
* Add mypy_extensions to requirement for ``NoReturn``

Co-authored-by: Pierre Sassoulas <pierre.sassoulas@gmail.com>
  • Loading branch information
DanielNoord and Pierre-Sassoulas committed Sep 4, 2021
1 parent 6c81831 commit 2500086
Show file tree
Hide file tree
Showing 69 changed files with 965 additions and 775 deletions.
6 changes: 2 additions & 4 deletions pylint/checkers/similar.py
Expand Up @@ -49,7 +49,6 @@
import sys
from collections import defaultdict
from getopt import getopt
from io import TextIOWrapper
from itertools import chain, groupby
from typing import (
Any,
Expand All @@ -61,6 +60,7 @@
NamedTuple,
NewType,
Set,
TextIO,
Tuple,
)

Expand Down Expand Up @@ -368,9 +368,7 @@ def __init__(
self.ignore_signatures = ignore_signatures
self.linesets: List["LineSet"] = []

def append_stream(
self, streamid: str, stream: TextIOWrapper, encoding=None
) -> None:
def append_stream(self, streamid: str, stream: TextIO, encoding=None) -> None:
"""append a file to search for similarities"""
if encoding is None:
readlines = stream.readlines
Expand Down
6 changes: 3 additions & 3 deletions pylint/lint/utils.py
Expand Up @@ -5,7 +5,7 @@
import sys
import traceback
from datetime import datetime
from pathlib import Path
from pathlib import Path, PosixPath
from typing import Union

from pylint.config import PYLINT_HOME
Expand All @@ -17,7 +17,7 @@ class ArgumentPreprocessingError(Exception):


def prepare_crash_report(
ex: Exception, filepath: str, crash_file_path: Union[Path, str]
ex: Exception, filepath: PosixPath, crash_file_path: Union[Path, str]
) -> Path:
issue_template_path = (
Path(PYLINT_HOME) / datetime.now().strftime(str(crash_file_path))
Expand Down Expand Up @@ -63,7 +63,7 @@ def prepare_crash_report(
return issue_template_path


def get_fatal_error_message(filepath: str, issue_template_path: Path) -> str:
def get_fatal_error_message(filepath: str, issue_template_path: str) -> str:
return (
f"Fatal error while checking '{filepath}'. "
f"Please open an issue in our bug tracker so we address this. "
Expand Down
4 changes: 2 additions & 2 deletions pylint/message/message_definition.py
Expand Up @@ -18,8 +18,8 @@ def __init__(
description: str,
symbol: str,
scope: str,
minversion: Optional[Tuple[int, int, int, str, int]] = None,
maxversion: Optional[Tuple[int, int, int, str, int]] = None,
minversion: Optional[Tuple[int, int]] = None,
maxversion: Optional[Tuple[int, int]] = None,
old_names: List[Tuple[str, str]] = None,
):
self.checker_name = checker.name
Expand Down
4 changes: 2 additions & 2 deletions pylint/testutils/output_line.py
Expand Up @@ -58,10 +58,10 @@ def __init__(self, row, exception):
class OutputLine(NamedTuple):
symbol: str
lineno: int
column: int
column: str
object: Any
msg: str
confidence: str
confidence: interfaces.Confidence

@classmethod
def from_msg(cls, msg):
Expand Down
1 change: 1 addition & 0 deletions requirements_test_min.txt
Expand Up @@ -2,3 +2,4 @@
astroid==2.7.3 # Pinned to a specific version for tests
pytest~=6.2
pytest-benchmark~=3.4
mypy_extensions==0.4.3
62 changes: 35 additions & 27 deletions tests/checkers/unittest_base.py
Expand Up @@ -39,24 +39,24 @@
class TestDocstring(CheckerTestCase):
CHECKER_CLASS: Type = base.DocStringChecker

def test_missing_docstring_module(self):
def test_missing_docstring_module(self) -> None:
module = astroid.parse("something")
message = Message("missing-module-docstring", node=module)
with self.assertAddsMessages(message):
self.checker.visit_module(module)

def test_missing_docstring_empty_module(self):
def test_missing_docstring_empty_module(self) -> None:
module = astroid.parse("")
with self.assertNoMessages():
self.checker.visit_module(module)

def test_empty_docstring_module(self):
def test_empty_docstring_module(self) -> None:
module = astroid.parse("''''''")
message = Message("empty-docstring", node=module, args=("module",))
with self.assertAddsMessages(message):
self.checker.visit_module(module)

def test_empty_docstring_function(self):
def test_empty_docstring_function(self) -> None:
func = astroid.extract_node(
"""
def func(tion):
Expand All @@ -67,7 +67,7 @@ def func(tion):
self.checker.visit_functiondef(func)

@set_config(docstring_min_length=2)
def test_short_function_no_docstring(self):
def test_short_function_no_docstring(self) -> None:
func = astroid.extract_node(
"""
def func(tion):
Expand All @@ -77,7 +77,7 @@ def func(tion):
self.checker.visit_functiondef(func)

@set_config(docstring_min_length=2)
def test_long_function_no_docstring(self):
def test_long_function_no_docstring(self) -> None:
func = astroid.extract_node(
"""
def func(tion):
Expand All @@ -90,7 +90,7 @@ def func(tion):
self.checker.visit_functiondef(func)

@set_config(docstring_min_length=2)
def test_long_function_nested_statements_no_docstring(self):
def test_long_function_nested_statements_no_docstring(self) -> None:
func = astroid.extract_node(
"""
def func(tion):
Expand All @@ -105,7 +105,7 @@ def func(tion):
self.checker.visit_functiondef(func)

@set_config(docstring_min_length=2)
def test_function_no_docstring_by_name(self):
def test_function_no_docstring_by_name(self) -> None:
func = astroid.extract_node(
"""
def __fun__(tion):
Expand All @@ -114,7 +114,7 @@ def __fun__(tion):
with self.assertNoMessages():
self.checker.visit_functiondef(func)

def test_class_no_docstring(self):
def test_class_no_docstring(self) -> None:
klass = astroid.extract_node(
"""
class Klass(object):
Expand All @@ -124,7 +124,7 @@ class Klass(object):
with self.assertAddsMessages(message):
self.checker.visit_classdef(klass)

def test_inner_function_no_docstring(self):
def test_inner_function_no_docstring(self) -> None:
func = astroid.extract_node(
"""
def func(tion):
Expand All @@ -146,7 +146,7 @@ class TestNameChecker(CheckerTestCase):
attr_rgx=re.compile("[A-Z]+"),
property_classes=("abc.abstractproperty", ".custom_prop"),
)
def test_property_names(self):
def test_property_names(self) -> None:
# If a method is annotated with @property, its name should
# match the attr regex. Since by default the attribute regex is the same
# as the method regex, we override it here.
Expand Down Expand Up @@ -189,7 +189,7 @@ def QUX(self): #@
self.checker.visit_functiondef(methods[1])

@set_config(attr_rgx=re.compile("[A-Z]+"))
def test_property_setters(self):
def test_property_setters(self) -> None:
method = astroid.extract_node(
"""
class FooClass(object):
Expand All @@ -204,7 +204,7 @@ def FOOSETTER(self): #@
with self.assertNoMessages():
self.checker.visit_functiondef(method)

def test_module_level_names(self):
def test_module_level_names(self) -> None:
assign = astroid.extract_node(
"""
import collections
Expand Down Expand Up @@ -289,7 +289,7 @@ class TestMultiNamingStyle(CheckerTestCase):
MULTI_STYLE_RE = re.compile("(?:(?P<UP>[A-Z]+)|(?P<down>[a-z]+))$")

@set_config(class_rgx=MULTI_STYLE_RE)
def test_multi_name_detection_majority(self):
def test_multi_name_detection_majority(self) -> None:
classes = astroid.extract_node(
"""
class classb(object): #@
Expand Down Expand Up @@ -317,7 +317,7 @@ class CLASSC(object): #@
self.checker.leave_module(cls.root)

@set_config(class_rgx=MULTI_STYLE_RE)
def test_multi_name_detection_first_invalid(self):
def test_multi_name_detection_first_invalid(self) -> None:
classes = astroid.extract_node(
"""
class class_a(object): #@
Expand Down Expand Up @@ -391,7 +391,7 @@ def FUNC(): #@
@set_config(
function_rgx=re.compile("(?:(?P<ignore>FOO)|(?P<UP>[A-Z]+)|(?P<down>[a-z]+))$")
)
def test_multi_name_detection_exempt(self):
def test_multi_name_detection_exempt(self) -> None:
function_defs = astroid.extract_node(
"""
def FOO(): #@
Expand Down Expand Up @@ -424,7 +424,7 @@ def UPPER(): #@
class TestComparison(CheckerTestCase):
CHECKER_CLASS = base.ComparisonChecker

def test_comparison(self):
def test_comparison(self) -> None:
node = astroid.extract_node("foo == True")
message = Message(
"singleton-comparison",
Expand Down Expand Up @@ -545,15 +545,19 @@ class TestNamePresets(unittest.TestCase):
SNAKE_CASE_NAMES | CAMEL_CASE_NAMES | UPPER_CASE_NAMES | PASCAL_CASE_NAMES
)

def _test_name_is_correct_for_all_name_types(self, naming_style, name):
def _test_name_is_correct_for_all_name_types(
self, naming_style: Type[base.NamingStyle], name: str
) -> None:
for name_type in base.KNOWN_NAME_TYPES:
self._test_is_correct(naming_style, name, name_type)

def _test_name_is_incorrect_for_all_name_types(self, naming_style, name):
def _test_name_is_incorrect_for_all_name_types(
self, naming_style: Type[base.NamingStyle], name: str
) -> None:
for name_type in base.KNOWN_NAME_TYPES:
self._test_is_incorrect(naming_style, name, name_type)

def _test_should_always_pass(self, naming_style):
def _test_should_always_pass(self, naming_style: Type[base.NamingStyle]) -> None:
always_pass_data = [
("__add__", "method"),
("__set_name__", "method"),
Expand All @@ -564,18 +568,22 @@ def _test_should_always_pass(self, naming_style):
self._test_is_correct(naming_style, name, name_type)

@staticmethod
def _test_is_correct(naming_style, name, name_type):
def _test_is_correct(
naming_style: Type[base.NamingStyle], name: str, name_type: str
) -> None:
rgx = naming_style.get_regex(name_type)
fail = f"{name!r} does not match pattern {rgx!r} (style: {naming_style}, type: {name_type})"
assert rgx.match(name), fail

@staticmethod
def _test_is_incorrect(naming_style, name, name_type):
def _test_is_incorrect(
naming_style: Type[base.NamingStyle], name: str, name_type: str
) -> None:
rgx = naming_style.get_regex(name_type)
fail = f"{name!r} not match pattern {rgx!r} (style: {naming_style}, type: {name_type})"
assert not rgx.match(name), fail

def test_snake_case(self):
def test_snake_case(self) -> None:
naming_style = base.SnakeCaseStyle

for name in self.SNAKE_CASE_NAMES:
Expand All @@ -585,7 +593,7 @@ def test_snake_case(self):

self._test_should_always_pass(naming_style)

def test_camel_case(self):
def test_camel_case(self) -> None:
naming_style = base.CamelCaseStyle

for name in self.CAMEL_CASE_NAMES:
Expand All @@ -595,7 +603,7 @@ def test_camel_case(self):

self._test_should_always_pass(naming_style)

def test_upper_case(self):
def test_upper_case(self) -> None:
naming_style = base.UpperCaseStyle

for name in self.UPPER_CASE_NAMES:
Expand All @@ -606,7 +614,7 @@ def test_upper_case(self):

self._test_should_always_pass(naming_style)

def test_pascal_case(self):
def test_pascal_case(self) -> None:
naming_style = base.PascalCaseStyle

for name in self.PASCAL_CASE_NAMES:
Expand All @@ -618,7 +626,7 @@ def test_pascal_case(self):


class TestBaseChecker(unittest.TestCase):
def test_doc(self):
def test_doc(self) -> None:
class OtherBasicChecker(BaseChecker):
name = "basic"
msgs = {
Expand Down
18 changes: 9 additions & 9 deletions tests/checkers/unittest_classes.py
Expand Up @@ -26,7 +26,7 @@ class TestVariablesChecker(CheckerTestCase):

CHECKER_CLASS = classes.ClassChecker

def test_bitbucket_issue_164(self):
def test_bitbucket_issue_164(self) -> None:
"""Issue 164 report a false negative for access-member-before-definition"""
n1, n2 = astroid.extract_node(
"""
Expand All @@ -43,7 +43,7 @@ def __init__(self):
self.walk(n1.root())

@set_config(exclude_protected=("_meta", "_manager"))
def test_exclude_protected(self):
def test_exclude_protected(self) -> None:
"""Test that exclude-protected can be used to
exclude names from protected-access warning.
"""
Expand All @@ -67,7 +67,7 @@ def __init__(self):
):
self.walk(node.root())

def test_regression_non_parent_init_called_tracemalloc(self):
def test_regression_non_parent_init_called_tracemalloc(self) -> None:
# This used to raise a non-parent-init-called on Pylint 1.3
# See issue https://bitbucket.org/logilab/pylint/issue/308/
# for reference.
Expand All @@ -82,7 +82,7 @@ def __init__(self, traces): #@
with self.assertNoMessages():
self.checker.visit_functiondef(node)

def test_super_init_not_called_regression(self):
def test_super_init_not_called_regression(self) -> None:
# This should not emit a super-init-not-called
# warning. It previously did this, because
# ``next(node.infer())`` was used in that checker's
Expand All @@ -100,7 +100,7 @@ def __init__(self): #@
with self.assertNoMessages():
self.checker.visit_functiondef(node)

def test_uninferable_attribute(self):
def test_uninferable_attribute(self) -> None:
"""Make sure protect-access doesn't raise an exception Uninferable attributes"""

node = astroid.extract_node(
Expand All @@ -121,7 +121,7 @@ def __no_special__(cls):
self.checker.visit_attribute(node.value)

@set_config(check_protected_access_in_special_methods=True)
def test_check_protected_access_in_special_methods(self):
def test_check_protected_access_in_special_methods(self) -> None:
"""Test that check-protected-access-in-special-methods can be used to
trigger protected-access message emission for single underscore prefixed names
inside special methods
Expand Down Expand Up @@ -170,7 +170,7 @@ def _fake_special_(self, other):
self.walk(node.root())

@set_config(check_protected_access_in_special_methods=False)
def test_check_protected_access_in_special_methods_deact(self):
def test_check_protected_access_in_special_methods_deact(self) -> None:
"""Test that when check-protected-access-in-special-methods is False (default)
no protected-access message emission for single underscore prefixed names
inside special methods occur
Expand Down Expand Up @@ -215,7 +215,7 @@ def _fake_special_(self, other):
):
self.walk(node.root())

def test_private_attribute_hides_method(self):
def test_private_attribute_hides_method(self) -> None:
node = astroid.extract_node(
"""
class Parent:
Expand All @@ -230,7 +230,7 @@ def __private(self): #@
with self.assertNoMessages():
self.checker.visit_functiondef(node)

def test_protected_attribute_hides_method(self):
def test_protected_attribute_hides_method(self) -> None:
node = astroid.extract_node(
"""
class Parent:
Expand Down

0 comments on commit 2500086

Please sign in to comment.