A Pytest Plugin for Mypy static type checking integration
npx @tessl/cli install tessl/pypi-pytest-mypy@1.0.00
# pytest-mypy
1
2
A pytest plugin that seamlessly integrates the mypy static type checker into pytest test runs, enabling automatic type checking of Python source files as part of the testing process. This plugin extends pytest with mypy-specific command-line flags and creates type checking test items that execute alongside regular tests, helping developers catch type-related issues early in the development cycle.
3
4
## Package Information
5
6
- **Package Name**: pytest-mypy
7
- **Language**: Python
8
- **Installation**: `pip install pytest-mypy`
9
10
## Core Imports
11
12
```python
13
import pytest_mypy
14
```
15
16
The plugin is automatically registered via pytest's entry point system when installed:
17
18
```python
19
# Entry point registration in pyproject.toml
20
[project.entry-points.pytest11]
21
mypy = "pytest_mypy"
22
```
23
24
No explicit imports are required for basic usage.
25
26
## Basic Usage
27
28
```python
29
# Enable mypy checking with pytest
30
# Command line usage:
31
# pytest --mypy src/
32
33
# Configure in conftest.py for programmatic control
34
def pytest_configure(config):
35
plugin = config.pluginmanager.getplugin('mypy')
36
plugin.mypy_argv.append('--check-untyped-defs')
37
plugin.mypy_argv.append('--ignore-missing-imports')
38
```
39
40
## Architecture
41
42
The plugin operates through pytest's hook system and creates specialized test items:
43
44
- **Pytest Hooks**: Integrate mypy into pytest's collection and execution phases
45
- **MypyFile/MypyFileItem**: Handle per-file type checking with detailed error reporting
46
- **MypyStatusItem**: Validate overall mypy exit status across all checked files
47
- **MypyResults**: Cache and manage mypy execution output for efficient parallel execution
48
- **Plugin Classes**: Support both standalone and xdist parallel execution modes
49
50
## Capabilities
51
52
### Command Line Configuration
53
54
Comprehensive command-line interface for controlling mypy behavior within pytest, including error reporting styles, configuration files, and failure handling modes.
55
56
```python { .api }
57
def pytest_addoption(parser: pytest.Parser) -> None:
58
"""Add mypy-specific command line options to pytest."""
59
60
def pytest_configure(config: pytest.Config) -> None:
61
"""Initialize plugin configuration and register sub-plugins based on options."""
62
```
63
64
Available options:
65
- `--mypy`: Enable mypy checking
66
- `--mypy-ignore-missing-imports`: Suppress import resolution errors
67
- `--mypy-config-file`: Specify custom mypy configuration file
68
- `--mypy-report-style`: Choose error output format
69
- `--mypy-no-status-check`: Ignore mypy exit status
70
- `--mypy-xfail`: Mark mypy errors as expected failures
71
72
[Command Line Interface](./command-line.md)
73
74
### Test Item Integration
75
76
Specialized pytest test items for mypy type checking that integrate with pytest's collection, execution, and reporting systems.
77
78
```python { .api }
79
class MypyFileItem(MypyItem):
80
"""Test item for mypy errors in a specific file."""
81
def runtest(self) -> None: ...
82
def reportinfo(self) -> Tuple[Path, None, str]: ...
83
84
class MypyStatusItem(MypyItem):
85
"""Test item for overall mypy exit status validation."""
86
def runtest(self) -> None: ...
87
```
88
89
[Test Items](./test-items.md)
90
91
### Results Caching and Management
92
93
Efficient caching system for mypy execution results, supporting both single-process and xdist parallel execution modes.
94
95
```python { .api }
96
class MypyResults:
97
"""Parsed and cached mypy execution results."""
98
opts: List[str]
99
args: List[str]
100
stdout: str
101
stderr: str
102
status: int
103
path_lines: Dict[Optional[Path], List[str]]
104
105
@classmethod
106
def from_mypy(cls, paths: List[Path], *, opts: Optional[List[str]] = None) -> MypyResults: ...
107
@classmethod
108
def from_session(cls, session: pytest.Session) -> MypyResults: ...
109
```
110
111
[Results Management](./results-management.md)
112
113
### Programmatic Configuration
114
115
Runtime configuration capabilities through conftest.py for advanced mypy customization and formatter overrides.
116
117
```python { .api }
118
# Global configuration variables
119
mypy_argv: List[str]
120
test_name_formatter: Callable[[MypyFileItem], str]
121
file_error_formatter: Callable[[MypyItem, MypyResults, List[str]], str]
122
```
123
124
[Configuration](./configuration.md)
125
126
## Types
127
128
```python { .api }
129
class MypyError(Exception):
130
"""Exception raised when mypy finds type checking violations."""
131
132
@dataclass(frozen=True)
133
class MypyConfigStash:
134
"""Plugin data stored in pytest.Config stash."""
135
mypy_results_path: Path
136
137
@classmethod
138
def from_serialized(cls, serialized: str) -> MypyConfigStash: ...
139
def serialized(self) -> str: ...
140
141
class MypyFile(pytest.File):
142
"""File collector that generates mypy test items."""
143
def collect(self) -> Iterator[MypyItem]: ...
144
145
class MypyCollectionPlugin:
146
"""Plugin that collects MypyFile instances during pytest collection."""
147
def pytest_collect_file(self, file_path: Path, parent: pytest.Collector) -> Optional[MypyFile]: ...
148
149
# Global configuration variables
150
mypy_argv: List[str] # Global mypy command line arguments
151
test_name_formatter: Callable[[MypyFileItem], str] # Test name formatting function
152
file_error_formatter: Callable[[MypyItem, MypyResults, List[str]], str] # Error formatting function
153
item_marker: str # Marker name for mypy test items ("mypy")
154
nodeid_name: str # Base node ID name ("mypy")
155
terminal_summary_title: str # Terminal summary section title ("mypy")
156
157
# Stash keys for configuration storage
158
stash_key: Dict[str, pytest.StashKey]
159
160
def _error_severity(line: str) -> Optional[str]:
161
"""Extract error severity level from mypy output line."""
162
163
# Plugin classes for xdist support
164
class MypyXdistControllerPlugin:
165
"""Plugin active only on xdist controller processes."""
166
def pytest_configure_node(self, node: WorkerController) -> None: ...
167
168
class MypyControllerPlugin:
169
"""Plugin for main/controller processes (not xdist workers)."""
170
def pytest_terminal_summary(self, terminalreporter: TerminalReporter, config: pytest.Config) -> None: ...
171
def pytest_unconfigure(self, config: pytest.Config) -> None: ...
172
```