Skip to content

Support the importlib.resources files API in rewritten files #9173

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

Merged
merged 4 commits into from
Oct 9, 2021
Merged
Show file tree
Hide file tree
Changes from 3 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
1 change: 1 addition & 0 deletions changelog/9169.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Support for the ``files`` API from ``importlib.resources`` within rewritten files.
12 changes: 10 additions & 2 deletions src/_pytest/assertion/rewrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def __init__(self, config: Config) -> None:
except ValueError:
self.fnpats = ["test_*.py", "*_test.py"]
self.session: Optional[Session] = None
self._rewritten_names: Set[str] = set()
self._rewritten_names: Dict[str, Path] = {}
self._must_rewrite: Set[str] = set()
# flag to guard against trying to rewrite a pyc file while we are already writing another pyc file,
# which might result in infinite recursion (#3506)
Expand Down Expand Up @@ -134,7 +134,7 @@ def exec_module(self, module: types.ModuleType) -> None:
fn = Path(module.__spec__.origin)
state = self.config.stash[assertstate_key]

self._rewritten_names.add(module.__name__)
self._rewritten_names[module.__name__] = fn

# The requested module looks like a test file, so rewrite it. This is
# the most magical part of the process: load the source, rewrite the
Expand Down Expand Up @@ -276,6 +276,14 @@ def get_data(self, pathname: Union[str, bytes]) -> bytes:
with open(pathname, "rb") as f:
return f.read()

if sys.version_info >= (3, 9):
Copy link
Contributor

Choose a reason for hiding this comment

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

Users of Python 3.8 and earlier can also get the files support by using importlib_resources backport. Are you okay with this functionality not being supported in those environments?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm personally fine with that 😊


def get_resource_reader(self, name: str) -> importlib.abc.TraversableResources: # type: ignore
from types import SimpleNamespace
from importlib.readers import FileReader

return FileReader(SimpleNamespace(path=self._rewritten_names[name]))


def _write_pyc_fp(
fp: IO[bytes], source_stat: os.stat_result, co: types.CodeType
Expand Down
28 changes: 28 additions & 0 deletions testing/test_assertrewrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -795,6 +795,34 @@ def test_zipfile(self, pytester: Pytester) -> None:
)
assert pytester.runpytest().ret == ExitCode.NO_TESTS_COLLECTED

@pytest.mark.skipif(
sys.version_info < (3, 9),
reason="importlib.resources.files was introduced in 3.9",
)
def test_load_resource_via_files_with_rewrite(self, pytester: Pytester) -> None:
example = pytester.path.joinpath("demo") / "example"
init = pytester.path.joinpath("demo") / "__init__.py"
pytester.makepyfile(
**{
"demo/__init__.py": """
from importlib.resources import files

def load():
return files(__name__)
""",
"test_load": f"""
pytest_plugins = ["demo"]

def test_load():
from demo import load
assert list(str(i) for i in load().iterdir()) == [{str(example)!r}, {str(init)!r}]
""",
}
)
example.mkdir()

assert pytester.runpytest("-vv").ret == ExitCode.OK

def test_readonly(self, pytester: Pytester) -> None:
sub = pytester.mkdir("testing")
sub.joinpath("test_readonly.py").write_bytes(
Expand Down