Skip to content

Commit

Permalink
Fix errors when using --import-mode=importlib with dataclasses or p…
Browse files Browse the repository at this point in the history
…ickle

Fixes pytest-dev#7856, fixes pytest-dev#7859
  • Loading branch information
tadeu committed Oct 7, 2020
1 parent 95917f8 commit c08f4d1
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 0 deletions.
1 change: 1 addition & 0 deletions AUTHORS
Expand Up @@ -90,6 +90,7 @@ Dmitry Pribysh
Duncan Betts
Edison Gustavo Muenz
Edoardo Batini
Edson Tadeu M. Manoel
Eduardo Schettino
Eli Boyarski
Elizaveta Shashkova
Expand Down
1 change: 1 addition & 0 deletions changelog/7856.bugfix.rst
@@ -0,0 +1 @@
An error with ``--import-mode=importlib`` used with modules containing dataclasses or pickle was fixed.
1 change: 1 addition & 0 deletions src/_pytest/pathlib.py
Expand Up @@ -480,6 +480,7 @@ def import_path(
"Can't find module {} at location {}".format(module_name, str(path))
)
mod = importlib.util.module_from_spec(spec)
sys.modules[module_name] = mod
spec.loader.exec_module(mod) # type: ignore[union-attr]
return mod

Expand Down
51 changes: 51 additions & 0 deletions testing/test_pathlib.py
Expand Up @@ -401,3 +401,54 @@ def test_commonpath() -> None:
assert commonpath(subpath, path) == path
assert commonpath(Path(str(path) + "suffix"), path) == path.parent
assert commonpath(path, path.parent.parent) == path.parent.parent


@pytest.fixture
def module_with_dataclass(tmpdir):
fn = tmpdir.join("test_dataclass.py")
fn.write(
dedent(f"""\
{'from __future__ import annotations' if (3, 7) <= sys.version_info < (3, 10) else ''}
from dataclasses import dataclass
@dataclass
class DataClass:
value: str
def test_dataclass():
assert DataClass(value='test').value == 'test'
"""
)
)
return fn


@pytest.fixture
def module_with_pickle(tmpdir):
fn = tmpdir.join("test_dataclass.py")
fn.write(
dedent("""\
import pickle
def do_action():
pass
def test_pickle():
pickle.dumps(do_action)
"""
)
)
return fn


def test_importmode_importlib_with_dataclass(module_with_dataclass):
"""Ensure that importlib mode works with a module containing dataclasses"""
module = import_path(module_with_dataclass, mode="importlib")
module.test_dataclass()


def test_importmode_importlib_with_pickle(module_with_pickle):
"""Ensure that importlib mode works with pickle"""
module = import_path(module_with_pickle, mode="importlib")
module.test_pickle()

0 comments on commit c08f4d1

Please sign in to comment.