Skip to content

Commit

Permalink
Add a test and comments, update changelog
Browse files Browse the repository at this point in the history
  • Loading branch information
hoodmane committed Nov 11, 2024
1 parent 27a16f3 commit 8a26541
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
3 changes: 3 additions & 0 deletions docs/project/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ myst:
- {{ Fix }} Fix sessionStorage-related crash when running in sandboxed iframe.
{pr}`5186`

- {{ Fix }} `JsFinder.find_spec()` no longer crashes when called during pytest test collection.
{pr}`5170`

### Packages

- Upgraded `crc32c` to 2.7.1 {pr}`5169`
Expand Down
3 changes: 3 additions & 0 deletions src/py/_pyodide/_importhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ def find_spec(
try:
parent_module = sys.modules[parent]
except KeyError:
# Note: This will never happen when we're called from importlib,
# but pytest hits this codepath. See
# `test_importhook_called_from_pytest`.
return None
if not isinstance(parent_module, JsProxy):
# Not one of us.
Expand Down
21 changes: 21 additions & 0 deletions src/tests/test_pyodide.py
Original file line number Diff line number Diff line change
Expand Up @@ -1516,6 +1516,27 @@ def test_module_not_found_note(selenium_standalone):
assert len(e.value.__notes__) == 1


@run_in_pyodide
def test_importhook_called_from_pytest(selenium):
"""
Whenever importlib itself resolves `import a.b`, it splits on the . and
first imports `a` and then `a.b`. However, pytest does not, it calls
`find_spec("a.b")` directly here:
https://github.com/pytest-dev/pytest/blob/ea0fa639445ae08616edd2c15189a1a76168f018/src/_pytest/pathlib.py#L693-L698
This previously could lead to crashes in `JsFinder`.
"""
import sys

def _import_module_using_spec(module_name):
"""Modeled on a fragment of _pytest.pathlib._import_module_using_spec"""
for meta_importer in sys.meta_path:
spec = meta_importer.find_spec(module_name, path=[])

# Assertion: This should not raise KeyError.
_import_module_using_spec("a.b")


def test_args(selenium_standalone_noload):
selenium = selenium_standalone_noload
assert selenium.run_js(
Expand Down

0 comments on commit 8a26541

Please sign in to comment.