From f7f60aa06ada898e3fb66df2bc0147c1024c6b1f Mon Sep 17 00:00:00 2001 From: Hood Chatham Date: Wed, 17 Apr 2024 10:22:30 +0200 Subject: [PATCH 1/2] Add a test module for run_in_pyodide functions This makes name resolution a bit nicer. If we define a class A in the test, 1. A.__module__ is no longer "builtins" 2. sys.modules[A.__module__] points back to our current global scope 3. __file__ now has the correct value --- pytest_pyodide/_decorator_in_pyodide.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/pytest_pyodide/_decorator_in_pyodide.py b/pytest_pyodide/_decorator_in_pyodide.py index 638c717..92bdd67 100644 --- a/pytest_pyodide/_decorator_in_pyodide.py +++ b/pytest_pyodide/_decorator_in_pyodide.py @@ -17,9 +17,11 @@ """ import pickle +import sys from base64 import b64decode, b64encode from inspect import isclass from io import BytesIO +from types import ModuleType from typing import Any import pyodide_js @@ -108,9 +110,15 @@ async def run_in_pyodide_main( mod = decode(mod64) args: tuple[Any] = decode(args64) + # Set up test module + MODULE_NAME = "test_module" + module = ModuleType(module_filename) + module.__file__ = module_filename + sys.modules[MODULE_NAME] = module + d = module.__dict__ + # Compile and execute the ast co = compile(mod, module_filename, "exec") - d: dict[str, Any] = {} exec(co, d) try: @@ -142,6 +150,9 @@ def get_locals(frame): except ImportError: pass return (1, encode(e)) + finally: + # Remove test module + del sys.modules[MODULE_NAME] __all__ = ["PyodideHandle", "encode"] From 033bc2102811ce72d0d06882242c0a82710fb28a Mon Sep 17 00:00:00 2001 From: Hood Chatham Date: Wed, 17 Apr 2024 17:38:07 +0200 Subject: [PATCH 2/2] Address review comment --- pytest_pyodide/_decorator_in_pyodide.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/pytest_pyodide/_decorator_in_pyodide.py b/pytest_pyodide/_decorator_in_pyodide.py index 92bdd67..23da52e 100644 --- a/pytest_pyodide/_decorator_in_pyodide.py +++ b/pytest_pyodide/_decorator_in_pyodide.py @@ -97,6 +97,9 @@ def decode(x: str) -> Any: return Unpickler(BytesIO(b64decode(x))).load() +TEST_MODULE_NAME = "__test_module__" + + async def run_in_pyodide_main( mod64: str, args64: str, module_filename: str, func_name: str, async_func: bool ) -> tuple[int, str]: @@ -111,10 +114,9 @@ async def run_in_pyodide_main( args: tuple[Any] = decode(args64) # Set up test module - MODULE_NAME = "test_module" module = ModuleType(module_filename) module.__file__ = module_filename - sys.modules[MODULE_NAME] = module + sys.modules[TEST_MODULE_NAME] = module d = module.__dict__ # Compile and execute the ast @@ -152,7 +154,7 @@ def get_locals(frame): return (1, encode(e)) finally: # Remove test module - del sys.modules[MODULE_NAME] + del sys.modules[TEST_MODULE_NAME] __all__ = ["PyodideHandle", "encode"]