forked from emscripten-core/emscripten
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.py
2537 lines (2131 loc) · 87 KB
/
common.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
# Copyright 2021 The Emscripten Authors. All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
from enum import Enum
from functools import wraps
from pathlib import Path
from subprocess import PIPE, STDOUT
from typing import Dict, Tuple
from urllib.parse import unquote, unquote_plus, urlparse, parse_qs
from http.server import HTTPServer, SimpleHTTPRequestHandler
import contextlib
import difflib
import hashlib
import itertools
import logging
import multiprocessing
import os
import re
import shlex
import shutil
import stat
import string
import subprocess
import sys
import tempfile
import textwrap
import time
import webbrowser
import unittest
import queue
import clang_native
import jsrun
import line_endings
from tools.shared import EMCC, EMXX, DEBUG
from tools.shared import get_canonical_temp_dir, path_from_root
from tools.utils import MACOS, WINDOWS, read_file, read_binary, write_binary, exit_with_error
from tools.settings import COMPILE_TIME_SETTINGS
from tools import shared, feature_matrix, building, config, utils
logger = logging.getLogger('common')
# User can specify an environment variable EMTEST_BROWSER to force the browser
# test suite to run using another browser command line than the default system
# browser.
# There are two special value that can be used here if running in an actual
# browser is not desired:
# EMTEST_BROWSER=0 : This will disable the actual running of the test and simply
# verify that it compiles and links.
# EMTEST_BROWSER=node : This will attempt to run the browser test under node.
# For most browser tests this does not work, but it can
# be useful for running pthread tests under node.
EMTEST_BROWSER = None
EMTEST_DETECT_TEMPFILE_LEAKS = None
EMTEST_SAVE_DIR = None
# generally js engines are equivalent, testing 1 is enough. set this
# to force testing on all js engines, good to find js engine bugs
EMTEST_ALL_ENGINES = None
EMTEST_SKIP_SLOW = None
EMTEST_SKIP_FLAKY = None
EMTEST_RETRY_FLAKY = None
EMTEST_LACKS_NATIVE_CLANG = None
EMTEST_VERBOSE = None
EMTEST_REBASELINE = None
# Verbosity level control for subprocess calls to configure + make.
# 0: disabled.
# 1: Log stderr of configure/make.
# 2: Log stdout and stderr configure/make. Print out subprocess commands that were executed.
# 3: Log stdout and stderr, and pass VERBOSE=1 to CMake/configure/make steps.
EMTEST_BUILD_VERBOSE = int(os.getenv('EMTEST_BUILD_VERBOSE', '0'))
if 'EM_BUILD_VERBOSE' in os.environ:
exit_with_error('EM_BUILD_VERBOSE has been renamed to EMTEST_BUILD_VERBOSE')
# Special value for passing to assert_returncode which means we expect that program
# to fail with non-zero return code, but we don't care about specifically which one.
NON_ZERO = -1
TEST_ROOT = path_from_root('test')
LAST_TEST = path_from_root('out/last_test.txt')
WEBIDL_BINDER = shared.bat_suffix(path_from_root('tools/webidl_binder'))
EMBUILDER = shared.bat_suffix(path_from_root('embuilder'))
EMMAKE = shared.bat_suffix(path_from_root('emmake'))
EMCMAKE = shared.bat_suffix(path_from_root('emcmake'))
EMCONFIGURE = shared.bat_suffix(path_from_root('emconfigure'))
EMRUN = shared.bat_suffix(shared.path_from_root('emrun'))
WASM_DIS = Path(building.get_binaryen_bin(), 'wasm-dis')
LLVM_OBJDUMP = os.path.expanduser(shared.build_llvm_tool_path(shared.exe_suffix('llvm-objdump')))
PYTHON = sys.executable
if not config.NODE_JS_TEST:
config.NODE_JS_TEST = config.NODE_JS
requires_network = unittest.skipIf(os.getenv('EMTEST_SKIP_NETWORK_TESTS'), 'This test requires network access')
def test_file(*path_components):
"""Construct a path relative to the emscripten "tests" directory."""
return str(Path(TEST_ROOT, *path_components))
def copytree(src, dest):
shutil.copytree(src, dest, dirs_exist_ok=True)
# checks if browser testing is enabled
def has_browser():
return EMTEST_BROWSER != '0'
def compiler_for(filename, force_c=False):
if shared.suffix(filename) in ('.cc', '.cxx', '.cpp') and not force_c:
return EMXX
else:
return EMCC
# Generic decorator that calls a function named 'condition' on the test class and
# skips the test if that function returns true
def skip_if(func, condition, explanation='', negate=False):
assert callable(func)
explanation_str = ' : %s' % explanation if explanation else ''
@wraps(func)
def decorated(self, *args, **kwargs):
choice = self.__getattribute__(condition)()
if negate:
choice = not choice
if choice:
self.skipTest(condition + explanation_str)
func(self, *args, **kwargs)
return decorated
def is_slow_test(func):
assert callable(func)
@wraps(func)
def decorated(self, *args, **kwargs):
if EMTEST_SKIP_SLOW:
return self.skipTest('skipping slow tests')
return func(self, *args, **kwargs)
return decorated
def flaky(note=''):
assert not callable(note)
if EMTEST_SKIP_FLAKY:
return unittest.skip(note)
if not EMTEST_RETRY_FLAKY:
return lambda f: f
def decorated(f):
@wraps(f)
def modified(*args, **kwargs):
for i in range(EMTEST_RETRY_FLAKY):
try:
return f(*args, **kwargs)
except AssertionError as exc:
preserved_exc = exc
logging.info(f'Retrying flaky test (attempt {i}/{EMTEST_RETRY_FLAKY} failed): {exc}')
raise AssertionError('Flaky test has failed too many times') from preserved_exc
return modified
return decorated
def disabled(note=''):
assert not callable(note)
return unittest.skip(note)
def no_mac(note=''):
assert not callable(note)
if MACOS:
return unittest.skip(note)
return lambda f: f
def no_windows(note=''):
assert not callable(note)
if WINDOWS:
return unittest.skip(note)
return lambda f: f
def no_wasm64(note=''):
assert not callable(note)
def decorated(f):
return skip_if(f, 'is_wasm64', note)
return decorated
def no_2gb(note):
assert not callable(note)
def decorator(f):
assert callable(f)
@wraps(f)
def decorated(self, *args, **kwargs):
# 2200mb is the value used by the core_2gb test mode
if self.get_setting('INITIAL_MEMORY') == '2200mb':
self.skipTest(note)
f(self, *args, **kwargs)
return decorated
return decorator
def no_4gb(note):
assert not callable(note)
def decorator(f):
assert callable(f)
@wraps(f)
def decorated(self, *args, **kwargs):
if self.is_4gb():
self.skipTest(note)
f(self, *args, **kwargs)
return decorated
return decorator
def only_windows(note=''):
assert not callable(note)
if not WINDOWS:
return unittest.skip(note)
return lambda f: f
def requires_native_clang(func):
assert callable(func)
@wraps(func)
def decorated(self, *args, **kwargs):
if EMTEST_LACKS_NATIVE_CLANG:
return self.skipTest('native clang tests are disabled')
return func(self, *args, **kwargs)
return decorated
def requires_node(func):
assert callable(func)
@wraps(func)
def decorated(self, *args, **kwargs):
self.require_node()
return func(self, *args, **kwargs)
return decorated
def requires_node_canary(func):
assert callable(func)
@wraps(func)
def decorated(self, *args, **kwargs):
self.require_node_canary()
return func(self, *args, **kwargs)
return decorated
def requires_wasm64(func):
assert callable(func)
@wraps(func)
def decorated(self, *args, **kwargs):
self.require_wasm64()
return func(self, *args, **kwargs)
return decorated
def requires_wasm_legacy_eh(func):
assert callable(func)
@wraps(func)
def decorated(self, *args, **kwargs):
self.require_wasm_legacy_eh()
return func(self, *args, **kwargs)
return decorated
def requires_wasm_eh(func):
assert callable(func)
@wraps(func)
def decorated(self, *args, **kwargs):
self.require_wasm_eh()
return func(self, *args, **kwargs)
return decorated
def requires_v8(func):
assert callable(func)
@wraps(func)
def decorated(self, *args, **kwargs):
self.require_v8()
return func(self, *args, **kwargs)
return decorated
def requires_wasm2js(f):
assert callable(f)
@wraps(f)
def decorated(self, *args, **kwargs):
self.require_wasm2js()
return f(self, *args, **kwargs)
return decorated
def requires_jspi(func):
assert callable(func)
@wraps(func)
def decorated(self, *args, **kwargs):
self.require_jspi()
return func(self, *args, **kwargs)
return decorated
def node_pthreads(f):
assert callable(f)
@wraps(f)
def decorated(self, *args, **kwargs):
self.setup_node_pthreads()
f(self, *args, **kwargs)
return decorated
def crossplatform(f):
f.is_crossplatform_test = True
return f
@contextlib.contextmanager
def env_modify(updates):
"""A context manager that updates os.environ."""
# This could also be done with mock.patch.dict() but taking a dependency
# on the mock library is probably not worth the benefit.
old_env = os.environ.copy()
print("env_modify: " + str(updates))
# Setting a value to None means clear the environment variable
clears = [key for key, value in updates.items() if value is None]
updates = {key: value for key, value in updates.items() if value is not None}
os.environ.update(updates)
for key in clears:
if key in os.environ:
del os.environ[key]
try:
yield
finally:
os.environ.clear()
os.environ.update(old_env)
# Decorator version of env_modify
def with_env_modify(updates):
assert not callable(updates)
def decorated(f):
@wraps(f)
def modified(self, *args, **kwargs):
with env_modify(updates):
return f(self, *args, **kwargs)
return modified
return decorated
def also_with_wasmfs(f):
assert callable(f)
@wraps(f)
def metafunc(self, wasmfs, *args, **kwargs):
if DEBUG:
print('parameterize:wasmfs=%d' % wasmfs)
if wasmfs:
self.setup_wasmfs_test()
else:
self.emcc_args += ['-DMEMFS']
f(self, *args, **kwargs)
parameterize(metafunc, {'': (False,),
'wasmfs': (True,)})
return metafunc
def also_with_nodefs(func):
@wraps(func)
def metafunc(self, fs, *args, **kwargs):
if DEBUG:
print('parameterize:fs=%s' % (fs))
if fs == 'nodefs':
self.setup_nodefs_test()
else:
self.emcc_args += ['-DMEMFS']
assert fs is None
func(self, *args, **kwargs)
parameterize(metafunc, {'': (None,),
'nodefs': ('nodefs',)})
return metafunc
def also_with_nodefs_both(func):
@wraps(func)
def metafunc(self, fs, *args, **kwargs):
if DEBUG:
print('parameterize:fs=%s' % (fs))
if fs == 'nodefs':
self.setup_nodefs_test()
elif fs == 'rawfs':
self.setup_noderawfs_test()
else:
self.emcc_args += ['-DMEMFS']
assert fs is None
func(self, *args, **kwargs)
parameterize(metafunc, {'': (None,),
'nodefs': ('nodefs',),
'rawfs': ('rawfs',)})
return metafunc
def with_all_fs(func):
@wraps(func)
def metafunc(self, wasmfs, fs, *args, **kwargs):
if DEBUG:
print('parameterize:fs=%s' % (fs))
if wasmfs:
self.setup_wasmfs_test()
if fs == 'nodefs':
self.setup_nodefs_test()
elif fs == 'rawfs':
self.setup_noderawfs_test()
else:
self.emcc_args += ['-DMEMFS']
assert fs is None
func(self, *args, **kwargs)
parameterize(metafunc, {'': (False, None,),
'nodefs': (False, 'nodefs',),
'rawfs': (False, 'rawfs',),
'wasmfs': (True, None,),
'wasmfs_nodefs': (True, 'nodefs',),
'wasmfs_rawfs': (True, 'rawfs',)})
return metafunc
def also_with_noderawfs(func):
assert callable(func)
@wraps(func)
def metafunc(self, rawfs, *args, **kwargs):
if DEBUG:
print('parameterize:rawfs=%d' % rawfs)
if rawfs:
self.setup_noderawfs_test()
else:
self.emcc_args += ['-DMEMFS']
func(self, *args, **kwargs)
parameterize(metafunc, {'': (False,),
'rawfs': (True,)})
return metafunc
# Decorator version of env_modify
def also_with_env_modify(name_updates_mapping):
def decorated(f):
@wraps(f)
def metafunc(self, updates, *args, **kwargs):
if DEBUG:
print('parameterize:env_modify=%s' % (updates))
if updates:
with env_modify(updates):
return f(self, *args, **kwargs)
else:
return f(self, *args, **kwargs)
params = {'': (None,)}
for name, updates in name_updates_mapping.items():
params[name] = (updates,)
parameterize(metafunc, params)
return metafunc
return decorated
def also_with_minimal_runtime(f):
assert callable(f)
@wraps(f)
def metafunc(self, with_minimal_runtime, *args, **kwargs):
if DEBUG:
print('parameterize:minimal_runtime=%s' % with_minimal_runtime)
assert self.get_setting('MINIMAL_RUNTIME') is None
if with_minimal_runtime:
self.set_setting('MINIMAL_RUNTIME', 1)
# This extra helper code is needed to cleanly handle calls to exit() which throw
# an ExitCode exception.
self.emcc_args += ['--pre-js', test_file('minimal_runtime_exit_handling.js')]
f(self, *args, **kwargs)
parameterize(metafunc, {'': (False,),
'minimal_runtime': (True,)})
return metafunc
def also_with_wasm_bigint(f):
assert callable(f)
@wraps(f)
def metafunc(self, with_bigint, *args, **kwargs):
if DEBUG:
print('parameterize:bigint=%s' % with_bigint)
if with_bigint:
if self.is_wasm2js():
self.skipTest('wasm2js does not support WASM_BIGINT')
if self.get_setting('WASM_BIGINT') is not None:
self.skipTest('redundant in bigint test config')
self.set_setting('WASM_BIGINT')
nodejs = self.require_node()
self.node_args += shared.node_bigint_flags(nodejs)
f(self, *args, **kwargs)
else:
f(self, *args, **kwargs)
parameterize(metafunc, {'': (False,),
'bigint': (True,)})
return metafunc
def also_with_wasm64(f):
assert callable(f)
@wraps(f)
def metafunc(self, with_wasm64, *args, **kwargs):
if DEBUG:
print('parameterize:wasm64=%s' % with_wasm64)
if with_wasm64:
self.require_wasm64()
self.set_setting('MEMORY64')
f(self, *args, **kwargs)
else:
f(self, *args, **kwargs)
parameterize(metafunc, {'': (False,),
'wasm64': (True,)})
return metafunc
def also_with_wasm2js(f):
assert callable(f)
@wraps(f)
def metafunc(self, with_wasm2js, *args, **kwargs):
assert self.get_setting('WASM') is None
if DEBUG:
print('parameterize:wasm2js=%s' % with_wasm2js)
if with_wasm2js:
self.require_wasm2js()
self.set_setting('WASM', 0)
f(self, *args, **kwargs)
else:
f(self, *args, **kwargs)
parameterize(metafunc, {'': (False,),
'wasm2js': (True,)})
return metafunc
def can_do_standalone(self, impure=False):
# Pure standalone engines don't support MEMORY64 yet. Even with MEMORY64=2 (lowered)
# the WASI APIs that take pointer values don't have 64-bit variants yet.
if not impure:
if self.get_setting('MEMORY64'):
return False
# This is way to detect the core_2gb test mode in test_core.py
if self.get_setting('INITIAL_MEMORY') == '2200mb':
return False
return self.is_wasm() and \
self.get_setting('STACK_OVERFLOW_CHECK', 0) < 2 and \
not self.get_setting('MINIMAL_RUNTIME') and \
not self.get_setting('SAFE_HEAP') and \
not any(a.startswith('-fsanitize=') for a in self.emcc_args)
# Impure means a test that cannot run in a wasm VM yet, as it is not 100%
# standalone. We can still run them with the JS code though.
def also_with_standalone_wasm(impure=False):
def decorated(func):
@wraps(func)
def metafunc(self, standalone):
if DEBUG:
print('parameterize:standalone=%s' % standalone)
if not standalone:
func(self)
else:
if not can_do_standalone(self, impure):
self.skipTest('Test configuration is not compatible with STANDALONE_WASM')
self.set_setting('STANDALONE_WASM')
if not impure:
self.set_setting('PURE_WASI')
# we will not legalize the JS ffi interface, so we must use BigInt
# support in order for JS to have a chance to run this without trapping
# when it sees an i64 on the ffi.
self.set_setting('WASM_BIGINT')
self.emcc_args.append('-Wno-unused-command-line-argument')
# if we are impure, disallow all wasm engines
if impure:
self.wasm_engines = []
nodejs = self.require_node()
self.node_args += shared.node_bigint_flags(nodejs)
func(self)
parameterize(metafunc, {'': (False,),
'standalone': (True,)})
return metafunc
return decorated
def also_with_asan(f):
assert callable(f)
@wraps(f)
def metafunc(self, asan, *args, **kwargs):
if asan:
if self.is_wasm64():
self.skipTest('TODO: ASAN in memory64')
if self.is_2gb() or self.is_4gb():
self.skipTest('asan doesnt support GLOBAL_BASE')
self.emcc_args.append('-fsanitize=address')
f(self, *args, **kwargs)
parameterize(metafunc, {'': (False,),
'asan': (True,)})
return metafunc
def also_with_modularize(f):
assert callable(f)
@wraps(f)
def metafunc(self, modularize, *args, **kwargs):
if modularize:
self.emcc_args += ['--extern-post-js', test_file('modularize_post_js.js'), '-sMODULARIZE']
f(self, *args, **kwargs)
parameterize(metafunc, {'': (False,),
'modularize': (True,)})
return metafunc
# Tests exception handling and setjmp/longjmp handling. This tests three
# combinations:
# - Emscripten EH + Emscripten SjLj
# - Wasm EH + Wasm SjLj
# - Wasm EH + Wasm SjLj (Legacy)
def with_all_eh_sjlj(f):
assert callable(f)
@wraps(f)
def metafunc(self, mode, *args, **kwargs):
if DEBUG:
print('parameterize:eh_mode=%s' % mode)
if mode in {'wasm', 'wasm_legacy'}:
# Wasm EH is currently supported only in wasm backend and V8
if self.is_wasm2js():
self.skipTest('wasm2js does not support wasm EH/SjLj')
self.emcc_args.append('-fwasm-exceptions')
self.set_setting('SUPPORT_LONGJMP', 'wasm')
if mode == 'wasm':
self.require_wasm_eh()
if mode == 'wasm_legacy':
self.require_wasm_legacy_eh()
f(self, *args, **kwargs)
else:
self.set_setting('DISABLE_EXCEPTION_CATCHING', 0)
self.set_setting('SUPPORT_LONGJMP', 'emscripten')
# DISABLE_EXCEPTION_CATCHING=0 exports __cxa_can_catch,
# so if we don't build in C++ mode, wasm-ld will
# error out because libc++abi is not included. See
# https://github.com/emscripten-core/emscripten/pull/14192 for details.
self.set_setting('DEFAULT_TO_CXX')
f(self, *args, **kwargs)
parameterize(metafunc, {'emscripten': ('emscripten',),
'wasm': ('wasm',),
'wasm_legacy': ('wasm_legacy',)})
return metafunc
# This works just like `with_all_eh_sjlj` above but doesn't enable exceptions.
# Use this for tests that use setjmp/longjmp but not exceptions handling.
def with_all_sjlj(f):
assert callable(f)
@wraps(f)
def metafunc(self, mode, *args, **kwargs):
if mode in {'wasm', 'wasm_legacy'}:
if self.is_wasm2js():
self.skipTest('wasm2js does not support wasm SjLj')
self.set_setting('SUPPORT_LONGJMP', 'wasm')
if mode == 'wasm':
self.require_wasm_eh()
if mode == 'wasm_legacy':
self.require_wasm_legacy_eh()
f(self, *args, **kwargs)
else:
self.set_setting('SUPPORT_LONGJMP', 'emscripten')
f(self, *args, **kwargs)
parameterize(metafunc, {'emscripten': ('emscripten',),
'wasm': ('wasm',),
'wasm_legacy': ('wasm_legacy',)})
return metafunc
def ensure_dir(dirname):
dirname = Path(dirname)
dirname.mkdir(parents=True, exist_ok=True)
def limit_size(string):
maxbytes = 800000 * 20
if sys.stdout.isatty():
maxlines = 500
max_line = 500
else:
max_line = 5000
maxlines = 1000
lines = string.splitlines()
for i, line in enumerate(lines):
if len(line) > max_line:
lines[i] = line[:max_line] + '[..]'
if len(lines) > maxlines:
lines = lines[0:maxlines // 2] + ['[..]'] + lines[-maxlines // 2:]
lines.append('(not all output shown. See `limit_size`)')
string = '\n'.join(lines) + '\n'
if len(string) > maxbytes:
string = string[0:maxbytes // 2] + '\n[..]\n' + string[-maxbytes // 2:]
return string
def create_file(name, contents, binary=False, absolute=False):
name = Path(name)
assert absolute or not name.is_absolute(), name
if binary:
name.write_bytes(contents)
else:
# Dedent the contents of text files so that the files on disc all
# start in column 1, even if they are indented when embedded in the
# python test code.
contents = textwrap.dedent(contents)
name.write_text(contents, encoding='utf-8')
@contextlib.contextmanager
def chdir(dir):
"""A context manager that performs actions in the given directory."""
orig_cwd = os.getcwd()
os.chdir(dir)
try:
yield
finally:
os.chdir(orig_cwd)
def make_executable(name):
Path(name).chmod(stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
def make_dir_writeable(dirname):
# Some tests make files and subdirectories read-only, so rmtree/unlink will not delete
# them. Force-make everything writable in the subdirectory to make it
# removable and re-attempt.
os.chmod(dirname, 0o777)
for directory, subdirs, files in os.walk(dirname):
for item in files + subdirs:
i = os.path.join(directory, item)
if not os.path.islink(i):
os.chmod(i, 0o777)
def force_delete_dir(dirname):
make_dir_writeable(dirname)
utils.delete_dir(dirname)
def force_delete_contents(dirname):
make_dir_writeable(dirname)
utils.delete_contents(dirname)
def find_browser_test_file(filename):
"""Looks for files in test/browser and then in test/
"""
if not os.path.exists(filename):
fullname = test_file('browser', filename)
if not os.path.exists(fullname):
fullname = test_file(filename)
filename = fullname
return filename
def parameterize(func, parameters):
"""Add additional parameterization to a test function.
This function create or adds to the `_parameterize` property of a function
which is then expanded by the RunnerMeta metaclass into multiple separate
test functions.
"""
prev = getattr(func, '_parameterize', None)
assert not any(p.startswith('_') for p in parameters)
if prev:
# If we're parameterizing 2nd time, construct a cartesian product for various combinations.
func._parameterize = {
'_'.join(filter(None, [k1, k2])): v2 + v1 for (k1, v1), (k2, v2) in itertools.product(prev.items(), parameters.items())
}
else:
func._parameterize = parameters
def parameterized(parameters):
"""
Mark a test as parameterized.
Usage:
@parameterized({
'subtest1': (1, 2, 3),
'subtest2': (4, 5, 6),
})
def test_something(self, a, b, c):
... # actual test body
This is equivalent to defining two tests:
def test_something_subtest1(self):
# runs test_something(1, 2, 3)
def test_something_subtest2(self):
# runs test_something(4, 5, 6)
"""
def decorator(func):
parameterize(func, parameters)
return func
return decorator
class RunnerMeta(type):
@classmethod
def make_test(mcs, name, func, suffix, args):
"""
This is a helper function to create new test functions for each parameterized form.
:param name: the original name of the function
:param func: the original function that we are parameterizing
:param suffix: the suffix to append to the name of the function for this parameterization
:param args: the positional arguments to pass to the original function for this parameterization
:returns: a tuple of (new_function_name, new_function_object)
"""
# Create the new test function. It calls the original function with the specified args.
# We use @functools.wraps to copy over all the function attributes.
@wraps(func)
def resulting_test(self):
return func(self, *args)
# Add suffix to the function name so that it displays correctly.
if suffix:
resulting_test.__name__ = f'{name}_{suffix}'
else:
resulting_test.__name__ = name
# On python 3, functions have __qualname__ as well. This is a full dot-separated path to the
# function. We add the suffix to it as well.
resulting_test.__qualname__ = f'{func.__qualname__}_{suffix}'
return resulting_test.__name__, resulting_test
def __new__(mcs, name, bases, attrs):
# This metaclass expands parameterized methods from `attrs` into separate ones in `new_attrs`.
new_attrs = {}
for attr_name, value in attrs.items():
# Check if a member of the new class has _parameterize, the tag inserted by @parameterized.
if hasattr(value, '_parameterize'):
# If it does, we extract the parameterization information, build new test functions.
for suffix, args in value._parameterize.items():
new_name, func = mcs.make_test(attr_name, value, suffix, args)
assert new_name not in new_attrs, 'Duplicate attribute name generated when parameterizing %s' % attr_name
new_attrs[new_name] = func
else:
# If not, we just copy it over to new_attrs verbatim.
assert attr_name not in new_attrs, '%s collided with an attribute from parameterization' % attr_name
new_attrs[attr_name] = value
# We invoke type, the default metaclass, to actually create the new class, with new_attrs.
return type.__new__(mcs, name, bases, new_attrs)
class RunnerCore(unittest.TestCase, metaclass=RunnerMeta):
# default temporary directory settings. set_temp_dir may be called later to
# override these
temp_dir = shared.TEMP_DIR
canonical_temp_dir = get_canonical_temp_dir(shared.TEMP_DIR)
# This avoids cluttering the test runner output, which is stderr too, with compiler warnings etc.
# Change this to None to get stderr reporting, for debugging purposes
stderr_redirect = STDOUT
def is_wasm(self):
return self.get_setting('WASM') != 0
def is_wasm2js(self):
return not self.is_wasm()
def is_browser_test(self):
return False
def is_wasm64(self):
return self.get_setting('MEMORY64')
def is_4gb(self):
return self.get_setting('INITIAL_MEMORY') == '4200mb'
def is_2gb(self):
return self.get_setting('INITIAL_MEMORY') == '2200mb'
def check_dylink(self):
if self.is_wasm2js():
self.skipTest('no dynamic linking support in wasm2js yet')
if '-fsanitize=undefined' in self.emcc_args:
self.skipTest('no dynamic linking support in UBSan yet')
# MEMORY64=2 mode doesn't currently support dynamic linking because
# The side modules are lowered to wasm32 when they are built, making
# them unlinkable with wasm64 binaries.
if self.get_setting('MEMORY64') == 2:
self.skipTest('MEMORY64=2 + dynamic linking is not currently supported')
def require_v8(self):
if not config.V8_ENGINE or config.V8_ENGINE not in config.JS_ENGINES:
if 'EMTEST_SKIP_V8' in os.environ:
self.skipTest('test requires v8 and EMTEST_SKIP_V8 is set')
else:
self.fail('d8 required to run this test. Use EMTEST_SKIP_V8 to skip')
self.require_engine(config.V8_ENGINE)
self.emcc_args.append('-sENVIRONMENT=shell')
def get_nodejs(self):
if config.NODE_JS_TEST not in self.js_engines:
return None
return config.NODE_JS_TEST
def require_node(self):
nodejs = self.get_nodejs()
if not nodejs:
if 'EMTEST_SKIP_NODE' in os.environ:
self.skipTest('test requires node and EMTEST_SKIP_NODE is set')
else:
self.fail('node required to run this test. Use EMTEST_SKIP_NODE to skip')
self.require_engine(nodejs)
return nodejs
def node_is_canary(self, nodejs):
return nodejs and nodejs[0] and 'canary' in nodejs[0]
def require_node_canary(self):
nodejs = self.get_nodejs()
if self.node_is_canary(nodejs):
self.require_engine(nodejs)
return