forked from pyodide/pyodide
/
test_pyodide.py
1835 lines (1608 loc) · 53.1 KB
/
test_pyodide.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
import re
import shutil
import subprocess
from collections.abc import Sequence
from pathlib import Path
from textwrap import dedent
from typing import Any
import pytest
from pytest_pyodide import run_in_pyodide
from pytest_pyodide.fixture import selenium_standalone_noload_common
from pytest_pyodide.server import spawn_web_server
from conftest import DIST_PATH, ROOT_PATH
from pyodide.code import CodeRunner, eval_code, find_imports, should_quiet # noqa: E402
from pyodide_build.common import get_pyodide_root
def _strip_assertions_stderr(messages: Sequence[str]) -> list[str]:
"""Strip additional messages on stderr included when ASSERTIONS=1"""
res = []
for msg in messages:
if msg.strip() in [
"sigaction: signal type not supported: this is a no-op.",
"Calling stub instead of siginterrupt()",
"warning: no blob constructor, cannot create blobs with mimetypes",
"warning: no BlobBuilder",
]:
continue
res.append(msg)
return res
def test_find_imports():
res = find_imports(
"""
import numpy as np
from scipy import sparse
import matplotlib.pyplot as plt
"""
)
assert set(res) == {"numpy", "scipy", "matplotlib"}
# If there is a syntax error in the code, find_imports should return empty
# list.
res = find_imports(
"""
import numpy as np
from scipy import sparse
import matplotlib.pyplot as plt
for x in [1,2,3]
"""
)
assert res == []
def test_ffi_import_star():
exec("from pyodide.ffi import *", {})
def test_pyimport(selenium):
selenium.run_js(
"""
let platform = pyodide.pyimport("platform");
assert(() => platform.machine() === "wasm32");
assert(() => !pyodide.globals.has("platform"))
assertThrows(() => pyodide.pyimport("platform;"), "PythonError", "ModuleNotFoundError: No module named 'platform;'");
platform.destroy();
"""
)
def test_code_runner():
assert should_quiet("1+1;")
assert not should_quiet("1+1#;")
assert not should_quiet("5-2 # comment with trailing semicolon ;")
# Normal usage
assert CodeRunner("1+1").compile().run() == 2
assert CodeRunner("1+1\n1+1").compile().run() == 2
assert CodeRunner("x + 7").compile().run({"x": 3}) == 10
cr = CodeRunner("x + 7")
# Ast transform
import ast
l = cr.ast.body[0].value.left # type: ignore[attr-defined]
cr.ast.body[0].value.left = ast.BinOp( # type: ignore[attr-defined]
left=l, op=ast.Mult(), right=ast.Constant(value=2)
)
assert cr.compile().run({"x": 3}) == 13
# Code transform
assert cr.code
cr.code = cr.code.replace(co_consts=(0, 3, 5, None))
assert cr.run({"x": 4}) == 17
def test_code_runner_mode():
from codeop import PyCF_DONT_IMPLY_DEDENT # type: ignore[attr-defined]
assert CodeRunner("1+1\n1+1", mode="exec").compile().run() == 2
with pytest.raises(SyntaxError, match="invalid syntax"):
CodeRunner("1+1\n1+1", mode="eval").compile().run()
with pytest.raises(
SyntaxError,
match="multiple statements found while compiling a single statement",
):
CodeRunner("1+1\n1+1", mode="single").compile().run()
with pytest.raises(SyntaxError, match="invalid syntax"):
CodeRunner(
"def f():\n 1", mode="single", flags=PyCF_DONT_IMPLY_DEDENT
).compile().run()
def test_eval_code():
ns: dict[str, Any] = {}
assert (
eval_code(
"""
def f(x):
return 2*x + 5
f(77)
""",
ns,
)
== 2 * 77 + 5
)
assert ns["f"](7) == 2 * 7 + 5
assert eval_code("(x:=4)", ns) == 4
assert ns["x"] == 4
assert eval_code("x=7", ns) is None
assert ns["x"] == 7
# default return_mode ('last_expr'), semicolon
assert eval_code("1+1;", ns) is None
assert eval_code("1+1#;", ns) == 2
assert eval_code("5-2 # comment with trailing semicolon ;", ns) == 3
assert eval_code("4//2\n", ns) == 2
assert eval_code("2**1\n\n", ns) == 2
assert eval_code("4//2;\n", ns) is None
assert eval_code("2**1;\n\n", ns) is None
# 'last_expr_or_assign' return_mode, semicolon
assert eval_code("1 + 1", ns, return_mode="last_expr_or_assign") == 2
assert eval_code("x = 1 + 1", ns, return_mode="last_expr_or_assign") == 2
assert eval_code("a = 5 ; a += 1", ns, return_mode="last_expr_or_assign") == 6
assert eval_code("a = 5 ; a += 1;", ns, return_mode="last_expr_or_assign") is None
assert (
eval_code("l = [1, 1, 2] ; l[0] = 0", ns, return_mode="last_expr_or_assign")
is None
)
assert eval_code("a = b = 2", ns, return_mode="last_expr_or_assign") == 2
# 'none' return_mode, (useless) semicolon
assert eval_code("1 + 1", ns, return_mode="none") is None
assert eval_code("x = 1 + 1", ns, return_mode="none") is None
assert eval_code("a = 5 ; a += 1", ns, return_mode="none") is None
assert eval_code("a = 5 ; a += 1;", ns, return_mode="none") is None
assert eval_code("l = [1, 1, 2] ; l[0] = 0", ns, return_mode="none") is None
# with 'quiet_trailing_semicolon' set to False
assert eval_code("1+1;", ns, quiet_trailing_semicolon=False) == 2
assert eval_code("1+1#;", ns, quiet_trailing_semicolon=False) == 2
assert (
eval_code(
"5-2 # comment with trailing semicolon ;",
ns,
quiet_trailing_semicolon=False,
)
== 3
)
assert eval_code("4//2\n", ns, quiet_trailing_semicolon=False) == 2
assert eval_code("2**1\n\n", ns, quiet_trailing_semicolon=False) == 2
assert eval_code("4//2;\n", ns, quiet_trailing_semicolon=False) == 2
assert eval_code("2**1;\n\n", ns, quiet_trailing_semicolon=False) == 2
def test_eval_code_locals():
globals: dict[str, Any] = {}
eval_code("x=2", globals, {})
with pytest.raises(NameError):
eval_code("x", globals, {})
locals: dict[str, Any] = {}
eval_code("import sys; sys.getrecursionlimit()", globals, locals)
with pytest.raises(NameError):
eval_code("sys.getrecursionlimit()", globals, {})
eval_code("sys.getrecursionlimit()", globals, locals)
eval_code(
"from importlib import invalidate_caches; invalidate_caches()", globals, locals
)
with pytest.raises(NameError):
eval_code("invalidate_caches()", globals, globals)
eval_code("invalidate_caches()", globals, locals)
# See https://github.com/pyodide/pyodide/issues/3578
with pytest.raises(NameError):
eval_code("print(self)")
res = eval_code(
"""
var = "Hello"
def test():
return var
test()
"""
)
assert res == "Hello"
def test_unpack_archive(selenium_standalone):
selenium = selenium_standalone
js_error = selenium.run_js(
"""
var error = "";
try {
pyodide.unpackArchive([1, 2, 3], "zip", "abc");
} catch (te) {
error = te.toString();
}
return error
"""
)
expected_err_msg = "TypeError: Expected argument 'buffer' to be an ArrayBuffer or an ArrayBuffer view"
assert js_error == expected_err_msg
@run_in_pyodide
def test_dup_pipe(selenium):
# See https://github.com/emscripten-core/emscripten/issues/14640
import os
[fdr1, fdw1] = os.pipe()
fdr2 = os.dup(fdr1)
fdw2 = os.dup2(fdw1, 50)
# Closing any of fdr, fdr2, fdw, or fdw2 will currently destroy the pipe.
# This bug is fixed upstream:
# https://github.com/emscripten-core/emscripten/pull/14685
s1 = b"some stuff"
s2 = b"other stuff to write"
os.write(fdw1, s1)
assert os.read(fdr2, 100) == s1
os.write(fdw2, s2)
assert os.read(fdr1, 100) == s2
@run_in_pyodide
def test_dup_temp_file(selenium):
# See https://github.com/emscripten-core/emscripten/issues/15012
import os
from tempfile import TemporaryFile
tf = TemporaryFile(buffering=0)
fd1 = os.dup(tf.fileno())
os.dup2(tf.fileno(), 50)
s = b"hello there!"
tf.write(s)
tf2 = open(fd1, "w+")
assert tf2.tell() == len(s)
# This next assertion actually demonstrates a bug in dup: the correct value
# to return should be b"".
assert os.read(fd1, 50) == b""
tf2.seek(1)
assert tf.tell() == 1
assert tf.read(100) == b"ello there!"
@run_in_pyodide
def test_dup_stdout(selenium):
# Test redirecting stdout using low level os.dup operations.
# This sort of redirection is used in pytest.
import os
import sys
from tempfile import TemporaryFile
tf = TemporaryFile(buffering=0)
save_stdout = os.dup(sys.stdout.fileno())
os.dup2(tf.fileno(), sys.stdout.fileno())
print("hi!!")
print("there...")
assert tf.tell() == len("hi!!\nthere...\n")
os.dup2(save_stdout, sys.stdout.fileno())
print("not captured")
os.dup2(tf.fileno(), sys.stdout.fileno())
print("captured")
assert tf.tell() == len("hi!!\nthere...\ncaptured\n")
os.dup2(save_stdout, sys.stdout.fileno())
os.close(save_stdout)
tf.seek(0)
assert tf.read(1000).decode() == "hi!!\nthere...\ncaptured\n"
@pytest.mark.skip_pyproxy_check
def test_monkeypatch_eval_code(selenium):
try:
selenium.run(
"""
import pyodide
old_eval_code = pyodide.code.eval_code
x = 3
def eval_code(code, globals=None, locals=None):
return [globals["x"], old_eval_code(code, globals, locals)]
pyodide.code.eval_code = eval_code
"""
)
assert selenium.run("x = 99; 5") == [3, 5]
assert selenium.run("7") == [99, 7]
finally:
selenium.run(
"""
pyodide.code.eval_code = old_eval_code
"""
)
def test_hiwire_is_promise(selenium):
for s in [
"0",
"1",
"'x'",
"''",
"false",
"undefined",
"null",
"NaN",
"0n",
"[0,1,2]",
"[]",
"{}",
"{a : 2}",
"(()=>{})",
"((x) => x*x)",
"(function(x, y){ return x*x + y*y; })",
"Array",
"Map",
"Set",
"Promise",
"new Array()",
"new Map()",
"new Set()",
]:
assert selenium.run_js(
f"return pyodide._module.hiwire.isPromise({s}) === false;"
)
if not selenium.browser == "node":
assert selenium.run_js(
"return pyodide._module.hiwire.isPromise(document.all) === false;"
)
assert selenium.run_js(
"return pyodide._module.hiwire.isPromise(Promise.resolve()) === true;"
)
assert selenium.run_js(
"""
return pyodide._module.hiwire.isPromise(new Promise((resolve, reject) => {}));
"""
)
assert not selenium.run_js(
"""
let d = pyodide.runPython("{}");
try {
return pyodide._module.hiwire.isPromise(d);
} finally {
d.destroy();
}
"""
)
def test_keyboard_interrupt(selenium):
x = selenium.run_js(
"""
let x = new Int8Array(1);
pyodide.setInterruptBuffer(x);
self.triggerKeyboardInterrupt = function(){
x[0] = 2;
}
try {
pyodide.runPython(`
from js import triggerKeyboardInterrupt
for x in range(100000):
if x == 2000:
triggerKeyboardInterrupt()
`);
} catch(e){}
pyodide.setInterruptBuffer(undefined);
return pyodide.globals.get('x');
"""
)
assert 2000 < x < 2500
def test_run_python_async_toplevel_await(selenium):
selenium.run_js(
"""
await pyodide.runPythonAsync(`
from js import fetch
resp = await fetch("repodata.json")
json = (await resp.json()).to_py()["packages"]
assert "micropip" in json
`);
"""
)
def test_run_python_proxy_leak(selenium):
selenium.run_js(
"""
pyodide.runPython("")
await pyodide.runPythonAsync("")
"""
)
def test_run_python_last_exc(selenium):
selenium.run_js(
"""
try {
pyodide.runPython("x = ValueError(77); raise x");
} catch(e){}
pyodide.runPython(`
import sys
assert sys.last_value is x
assert sys.last_type is type(x)
assert sys.last_traceback is x.__traceback__
`);
"""
)
def test_check_interrupt(selenium):
assert selenium.run_js(
"""
let buffer = new Uint8Array(1);
let x = 0;
pyodide.setInterruptBuffer(buffer);
function test(){
buffer[0] = 2;
pyodide.checkInterrupt();
x = 1;
}
self.test = test;
let err;
try {
pyodide.runPython(`
from js import test;
try:
test();
finally:
del test
`);
} catch(e){
err = e;
}
return x === 0 && err.message.includes("KeyboardInterrupt");
"""
)
assert selenium.run_js(
"""
let buffer = new Uint8Array(1);
pyodide.setInterruptBuffer(buffer);
buffer[0] = 2;
let err_code = 0;
for(let i = 0; i < 1000; i++){
err_code = err_code || pyodide._module._PyErr_CheckSignals();
}
let err_occurred = pyodide._module._PyErr_Occurred();
console.log({err_code, err_occurred});
pyodide._module._PyErr_Clear();
return buffer[0] === 0 && err_code === -1 && err_occurred !== 0;
"""
)
def test_check_interrupt_custom_signal_handler(selenium):
try:
selenium.run_js(
"""
pyodide.runPython(`
import signal
interrupt_occurred = False
def signal_handler(*args):
global interrupt_occurred
interrupt_occurred = True
signal.signal(signal.SIGINT, signal_handler)
None
`);
"""
)
selenium.run_js(
"""
let buffer = new Uint8Array(1);
let x = 0;
pyodide.setInterruptBuffer(buffer);
function test(){
buffer[0] = 2;
pyodide.checkInterrupt();
x = 1;
}
self.test = test;
let err;
pyodide.runPython(`
interrupt_occurred = False
from js import test
test()
assert interrupt_occurred == True
del test
`);
"""
)
assert selenium.run_js(
"""
pyodide.runPython(`
interrupt_occurred = False
`);
let buffer = new Uint8Array(1);
pyodide.setInterruptBuffer(buffer);
buffer[0] = 2;
let err_code = 0;
for(let i = 0; i < 1000; i++){
err_code = err_code || pyodide._module._PyErr_CheckSignals();
}
let interrupt_occurred = pyodide.globals.get("interrupt_occurred");
return buffer[0] === 0 && err_code === 0 && interrupt_occurred;
"""
)
finally:
# Restore signal handler
selenium.run_js(
"""
pyodide.runPython(`
import signal
signal.signal(signal.SIGINT, signal.default_int_handler)
None
`);
"""
)
def test_async_leak(selenium):
assert 0 == selenium.run_js(
"""
pyodide.runPython(`d = 888.888`);
pyodide.runPython(`async def test(): return d`);
async function test(){
let t = pyodide.runPython(`test()`);
await t;
t.destroy();
}
await test();
let init_refcount = pyodide.runPython(`from sys import getrefcount; getrefcount(d)`);
await test(); await test(); await test(); await test();
let new_refcount = pyodide.runPython(`getrefcount(d)`);
return new_refcount - init_refcount;
"""
)
def test_run_python_js_error(selenium):
selenium.run_js(
"""
function throwError(){
throw new Error("blah!");
}
self.throwError = throwError;
pyodide.runPython(`
from js import throwError
from unittest import TestCase
from pyodide.ffi import JsException
raises = TestCase().assertRaisesRegex
with raises(JsException, "blah!"):
throwError()
`);
"""
)
@pytest.mark.xfail_browsers(node="No DOMException in node")
@run_in_pyodide
def test_run_python_dom_error(selenium):
import pytest
from js import DOMException
from pyodide.ffi import JsException
with pytest.raises(JsException, match="oops"):
raise DOMException.new("oops")
def test_run_python_locals(selenium):
selenium.run_js(
"""
let dict = pyodide.globals.get("dict");
let locals = dict([["x", 7]]);
let globals = dict([["x", 5], ["y", 29]]);
dict.destroy();
let result = pyodide.runPython("z = 13; x + y", {locals, globals});
assert(() => locals.get("z") === 13);
assert(() => locals.has("x"));
let result2 = pyodide.runPython("del x; x + y", {locals, globals});
assert(() => !locals.has("x"));
assert(() => result === 7 + 29);
assert(() => result2 === 5 + 29);
locals.destroy();
globals.destroy();
"""
)
def test_create_once_callable(selenium):
selenium.run_js(
"""
self.call7 = function call7(f){
return f(7);
}
pyodide.runPython(`
from pyodide.ffi import create_once_callable, JsException
from js import call7;
from unittest import TestCase
raises = TestCase().assertRaisesRegex
class Square:
def __call__(self, x):
return x*x
def __del__(self):
global destroyed
destroyed = True
f = Square()
import sys
assert sys.getrefcount(f) == 2
proxy = create_once_callable(f)
assert sys.getrefcount(f) == 3
assert call7(proxy) == 49
assert sys.getrefcount(f) == 2
with raises(JsException, "can only be called once"):
call7(proxy)
destroyed = False
del f
assert destroyed == True
del proxy
`);
"""
)
@run_in_pyodide
def test_create_proxy(selenium):
from pyodide.code import run_js
from pyodide.ffi import create_proxy
[testAddListener, testCallListener, testRemoveListener] = run_js(
"""
function testAddListener(f){
self.listener = f;
}
function testCallListener(f){
return self.listener();
}
function testRemoveListener(f){
return self.listener === f;
}
[testAddListener, testCallListener, testRemoveListener]
"""
)
destroyed = False
class Test:
def __call__(self):
return 7
def __del__(self):
nonlocal destroyed
destroyed = True
f = Test()
import sys
assert sys.getrefcount(f) == 2
proxy = create_proxy(f)
assert sys.getrefcount(f) == 3
assert proxy() == 7 # type:ignore[operator]
testAddListener(proxy)
assert sys.getrefcount(f) == 3
assert testCallListener() == 7
assert sys.getrefcount(f) == 3
assert testCallListener() == 7
assert sys.getrefcount(f) == 3
assert testRemoveListener(proxy)
assert sys.getrefcount(f) == 3
proxy.destroy()
assert sys.getrefcount(f) == 2
destroyed = False
del f
assert destroyed
@run_in_pyodide
def test_create_proxy_capture_this(selenium):
from pyodide.code import run_js
from pyodide.ffi import create_proxy
o = run_js("({})")
def f(self):
assert self == o
o.f = create_proxy(f, capture_this=True)
run_js("(o) => { o.f(); o.f.destroy(); }")(o)
@run_in_pyodide
def test_create_proxy_roundtrip(selenium):
from pyodide.code import run_js
from pyodide.ffi import JsDoubleProxy, create_proxy
f = {} # type: ignore[var-annotated]
o = run_js("({})")
o.f = create_proxy(f, roundtrip=True)
assert isinstance(o.f, JsDoubleProxy)
assert o.f.unwrap() is f
o.f.destroy()
o.f = create_proxy(f, roundtrip=False)
assert o.f is f # type: ignore[comparison-overlap]
run_js("(o) => { o.f.destroy(); }")(o)
@run_in_pyodide
def test_return_destroyed_value(selenium):
import pytest
from pyodide.code import run_js
from pyodide.ffi import JsException, create_proxy
f = run_js("(function(x){ return x; })")
p = create_proxy([])
p.destroy()
with pytest.raises(JsException, match='The object was of type "list" and had repr'):
f(p)
def test_docstrings_a():
from _pyodide._core_docs import _instantiate_token
from _pyodide.docstring import dedent_docstring, get_cmeth_docstring
from pyodide.ffi import JsPromise
jsproxy = JsPromise(_instantiate_token)
c_docstring = get_cmeth_docstring(jsproxy.then)
assert c_docstring == "then(onfulfilled, onrejected)\n--\n\n" + dedent_docstring(
jsproxy.then.__doc__
)
def test_docstrings_b(selenium):
from _pyodide._core_docs import _instantiate_token
from _pyodide.docstring import dedent_docstring
from pyodide.ffi import JsPromise, create_once_callable
jsproxy = JsPromise(_instantiate_token)
ds_then_should_equal = dedent_docstring(jsproxy.then.__doc__)
sig_then_should_equal = "(onfulfilled, onrejected)"
ds_once_should_equal = dedent_docstring(create_once_callable.__doc__)
sig_once_should_equal = "(obj, /)"
selenium.run_js("self.a = Promise.resolve();")
[ds_then, sig_then, ds_once, sig_once] = selenium.run(
"""
from js import a
from pyodide.ffi import create_once_callable as b
[
a.then.__doc__, a.then.__text_signature__,
b.__doc__, b.__text_signature__
]
"""
)
assert ds_then == ds_then_should_equal
assert sig_then == sig_then_should_equal
assert ds_once == ds_once_should_equal
assert sig_once == sig_once_should_equal
@pytest.mark.skip_refcount_check
@pytest.mark.skip_pyproxy_check
def test_restore_state(selenium):
selenium.run_js(
"""
pyodide.registerJsModule("a", {somefield : 82});
pyodide.registerJsModule("b", { otherfield : 3 });
pyodide.runPython("x = 7; from a import somefield");
let state = pyodide._api.saveState();
pyodide.registerJsModule("c", { thirdfield : 9 });
pyodide.runPython("y = 77; from b import otherfield; import c;");
pyodide._api.restoreState(state);
state.destroy();
"""
)
selenium.run(
"""
from unittest import TestCase
raises = TestCase().assertRaises
import sys
assert x == 7
assert "a" in sys.modules
assert somefield == 82
with raises(NameError):
y
with raises(NameError):
otherfield
assert "b" not in sys.modules
import b
with raises(ModuleNotFoundError):
import c
"""
)
@pytest.mark.xfail_browsers(safari="TODO: traceback is not the same on Safari")
@pytest.mark.skip_refcount_check
def test_fatal_error(selenium_standalone):
assert selenium_standalone.run_js(
"""
try {
pyodide.runPython(`
from _pyodide_core import trigger_fatal_error
def f():
g()
def g():
h()
def h():
trigger_fatal_error()
f()
`);
} catch(e){
return e.toString();
}
"""
)
import re
def strip_stack_trace(x):
x = re.sub("\n.*site-packages.*", "", x)
x = re.sub("/lib/python.*/", "", x)
x = re.sub("/lib/python.*/", "", x)
x = re.sub("warning: no [bB]lob.*\n", "", x)
x = re.sub("Error: intentionally triggered fatal error!\n", "", x)
x = re.sub(" +at .*\n", "", x)
x = re.sub(".*@https?://[0-9.:]*/.*\n", "", x)
x = re.sub(".*@debugger.*\n", "", x)
x = re.sub(".*@chrome.*\n", "", x)
x = re.sub("line [0-9]*", "line xxx", x)
x = x.replace("\n\n", "\n")
return x
err_msg = strip_stack_trace(selenium_standalone.logs)
err_msg = "".join(_strip_assertions_stderr(err_msg.splitlines(keepends=True)))
assert (
err_msg
== dedent(
strip_stack_trace(
"""
Pyodide has suffered a fatal error. Please report this to the Pyodide maintainers.
The cause of the fatal error was:
Stack (most recent call first):
File "<exec>", line 8 in h
File "<exec>", line 6 in g
File "<exec>", line 4 in f
File "<exec>", line 9 in <module>
File "/lib/pythonxxx/pyodide/_base.py", line 242 in run
File "/lib/pythonxxx/pyodide/_base.py", line 344 in eval_code
"""
)
).strip()
)
selenium_standalone.run_js(
"""
assertThrows(() => pyodide.runPython, "Error", "Pyodide already fatally failed and can no longer be used.")
assertThrows(() => pyodide.globals, "Error", "Pyodide already fatally failed and can no longer be used.")
"""
)
@pytest.mark.skip_refcount_check
def test_exit_error(selenium_standalone):
x = selenium_standalone.run_js(
"""
try {
pyodide.runPython(`
import os
def f():
g()
def g():
h()
def h():
os._exit(0)
f()
`);
} catch(e){
return e.toString();
}
"""
)
assert x == "Exit: Program terminated with exit(0)"
def test_reentrant_error(selenium):
caught = selenium.run_js(
"""
function raisePythonKeyboardInterrupt(){
pyodide.globals.get("pyfunc")();
}
let caught = false;
try {
pyodide.runPython(`
def pyfunc():
raise KeyboardInterrupt
from js import raisePythonKeyboardInterrupt
try:
raisePythonKeyboardInterrupt()
except Exception as e:
pass
`);
} catch(e){
caught = true;
}
return caught;
"""
)
assert caught
@pytest.mark.xfail_browsers(safari="TODO: traceback is not exactly the same on Safari")
def test_js_stackframes(selenium):
res = selenium.run_js(
"""
self.b = function b(){
pyodide.pyimport("???");
}
self.d1 = function d1(){
pyodide.runPython("c2()");
}
self.d2 = function d2(){
d1();
}
self.d3 = function d3(){
d2();
}
self.d4 = function d4(){
d3();
}
pyodide.runPython(`
def c1():
from js import b
b()
def c2():
c1()
def e():
from js import d4
from pyodide.ffi import to_js
from traceback import extract_tb
try:
d4()
except Exception as ex:
return to_js([[x.filename, x.name] for x in extract_tb(ex.__traceback__)])
`);
let e = pyodide.globals.get("e");
let res = e();
e.destroy();
return res;
"""
)
def normalize_tb(t):
res = []
for [file, name] in t:
if file.endswith((".js", ".html")):
file = file.rpartition("/")[-1]
if file.endswith(".py"):
file = "/".join(file.split("/")[-2:])
if (
re.fullmatch(r"\:[0-9]*", file)
or file == "evalmachine.<anonymous>"
or file == "debugger eval code"
):
file = "test.html"
res.append([file, name])
return res
frames = [
["<exec>", "e"],