Skip to content

Commit ac2cc44

Browse files
committed
Fix errors when using --import-mode=importlib with dataclasses or pickle
Fixes #7856, fixes #7859
1 parent 95917f8 commit ac2cc44

File tree

4 files changed

+56
-0
lines changed

4 files changed

+56
-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 or pickle 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

+53
Original file line numberDiff line numberDiff line change
@@ -401,3 +401,56 @@ 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+
f"""
412+
{'from __future__ import annotations' if (3, 7) <= sys.version_info < (3, 10) else ''}
413+
414+
from dataclasses import dataclass
415+
416+
@dataclass
417+
class DataClass:
418+
value: str
419+
420+
def test_dataclass():
421+
assert DataClass(value='test').value == 'test'
422+
"""
423+
)
424+
)
425+
return fn
426+
427+
428+
@pytest.fixture
429+
def module_with_pickle(tmpdir):
430+
fn = tmpdir.join("test_dataclass.py")
431+
fn.write(
432+
dedent(
433+
"""
434+
import pickle
435+
436+
def do_action():
437+
pass
438+
439+
def test_pickle():
440+
pickle.dumps(do_action)
441+
"""
442+
)
443+
)
444+
return fn
445+
446+
447+
def test_importmode_importlib_with_dataclass(module_with_dataclass):
448+
"""Ensure that importlib mode works with a module containing dataclasses"""
449+
module = import_path(module_with_dataclass, mode="importlib")
450+
module.test_dataclass() # type: ignore[attr-defined]
451+
452+
453+
def test_importmode_importlib_with_pickle(module_with_pickle):
454+
"""Ensure that importlib mode works with pickle"""
455+
module = import_path(module_with_pickle, mode="importlib")
456+
module.test_pickle() # type: ignore[attr-defined]

0 commit comments

Comments
 (0)