File
Blob: src/workerd/server/tests/python/pytest/tests/test_env.py
| 1 | import pytest |
| 2 | from js import Date, Reflect |
| 3 | from workers import env, import_from_javascript, patch_env |
| 4 | |
| 5 | from pyodide import __version__ |
| 6 | from pyodide.ffi import create_proxy, to_js |
| 7 | |
| 8 | if __version__ == "0.26.0a2": |
| 9 | pytest.skip("Not supported on 0.26.0a2", allow_module_level=True) |
| 10 | |
| 11 | |
| 12 | @pytest.mark.asyncio |
| 13 | async def test_memory_cache(): |
| 14 | # Test that cache exists and is accessible |
| 15 | assert env.CACHE, "env.CACHE should exist" |
| 16 | |
| 17 | # Test accessing the cache |
| 18 | async def memory_cache_read(x): |
| 19 | return to_js( |
| 20 | { |
| 21 | "value": 123, |
| 22 | "expiration": Date.now() + 10000, |
| 23 | } |
| 24 | ) |
| 25 | |
| 26 | cached = await env.CACHE.read( |
| 27 | "hello", |
| 28 | create_proxy(memory_cache_read), |
| 29 | ) |
| 30 | assert cached == 123, "cached value should be 123" |
| 31 | |
| 32 | |
| 33 | @pytest.mark.asyncio |
| 34 | async def test_with_env(): |
| 35 | workers_module = import_from_javascript("cloudflare:workers") |
| 36 | |
| 37 | # Test withEnv |
| 38 | async def import_with_env(): |
| 39 | workers_module = import_from_javascript("cloudflare:workers") |
| 40 | env = workers_module.env |
| 41 | return env.FOO |
| 42 | |
| 43 | result = await workers_module.withEnv(to_js({"FOO": 1}), import_with_env) |
| 44 | assert result == 1 |
| 45 | |
| 46 | |
| 47 | def check_normal(): |
| 48 | assert env.secret == "thisisasecret" |
| 49 | assert not hasattr(env, "NAME") |
| 50 | assert not hasattr(env, "place") |
| 51 | assert not hasattr(env, "extra") |
| 52 | assert set(Reflect.ownKeys(env).to_py()).issuperset({"secret"}) |
| 53 | |
| 54 | |
| 55 | def test_patch_env(): |
| 56 | check_normal() |
| 57 | |
| 58 | with patch_env(NAME=1, place="Somewhere"): |
| 59 | assert env.NAME == 1 |
| 60 | assert env.place == "Somewhere" |
| 61 | assert not hasattr(env, "secret") |
| 62 | |
| 63 | check_normal() |
| 64 | |
| 65 | with patch_env({"NAME": 1, "place": "Somewhere"}): |
| 66 | assert env.NAME == 1 |
| 67 | assert env.place == "Somewhere" |
| 68 | assert not hasattr(env, "secret") |
| 69 | |
| 70 | check_normal() |
| 71 | |
| 72 | with patch_env([("NAME", 1), ("place", "Somewhere")]): |
| 73 | assert env.NAME == 1 |
| 74 | assert env.place == "Somewhere" |
| 75 | assert not hasattr(env, "secret") |
| 76 | |
| 77 | check_normal() |
| 78 | |
| 79 | with patch_env({"NAME": 1, "place": "Somewhere"}, extra=22): |
| 80 | assert env.NAME == 1 |
| 81 | assert env.place == "Somewhere" |
| 82 | assert env.extra == 22 |
| 83 | assert not hasattr(env, "secret") |
| 84 | |
| 85 | check_normal() |
| 86 | |
| 87 | try: |
| 88 | with patch_env(NAME=1, place="Somewhere"): |
| 89 | raise RuntimeError("oops") # noqa: TRY301 |
| 90 | except Exception: |
| 91 | pass |
| 92 | |
| 93 | check_normal() |