forked from pyodide/pyodide
/
test_jsproxy.py
2430 lines (2047 loc) · 60.6 KB
/
test_jsproxy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# See also test_typeconversions, and test_python.
import pytest
from hypothesis import example, given
from hypothesis import strategies as st
from pytest_pyodide import run_in_pyodide
from pytest_pyodide.hypothesis import std_hypothesis_settings
def test_jsproxy_dir(selenium):
result = selenium.run_js(
"""
self.a = { x : 2, y : "9" };
self.b = function(){};
let pyresult = pyodide.runPython(`
from js import a
from js import b
[dir(a), dir(b)]
`);
let result = pyresult.toJs();
pyresult.destroy();
return result;
"""
)
jsproxy_items = {
"__bool__",
"__class__",
"__defineGetter__",
"__defineSetter__",
"__delattr__",
"constructor",
"toString",
"typeof",
"valueOf",
}
a_items = {"x", "y"}
callable_items = {"__call__", "new"}
set0 = set(result[0])
set1 = set(result[1])
assert set0.issuperset(jsproxy_items)
assert set0.isdisjoint(callable_items)
assert set0.issuperset(a_items)
assert set1.issuperset(jsproxy_items)
assert set1.issuperset(callable_items)
assert set1.isdisjoint(a_items)
selenium.run_js(
"""
self.a = [0,1,2,3,4,5,6,7,8,9];
a[27] = 0;
a[":"] = 0;
a["/"] = 0;
a.abcd = 0;
a.α = 0;
pyodide.runPython(`
from js import a
d = dir(a)
assert '0' not in d
assert '9' not in d
assert '27' not in d
assert ':' in d
assert '/' in d
assert 'abcd' in d
assert 'α' in d
`);
"""
)
def test_jsproxy_getattr(selenium):
assert (
selenium.run_js(
"""
self.a = { x : 2, y : "9", typeof : 7 };
let pyresult = pyodide.runPython(`
from js import a
[ a.x, a.y, a.typeof ]
`);
let result = pyresult.toJs();
pyresult.destroy();
return result;
"""
)
== [2, "9", "object"]
)
@pytest.mark.xfail_browsers(node="No document in node")
@run_in_pyodide
def test_jsproxy_document(selenium):
from js import document
el = document.createElement("div")
assert el.tagName == "DIV"
assert bool(el)
assert not document.body.children
document.body.appendChild(el)
assert document.body.children
assert len(document.body.children) == 1
assert document.body.children[0] == el
assert repr(document) == "[object HTMLDocument]"
assert len(dir(el)) >= 200
assert "appendChild" in dir(el)
@pytest.mark.parametrize(
"js,result",
[
("{}", False),
("{a:1}", True),
("[]", False),
("[1]", True),
("new Map()", False),
("new Map([[0, 0]])", True),
("new Set()", False),
("new Set([0])", True),
("class T {}; T", True),
("class T {}; new T()", True),
("new Uint8Array(0)", False),
("new Uint8Array(1)", True),
("new ArrayBuffer(0)", False),
("new ArrayBuffer(1)", True),
],
)
@run_in_pyodide
def test_jsproxy_bool(selenium, js, result):
from pyodide.code import run_js
assert bool(run_js(js)) == result
@pytest.mark.xfail_browsers(node="No document in node")
@pytest.mark.parametrize(
"js,result",
[
("document.createElement('div')", True),
("document.createElement('select')", True),
("document.createElement('p')", True),
("document.createElement('style')", True),
("document.createElement('ul')", True),
("document.createElement('ul').style", True),
("document.querySelectorAll('x')", False),
("document.querySelectorAll('body')", True),
("document.all", False),
],
)
@run_in_pyodide
def test_jsproxy_bool_html(selenium, js, result):
from pyodide.code import run_js
assert bool(run_js(js)) == result
@pytest.mark.xfail_browsers(node="No ImageData in node")
@run_in_pyodide
def test_jsproxy_imagedata(selenium):
from js import ImageData
assert ImageData.new(64, 64).width == 64
assert ImageData.typeof == "function"
def test_jsproxy_function(selenium):
selenium.run_js("self.square = function (x) { return x*x; };")
assert (
selenium.run(
"""
from js import square
square(2)
"""
)
== 4
)
def test_jsproxy_class(selenium):
selenium.run_js(
"""
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
self.TEST = new Point(42, 43);
"""
)
assert (
selenium.run(
"""
from js import TEST
del TEST.y
hasattr(TEST, 'y')
"""
)
is False
)
@run_in_pyodide
def test_jsproxy_map(selenium):
import pytest
from pyodide.code import run_js
TEST = run_js('new Map([["x", 42], ["y", 43]])')
assert "y" in TEST
del TEST["y"]
assert "y" not in TEST
with pytest.raises(KeyError):
del TEST["y"]
assert TEST == TEST
assert TEST != "foo"
TEST = run_js("({foo: 'bar', baz: 'bap'})")
assert dict(TEST.object_entries()) == {"foo": "bar", "baz": "bap"}
def test_jsproxy_iter(selenium):
selenium.run_js(
"""
function makeIterator(array) {
let nextIndex = 0;
return {
next: function() {
return nextIndex < array.length ?
{value: array[nextIndex++], done: false} :
{done: true};
}
};
}
self.ITER = makeIterator([1, 2, 3]);"""
)
assert selenium.run("from js import ITER\n" "list(ITER)") == [1, 2, 3]
def test_jsproxy_implicit_iter(selenium):
selenium.run_js(
"""
self.ITER = [1, 2, 3];
"""
)
assert selenium.run("from js import ITER, Object\n" "list(ITER)") == [1, 2, 3]
assert selenium.run("from js import ITER, Object\n" "list(ITER.values())") == [
1,
2,
3,
]
assert selenium.run(
"from js import ITER, Object\n" "list(Object.values(ITER))"
) == [1, 2, 3]
def test_jsproxy_call(selenium):
assert (
selenium.run_js(
"""
self.f = function(){ return arguments.length; };
let pyresult = pyodide.runPython(
`
from js import f
[f(*range(n)) for n in range(10)]
`
);
let result = pyresult.toJs();
pyresult.destroy();
return result;
"""
)
== list(range(10))
)
def test_jsproxy_call_kwargs(selenium):
assert (
selenium.run_js(
"""
self.kwarg_function = ({ a = 1, b = 1 }) => {
return [a, b];
};
return pyodide.runPython(
`
from js import kwarg_function
kwarg_function(b = 2, a = 10)
`
);
"""
)
== [10, 2]
)
@pytest.mark.xfail
def test_jsproxy_call_meth_py(selenium):
assert selenium.run_js(
"""
self.a = {};
return pyodide.runPython(
`
from js import a
def f(self):
return self
a.f = f
a.f() == a
`
);
"""
)
def test_jsproxy_call_meth_js(selenium):
assert selenium.run_js(
"""
self.a = {};
function f(){return this;}
a.f = f;
return pyodide.runPython(
`
from js import a
a.f() == a
`
);
"""
)
def test_jsproxy_call_meth_js_kwargs(selenium):
assert selenium.run_js(
"""
self.a = {};
function f({ x = 1, y = 1 }){
return [this, x, y];
}
a.f = f;
return pyodide.runPython(
`
from js import a
[r0, r1, r2] = a.f(y=10, x=2)
r0 == a and r1 == 2 and r2 == 10
`
);
"""
)
def test_call_pyproxy_destroy_args(selenium):
selenium.run_js(
r"""
let y;
self.f = function(x){ y = x; }
pyodide.runPython(`
from js import f
f({})
f([])
`);
assertThrows(() => y.length, "Error",
"This borrowed proxy was automatically destroyed at the end of a function call.*\n" +
'The object was of type "list" and had repr "\\[\\]"'
);
"""
)
selenium.run_js(
"""
let y;
self.f = async function(x){
await sleep(5);
y = x;
}
await pyodide.runPythonAsync(`
from js import f
await f({})
await f([])
`);
assertThrows(() => y.length, "Error", "This borrowed proxy was automatically destroyed");
"""
)
def test_call_pyproxy_set_global(selenium):
selenium.run_js(
"""
self.setGlobal = function(x){
if(self.myGlobal instanceof pyodide.ffi.PyProxy){
self.myGlobal.destroy();
}
if(x instanceof pyodide.ffi.PyProxy){
x = x.copy();
}
self.myGlobal = x;
}
pyodide.runPython(`
from js import setGlobal
setGlobal(2)
setGlobal({})
setGlobal([])
setGlobal(3)
`);
"""
)
selenium.run_js(
"""
self.setGlobal = async function(x){
await sleep(5);
if(self.myGlobal instanceof pyodide.ffi.PyProxy){
self.myGlobal.destroy();
}
if(x instanceof pyodide.ffi.PyProxy){
x = x.copy();
}
self.myGlobal = x;
}
await pyodide.runPythonAsync(`
from js import setGlobal
await setGlobal(2)
await setGlobal({})
await setGlobal([])
await setGlobal(3)
`);
"""
)
def test_call_pyproxy_destroy_result(selenium):
selenium.run_js(
"""
self.f = function(){
let dict = pyodide.globals.get("dict");
let result = dict();
dict.destroy();
return result;
}
pyodide.runPython(`
from js import f
import sys
d = f()
assert sys.getrefcount(d) == 2
`);
"""
)
selenium.run_js(
"""
self.f = async function(){
await sleep(5);
let dict = pyodide.globals.get("dict");
let result = dict();
dict.destroy();
return result;
}
await pyodide.runPythonAsync(`
from js import f
import sys
d = await f()
`);
pyodide.runPython(`
assert sys.getrefcount(d) == 2
`);
"""
)
@pytest.mark.skip_refcount_check
def test_call_pyproxy_return_arg(selenium):
selenium.run_js(
"""
self.f = function f(x){
return x;
}
pyodide.runPython(`
from js import f
l = [1,2,3]
x = f(l)
assert x is l
import sys
assert sys.getrefcount(x) == 3
`);
"""
)
selenium.run_js(
"""
self.f = async function f(x){
await sleep(5);
return x;
}
await pyodide.runPythonAsync(`
from js import f
l = [1,2,3]
x = await f(l)
assert x is l
`);
pyodide.runPython(`
import sys
assert sys.getrefcount(x) == 3
`);
"""
)
@run_in_pyodide
def test_import_invocation(selenium):
import js
def temp():
print("okay?")
from pyodide.ffi import create_once_callable
js.setTimeout(create_once_callable(temp), 100)
js.fetch("repodata.json")
@run_in_pyodide
def test_import_bind(selenium):
from js import fetch
fetch("repodata.json")
@run_in_pyodide
def test_nested_attribute_access(selenium):
import js
from js import self
assert js.Float64Array.BYTES_PER_ELEMENT == 8
assert self.Float64Array.BYTES_PER_ELEMENT == 8
def test_destroy_attribute(selenium):
selenium.run_js(
"""
let test = pyodide.runPython(`
class Test:
a = {}
test = Test()
test
`);
pyodide.runPython(`
import sys
assert sys.getrefcount(test) == 3
assert sys.getrefcount(test.a) == 2
`);
test.a;
pyodide.runPython(`
assert sys.getrefcount(test) == 3
assert sys.getrefcount(test.a) == 3
`);
test.a.destroy();
pyodide.runPython(`
assert sys.getrefcount(test) == 3
assert sys.getrefcount(test.a) == 2
`);
test.a;
pyodide.runPython(`
assert sys.getrefcount(test) == 3
assert sys.getrefcount(test.a) == 3
`);
test.destroy();
pyodide.runPython(`
assert sys.getrefcount(test) == 2
assert sys.getrefcount(test.a) == 2
`);
"""
)
@run_in_pyodide
def test_window_isnt_super_weird_anymore(selenium):
import js
from js import Array, self
assert self.Array != self
assert self.Array == Array
assert self.self.self.self == self
assert js.self.Array == Array
assert js.self.self.self.self == self
assert self.self.self.self.Array == Array
@pytest.mark.skip_refcount_check
@pytest.mark.skip_pyproxy_check
def test_mount_object(selenium_standalone):
selenium = selenium_standalone
result = selenium.run_js(
"""
function x1(){
return "x1";
}
function x2(){
return "x2";
}
function y(){
return "y";
}
let a = { x : x1, y, s : 3, t : 7};
let b = { x : x2, y, u : 3, t : 7};
pyodide.registerJsModule("a", a);
pyodide.registerJsModule("b", b);
let result_proxy = pyodide.runPython(`
from a import x
from b import x as x2
result = [x(), x2()]
import a
import b
result += [a.s, dir(a), dir(b)]
result
`);
let result = result_proxy.toJs()
result_proxy.destroy();
return result;
"""
)
assert result[:3] == ["x1", "x2", 3]
assert {x for x in result[3] if len(x) == 1} == {"x", "y", "s", "t"}
assert {x for x in result[4] if len(x) == 1} == {"x", "y", "u", "t"}
selenium.run_js(
"""
pyodide.unregisterJsModule("a");
pyodide.unregisterJsModule("b");
"""
)
selenium.run(
"""
import sys
del sys.modules["a"]
del sys.modules["b"]
"""
)
def test_unregister_jsmodule(selenium):
selenium.run_js(
"""
let a = new Map(Object.entries({ s : 7 }));
let b = new Map(Object.entries({ t : 3 }));
pyodide.registerJsModule("a", a);
pyodide.registerJsModule("a", b);
pyodide.unregisterJsModule("a");
await pyodide.runPythonAsync(`
from unittest import TestCase
raises = TestCase().assertRaises
with raises(ImportError):
import a
`);
"""
)
def test_unregister_jsmodule_error(selenium):
selenium.run_js(
"""
try {
pyodide.unregisterJsModule("doesnotexist");
throw new Error("unregisterJsModule should have thrown an error.");
} catch(e){
if(!e.message.includes("Cannot unregister 'doesnotexist': no Javascript module with that name is registered")){
throw e;
}
}
"""
)
@pytest.mark.skip_refcount_check
@pytest.mark.skip_pyproxy_check
@run_in_pyodide
def test_jsmod_import_star1(selenium):
import sys
from typing import Any
from pyodide.code import run_js
run_js("pyodide.registerJsModule('xx', {a: 2, b: 7, f(x){ return x + 1; }});")
g: dict[str, Any] = {}
exec("from xx import *", g)
try:
assert "a" in g
assert "b" in g
assert "f" in g
assert "__all__" not in g
assert g["a"] == 2
assert g["b"] == 7
assert g["f"](9) == 10
finally:
sys.modules.pop("xx", None)
run_js("pyodide.unregisterJsModule('xx');")
@pytest.mark.skip_refcount_check
@pytest.mark.skip_pyproxy_check
@run_in_pyodide
def test_jsmod_import_star2(selenium):
import sys
from typing import Any
from pyodide.code import run_js
run_js(
"pyodide.registerJsModule('xx', {a: 2, b: 7, f(x){ return x + 1; }, __all__ : pyodide.toPy(['a'])});"
)
g: dict[str, Any] = {}
exec("from xx import *", g)
try:
assert "a" in g
assert "b" not in g
assert "f" not in g
assert "__all__" not in g
assert g["a"] == 2
finally:
sys.modules.pop("xx", None)
run_js("pyodide.unregisterJsModule('xx');")
@pytest.mark.skip_refcount_check
@pytest.mark.skip_pyproxy_check
def test_nested_import(selenium_standalone):
selenium = selenium_standalone
assert (
selenium.run_js(
"""
self.a = { b : { c : { d : 2 } } };
return pyodide.runPython("from js.a.b import c; c.d");
"""
)
== 2
)
selenium.run(
"""
import sys
del sys.modules["js.a"]
del sys.modules["js.a.b"]
"""
)
@pytest.mark.skip_refcount_check
@pytest.mark.skip_pyproxy_check
def test_register_jsmodule_docs_example(selenium_standalone):
selenium = selenium_standalone
selenium.run_js(
"""
let my_module = {
f : function(x){
return x*x + 1;
},
g : function(x){
console.log(`Calling g on argument ${x}`);
return x;
},
submodule : {
h : function(x) {
return x*x - 1;
},
c : 2,
},
};
pyodide.registerJsModule("my_js_module", my_module);
"""
)
selenium.run(
"""
import my_js_module
from my_js_module.submodule import h, c
assert my_js_module.f(7) == 50
assert h(9) == 80
assert c == 2
import sys
del sys.modules["my_js_module"]
del sys.modules["my_js_module.submodule"]
"""
)
@run_in_pyodide
def test_object_entries_keys_values(selenium):
from pyodide.code import run_js
x = run_js("({ a : 2, b : 3, c : 4 })")
assert x.object_entries().to_py() == [["a", 2], ["b", 3], ["c", 4]]
assert x.object_keys().to_py() == ["a", "b", "c"]
assert x.object_values().to_py() == [2, 3, 4]
def test_mixins_feature_presence(selenium):
selenium.run_js(
"""
let fields = [
[{ [Symbol.iterator](){} }, "__iter__"],
[{ next(){} }, "__next__", "__iter__"],
[{ length : 1 }, "__len__"],
[{ get(){} }, "__getitem__"],
[{ set(){} }, "__setitem__", "__delitem__"],
[{ has(){} }, "__contains__"],
[{ then(){} }, "__await__"]
];
let test_object = pyodide.runPython(`
from js import console
def test_object(obj, keys_expected):
for [key, expected_val] in keys_expected.object_entries():
actual_val = hasattr(obj, key)
if actual_val != expected_val:
console.log(obj)
console.log(key)
console.log(actual_val)
assert False
test_object
`);
for(let flags = 0; flags < (1 << fields.length); flags ++){
let o = {};
let keys_expected = {};
for(let [idx, [obj, ...keys]] of fields.entries()){
if(flags & (1<<idx)){
Object.assign(o, obj);
}
for(let key of keys){
keys_expected[key] = keys_expected[key] || !!(flags & (1<<idx));
}
}
test_object(o, keys_expected);
}
test_object.destroy();
"""
)
def test_mixins_calls(selenium):
result = selenium.run_js(
"""
self.testObjects = {};
testObjects.iterable = { *[Symbol.iterator](){
yield 3; yield 5; yield 7;
} };
testObjects.iterator = testObjects.iterable[Symbol.iterator]();
testObjects.has_len1 = { length : 7, size : 10 };
testObjects.has_len2 = { length : 7 };
testObjects.has_get = { get(x){ return x; } };
testObjects.has_getset = new Map();
testObjects.has_has = { has(x){ return typeof(x) === "string" && x.startsWith("x") } };
testObjects.has_includes = { includes(x){ return typeof(x) === "string" && x.startsWith("a") } };
testObjects.has_has_includes = {
includes(x){ return typeof(x) === "string" && x.startsWith("a") },
has(x){ return typeof(x) === "string" && x.startsWith("x") }
};
testObjects.awaitable = { then(cb){ cb(7); } };
let pyresult = await pyodide.runPythonAsync(`
from js import testObjects as obj
result = []
result.append(["iterable1", list(iter(obj.iterable)), [3, 5, 7]])
result.append(["iterable2", [*obj.iterable], [3, 5, 7]])
it = obj.iterator
result.append(["iterator", [next(it), next(it), next(it)], [3, 5, 7]])
result.append(["has_len1", len(obj.has_len1), 10])
result.append(["has_len2", len(obj.has_len2), 7])
result.append(["has_get1", obj.has_get[10], 10])
result.append(["has_get2", obj.has_get[11], 11])
m = obj.has_getset
m[1] = 6
m[2] = 77
m[3] = 9
m[2] = 5
del m[3]
result.append(["has_getset", [x.to_py() for x in m.entries()], [[1, 6], [2, 5]]])
result.append(["has_has", [n in obj.has_has for n in ["x9", "a9"]], [True, False]])
result.append(["has_includes", [n in obj.has_includes for n in ["x9", "a9"]], [False, True]])
result.append(["has_has_includes", [n in obj.has_has_includes for n in ["x9", "a9"]], [True, False]])
result.append(["awaitable", await obj.awaitable, 7])
result
`);
let result = pyresult.toJs();
pyresult.destroy();
return result;
"""
)
for [desc, a, b] in result:
assert a == b, desc
def test_mixins_errors_1(selenium):
selenium.run_js(
"""
self.a = [];
self.b = {
has(){ return false; },
get(){ return undefined; },
set(){ return false; },
delete(){ return false; },
};
await pyodide.runPythonAsync(`
from unittest import TestCase
raises = TestCase().assertRaises
from js import a, b
with raises(IndexError):
a[0]
with raises(IndexError):
del a[0]
with raises(KeyError):
b[0]
with raises(KeyError):
del b[0]
`);
"""
)
def test_mixins_errors_2(selenium):
selenium.run_js(
"""
self.c = {
next(){},
length : 1,
get(){},
set(){},
has(){},
then(){}
};
self.d = {
[Symbol.iterator](){},
};
pyodide.runPython("from js import c, d");
delete c.next;
delete c.length;
delete c.get;
delete c.set;
delete c.has;
delete c.then;
delete d[Symbol.iterator];
pyodide.runPython(`
from contextlib import contextmanager
from unittest import TestCase
@contextmanager
def raises(exc, match=None):
with TestCase().assertRaisesRegex(exc, match) as e:
yield e
from pyodide.ffi import JsException
msg = "^TypeError:.* is not a function.*"
with raises(JsException, match=msg):
next(c)
with raises(JsException, match=msg):
iter(d)
with raises(TypeError, match="object does not have a valid length"):
len(c)
with raises(JsException, match=msg):
c[0]
with raises(JsException, match=msg):
c[0] = 7
with raises(JsException, match=msg):
del c[0]
`)
await pyodide.runPythonAsync(`
with raises(TypeError, match="can't be used in 'await' expression"):
await c
`);
"""
)
@run_in_pyodide
def test_mixins_errors_3(selenium):
from unittest import TestCase
from pyodide.code import run_js
raises = TestCase().assertRaises
l = run_js(
"""
const l = [0, false, NaN, undefined, null];
l[6] = 7;
l
"""
)
with raises(IndexError):
l[10]
with raises(IndexError):
l[5]
assert len(l) == 7
l[0]
l[1]
l[2]
l[3]
l[4]
l[6]
del l[1]
with raises(IndexError):
l[4]
l[5]
del l[4]
l[3]
l[4]
@run_in_pyodide