summaryrefslogtreecommitdiffstatshomepage
path: root/tests
diff options
context:
space:
mode:
authorDamien George <damien@micropython.org>2024-05-14 22:15:48 +1000
committerDamien George <damien@micropython.org>2024-05-16 12:49:42 +1000
commitcfd5a8ea3a80930a79dbae6a6aff54587393d0b8 (patch)
treed77f0cd4be4c9253b934ce6dc532f1b8c67975fe /tests
parentaa2e3880c13036c65aa3381ed5f104c59ebad86e (diff)
downloadmicropython-cfd5a8ea3a80930a79dbae6a6aff54587393d0b8.tar.gz
micropython-cfd5a8ea3a80930a79dbae6a6aff54587393d0b8.zip
webassembly/proxy_c: Return undefined if dict lookup failed on JS side.
Instead of raising KeyError. These semantics match JavaScript behaviour and make it much more seamless to pass Python dicts through to JavaScript as though they were JavaScript {} objects. Signed-off-by: Damien George <damien@micropython.org>
Diffstat (limited to 'tests')
-rw-r--r--tests/ports/webassembly/py_proxy_dict_undefined.mjs34
-rw-r--r--tests/ports/webassembly/py_proxy_dict_undefined.mjs.exp11
2 files changed, 45 insertions, 0 deletions
diff --git a/tests/ports/webassembly/py_proxy_dict_undefined.mjs b/tests/ports/webassembly/py_proxy_dict_undefined.mjs
new file mode 100644
index 0000000000..d47a6a028b
--- /dev/null
+++ b/tests/ports/webassembly/py_proxy_dict_undefined.mjs
@@ -0,0 +1,34 @@
+// Test passing a Python dict into JavaScript, how it behaves with undefined keys.
+// If JavaScript accesses a key that does not exist, `undefined` should be returned.
+// This is different to Python-side behaviour, where `KeyError` is raised.
+
+const mp = await (await import(process.argv[2])).loadMicroPython();
+
+// Create a JavaScript function with default arguments.
+// When `value` is `undefined` it will receive its default.
+function withDefault({ value = "OK" } = {}) {
+ console.log(value);
+}
+
+globalThis.withDefault = withDefault;
+
+// Call the function from JavaScript with various arguments.
+withDefault();
+withDefault({});
+withDefault({ value: null });
+withDefault({ value: undefined });
+withDefault({ value: () => {} });
+
+console.log("====");
+
+// Call the function from Python with the same arguments as above.
+// The results should be the same.
+mp.runPython(`
+import js
+
+js.withDefault()
+js.withDefault({})
+js.withDefault({"value": None})
+js.withDefault({"value": js.undefined})
+js.withDefault({"value": (lambda: {})})
+`);
diff --git a/tests/ports/webassembly/py_proxy_dict_undefined.mjs.exp b/tests/ports/webassembly/py_proxy_dict_undefined.mjs.exp
new file mode 100644
index 0000000000..6cf5b9fa12
--- /dev/null
+++ b/tests/ports/webassembly/py_proxy_dict_undefined.mjs.exp
@@ -0,0 +1,11 @@
+OK
+OK
+null
+OK
+[Function: value]
+====
+OK
+OK
+null
+OK
+[Function: obj] { _ref: 7 }