Backtestspytestrun-20261106-234554#993

Issue #993 Merged fix PR #14824 Run 6 Nov 2026 · run-20261106-234554 pytest-dev/pytest

ImportError raised by plugins make pytest return EXIT_TESTSFAILED

Worse

The merged fix was judged better than our patch.

In this judgment, Patch B = our agent, Patch A = the merged fix.

The issue's title and body complain that ImportErrors raised by plugins at startup escape as a raw traceback and yield exit code 1. The root cause is that `import_plugin` re-raises ImportError and nothing in `_main` catches it, regardless of whether the plugin was requested via `-p`, `pytest_plugins`, `PYTEST_PLUGINS`, or an entry point.

Patch A fixes that root cause: it classifies plugin load failures (not found -> UsageError/4, found but raised -> PluginImportFailure/3), catches the new exception in `_main`, prints a filtered traceback consistent with the existing conftest-error path, handles entry-point loading and UsageError passthrough, and fixes the `e.args[0]` IndexError on a bare `raise ImportError`. It updates every existing test that relied on ImportError, adds broad acceptance tests covering all four load paths, and documents the exit codes and the behaviour change. Its choice of 3 for a broken plugin vs 4 for a broken conftest is deliberate, documented, and matches the issue's own suggestion that the code should be 3; the issue's two asks ('same code' and 'should be 3') are in tension, so failing the independent 'same exit code' test is a defensible design choice rather than a defect.

Patch B only wraps `consider_conftest` so a `pytest_plugins` failure becomes a ConftestImportFailure. That fixes example 2 and the IndexError, but a plugin that fails under `-p` (the independent test shows exit code 1 still), under `PYTEST_PLUGINS`, or as a pytest11 entry point still crashes out with code 1, which is exactly the title's complaint. B's tests are reasonable for the path it covers but it leaves the general problem unresolved.

A is larger and breaking in exception types, but the extra scope directly serves the issue rather than being unrelated churn. A wins on correctness and test coverage.

Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.

Solve

9m 37s

Wall-clock time in the container

Full test suite

No new failures

2,929 passed · 27 skipped · 2,956 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

84vs 301 merged

Changed lines, ours vs merged

Currently there's some inconsistency on which exit code is returned by pytest when import errors happen during startup.

example 1

# contents of conftest.py
raise ImportError

# contents of test_foo.py
def test_foo():
    pass

Running py.test in this directory produces error code 4 - EXIT_USAGEERROR.

example 2

# contents of conftest.py
pytest_plugins = 'plugin'

# contents of plugin.py
raise ImportError

# contents of test_foo.py
def test_foo():
    pass

Here py.test produces error code 1 - EXIT_TESTSFAILED.

Shouldn't they all return the same error code? Furthermore, shouldn't the error code be 3 - EXIT_INTERNALERROR instead?

The two patches

