Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/_pytest/outcomes.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ def importorskip(
warnings.simplefilter("ignore")
try:
__import__(modname)
except ImportError as exc:
except ModuleNotFoundError as exc:
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
Original file line number Diff line number Diff line change
@@ -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


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