Skip to content

Commit 52ffccb

Browse files
authored
enable mypy strict checks (#16)
1 parent 8504758 commit 52ffccb

File tree

4 files changed

+34
-19
lines changed

4 files changed

+34
-19
lines changed

mypy.ini

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
11
[mypy]
22
ignore_missing_imports = True
3-
strict_optional = True
3+
# strict checks
4+
strict_optional = True
5+
disallow_any_generics = True
6+
disallow_untyped_defs = True
7+
warn_unused_ignores = True
8+
strict_equality = True

pytest_mypy/collect.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
11
import tempfile
2-
from typing import Any, Dict, List
2+
from typing import Any, Dict, List, Iterator, TYPE_CHECKING, Optional
33

44
import pytest
55
import yaml
66
from _pytest.config.argparsing import Parser
7+
from _pytest.nodes import Node
8+
from py._path.local import LocalPath
79

810
from pytest_mypy import utils
911
from pytest_mypy.utils import string_to_bool
1012

13+
if TYPE_CHECKING:
14+
from pytest_mypy.item import YamlTestItem
15+
16+
1117

1218
class File:
1319
def __init__(self, path: str, content: str):
@@ -36,7 +42,7 @@ def parse_environment_variables(env_vars: List[str]) -> Dict[str, str]:
3642

3743

3844
class SafeLineLoader(yaml.SafeLoader):
39-
def construct_mapping(self, node, deep=False):
45+
def construct_mapping(self, node: yaml.Node, deep: bool = False) -> None:
4046
mapping = super().construct_mapping(node, deep=deep)
4147
# Add 1 so line numbering starts at 1
4248
starting_line = node.start_mark.line + 1
@@ -48,7 +54,7 @@ def construct_mapping(self, node, deep=False):
4854

4955

5056
class YamlTestFile(pytest.File):
51-
def collect(self):
57+
def collect(self) -> Iterator['YamlTestItem']:
5258
from pytest_mypy.item import YamlTestItem
5359

5460
parsed_file = yaml.load(stream=self.fspath.read_text('utf8'), Loader=SafeLineLoader)
@@ -93,9 +99,10 @@ def collect(self):
9399
mypy_config=additional_mypy_config)
94100

95101

96-
def pytest_collect_file(path, parent):
102+
def pytest_collect_file(path: LocalPath, parent: Node) -> Optional[YamlTestFile]:
97103
if path.ext in {'.yaml', '.yml'} and path.basename.startswith(('test-', 'test_')):
98104
return YamlTestFile(path, parent=parent, config=parent.config)
105+
return None
99106

100107

101108
def pytest_addoption(parser: Parser) -> None:

pytest_mypy/item.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
from mypy import build
1515
from mypy.fscache import FileSystemCache
1616
from mypy.main import process_options
17+
from py._io.terminalwriter import TerminalWriter
18+
1719
from pytest_mypy import utils
1820
from pytest_mypy.collect import File, YamlTestFile
1921
from pytest_mypy.utils import (
@@ -25,7 +27,7 @@
2527

2628

2729
class TraceLastReprEntry(ReprEntry):
28-
def toterminal(self, tw):
30+
def toterminal(self, tw: TerminalWriter) -> None:
2931
self.reprfileloc.toterminal(tw)
3032
for line in self.lines:
3133
red = line.startswith("E ")
@@ -199,7 +201,7 @@ def execute_extension_hook(self) -> None:
199201
extension_hook = getattr(module, func_name)
200202
extension_hook(self)
201203

202-
def runtest(self):
204+
def runtest(self) -> None:
203205
try:
204206
temp_dir = tempfile.TemporaryDirectory(prefix='pytest-mypy-', dir=self.root_directory)
205207

@@ -309,5 +311,5 @@ def repr_failure(self, excinfo: ExceptionInfo) -> str:
309311
else:
310312
return super().repr_failure(excinfo, style='native')
311313

312-
def reportinfo(self):
314+
def reportinfo(self) -> Tuple[str, Optional[str], str]:
313315
return self.fspath, None, self.name

pytest_mypy/utils.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,13 @@
77
import re
88
import sys
99
from pathlib import Path
10-
from typing import Callable, Iterator, List, Optional, Tuple
10+
from typing import Callable, Iterator, List, Optional, Tuple, Union
1111

1212
from decorator import contextmanager
1313

1414

1515
@contextmanager
16-
def temp_environ():
16+
def temp_environ() -> Iterator[None]:
1717
"""Allow the ability to set os.environ temporarily"""
1818
environ = dict(os.environ)
1919
try:
@@ -24,7 +24,7 @@ def temp_environ():
2424

2525

2626
@contextmanager
27-
def temp_path():
27+
def temp_path() -> Iterator[None]:
2828
"""A context manager which allows the ability to set sys.path temporarily"""
2929
path = sys.path[:]
3030
try:
@@ -34,7 +34,7 @@ def temp_path():
3434

3535

3636
@contextmanager
37-
def temp_sys_modules():
37+
def temp_sys_modules() -> Iterator[None]:
3838
sys_modules = sys.modules.copy()
3939
try:
4040
yield
@@ -56,14 +56,14 @@ def fname_to_module(fpath: Path, root_path: Path) -> Optional[str]:
5656

5757

5858
class TypecheckAssertionError(AssertionError):
59-
def __init__(self, error_message: Optional[str] = None, lineno: int = 0):
60-
self.error_message = error_message
59+
def __init__(self, error_message: Optional[str] = None, lineno: int = 0) -> None:
60+
self.error_message = error_message or ''
6161
self.lineno = lineno
6262

63-
def first_line(self):
63+
def first_line(self) -> str:
6464
return self.__class__.__name__ + '(message="Invalid output")'
6565

66-
def __str__(self):
66+
def __str__(self) -> str:
6767
return self.error_message
6868

6969

@@ -258,7 +258,8 @@ def assert_string_arrays_equal(expected: List[str], actual: List[str]) -> None:
258258
lineno=lineno)
259259

260260

261-
def build_output_line(fname: str, lnum: int, severity: str, message: str, col=None) -> str:
261+
def build_output_line(fname: str, lnum: int, severity: str, message: str,
262+
col: Optional[str] = None) -> str:
262263
if col is None:
263264
return f'{fname}:{lnum + 1}: {severity}: {message}'
264265
else:
@@ -294,7 +295,7 @@ def extract_errors_from_comments(fname: str, input_lines: List[str]) -> List[str
294295

295296

296297
def get_func_first_lnum(attr: Callable[..., None]) -> Optional[Tuple[int, List[str]]]:
297-
lines, _ = inspect.getsourcelines(attr) # type: ignore[arg-type]
298+
lines, _ = inspect.getsourcelines(attr)
298299
for lnum, line in enumerate(lines):
299300
no_space_line = line.strip()
300301
if f'def {attr.__name__}' in no_space_line:
@@ -303,7 +304,7 @@ def get_func_first_lnum(attr: Callable[..., None]) -> Optional[Tuple[int, List[s
303304

304305

305306
@contextmanager
306-
def cd(path):
307+
def cd(path: Union[str, Path]) -> Iterator[None]:
307308
"""Context manager to temporarily change working directories"""
308309
if not path:
309310
return

0 commit comments

Comments
 (0)