Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changed importError to ModuleNotFoundError #12220

Merged
merged 14 commits into from Apr 26, 2024
2 changes: 1 addition & 1 deletion src/_pytest/outcomes.py
Expand Up @@ -225,7 +225,7 @@
warnings.simplefilter("ignore")
try:
__import__(modname)
except ImportError as exc:
except ModuleNotFoundError as exc:

Check warning on line 228 in src/_pytest/outcomes.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/outcomes.py#L228

Added line #L228 was not covered by tests
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's add a new parameter to this function, *, exc_type: Type[ImportError] = ModuleNotFoundError and use it here:

Suggested change
except ModuleNotFoundError as exc:
except exc_type as exc:

This way we provide a escape hatch to users which rely on the old behavior.

Also please update the docs, describing the parameters and explicitly showing an example for users that want the old behavior.

if reason is None:
reason = f"could not import {modname!r}: {exc}"
raise Skipped(reason, allow_module_level=True) from None
Expand Down
24 changes: 24 additions & 0 deletions testing/test_runner.py
@@ -1,4 +1,5 @@
# mypy: allow-untyped-defs
import builtins
from functools import partial
import inspect
import os
Expand All @@ -7,6 +8,8 @@
import types
from typing import Dict
from typing import List
from typing import Mapping
from typing import Sequence
from typing import Tuple
from typing import Type

Expand Down Expand Up @@ -762,6 +765,27 @@ def test_importorskip_imports_last_module_part() -> None:
assert os.path == ospath


def test_importorskip_importError_Exception() -> None:
## Mocking the import function to raise a importError
realimport = builtins.__import__
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use monkeypatch instead of hand-rolling this.


def myimport(
name: str,
globals: Mapping[str, object] | None = None,
locals: Mapping[str, object] | None = None,
fromlist: Sequence[str] = (),
level: int = 0,
) -> types.ModuleType:
raise ImportError

builtins.__import__ = myimport

with pytest.raises(ImportError):
pytest.importorskip("abcdefghi")

builtins.__import__ = realimport
shekhuverma marked this conversation as resolved.
Show resolved Hide resolved


def test_importorskip_dev_module(monkeypatch) -> None:
try:
mod = types.ModuleType("mockmodule")
Expand Down