diff --git a/src/pytest_mypy.py b/src/pytest_mypy.py index 7c2ca8d..80a5833 100644 --- a/src/pytest_mypy.py +++ b/src/pytest_mypy.py @@ -14,6 +14,14 @@ nodeid_name = 'mypy' +def default_file_error_formatter(item, results, errors): + """Create a string to be displayed when mypy finds errors in a file.""" + return '\n'.join(errors) + + +file_error_formatter = default_file_error_formatter + + def pytest_addoption(parser): """Add options for enabling and running mypy.""" group = parser.getgroup('mypy') @@ -158,7 +166,7 @@ def runtest(self): abspath = os.path.abspath(str(self.fspath)) errors = results['abspath_errors'].get(abspath) if errors: - raise MypyError('\n'.join(errors)) + raise MypyError(file_error_formatter(self, results, errors)) def reportinfo(self): """Produce a heading for the test report.""" diff --git a/tests/test_pytest_mypy.py b/tests/test_pytest_mypy.py index eabca0e..6fe1ec5 100644 --- a/tests/test_pytest_mypy.py +++ b/tests/test_pytest_mypy.py @@ -286,3 +286,30 @@ def pytest_collection_modifyitems(session, config, items): testdir.mkdir(name) result = testdir.runpytest_subprocess('--mypy', *xdist_args, name) assert result.ret != 0 + + +def test_api_error_formatter(testdir, xdist_args): + """Ensure that the plugin can be configured in a conftest.py.""" + testdir.makepyfile(bad=''' + def pyfunc(x: int) -> str: + return x * 2 + ''') + testdir.makepyfile(conftest=''' + def custom_file_error_formatter(item, results, errors): + return '\\n'.join( + '{path}:{error}'.format( + path=item.fspath, + error=error, + ) + for error in errors + ) + + def pytest_configure(config): + plugin = config.pluginmanager.getplugin('mypy') + plugin.file_error_formatter = custom_file_error_formatter + ''') + result = testdir.runpytest_subprocess('--mypy', *xdist_args) + result.stdout.fnmatch_lines([ + '*/bad.py:2: error: Incompatible return value*', + ]) + assert result.ret != 0