Our patch+82 −2
src/_pytest/config/__init__.pyindex 8c6052bc4..67bae0565 100644@@ -788,7 +788,13 @@ class PytestPluginManager(PluginManager):                         )                     mods.append(mod)         self.trace(f"loading conftestmodule {mod!r}")-        self.consider_conftest(mod, registration_name=conftestpath_plugin_name)+        try:+            self.consider_conftest(mod, registration_name=conftestpath_plugin_name)+        except ImportError as e:+            # Plugins requested via ``pytest_plugins`` are imported while the+            # conftest is registered; failing to import them is a failure to+            # load the conftest, same as an ImportError in the conftest itself.+            raise ConftestImportFailure(conftestpath, cause=e) from e         return mod      def _check_non_top_pytest_plugins(@@ -926,7 +932,7 @@ class PytestPluginManager(PluginManager):                 mod = sys.modules[importspec]         except ImportError as e:             raise ImportError(-                f'Error importing plugin "{modname}": {e.args[0]}'+                f'Error importing plugin "{modname}": {e}'             ).with_traceback(e.__traceback__) from e          except Skipped as e:testing/acceptance_test.pyindex f941cbe19..f1b8bd149 100644@@ -230,6 +230,80 @@ class TestGeneralUsage:             "E   ModuleNotFoundError: No module named 'qwerty'",         ] +    def test_conftest_import_error_exit_code(self, pytester: Pytester) -> None:+        """An ImportError raised by an initial conftest is a usage error."""+        pytester.makeconftest("raise ImportError('broken conftest')")+        pytester.makepyfile("def test_foo(): pass")+        result = pytester.runpytest_subprocess()+        assert result.ret == ExitCode.USAGE_ERROR+        result.stderr.fnmatch_lines(+            [+                "ImportError while loading conftest *conftest.py*",+                "E   ImportError: broken conftest",+            ]+        )++    def test_conftest_pytest_plugins_import_error_exit_code(+        self, pytester: Pytester+    ) -> None:+        """An ImportError raised by a plugin requested via ``pytest_plugins``+        in an initial conftest is reported like an ImportError in the conftest+        itself, with the same exit code."""+        pytester.syspathinsert()+        pytester.makeconftest("pytest_plugins = 'broken_plugin'")+        pytester.makepyfile(+            broken_plugin="raise ImportError('broken plugin')",+            test_foo="def test_foo(): pass",+        )+        result = pytester.runpytest_subprocess()+        assert result.ret == ExitCode.USAGE_ERROR+        result.stderr.fnmatch_lines(+            [+                "ImportError while loading conftest *conftest.py*",+                "*Error importing plugin*broken_plugin*broken plugin*",+            ]+        )+        result.stderr.no_fnmatch_line("*Traceback (most recent call last)*")++    def test_conftest_pytest_plugins_bare_import_error_exit_code(+        self, pytester: Pytester+    ) -> None:+        """Same as above, but the plugin raises an ImportError without+        arguments."""+        pytester.syspathinsert()+        pytester.makeconftest("pytest_plugins = 'broken_plugin'")+        pytester.makepyfile(+            broken_plugin="raise ImportError",+            test_foo="def test_foo(): pass",+        )+        result = pytester.runpytest_subprocess()+        assert result.ret == ExitCode.USAGE_ERROR+        result.stderr.fnmatch_lines(+            [+                "ImportError while loading conftest *conftest.py*",+                '*Error importing plugin "broken_plugin":*',+            ]+        )+        result.stderr.no_fnmatch_line("*Traceback (most recent call last)*")++    def test_conftest_pytest_plugins_import_error_with_help(+        self, pytester: Pytester+    ) -> None:+        """``--help`` still works when a plugin requested via ``pytest_plugins``+        in an initial conftest fails to import, same as for a conftest which+        fails to import itself."""+        pytester.syspathinsert()+        pytester.makeconftest("pytest_plugins = 'broken_plugin'")+        pytester.makepyfile(broken_plugin="raise ImportError('broken plugin')")+        result = pytester.runpytest_subprocess("--help")+        assert result.ret == ExitCode.OK+        result.stdout.fnmatch_lines(+            [+                "*--version*",+                "*warning*could not load initial conftests*conftest.py*",+            ]+        )+     def test_early_skip(self, pytester: Pytester) -> None:         pytester.mkdir("xyz")         pytester.makeconftest( 
Merged fix · PR #14824+268 −33
changelog/993.breaking.rstnew file mode 100644index 000000000..27896af84@@ -0,0 +1,6 @@+Plugin import failures at startup are now reported and classified instead of escaping as a raw traceback with the accidental exit code ``1``:++* a plugin that cannot be found -- via ``-p``, ``pytest_plugins`` or ``PYTEST_PLUGINS`` -- exits with :class:`pytest.ExitCode` ``USAGE_ERROR`` (``4``), like a ``conftest.py`` that fails to import;+* a plugin that is found but raises while importing -- including a broken ``pytest11`` entry point or a missing plugin dependency -- exits with :class:`pytest.ExitCode` ``INTERNAL_ERROR`` (``3``), with the traceback preserved.++:func:`pytest.main` now returns these codes instead of raising ``ImportError``. Also fixed an ``IndexError`` from pytest's own internals when the plugin raised an exception with no arguments.doc/en/reference/exit-codes.rstindex 485bd4fe2..fff25c96e 100644@@ -8,8 +8,8 @@ Running ``pytest`` can result in seven different exit codes: :Exit code 0: All tests were collected and passed successfully :Exit code 1: Tests were collected and run but some of the tests failed :Exit code 2: Test execution was interrupted by the user-:Exit code 3: Internal error happened while executing tests-:Exit code 4: pytest command line usage error+:Exit code 3: Internal error happened while executing tests, or a plugin raised while importing+:Exit code 4: pytest command line usage error, including a plugin that cannot be found or a ``conftest.py`` that fails to import :Exit code 5: No tests were collected :Exit code 6: Maximum number of warnings exceeded (see :option:`--max-warnings`) src/_pytest/config/__init__.pyindex 8c6052bc4..75484f991 100644@@ -142,7 +142,17 @@ class ConftestImportFailure(Exception):         return f"{type(self.cause).__name__}: {self.cause} (from {self.path})"  -def filter_traceback_for_conftest_import_failure(+class PluginImportFailure(Exception):+    """A plugin was found, but raised while being imported.++    This is deliberately distinct from a plugin which could not be found at+    all: not finding it means pytest was pointed at something that isn't there,+    which is a :class:`UsageError`, while a plugin blowing up on import is a+    defect in the plugin and reported as an internal error.+    """+++def filter_traceback_for_import_failure(     entry: _pytest._code.TracebackEntry, ) -> bool:     """Filter tracebacks entries which point to pytest internals or importlib.@@ -153,13 +163,11 @@ def filter_traceback_for_conftest_import_failure(     return filter_traceback(entry) and "importlib" not in str(entry.path).split(os.sep)  -def print_conftest_import_error(e: ConftestImportFailure, file: TextIO) -> None:-    exc_info = ExceptionInfo.from_exception(e.cause)+def _print_import_error(header: str, cause: BaseException, file: TextIO) -> None:+    exc_info = ExceptionInfo.from_exception(cause)     tw = TerminalWriter(file)-    tw.line(f"ImportError while loading conftest '{e.path}'.", red=True)-    exc_info.traceback = exc_info.traceback.filter(-        filter_traceback_for_conftest_import_failure-    )+    tw.line(header, red=True)+    exc_info.traceback = exc_info.traceback.filter(filter_traceback_for_import_failure)     exc_repr = (         exc_info.getrepr(style="short", chain=False)         if exc_info.traceback@@ -170,6 +178,17 @@ def print_conftest_import_error(e: ConftestImportFailure, file: TextIO) -> None:         tw.line(line.rstrip(), red=True)  +def print_conftest_import_error(e: ConftestImportFailure, file: TextIO) -> None:+    _print_import_error(+        f"ImportError while loading conftest '{e.path}'.", e.cause, file+    )+++def print_plugin_import_error(e: PluginImportFailure, file: TextIO) -> None:+    assert e.__cause__ is not None, f"{e!r} must be raised `from` the original error"+    _print_import_error(f'Error while loading plugin "{e}".', e.__cause__, file)++ def print_usage_error(e: UsageError, file: TextIO) -> None:     tw = TerminalWriter(file)     for msg in e.args:@@ -232,6 +251,9 @@ def _main(         except ConftestImportFailure as e:             print_conftest_import_error(e, file=sys.stderr)             return ExitCode.USAGE_ERROR+        except PluginImportFailure as e:+            print_plugin_import_error(e, file=sys.stderr)+            return ExitCode.INTERNAL_ERROR          try:             ret: ExitCode | int = config.hook.pytest_cmdline_main(config=config)@@ -924,16 +946,46 @@ class PytestPluginManager(PluginManager):                 # testing/test_config.py::test_disable_plugin_autoload.                 __import__(importspec)                 mod = sys.modules[importspec]-        except ImportError as e:-            raise ImportError(-                f'Error importing plugin "{modname}": {e.args[0]}'-            ).with_traceback(e.__traceback__) from e-         except Skipped as e:             self.skipped_plugins.append((modname, e.msg or ""))+        except ModuleNotFoundError as e:+            if _is_missing_module(e, importspec):+                # The plugin itself is nowhere to be found - pytest was pointed+                # at something which does not exist, so this is a usage error.+                raise UsageError(f'Error importing plugin "{modname}": {e}') from e+            # Some *other* module the plugin imports is missing: the plugin was+            # found, so this is a defect in the plugin, not a usage error.+            raise PluginImportFailure(modname) from e+        except UsageError:+            raise+        except Exception as e:+            raise PluginImportFailure(modname) from e         else:             self.register(mod, modname) +    def load_setuptools_entrypoints(self, group: str, name: str | None = None) -> int:+        """:meta private:"""+        try:+            return super().load_setuptools_entrypoints(group, name=name)+        except UsageError:+            raise+        except Exception as e:+            # An installed plugin which cannot be loaded is a defect in that+            # plugin - the user did nothing wrong by having it installed.+            raise PluginImportFailure(name or group) from e+++def _is_missing_module(e: ModuleNotFoundError, importspec: str) -> bool:+    """Whether ``e`` means that ``importspec`` itself could not be found.++    A ``ModuleNotFoundError`` naming some other module means the plugin was+    located but one of its own imports is unsatisfied.+    """+    if e.name is None:+        return False+    # A missing parent package also means importspec cannot be found.+    return e.name == importspec or importspec.startswith(f"{e.name}.")+  def _get_plugin_specs_as_list(     specs: types.ModuleType | str | Sequence[str] | None,testing/acceptance_test.pyindex f941cbe19..3983bd000 100644@@ -13,6 +13,7 @@ import types import setuptools  from _pytest.config import ExitCode+from _pytest.monkeypatch import MonkeyPatch from _pytest.pathlib import symlink_or_skip from _pytest.pytester import Pytester import pytest@@ -510,9 +511,10 @@ class TestGeneralUsage:     ) -> None:         """Test that str values passed to main() as `plugins` arg are         interpreted as module names to be imported and registered (#855)."""-        with pytest.raises(ImportError) as excinfo:-            pytest.main([str(pytester.path)], plugins=["invalid.module"])-        assert "invalid" in str(excinfo.value)+        # A plugin which cannot be found is a usage error, reported through the+        # return value rather than raised out of pytest.main() (#993).+        ret = pytest.main([str(pytester.path)], plugins=["invalid.module"])+        assert ret == ExitCode.USAGE_ERROR          p = pytester.path.joinpath("test_test_plugins_given_as_strings.py")         p.write_text("def test_foo(): pass", encoding="utf-8")@@ -1088,6 +1090,138 @@ def test_zipimport_hook(pytester: Pytester) -> None:     result.stdout.no_fnmatch_line("*INTERNALERROR>*")  +class TestStartupPluginImportErrors:+    """Exit codes for plugins which fail to load at startup (#993).++    A plugin which cannot be found means pytest was pointed at something which+    is not there, which is a usage error; a plugin which is found but blows up+    while importing is a defect in the plugin, reported as an internal error.+    """++    @pytest.fixture+    def broken_plugin(self, pytester: Pytester) -> Pytester:+        pytester.syspathinsert()+        pytester.makepyfile(myplugin="raise ValueError('plugin is broken')")+        pytester.makepyfile("def test_foo(): pass")+        return pytester++    @pytest.fixture+    def missing_plugin(self, pytester: Pytester) -> Pytester:+        pytester.syspathinsert()+        pytester.makepyfile("def test_foo(): pass")+        return pytester++    def test_missing_via_cmdline(self, missing_plugin: Pytester) -> None:+        result = missing_plugin.runpytest("-p", "nosuchplugin")+        assert result.ret == ExitCode.USAGE_ERROR+        result.stderr.fnmatch_lines(['*Error importing plugin "nosuchplugin"*'])++    def test_missing_via_conftest(self, missing_plugin: Pytester) -> None:+        missing_plugin.makeconftest("pytest_plugins = ['nosuchplugin']")+        result = missing_plugin.runpytest()+        assert result.ret == ExitCode.USAGE_ERROR++    def test_missing_via_env(+        self, missing_plugin: Pytester, monkeypatch: MonkeyPatch+    ) -> None:+        monkeypatch.setenv("PYTEST_PLUGINS", "nosuchplugin")+        result = missing_plugin.runpytest()+        assert result.ret == ExitCode.USAGE_ERROR++    def test_broken_via_cmdline(self, broken_plugin: Pytester) -> None:+        result = broken_plugin.runpytest("-p", "myplugin")+        assert result.ret == ExitCode.INTERNAL_ERROR+        result.stderr.fnmatch_lines(+            [+                'Error while loading plugin "myplugin".',+                "*myplugin.py:1: in <module>*",+                "E*ValueError: plugin is broken",+            ]+        )++    def test_broken_via_conftest(self, broken_plugin: Pytester) -> None:+        broken_plugin.makeconftest("pytest_plugins = ['myplugin']")+        result = broken_plugin.runpytest()+        assert result.ret == ExitCode.INTERNAL_ERROR++    def test_broken_via_env(+        self, broken_plugin: Pytester, monkeypatch: MonkeyPatch+    ) -> None:+        monkeypatch.setenv("PYTEST_PLUGINS", "myplugin")+        result = broken_plugin.runpytest()+        assert result.ret == ExitCode.INTERNAL_ERROR++    def test_usage_error_passes_through(self, pytester: Pytester) -> None:+        """A plugin raising UsageError at import keeps its usage-error semantics."""+        pytester.syspathinsert()+        pytester.makepyfile(+            myplugin="import pytest\nraise pytest.UsageError('config trouble')"+        )+        result = pytester.runpytest("-p", "myplugin")+        assert result.ret == ExitCode.USAGE_ERROR+        result.stderr.fnmatch_lines(["ERROR: config trouble*"])++    def test_broken_via_entry_point(+        self, pytester: Pytester, monkeypatch: MonkeyPatch+    ) -> None:+        monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False)++        class DummyEntryPoint:+            name = "myplugin"+            group = "pytest11"++            def load(self):+                raise ValueError("plugin is broken")++        class Distribution:+            version = "1.0"+            files = ("foo.txt",)+            metadata = {"name": "foo"}+            entry_points = (DummyEntryPoint(),)++        monkeypatch.setattr(+            importlib.metadata, "distributions", lambda: (Distribution(),)+        )+        pytester.makepyfile("def test_foo(): pass")+        result = pytester.runpytest()+        assert result.ret == ExitCode.INTERNAL_ERROR++    def test_import_error_without_args(self, pytester: Pytester) -> None:+        """A bare ``raise ImportError`` used to crash with an IndexError (#993)."""+        pytester.syspathinsert()+        pytester.makepyfile(myplugin="raise ImportError")+        pytester.makepyfile("def test_foo(): pass")+        result = pytester.runpytest("-p", "myplugin")+        assert result.ret == ExitCode.INTERNAL_ERROR+        result.stderr.no_fnmatch_line("*IndexError*")+        result.stderr.fnmatch_lines(['Error while loading plugin "myplugin".'])++    def test_missing_dependency_is_not_a_usage_error(self, pytester: Pytester) -> None:+        """The plugin was found; one of *its* imports is unsatisfied (#993)."""+        pytester.syspathinsert()+        pytester.makepyfile(myplugin="import nosuchdependency")+        pytester.makepyfile("def test_foo(): pass")+        result = pytester.runpytest("-p", "myplugin")+        assert result.ret == ExitCode.INTERNAL_ERROR++    def test_missing_submodule_of_existing_package(self, pytester: Pytester) -> None:+        """The package exists but the requested plugin module within it does not."""+        pytester.syspathinsert()+        pytester.mkpydir("mypkg")+        pytester.makepyfile("def test_foo(): pass")+        result = pytester.runpytest("-p", "mypkg.nosuchmodule")+        assert result.ret == ExitCode.USAGE_ERROR++    def test_conftest_import_failure_stays_a_usage_error(+        self, pytester: Pytester+    ) -> None:+        """conftest.py is not a plugin; it keeps reporting a usage error (#993)."""+        pytester.makeconftest("raise ValueError('conftest is broken')")+        pytester.makepyfile("def test_foo(): pass")+        result = pytester.runpytest()+        assert result.ret == ExitCode.USAGE_ERROR++ def test_import_plugin_unicode_name(pytester: Pytester) -> None:     pytester.makepyfile(myplugin="")     pytester.makepyfile("def test(): pass")testing/python/collect.pyindex c9023f985..dddd15b8f 100644@@ -8,6 +8,7 @@ from typing import Any  import _pytest._code from _pytest.config import ExitCode+from _pytest.config.exceptions import UsageError from _pytest.main import Session from _pytest.monkeypatch import MonkeyPatch from _pytest.nodes import Collector@@ -80,7 +81,7 @@ class TestModule:      def test_module_considers_pluginmanager_at_import(self, pytester: Pytester) -> None:         modcol = pytester.getmodulecol("pytest_plugins='xasdlkj',")-        with pytest.raises(ImportError):+        with pytest.raises(UsageError):             modcol.obj()      def test_invalid_test_module_name(self, pytester: Pytester) -> None:testing/test_config.pyindex 2a05deb31..dad1653e2 100644@@ -22,6 +22,7 @@ from _pytest.config import ConftestImportFailure from _pytest.config import console_main from _pytest.config import ExitCode from _pytest.config import parse_warning_filter+from _pytest.config import PluginImportFailure from _pytest.config.argparsing import get_ini_default_for_type from _pytest.config.argparsing import Parser from _pytest.config.exceptions import UsageError@@ -1858,7 +1859,35 @@ def test_setuptools_importerror_issue1479(         return (Distribution(),)      monkeypatch.setattr(importlib.metadata, "distributions", distributions)-    with pytest.raises(ImportError):+    with pytest.raises(PluginImportFailure) as excinfo:+        pytester.parseconfig()+    assert "Don't hide me!" in str(excinfo.value.__cause__)+++def test_setuptools_usage_error_passes_through(+    pytester: Pytester, monkeypatch: MonkeyPatch+) -> None:+    """A UsageError from an entry-point plugin is not reclassified (#993)."""+    monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False)++    class DummyEntryPoint:+        name = "mytestplugin"+        group = "pytest11"++        def load(self):+            raise UsageError("bad usage")++    class Distribution:+        version = "1.0"+        files = ("foo.txt",)+        metadata = {"name": "foo"}+        entry_points = (DummyEntryPoint(),)++    def distributions():+        return (Distribution(),)++    monkeypatch.setattr(importlib.metadata, "distributions", distributions)+    with pytest.raises(UsageError, match="bad usage"):         pytester.parseconfig()  testing/test_pluginmanager.pyindex 70c1cde28..03887de61 100644@@ -7,8 +7,11 @@ import shutil import sys import types +from _pytest._code import ExceptionInfo+from _pytest.config import _is_missing_module from _pytest.config import Config from _pytest.config import ExitCode+from _pytest.config import PluginImportFailure from _pytest.config import PytestPluginManager from _pytest.config.exceptions import UsageError from _pytest.main import Session@@ -252,13 +255,22 @@ def test_importplugin_error_message(         test_traceback()         """     )-    with pytest.raises(ImportError) as excinfo:+    with pytest.raises(PluginImportFailure) as excinfo:         pytestpm.import_plugin("qwe") -    assert str(excinfo.value).endswith(-        'Error importing plugin "qwe": Not possible to import: ☺'-    )-    assert "in test_traceback" in str(excinfo.traceback[-1])+    assert excinfo.value.args == ("qwe",)+    # The original error and traceback must stay reachable through the cause,+    # otherwise there is no way to tell where in the plugin things went wrong.+    assert excinfo.value.__cause__ is not None+    assert str(excinfo.value.__cause__) == "Not possible to import: ☺"+    cause = ExceptionInfo.from_exception(excinfo.value.__cause__)+    assert "in test_traceback" in str(cause.traceback[-1])+++def test_is_missing_module_without_name() -> None:+    """A ModuleNotFoundError raised without a module name cannot be attributed+    to the requested plugin, so it counts as a defect in the plugin."""+    assert not _is_missing_module(ModuleNotFoundError("boom"), "myplugin")   class TestPytestPluginManager:@@ -322,7 +334,7 @@ class TestPytestPluginManager:         self, monkeypatch: MonkeyPatch, pytestpm: PytestPluginManager     ) -> None:         monkeypatch.setenv("PYTEST_PLUGINS", "nonexisting", prepend=",")-        with pytest.raises(ImportError):+        with pytest.raises(UsageError):             pytestpm.consider_env()      def test_consider_env_entry_point_name(@@ -458,9 +470,9 @@ class TestPytestPluginManager:     def test_import_plugin_importname(         self, pytester: Pytester, pytestpm: PytestPluginManager     ) -> None:-        with pytest.raises(ImportError):+        with pytest.raises(UsageError):             pytestpm.import_plugin("qweqwex.y")-        with pytest.raises(ImportError):+        with pytest.raises(UsageError):             pytestpm.import_plugin("pytest_qweqwx.y")          pytester.syspathinsert()@@ -480,9 +492,9 @@ class TestPytestPluginManager:     def test_import_plugin_dotted_name(         self, pytester: Pytester, pytestpm: PytestPluginManager     ) -> None:-        with pytest.raises(ImportError):+        with pytest.raises(UsageError):             pytestpm.import_plugin("qweqwex.y")-        with pytest.raises(ImportError):+        with pytest.raises(UsageError):             pytestpm.import_plugin("pytest_qweqwex.y")          pytester.syspathinsert()@@ -503,17 +515,17 @@ class TestPytestPluginManager:             root=pytester.path,             consider_namespace_packages=False,         )-        with pytest.raises(ImportError):+        with pytest.raises(UsageError):             pytestpm.consider_conftest(mod, registration_name="unused")   class TestPytestPluginManagerBootstrapping:     def test_preparse_args(self, pytestpm: PytestPluginManager) -> None:-        with pytest.raises(ImportError):+        with pytest.raises(UsageError):             pytestpm.consider_preparse(["xyz", "-p", "hello123"])          # Handles -p without space (#3532).-        with pytest.raises(ImportError) as excinfo:+        with pytest.raises(UsageError) as excinfo:             pytestpm.consider_preparse(["-phello123"])         assert '"hello123"' in excinfo.value.args[0]         pytestpm.consider_preparse(["-pno:hello123"])testing/test_session.pyindex be1e66112..947388378 100644@@ -2,6 +2,7 @@ from __future__ import annotations  from _pytest.config import ExitCode+from _pytest.config.exceptions import UsageError from _pytest.monkeypatch import MonkeyPatch from _pytest.pytester import Pytester import pytest@@ -254,7 +255,7 @@ class TestNewSession(SessionTests):   def test_plugin_specify(pytester: Pytester) -> None:-    with pytest.raises(ImportError):+    with pytest.raises(UsageError):         pytester.parseconfig("-p", "nqweotexistent")     # pytest.raises(ImportError,     #    "config.do_configure(config)"