File
Blob: src/workerd/server/tests/python/pytest/tests/test_import_from_javascript.py
| 1 | import pytest |
| 2 | from js import setTimeout |
| 3 | from workers import import_from_javascript |
| 4 | |
| 5 | from pyodide import __version__ |
| 6 | from pyodide.ffi import create_once_callable |
| 7 | |
| 8 | |
| 9 | def test_import_from_javascript(): |
| 10 | # Import the workers module from cloudflare:workers |
| 11 | workers_module = import_from_javascript("cloudflare:workers") |
| 12 | |
| 13 | # Test that we can access the imported module's exports |
| 14 | assert hasattr(workers_module, "env"), "env property should exist" |
| 15 | assert hasattr(workers_module, "withEnv"), "withEnv function should exist" |
| 16 | assert hasattr(workers_module, "waitUntil"), "waitUntil function should exist" |
| 17 | |
| 18 | # Test with actual env values |
| 19 | assert workers_module.env.TEST_VALUE == "TEST_STRING", ( |
| 20 | "TEST_VALUE should be correctly set" |
| 21 | ) |
| 22 | |
| 23 | # Test sockets module |
| 24 | sockets_module = import_from_javascript("cloudflare:sockets") |
| 25 | assert hasattr(sockets_module, "connect"), ( |
| 26 | "sockets_module should have 'connect' attribute" |
| 27 | ) |
| 28 | |
| 29 | def f(): |
| 30 | pass |
| 31 | |
| 32 | setTimeout(create_once_callable(f), 1) |
| 33 | |
| 34 | |
| 35 | @pytest.mark.skipif(__version__ == "0.26.0a2", reason="Requires JSPI") |
| 36 | def test_import_vectorize(): |
| 37 | # Assert that imports that depend on JSPI work as expected |
| 38 | vectorize = import_from_javascript("cloudflare:vectorize") |
| 39 | assert hasattr(vectorize, "DistanceMetric") |
| 40 | |
| 41 | |
| 42 | def test_import_failures(): |
| 43 | # Try importing an unsafe module which should fail |
| 44 | with pytest.raises(ImportError): |
| 45 | import_from_javascript("internal:unsafe-eval") |
| 46 | |
| 47 | # Assert that non existent modules throw ImportError |
| 48 | with pytest.raises(ImportError): |
| 49 | import_from_javascript("crypto") |