Skip to content

Commit 1d30d6d

Browse files
committed
Enable custom error formatting
1 parent 6f8f19a commit 1d30d6d

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

src/pytest_mypy.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,14 @@
1414
nodeid_name = 'mypy'
1515

1616

17+
def default_file_error_formatter(item, results, errors):
18+
"""Create a string to be displayed when mypy finds errors in a file."""
19+
return '\n'.join(errors)
20+
21+
22+
file_error_formatter = default_file_error_formatter
23+
24+
1725
def pytest_addoption(parser):
1826
"""Add options for enabling and running mypy."""
1927
group = parser.getgroup('mypy')
@@ -158,7 +166,7 @@ def runtest(self):
158166
abspath = os.path.abspath(str(self.fspath))
159167
errors = results['abspath_errors'].get(abspath)
160168
if errors:
161-
raise MypyError('\n'.join(errors))
169+
raise MypyError(file_error_formatter(self, results, errors))
162170

163171
def reportinfo(self):
164172
"""Produce a heading for the test report."""

tests/test_pytest_mypy.py

+27
Original file line numberDiff line numberDiff line change
@@ -286,3 +286,30 @@ def pytest_collection_modifyitems(session, config, items):
286286
testdir.mkdir(name)
287287
result = testdir.runpytest_subprocess('--mypy', *xdist_args, name)
288288
assert result.ret != 0
289+
290+
291+
def test_api_error_formatter(testdir, xdist_args):
292+
"""Ensure that the plugin can be configured in a conftest.py."""
293+
testdir.makepyfile(bad='''
294+
def pyfunc(x: int) -> str:
295+
return x * 2
296+
''')
297+
testdir.makepyfile(conftest='''
298+
def custom_file_error_formatter(item, results, errors):
299+
return '\\n'.join(
300+
'{path}:{error}'.format(
301+
path=item.fspath,
302+
error=error,
303+
)
304+
for error in errors
305+
)
306+
307+
def pytest_configure(config):
308+
plugin = config.pluginmanager.getplugin('mypy')
309+
plugin.file_error_formatter = custom_file_error_formatter
310+
''')
311+
result = testdir.runpytest_subprocess('--mypy', *xdist_args)
312+
result.stdout.fnmatch_lines([
313+
'*/bad.py:2: error: Incompatible return value*',
314+
])
315+
assert result.ret != 0

0 commit comments

Comments
 (0)