forked from pyodide/pyodide
/
test_pyproxy.py
2361 lines (2038 loc) · 62.2 KB
/
test_pyproxy.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 time
import pytest
from pytest_pyodide.decorator import run_in_pyodide
def test_pyproxy_class(selenium):
selenium.run_js(
"""
pyodide.runPython(`
class Foo:
bar = 42
def get_value(self, value):
return value * 64
f = Foo()
`);
self.f = pyodide.globals.get('f');
assert(() => f.type === "Foo");
let f_get_value = f.get_value
assert(() => f_get_value(2) === 128);
f_get_value.destroy();
assert(() => f.bar === 42);
assert(() => 'bar' in f);
f.baz = 32;
assert(() => f.baz === 32);
pyodide.runPython(`assert hasattr(f, 'baz')`)
self.f_props = Object.getOwnPropertyNames(f);
delete f.baz
pyodide.runPython(`assert not hasattr(f, 'baz')`)
assert(() => f.toString().startsWith("<__main__.Foo"));
f.destroy();
"""
)
assert {
"__class__",
"__delattr__",
"__dict__",
"__dir__",
"__doc__",
"__eq__",
"__format__",
"__ge__",
"__getattribute__",
"__gt__",
"__hash__",
"__init__",
"__init_subclass__",
"__le__",
"__lt__",
"__module__",
"__ne__",
"__new__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__setattr__",
"__sizeof__",
"__str__",
"__subclasshook__",
"__weakref__",
"bar",
"baz",
"get_value",
}.difference(selenium.run_js("return f_props")) == set()
@run_in_pyodide
def test_pyproxy_tostring(selenium):
from pathlib import Path
from pyodide.code import run_js
from pyodide_js._api import setPyProxyToStringMethod
pyproxy_to_string = run_js("(e) => e.toString()")
p = Path("a/b/c")
assert pyproxy_to_string(p) == str(p)
setPyProxyToStringMethod(True)
assert pyproxy_to_string(p) == repr(p)
setPyProxyToStringMethod(False)
assert pyproxy_to_string(p) == str(p)
def test_del_builtin(selenium):
msg = "NameError"
with pytest.raises(selenium.JavascriptException, match=msg):
# can't del a builtin
selenium.run("del open")
# Can still get it even though we tried to del it.
assert selenium.run_js(
"""
let open = pyodide.globals.get("open");
let result = !!open;
open.destroy();
return result;
"""
)
assert selenium.run_js("return pyodide.globals.get('__name__');") == "__main__"
def test_in_globals(selenium):
selenium.run("yyyyy = 7")
assert (
selenium.run_js(
"""
let result = [];
result.push(pyodide.globals.has("xxxxx"));
result.push(pyodide.globals.has("yyyyy"));
result.push(pyodide.globals.has("globals"));
result.push(pyodide.globals.has("open"));
return result;
"""
)
== [False, True, True, True]
)
def test_pyproxy_copy(selenium):
selenium.run_js(
"""
let d = pyodide.runPython("list(range(10))")
e = d.copy();
d.destroy();
assert(() => e.length === 10);
e.destroy();
"""
)
def test_pyproxy_refcount(selenium):
selenium.run_js(
"""
function getRefCount(){
return pyodide.runPython("sys.getrefcount(pyfunc)");
}
self.jsfunc = function (f) { f(); };
pyodide.runPython(`
import sys
from js import jsfunc
def pyfunc(*args, **kwargs):
print(*args, **kwargs)
`);
// the refcount should be 2 because:
// 1. pyfunc exists
// 2. pyfunc is referenced from the sys.getrefcount()-test below
//
// Each time jsfunc is called a new PyProxy to pyfunc is created. That
// PyProxy is destroyed when the call finishes, so the calls to
// jsfunc(pyfunc) do not change the reference count.
assert(() => getRefCount() === 2);
pyodide.runPython(`
jsfunc(pyfunc)
`);
assert(() => getRefCount() === 2);
pyodide.runPython(`
jsfunc(pyfunc)
jsfunc(pyfunc)
`)
assert(() => getRefCount() === 2);
pyodide.runPython(`del jsfunc`)
"""
)
def test_pyproxy_destroy(selenium):
selenium.run_js(
"""
pyodide.runPython(`
class Foo:
def get_value(self, value):
return value * 64
f = Foo()
`);
let f = pyodide.globals.get('f');
assert(()=> f.get_value(1) === 64);
f.destroy();
assertThrows(() => f.get_value(1), "Error", "already been destroyed");
"""
)
def test_pyproxy_iter(selenium):
[ty, l] = selenium.run_js(
"""
let c = pyodide.runPython(`
def test():
for i in range(10):
yield i
test()
`);
let result = [c.type, [...c]];
c.destroy();
return result;
"""
)
assert ty == "generator"
assert l == list(range(10))
[ty, l] = selenium.run_js(
"""
let c = pyodide.runPython(`
from collections import ChainMap
ChainMap({"a" : 2, "b" : 3})
`);
let result = [c.type, [...c]];
c.destroy();
return result;
"""
)
assert ty == "ChainMap"
assert set(l) == {"a", "b"}
[result, result2] = selenium.run_js(
"""
let c = pyodide.runPython(`
def test():
acc = 0
for i in range(10):
r = yield acc
acc += i * r
test()
`)
let {done, value} = c.next();
let result = [];
while(!done){
result.push(value);
({done, value} = c.next(value + 1));
}
c.destroy();
function* test(){
let acc = 0;
for(let i=0; i < 10; i++){
let r = yield acc;
acc += i * r;
}
}
c = test();
({done, value} = c.next());
let result2 = [];
while(!done){
result2.push(value);
({done, value} = c.next(value + 1));
}
return [result, result2];
"""
)
assert result == result2
def test_pyproxy_iter_error(selenium):
selenium.run_js(
"""
let t = pyodide.runPython(`
class T:
def __iter__(self):
raise Exception('hi')
T()
`);
assertThrows(() => t[Symbol.iterator](), "PythonError", "hi");
t.destroy();
"""
)
def test_pyproxy_iter_error2(selenium):
selenium.run_js(
"""
let gen = pyodide.runPython(`
def g():
yield 1
yield 2
raise Exception('hi')
yield 3
g()
`);
assert(() => gen.next().value === 1);
assert(() => gen.next().value === 2);
assertThrows(() => gen.next(), "PythonError", "hi");
gen.destroy();
"""
)
def test_pyproxy_get_buffer(selenium):
selenium.run_js(
"""
pyodide.runPython(`
from sys import getrefcount
z1 = memoryview(bytes(range(24))).cast("b", [8,3])
z2 = z1[-1::-1]
`);
for(let x of ["z1", "z2"]){
pyodide.runPython(`assert getrefcount(${x}) == 2`);
let proxy = pyodide.globals.get(x);
pyodide.runPython(`assert getrefcount(${x}) == 3`);
let z = proxy.getBuffer();
pyodide.runPython(`assert getrefcount(${x}) == 4`);
proxy.destroy();
pyodide.runPython(`assert getrefcount(${x}) == 3`);
for(let idx1 = 0; idx1 < 8; idx1++) {
for(let idx2 = 0; idx2 < 3; idx2++){
let v1 = z.data[z.offset + z.strides[0] * idx1 + z.strides[1] * idx2];
let v2 = pyodide.runPython(`repr(${x}[${idx1}, ${idx2}])`);
console.log(`${v1}, ${typeof(v1)}, ${v2}, ${typeof(v2)}, ${v1===v2}`);
if(v1.toString() !== v2){
throw new Error(`Discrepancy ${x}[${idx1}, ${idx2}]: ${v1} != ${v2}`);
}
}
}
z.release();
pyodide.runPython(`assert getrefcount(${x}) == 2`);
pyodide.runPython(`del ${x}`);
}
"""
)
def test_get_empty_buffer(selenium):
"""Previously empty buffers would raise alignment errors
This is because when Python makes an empty buffer, apparently the pointer
field is allowed to contain random garbage, which in particular won't be aligned.
"""
selenium.run_js(
"""
let a = pyodide.runPython(`
from array import array
array("Q")
`);
let b = a.getBuffer();
b.release();
a.destroy();
"""
)
@pytest.mark.parametrize(
"array_type",
[
["i8", "Int8Array", "b"],
["u8", "Uint8Array", "B"],
["u8clamped", "Uint8ClampedArray", "B"],
["i16", "Int16Array", "h"],
["u16", "Uint16Array", "H"],
["i32", "Int32Array", "i"],
["u32", "Uint32Array", "I"],
["i64", "BigInt64Array", "q"],
["u64", "BigUint64Array", "Q"],
["f32", "Float32Array", "f"],
["f64", "Float64Array", "d"],
],
)
def test_pyproxy_get_buffer_type_argument(selenium, array_type):
selenium.run_js(
"""
self.a = pyodide.runPython("bytes(range(256))");
assert(() => a instanceof pyodide.ffi.PyBuffer);
"""
)
try:
mv = memoryview(bytes(range(256)))
ty, array_ty, fmt = array_type
[check, result] = selenium.run_js(
f"""
let buf = a.getBuffer({ty!r});
assert(() => buf instanceof pyodide.ffi.PyBufferView);
let check = (buf.data.constructor.name === {array_ty!r});
let result = Array.from(buf.data);
if(typeof result[0] === "bigint"){{
result = result.map(x => x.toString(16));
}}
buf.release();
return [check, result];
"""
)
assert check
if fmt.lower() == "q":
assert result == [hex(x).replace("0x", "") for x in list(mv.cast(fmt))]
elif fmt == "f" or fmt == "d":
from math import isclose, isnan
for a, b in zip(result, list(mv.cast(fmt)), strict=False):
if a and b and not (isnan(a) or isnan(b)):
assert isclose(a, b)
else:
assert result == list(mv.cast(fmt))
finally:
selenium.run_js("a.destroy(); self.a = undefined;")
def test_pyproxy_mixins1(selenium):
result = selenium.run_js(
"""
let [noimpls, awaitable, iterable, iterator, awaititerable, awaititerator] = pyodide.runPython(`
class NoImpls: pass
class Await:
def __await__(self):
return iter([])
class Iter:
def __iter__(self):
return iter([])
class Next:
def __next__(self):
pass
class AwaitIter(Await, Iter): pass
class AwaitNext(Await, Next): pass
from pyodide.ffi import to_js
to_js([NoImpls(), Await(), Iter(), Next(), AwaitIter(), AwaitNext()])
`);
let name_proxy = {noimpls, awaitable, iterable, iterator, awaititerable, awaititerator};
let result = {};
for(let [name, x] of Object.entries(name_proxy)){
let impls = {};
for(let [name, key] of [
["then", "then"],
["catch", "catch"],
["finally_", "finally"],
["iterable", Symbol.iterator],
["iterator", "next"],
]){
impls[name] = key in x;
}
for(let name of ["PyAwaitable", "PyIterable", "PyIterator"]){
impls[name] = x instanceof pyodide.ffi[name];
}
result[name] = impls;
x.destroy();
}
return result;
"""
)
assert result == dict(
noimpls=dict(
then=False,
catch=False,
finally_=False,
iterable=False,
iterator=False,
)
| dict(PyAwaitable=False, PyIterable=False, PyIterator=False),
awaitable=dict(
then=True, catch=True, finally_=True, iterable=False, iterator=False
)
| dict(PyAwaitable=True, PyIterable=False, PyIterator=False),
iterable=dict(
then=False, catch=False, finally_=False, iterable=True, iterator=False
)
| dict(PyAwaitable=False, PyIterable=True, PyIterator=False),
iterator=dict(
then=False, catch=False, finally_=False, iterable=True, iterator=True
)
| dict(PyAwaitable=False, PyIterable=True, PyIterator=True),
awaititerable=dict(
then=True, catch=True, finally_=True, iterable=True, iterator=False
)
| dict(PyAwaitable=True, PyIterable=True, PyIterator=False),
awaititerator=dict(
then=True, catch=True, finally_=True, iterable=True, iterator=True
)
| dict(PyAwaitable=True, PyIterable=True, PyIterator=True),
)
def test_pyproxy_mixins2(selenium):
selenium.run_js(
"""
let d = pyodide.runPython("{}");
assert(() => !("prototype" in d));
assert(() => !("caller" in d));
assert(() => !("name" in d));
assert(() => "length" in d);
assert(() => d instanceof pyodide.ffi.PyDict);
assert(() => d instanceof pyodide.ffi.PyProxyWithLength);
assert(() => d instanceof pyodide.ffi.PyProxyWithHas);
assert(() => d instanceof pyodide.ffi.PyProxyWithGet);
assert(() => d instanceof pyodide.ffi.PyProxyWithSet);
assert(() => "prototype" in d.__getitem__);
assert(() => d.__getitem__.prototype === undefined);
assert(() => !("length" in d.__getitem__));
assert(() => !("name" in d.__getitem__));
assert(() => d.$get.type === "builtin_function_or_method");
assert(() => d.get.type === undefined);
assert(() => d.set.type === undefined);
d.destroy();
"""
)
def test_pyproxy_mixins31(selenium):
selenium.run_js(
"""
"use strict";
let [Test, t] = pyodide.runPython(`
class Test: pass
from pyodide.ffi import to_js
to_js([Test, Test()])
`);
assert(() => Test.prototype === undefined);
assert(() => !("name" in Test));
assert(() => !("length" in Test));
assert(() => !("prototype" in t));
assert(() => !("caller" in t));
assert(() => !("name" in t));
assert(() => !("length" in t));
Test.prototype = 7;
Test.name = 7;
Test.length = 7;
pyodide.runPython("assert Test.prototype == 7");
pyodide.runPython("assert Test.name == 7");
pyodide.runPython("assert Test.length == 7");
// prototype cannot be removed once added because it is nonconfigurable...
assertThrows(() => delete Test.prototype, "TypeError", "");
delete Test.name;
delete Test.length;
pyodide.runPython(`assert Test.prototype == 7`);
pyodide.runPython(`assert not hasattr(Test, "name")`);
pyodide.runPython(`assert not hasattr(Test, "length")`);
Test.$a = 7;
Object.defineProperty(Test, "a", {
get(){ return Test.$a + 1; },
set(v) {
Test.$a = v;
}
});
pyodide.runPython("assert Test.a == 7")
assert(() => Test.a === 8);
Test.a = 9;
assert(() => Test.a === 10);
pyodide.runPython("assert Test.a == 9")
assertThrows(() => delete Test.a, "TypeError", "");
Object.defineProperty(Test, "b", {
get(){ return Test.$a + 2; },
});
assert(() => Test.b === 11);
assertThrows(() => Test.b = 7,"TypeError", "");
assertThrows(() => delete Test.b, "TypeError", "");
Test.destroy();
t.destroy();
"""
)
@pytest.mark.parametrize("configurable", [False, True])
@pytest.mark.parametrize("writable", [False, True])
def test_pyproxy_mixins32(selenium, configurable, writable):
# Probably should get rid of this...
match selenium.browser:
case "node" | "chrome":
template = "'{}' on proxy: trap returned falsish for property 'x'"
setText = template.format("set")
deleteText = template.format("deleteProperty")
case "firefox":
template = "proxy {} handler returned false"
setText = template.format("set")
deleteText = template.format("deleteProperty")
case "safari":
setText = "Proxy object's 'set' trap returned falsy value for property 'x'"
deleteText = "Unable to delete property."
selenium.run_js(
f"""
"use strict";
const configurable = !!{int(configurable)};
const writable = !!{int(writable)};
"""
"""
const d = pyodide.runPython("{}");
Object.defineProperty(d, "x", {
value: 9,
configurable,
writable,
});
assert(() => d.x === 9);
if(writable) {
d.x = 10;
assert(() => d.x === 10);
} else {
assertThrows(() => d.x = 10, "TypeError", "%s");
}
if(configurable) {
delete d.x;
assert(() => d.x === undefined);
} else {
assertThrows(() => delete d.x, "TypeError", "%s");
}
d.destroy();
"""
% (setText, deleteText)
)
def test_pyproxy_mixins41(selenium):
selenium.run_js(
"""
[Test, t] = pyodide.runPython(`
class Test:
caller="fifty"
prototype="prototype"
name="me"
length=7
def __call__(self, x):
return x + 1
from pyodide.ffi import to_js
to_js([Test, Test()])
`);
assert(() => Test.$prototype === "prototype");
assert(() => Test.prototype === "prototype");
assert(() => Test.name==="me");
assert(() => Test.length === 7);
assert(() => t.caller === "fifty");
assert(() => "prototype" in t);
assert(() => t.prototype === "prototype");
assert(() => t.name==="me");
assert(() => t.length === 7);
assert(() => t(7) === 8);
Test.destroy();
t.destroy();
"""
)
def test_pyproxy_mixins42(selenium):
selenium.run_js(
"""
let t = pyodide.runPython(`
class Test:
def __call__(self, x):
return x + 1
from pyodide.ffi import to_js
Test()
`);
assert(() => "prototype" in t);
assert(() => t.prototype === undefined);
t.destroy();
"""
)
def test_pyproxy_mixins5(selenium):
try:
r = selenium.run_js(
"""
"use strict";
const [Test, t] = pyodide.runPython(`
class Test:
def __len__(self):
return 9
from pyodide.ffi import to_js
to_js([Test, Test()])
`);
assert(() => !("length" in Test));
assert(() => t.length === 9);
assert(() => t instanceof pyodide.ffi.PyProxyWithLength);
assertThrows(() => {t.length = 10}, "TypeError", "");
assert(() => t.length === 9);
// For some reason, this is the normal behavior for a JS getter:
// delete just does nothing...
delete t.length;
assert(() => t.length === 9);
Test.destroy();
t.destroy();
"""
)
print(r)
finally:
print(selenium.logs)
def test_pyproxy_mixins6(selenium):
selenium.run_js(
"""
let l = pyodide.runPython(`
l = [5, 6, 7] ; l
`);
assert(() => l.get.type === undefined);
assert(() => l.get(1) === 6);
assert(() => l.length === 3);
assert(() => l instanceof pyodide.ffi.PyProxyWithLength);
assert(() => l instanceof pyodide.ffi.PyProxyWithHas);
assert(() => l instanceof pyodide.ffi.PyProxyWithGet);
assert(() => l instanceof pyodide.ffi.PyProxyWithSet);
l.set(0, 80);
pyodide.runPython(`
assert l[0] == 80
`);
l.delete(1);
pyodide.runPython(`
assert len(l) == 2 and l[1] == 7
`);
assert(() => l.length === 2 && l.get(1) === 7);
l.destroy();
"""
)
@pytest.mark.skip_pyproxy_check
def test_pyproxy_gc(selenium):
if not hasattr(selenium, "collect_garbage"):
pytest.skip("No gc exposed")
# Two ways to trigger garbage collection in Chrome:
# 1. options.add_argument("--js-flags=--expose-gc") in conftest, and use
# gc() in javascript.
# 2. selenium.driver.execute_cdp_cmd("HeapProfiler.collectGarbage", {})
#
# Unclear how to trigger gc in Firefox. Possible to do this by navigating to
# "about:memory" and then triggering a button press to the "GC" button, but
# that seems too annoying.
selenium.run_js(
"""
self.x = new FinalizationRegistry((val) => { self.val = val; });
x.register({}, 77);
gc();
"""
)
time.sleep(0.1)
selenium.run_js(
"""
gc();
"""
)
assert selenium.run_js("return self.val;") == 77
selenium.run_js(
"""
self.res = new Map();
let d = pyodide.runPython(`
from js import res
def get_ref_count(x):
res[x] = sys.getrefcount(d)
return res[x]
import sys
class Test:
def __del__(self):
res["destructor_ran"] = True
def get(self):
return 7
d = Test()
get_ref_count(0)
d
`);
let get_ref_count = pyodide.globals.get("get_ref_count");
get_ref_count(1);
d.get();
get_ref_count(2);
d.get();
d.destroy()
"""
)
selenium.collect_garbage()
selenium.run(
"""
get_ref_count(3)
del d
"""
)
selenium.collect_garbage()
a = selenium.run_js("return Array.from(res.entries());")
assert dict(a) == {0: 2, 1: 3, 2: 4, 3: 2, "destructor_ran": True}
@pytest.mark.skip_pyproxy_check
def test_pyproxy_gc_destroy(selenium):
if not hasattr(selenium, "collect_garbage"):
pytest.skip("No gc exposed")
selenium.run_js(
"""
self.res = new Map();
let d = pyodide.runPython(`
from js import res
def get_ref_count(x):
res[x] = sys.getrefcount(d)
return res[x]
import sys
class Test:
def __del__(self):
res["destructor_ran"] = True
def get(self):
return 7
d = Test()
get_ref_count(0)
d
`);
let get_ref_count = pyodide.globals.get("get_ref_count");
get_ref_count(1);
d.get();
get_ref_count(2);
d.get();
get_ref_count(3);
delete d;
get_ref_count.destroy();
"""
)
selenium.collect_garbage()
selenium.collect_garbage()
selenium.run(
"""
get_ref_count(4)
del d
"""
)
a = selenium.run_js("return Array.from(res.entries());")
assert dict(a) == {
0: 2,
1: 3,
2: 4,
3: 4,
4: 2,
"destructor_ran": True,
}
def test_pyproxy_implicit_copy(selenium):
result = selenium.run_js(
"""
let result = [];
let a = pyodide.runPython(`d = { 1 : 2}; d`);
let b = pyodide.runPython(`d`);
result.push(a.get(1));
result.push(b.get(1));
a.destroy();
b.destroy();
return result;
"""
)
assert result[0] == 2
assert result[1] == 2
@pytest.mark.skip_pyproxy_check
def test_errors(selenium):
selenium.run_js(
r"""
const origDebug = pyodide.setDebug(true);
try {
const t = pyodide.runPython(`
from pyodide.ffi import to_js
def te(self, *args, **kwargs):
raise Exception(repr(args))
class Temp:
__getattr__ = te
__setattr__ = te
__delattr__ = te
__dir__ = te
__call__ = te
__getitem__ = te
__setitem__ = te
__delitem__ = te
__iter__ = te
__len__ = te
__contains__ = te
__await__ = te
__repr__ = te
to_js(Temp())
Temp()
`);
assertThrows(() => t.x, "PythonError", "");
try {
t.x;
} catch(e){
assert(() => e instanceof pyodide.ffi.PythonError);
}
assertThrows(() => t.x = 2, "PythonError", "");
assertThrows(() => delete t.x, "PythonError", "");
assertThrows(() => Object.getOwnPropertyNames(t), "PythonError", "");
assertThrows(() => t(), "PythonError", "");
assertThrows(() => t.get(1), "PythonError", "");
assertThrows(() => t.set(1, 2), "PythonError", "");
assertThrows(() => t.delete(1), "PythonError", "");
assertThrows(() => t.has(1), "PythonError", "");
assertThrows(() => t.length, "PythonError", "");
assertThrows(() => t.toString(), "PythonError", "");
assertThrows(() => Array.from(t), "PythonError", "");
await assertThrowsAsync(async () => await t, "PythonError", "");
t.destroy();
assertThrows(() => t.type, "Error",
"Object has already been destroyed\n" +
'The object was of type "Temp" and an error was raised when trying to generate its repr'
);
} finally {
pyodide.setDebug(origDebug);
}
"""
)
@pytest.mark.skip_pyproxy_check
def test_nogil(selenium):
selenium.run_js(
r"""
let t = pyodide.runPython(`
def te(self, *args, **kwargs):
raise Exception(repr(args))
class Temp:
__getattr__ = te
__setattr__ = te
__delattr__ = te
__dir__ = te
__call__ = te
__getitem__ = te
__setitem__ = te
__delitem__ = te
__iter__ = te
__len__ = te
__contains__ = te
__await__ = te
__repr__ = te
Temp()
`);
// release GIL
const tstate = pyodide._module._PyEval_SaveThread();
try {
assertThrows(() => t.x, "NoGilError", "");
try {
t.x;
} catch(e){
assert(() => e instanceof pyodide._api.NoGilError);
}
assertThrows(() => t.x = 2, "NoGilError", "");
assertThrows(() => delete t.x, "NoGilError", "");
assertThrows(() => Object.getOwnPropertyNames(t), "NoGilError", "");
assertThrows(() => t(), "NoGilError", "");
assertThrows(() => t.get(1), "NoGilError", "");
assertThrows(() => t.set(1, 2), "NoGilError", "");
assertThrows(() => t.delete(1), "NoGilError", "");
assertThrows(() => t.has(1), "NoGilError", "");
assertThrows(() => t.length, "NoGilError", "");
assertThrows(() => t.toString(), "NoGilError", "");
assertThrows(() => Array.from(t), "NoGilError", "");
await assertThrowsAsync(async () => await t, "NoGilError", "");
assertThrows(() => t.destroy(), "NoGilError", "");
} finally {
// acquire GIL
pyodide._module._PyEval_RestoreThread(tstate)
}
"""
)
@pytest.mark.skip_pyproxy_check
def test_fatal_error(selenium_standalone):
"""Inject fatal errors in all the reasonable entrypoints"""
selenium_standalone.run_js(
"""
let fatal_error = false;
let old_fatal_error = pyodide._api.fatal_error;
pyodide._api.fatal_error = (e) => {
fatal_error = true;
throw e;
}
try {
function expect_fatal(func){
fatal_error = false;
try {
func();
} catch(e) {
// pass
} finally {
if(!fatal_error){
throw new Error(`No fatal error occurred: ${func.toString().slice(6)}`);
}
}
}