Skip to content

Commit abcc1cf

Browse files
committed
Fix error with --import-mode=importlib and modules containing dataclasses
fixes #7856
1 parent 95917f8 commit abcc1cf

File tree

4 files changed

+30
-0
lines changed

4 files changed

+30
-0
lines changed

AUTHORS

+1
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ Dmitry Pribysh
9090
Duncan Betts
9191
Edison Gustavo Muenz
9292
Edoardo Batini
93+
Edson Tadeu M. Manoel
9394
Eduardo Schettino
9495
Eli Boyarski
9596
Elizaveta Shashkova

changelog/7856.bugfix.rst

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
An error with ``--import-mode=importlib`` used with modules containing dataclasses was fixed.

src/_pytest/pathlib.py

+1
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,7 @@ def import_path(
480480
"Can't find module {} at location {}".format(module_name, str(path))
481481
)
482482
mod = importlib.util.module_from_spec(spec)
483+
sys.modules[module_name] = mod
483484
spec.loader.exec_module(mod) # type: ignore[union-attr]
484485
return mod
485486

testing/test_pathlib.py

+27
Original file line numberDiff line numberDiff line change
@@ -401,3 +401,30 @@ def test_commonpath() -> None:
401401
assert commonpath(subpath, path) == path
402402
assert commonpath(Path(str(path) + "suffix"), path) == path.parent
403403
assert commonpath(path, path.parent.parent) == path.parent.parent
404+
405+
406+
@pytest.fixture
407+
def module_with_dataclass(tmpdir):
408+
fn = tmpdir.join("test_dataclass.py")
409+
fn.write(
410+
dedent("""\
411+
from __future__ import annotations
412+
413+
from dataclasses import dataclass
414+
415+
@dataclass
416+
class DataClass:
417+
value: str
418+
419+
def test_dataclass():
420+
assert DataClass(value='test').value == 'test'
421+
"""
422+
)
423+
)
424+
return fn
425+
426+
427+
def test_importmode_importlib_with_dataclass(module_with_dataclass):
428+
"""Ensure that importlib mode works with a module containing dataclasses"""
429+
module = import_path(module_with_dataclass, mode="importlib")
430+
module.test_dataclass()

0 commit comments

Comments
 (0)