runtests.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. #!/usr/bin/env python
  2. #-------------------------------------------------------------------------------------------------------
  3. # Copyright (C) Microsoft. All rights reserved.
  4. # Copyright (c) 2021 ChakraCore Project Contributors. All rights reserved.
  5. # Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  6. #-------------------------------------------------------------------------------------------------------
  7. from __future__ import print_function
  8. from datetime import datetime
  9. from multiprocessing import Pool, Manager, cpu_count
  10. from threading import Timer
  11. import sys
  12. import os
  13. import glob
  14. import subprocess as SP
  15. import traceback
  16. import argparse
  17. import xml.etree.ElementTree as ET
  18. import re
  19. import time
  20. # handle command line args
  21. parser = argparse.ArgumentParser(
  22. description='ChakraCore *nix Test Script',
  23. formatter_class=argparse.RawDescriptionHelpFormatter,
  24. epilog='''\
  25. Samples:
  26. test all folders:
  27. runtests.py
  28. test only Array:
  29. runtests.py Array
  30. test a single file:
  31. runtests.py Basics/hello.js
  32. ''')
  33. DEFAULT_TIMEOUT = 60
  34. SLOW_TIMEOUT = 180
  35. parser.add_argument('folders', metavar='folder', nargs='*',
  36. help='folder subset to run tests')
  37. parser.add_argument('-b', '--binary', metavar='bin',
  38. help='ch full path')
  39. parser.add_argument('-v', '--verbose', action='store_true',
  40. help='increase verbosity of output')
  41. parser.add_argument('--sanitize', metavar='sanitizers',
  42. help='ignore tests known to be broken with these sanitizers')
  43. parser.add_argument('-d', '--debug', action='store_true',
  44. help='use debug build')
  45. parser.add_argument('-t', '--test', '--test-build', action='store_true',
  46. help='use test build')
  47. parser.add_argument('--variants', metavar='variant', nargs='+',
  48. help='run specified test variants')
  49. parser.add_argument('--include-slow', action='store_true',
  50. help='include slow tests (timeout ' + str(SLOW_TIMEOUT) + ' seconds)')
  51. parser.add_argument('--only-slow', action='store_true',
  52. help='run only slow tests')
  53. parser.add_argument('--tag', nargs='*',
  54. help='select tests with given tags')
  55. parser.add_argument('--not-tag', action='append',
  56. help='exclude tests with given tags')
  57. parser.add_argument('--flags', default='',
  58. help='global test flags to ch')
  59. parser.add_argument('--timeout', type=int, default=DEFAULT_TIMEOUT,
  60. help='test timeout (default ' + str(DEFAULT_TIMEOUT) + ' seconds)')
  61. parser.add_argument('--swb', action='store_true',
  62. help='use binary from VcBuild.SWB to run the test')
  63. parser.add_argument('--lldb', default=None,
  64. help='run test suit with lldb batch mode to get call stack for crashing processes (ignores baseline matching)', action='store_true')
  65. parser.add_argument('--x86', action='store_true',
  66. help='use x86 build')
  67. parser.add_argument('--x64', action='store_true',
  68. help='use x64 build')
  69. parser.add_argument('--arm', action='store_true',
  70. help='use arm build')
  71. parser.add_argument('--arm64', action='store_true',
  72. help='use arm64 build')
  73. parser.add_argument('-j', '--processcount', metavar='processcount', type=int,
  74. help='number of parallel threads to use')
  75. parser.add_argument('--warn-on-timeout', action='store_true',
  76. help='warn when a test times out instead of labelling it as an error immediately')
  77. parser.add_argument('--override-test-root', type=str,
  78. help='change the base directory for the tests (where rlexedirs will be sought)')
  79. parser.add_argument('--extra-flags', type=str,
  80. help='add extra flags to all executed tests')
  81. parser.add_argument('--orc','--only-return-code', action='store_true',
  82. help='only consider test return 0/non-0 for pass-fail (no baseline checks)')
  83. parser.add_argument('--show-passes', action='store_true',
  84. help='display passed tests, when false only failures and the result summary are shown')
  85. args = parser.parse_args()
  86. test_root = os.path.dirname(os.path.realpath(__file__))
  87. repo_root = os.path.dirname(test_root)
  88. # new test root
  89. if args.override_test_root:
  90. test_root = os.path.realpath(args.override_test_root)
  91. # arch: x86, x64, arm, arm64
  92. arch = None
  93. if args.x86:
  94. arch = 'x86'
  95. elif args.x64:
  96. arch = 'x64'
  97. elif args.arm:
  98. arch = 'arm'
  99. elif args.arm64:
  100. arch = 'arm64'
  101. if arch == None:
  102. arch = os.environ.get('_BuildArch', 'x86')
  103. if sys.platform != 'win32':
  104. arch = 'x64' # xplat: hard code arch == x64
  105. arch_alias = 'amd64' if arch == 'x64' else None
  106. # flavor: debug, test, release
  107. flavor = 'Debug' if args.debug else ('Test' if args.test else None)
  108. if flavor == None:
  109. print("ERROR: Test build target wasn't defined.")
  110. print("Try '-t' (test build) or '-d' (debug build).")
  111. sys.exit(1)
  112. # handling for extra flags
  113. extra_flags = ['-WERExceptionSupport']
  114. if args.extra_flags:
  115. extra_flags = args.extra_flags.split()
  116. # test variants
  117. if not args.variants:
  118. args.variants = ['interpreted', 'dynapogo']
  119. # append exe to the binary name on windows
  120. binary_name = "ch"
  121. if sys.platform == 'win32':
  122. binary_name = "ch.exe"
  123. # binary: full ch path
  124. binary = args.binary
  125. if binary == None:
  126. if sys.platform == 'win32':
  127. build = "VcBuild.SWB" if args.swb else "VcBuild"
  128. binary = os.path.join(repo_root, 'Build', build, 'bin', '{}_{}'.format(arch, flavor), binary_name)
  129. else:
  130. binary = os.path.join(repo_root, 'out', flavor, binary_name)
  131. if not os.path.isfile(binary):
  132. print('{} not found. Aborting.'.format(binary))
  133. sys.exit(1)
  134. # global tags/not_tags
  135. tags = set(args.tag or [])
  136. not_tags = set(args.not_tag or []).union(['fail', 'exclude_' + arch, 'exclude_' + flavor])
  137. if arch_alias:
  138. not_tags.add('exclude_' + arch_alias)
  139. if args.only_slow:
  140. tags.add('Slow')
  141. elif not args.include_slow:
  142. not_tags.add('Slow')
  143. elif args.include_slow and args.timeout == DEFAULT_TIMEOUT:
  144. args.timeout = SLOW_TIMEOUT
  145. # verbosity
  146. verbose = False
  147. show_passes = False
  148. if args.verbose:
  149. verbose = True
  150. show_passes = True
  151. print("Emitting verbose output...")
  152. elif args.show_passes:
  153. show_passes = True
  154. # xplat: temp hard coded to exclude unsupported tests
  155. if sys.platform != 'win32':
  156. not_tags.add('exclude_xplat')
  157. not_tags.add('require_winglob')
  158. not_tags.add('require_simd')
  159. else:
  160. not_tags.add('exclude_windows')
  161. # exclude tests that depend on features not supported on a platform
  162. if arch == 'arm' or arch == 'arm64':
  163. not_tags.add('require_asmjs')
  164. # exclude tests known to fail under certain sanitizers
  165. if args.sanitize != None:
  166. not_tags.add('exclude_sanitize_'+args.sanitize)
  167. if sys.platform == 'darwin':
  168. not_tags.add('exclude_mac')
  169. if 'require_icu' in not_tags or 'exclude_noicu' in not_tags:
  170. not_tags.add('Intl')
  171. not_compile_flags = None
  172. # use -j flag to specify number of parallel processes
  173. processcount = cpu_count()
  174. if args.processcount != None:
  175. processcount = int(args.processcount)
  176. # handle warn on timeout
  177. warn_on_timeout = False
  178. if args.warn_on_timeout == True:
  179. warn_on_timeout = True
  180. # handle limiting test result analysis to return codes
  181. return_code_only = False
  182. if args.orc == True:
  183. return_code_only = True
  184. # use tags/not_tags/not_compile_flags as case-insensitive
  185. def lower_set(s):
  186. return set([x.lower() for x in s] if s else [])
  187. tags = lower_set(tags)
  188. not_tags = lower_set(not_tags)
  189. not_compile_flags = lower_set(not_compile_flags)
  190. # split tags text into tags set
  191. _empty_set = set()
  192. def split_tags(text):
  193. return set(x.strip() for x in text.lower().split(',')) if text \
  194. else _empty_set
  195. # remove carriage returns at end of line to avoid platform difference
  196. def normalize_new_line(text):
  197. return re.sub(b'[\r]+\n', b'\n', text)
  198. # A test simply contains a collection of test attributes.
  199. # Misc attributes added by test run:
  200. # id unique counter to identify a test
  201. # filename full path of test file
  202. # elapsed_time elapsed time when running the test
  203. #
  204. class Test(dict):
  205. __setattr__ = dict.__setitem__
  206. __delattr__ = dict.__delitem__
  207. # support dot syntax for normal attribute access
  208. def __getattr__(self, key):
  209. return super(Test, self).__getattr__(key) if key.startswith('__') \
  210. else self.get(key)
  211. # mark start of this test run, to compute elapsed_time
  212. def start(self):
  213. self.start_time = datetime.now()
  214. # mark end of this test run, compute elapsed_time
  215. def done(self):
  216. if not self.elapsed_time:
  217. self.elapsed_time = (datetime.now() - self.start_time)\
  218. .total_seconds()
  219. # records pass_count/fail_count
  220. class PassFailCount(object):
  221. def __init__(self):
  222. self.pass_count = 0
  223. self.fail_count = 0
  224. def __str__(self):
  225. return 'passed {}, failed {}'.format(self.pass_count, self.fail_count)
  226. def total_count(self):
  227. return self.pass_count + self.fail_count
  228. # records total and individual folder's pass_count/fail_count
  229. class TestResult(PassFailCount):
  230. def __init__(self):
  231. super(self.__class__, self).__init__()
  232. self.folders = {}
  233. def _get_folder_result(self, folder):
  234. r = self.folders.get(folder)
  235. if not r:
  236. r = PassFailCount()
  237. self.folders[folder] = r
  238. return r
  239. def log(self, filename, fail=False):
  240. folder = os.path.basename(os.path.dirname(filename))
  241. r = self._get_folder_result(folder)
  242. if fail:
  243. r.fail_count += 1
  244. self.fail_count += 1
  245. else:
  246. r.pass_count += 1
  247. self.pass_count += 1
  248. # test variants:
  249. # interpreted: -maxInterpretCount:1 -maxSimpleJitRunCount:1 -bgjit-
  250. # dynapogo: -forceNative -off:simpleJit -bgJitDelay:0
  251. class TestVariant(object):
  252. def __init__(self, name, compile_flags=[], variant_not_tags=[]):
  253. self.name = name
  254. self.compile_flags = \
  255. ['-ExtendedErrorStackForTestHost',
  256. '-BaselineMode'] + compile_flags
  257. self._compile_flags_has_expansion = self._has_expansion(compile_flags)
  258. self.tags = tags.copy()
  259. self.not_tags = not_tags.union(variant_not_tags).union(
  260. ['{}_{}'.format(x, name) for x in ('fails','exclude')])
  261. self.msg_queue = Manager().Queue() # messages from multi processes
  262. self.test_result = TestResult()
  263. self.test_count = 0
  264. self._print_lines = [] # _print lines buffer
  265. self._last_len = 0
  266. if verbose:
  267. print("Added variant {0}:".format(name))
  268. print("Flags: " + ", ".join(self.compile_flags))
  269. print("Tags: " + ", ".join(self.tags))
  270. print("NotTags: " + ", ".join(self.not_tags))
  271. @staticmethod
  272. def _has_expansion(flags):
  273. return any(re.match('.*\${.*}', f) for f in flags)
  274. @staticmethod
  275. def _expand(flag, test):
  276. return re.sub('\${id}', str(test.id), flag)
  277. def _expand_compile_flags(self, test):
  278. if self._compile_flags_has_expansion:
  279. return [self._expand(flag, test) for flag in self.compile_flags]
  280. return self.compile_flags
  281. # check if this test variant should run a given test
  282. def _should_test(self, test):
  283. tags = split_tags(test.get('tags'))
  284. if not tags.isdisjoint(self.not_tags):
  285. return False
  286. if self.tags and not self.tags.issubset(tags):
  287. return False
  288. if not_compile_flags: # exclude unsupported compile-flags if any
  289. flags = test.get('compile-flags')
  290. if flags and \
  291. not not_compile_flags.isdisjoint(flags.lower().split()):
  292. return False
  293. return True
  294. # print output from multi-process run, to be sent with result message
  295. def _print(self, line):
  296. self._print_lines.append(line)
  297. # queue a test result from multi-process runs
  298. def _log_result(self, test, fail):
  299. if fail or show_passes:
  300. output = ''
  301. for line in self._print_lines:
  302. output = output + line + '\n' # collect buffered _print output
  303. else:
  304. output = ''
  305. self._print_lines = []
  306. self.msg_queue.put((test.filename, fail, test.elapsed_time, output))
  307. # (on main process) process one queued message
  308. def _process_msg(self, msg):
  309. filename, fail, elapsed_time, output = msg
  310. self.test_result.log(filename, fail=fail)
  311. if fail or show_passes:
  312. line = '[{}/{} {:4.2f}] {} -> {}'.format(
  313. self.test_result.total_count(),
  314. self.test_count,
  315. elapsed_time,
  316. 'Failed' if fail else 'Passed',
  317. self._short_name(filename))
  318. padding = self._last_len - len(line)
  319. print(line + ' ' * padding, end='\n' if fail else '\r')
  320. self._last_len = len(line) if not fail else 0
  321. if len(output) > 0:
  322. print(output)
  323. # get a shorter test file path for display only
  324. def _short_name(self, filename):
  325. folder = os.path.basename(os.path.dirname(filename))
  326. return os.path.join(folder, os.path.basename(filename))
  327. # (on main process) wait and process one queued message
  328. def _process_one_msg(self):
  329. self._process_msg(self.msg_queue.get())
  330. # log a failed test with details
  331. def _show_failed(self, test, flags, exit_code, output,
  332. expected_output=None, timedout=False):
  333. if timedout:
  334. if warn_on_timeout:
  335. self._print('WARNING: Test timed out!')
  336. else:
  337. self._print('ERROR: Test timed out!')
  338. self._print('{} {} {}'.format(binary, ' '.join(flags), test.filename))
  339. if not return_code_only:
  340. if expected_output == None or timedout:
  341. self._print("\nOutput:")
  342. self._print("----------------------------")
  343. self._print(output.decode('utf-8'))
  344. self._print("----------------------------")
  345. else:
  346. lst_output = output.split(b'\n')
  347. lst_expected = expected_output.split(b'\n')
  348. ln = min(len(lst_output), len(lst_expected))
  349. for i in range(0, ln):
  350. if lst_output[i] != lst_expected[i]:
  351. self._print("Output: (at line " + str(i+1) + ")")
  352. self._print("----------------------------")
  353. self._print(lst_output[i].decode('utf-8'))
  354. self._print("----------------------------")
  355. self._print("Expected Output:")
  356. self._print("----------------------------")
  357. self._print(lst_expected[i].decode('utf-8'))
  358. self._print("----------------------------")
  359. break
  360. self._print("exit code: {}".format(exit_code))
  361. if warn_on_timeout and timedout:
  362. self._log_result(test, fail=False)
  363. else:
  364. self._log_result(test, fail=True)
  365. # temp: try find real file name on hard drive if case mismatch
  366. def _check_file(self, folder, filename):
  367. path = os.path.join(folder, filename)
  368. if os.path.isfile(path):
  369. return path # file exists on disk
  370. filename_lower = filename.lower()
  371. files = os.listdir(folder)
  372. for i in range(len(files)):
  373. if files[i].lower() == filename_lower:
  374. self._print('\nWARNING: {} should be {}\n'.format(
  375. path, files[i]))
  376. return os.path.join(folder, files[i])
  377. # can't find the file, just return the path and let it error out
  378. return path
  379. # run one test under this variant
  380. def test_one(self, test):
  381. try:
  382. test.start()
  383. self._run_one_test(test)
  384. except Exception:
  385. test.done()
  386. self._print(traceback.format_exc())
  387. self._log_result(test, fail=True)
  388. # internally perform one test run
  389. def _run_one_test(self, test):
  390. folder = test.folder
  391. js_file = test.filename = self._check_file(folder, test.files)
  392. js_output = b''
  393. working_path = os.path.dirname(js_file)
  394. flags = test.get('compile-flags') or ''
  395. flags = self._expand_compile_flags(test) + \
  396. args.flags.split() + \
  397. flags.split()
  398. if test.get('custom-config-file') != None:
  399. flags = ['-CustomConfigFile:' + test.get('custom-config-file')]
  400. if args.lldb == None:
  401. cmd = [binary] + flags + [os.path.basename(js_file)]
  402. else:
  403. lldb_file = open(working_path + '/' + os.path.basename(js_file) + '.lldb.cmd', 'w')
  404. lldb_command = ['run'] + flags + [os.path.basename(js_file)]
  405. lldb_file.write(' '.join([str(s) for s in lldb_command]));
  406. lldb_file.close()
  407. cmd = ['lldb'] + [binary] + ['-s'] + [os.path.basename(js_file) + '.lldb.cmd'] + ['-o bt'] + ['-b']
  408. test.start()
  409. proc = SP.Popen(cmd, stdout=SP.PIPE, stderr=SP.STDOUT, cwd=working_path)
  410. timeout_data = [proc, False]
  411. def timeout_func(timeout_data):
  412. timeout_data[0].kill()
  413. timeout_data[1] = True
  414. timeout = test.get('timeout', args.timeout) # test override or default
  415. timer = Timer(timeout, timeout_func, [timeout_data])
  416. skip_baseline_match = False
  417. try:
  418. timer.start()
  419. js_output = normalize_new_line(proc.communicate()[0])
  420. exit_code = proc.wait()
  421. # if -lldb was set; check if test was crashed before corrupting the output
  422. search_for = " exited with status = 0 (0x00000000)"
  423. if args.lldb != None and exit_code == 0 and js_output.index(search_for) > 0:
  424. js_output = js_output[0:js_output.index(search_for)]
  425. exit_pos = js_output.rfind('\nProcess ')
  426. if exit_pos > len(js_output) - 20: # if [Process ????? <seach for>]
  427. if 'baseline' not in test:
  428. js_output = "pass"
  429. else:
  430. skip_baseline_match = True
  431. finally:
  432. timer.cancel()
  433. test.done()
  434. # shared _show_failed args
  435. fail_args = { 'test': test, 'flags': flags,
  436. 'exit_code': exit_code, 'output': js_output }
  437. # check timed out
  438. if (timeout_data[1]):
  439. return self._show_failed(timedout=True, **fail_args)
  440. # check ch failed
  441. if exit_code != 0:
  442. return self._show_failed(**fail_args)
  443. if not return_code_only:
  444. # check output
  445. if 'baseline' not in test:
  446. # output lines must be 'pass' or 'passed' or empty with at least 1 not empty
  447. passes = 0
  448. for line in js_output.split(b'\n'):
  449. if line !=b'':
  450. low = line.lower()
  451. if low == b'pass' or low == b'passed':
  452. passes = 1
  453. else:
  454. return self._show_failed(**fail_args)
  455. if passes == 0:
  456. return self._show_failed(**fail_args)
  457. else:
  458. baseline = test.get('baseline')
  459. if not skip_baseline_match and baseline:
  460. # perform baseline comparison
  461. baseline = self._check_file(folder, baseline)
  462. with open(baseline, 'rb') as bs_file:
  463. baseline_output = bs_file.read()
  464. # Clean up carriage return
  465. # todo: remove carriage return at the end of the line
  466. # or better fix ch to output same on all platforms
  467. expected_output = normalize_new_line(baseline_output)
  468. if expected_output != js_output:
  469. return self._show_failed(
  470. expected_output=expected_output, **fail_args)
  471. # passed
  472. if verbose:
  473. self._print('{} {} {}'.format(binary, ' '.join(flags), test.filename))
  474. self._log_result(test, fail=False)
  475. # run tests under this variant, using given multiprocessing Pool
  476. def _run(self, tests, pool):
  477. # filter tests to run
  478. tests = [x for x in tests if self._should_test(x)]
  479. self.test_count += len(tests)
  480. # run tests in parallel
  481. pool.map_async(run_one, [(self,test) for test in tests])
  482. while self.test_result.total_count() != self.test_count:
  483. self._process_one_msg()
  484. # print test result summary
  485. def print_summary(self, time):
  486. print('\n############ Results for {} tests ###########'\
  487. .format(self.name))
  488. for folder, result in sorted(self.test_result.folders.items()):
  489. print('{}: {}'.format(folder, result))
  490. print("----------------------------")
  491. print('Total: {}'.format(self.test_result))
  492. print('Time taken for {} tests: {} seconds\n'.format(self.name, round(time.total_seconds(),2)))
  493. sys.stdout.flush()
  494. # run all tests from testLoader
  495. def run(self, testLoader, pool, sequential_pool):
  496. print('\n############# Starting {} tests #############'\
  497. .format(self.name))
  498. if self.tags:
  499. print(' tags: {}'.format(self.tags))
  500. for x in self.not_tags:
  501. print(' exclude: {}'.format(x))
  502. sys.stdout.flush()
  503. start_time = datetime.now()
  504. tests, sequential_tests = [], []
  505. for folder in testLoader.folders():
  506. if folder.tags.isdisjoint(self.not_tags):
  507. dest = tests if not folder.is_sequential else sequential_tests
  508. dest += folder.tests
  509. if tests:
  510. self._run(tests, pool)
  511. if sequential_tests:
  512. self._run(sequential_tests, sequential_pool)
  513. self.print_summary(datetime.now() - start_time)
  514. # global run one test function for multiprocessing, used by TestVariant
  515. def run_one(data):
  516. try:
  517. variant, test = data
  518. variant.test_one(test)
  519. except Exception:
  520. print('ERROR: Unhandled exception!!!')
  521. traceback.print_exc()
  522. # A test folder contains a list of tests and maybe some tags.
  523. class TestFolder(object):
  524. def __init__(self, tests, tags=_empty_set):
  525. self.tests = tests
  526. self.tags = tags
  527. self.is_sequential = 'sequential' in tags
  528. # TestLoader loads all tests
  529. class TestLoader(object):
  530. def __init__(self, paths):
  531. self._folder_tags = self._load_folder_tags()
  532. self._test_id = 0
  533. self._folders = []
  534. for path in paths:
  535. if os.path.isfile(path):
  536. folder, file = os.path.dirname(path), os.path.basename(path)
  537. else:
  538. folder, file = path, None
  539. ftags = self._get_folder_tags(folder)
  540. if ftags != None: # Only honor entries listed in rlexedirs.xml
  541. tests = self._load_tests(folder, file)
  542. self._folders.append(TestFolder(tests, ftags))
  543. def folders(self):
  544. return self._folders
  545. # load folder/tags info from test_root/rlexedirs.xml
  546. @staticmethod
  547. def _load_folder_tags():
  548. xmlpath = os.path.join(test_root, 'rlexedirs.xml')
  549. try:
  550. xml = ET.parse(xmlpath).getroot()
  551. except IOError:
  552. print('ERROR: failed to read {}'.format(xmlpath))
  553. exit(-1)
  554. folder_tags = {}
  555. for x in xml:
  556. d = x.find('default')
  557. key = d.find('files').text.lower() # avoid case mismatch
  558. tags = d.find('tags')
  559. folder_tags[key] = \
  560. split_tags(tags.text) if tags != None else _empty_set
  561. return folder_tags
  562. # get folder tags if any
  563. def _get_folder_tags(self, folder):
  564. key = os.path.basename(os.path.normpath(folder)).lower()
  565. return self._folder_tags.get(key)
  566. def _next_test_id(self):
  567. self._test_id += 1
  568. return self._test_id
  569. # load all tests in folder using rlexe.xml file
  570. def _load_tests(self, folder, file):
  571. try:
  572. xmlpath = os.path.join(folder, 'rlexe.xml')
  573. xml = ET.parse(xmlpath).getroot()
  574. except IOError:
  575. return []
  576. def test_override(condition, check_tag, check_value, test):
  577. target = condition.find(check_tag)
  578. if target != None and target.text == check_value:
  579. for override in condition.find('override'):
  580. test[override.tag] = override.text
  581. def load_test(testXml):
  582. test = Test(folder=folder)
  583. for c in testXml.find('default'):
  584. if c.tag == 'timeout': # timeout seconds
  585. test[c.tag] = int(c.text)
  586. elif c.tag == 'tags' and c.tag in test: # merge multiple <tags>
  587. test[c.tag] = test[c.tag] + ',' + c.text
  588. else:
  589. test[c.tag] = c.text
  590. condition = testXml.find('condition')
  591. if condition != None:
  592. test_override(condition, 'target', arch_alias, test)
  593. return test
  594. tests = [load_test(x) for x in xml]
  595. if file != None:
  596. tests = [x for x in tests if x.files == file]
  597. if len(tests) == 0 and self.is_jsfile(file):
  598. tests = [Test(folder=folder, files=file, baseline='')]
  599. for test in tests: # assign unique test.id
  600. test.id = self._next_test_id()
  601. return tests
  602. @staticmethod
  603. def is_jsfile(path):
  604. return os.path.splitext(path)[1] == '.js'
  605. def main():
  606. # Set the right timezone, the tests need Pacific Standard Time
  607. # TODO: Windows. time.tzset only supports Unix
  608. if hasattr(time, 'tzset'):
  609. os.environ['TZ'] = 'US/Pacific'
  610. time.tzset()
  611. elif sys.platform == 'win32':
  612. os.system('tzutil /s "Pacific Standard time"')
  613. # By default run all tests
  614. if len(args.folders) == 0:
  615. files = (os.path.join(test_root, x) for x in os.listdir(test_root))
  616. args.folders = [f for f in sorted(files) if not os.path.isfile(f)]
  617. # load all tests
  618. testLoader = TestLoader(args.folders)
  619. # test variants
  620. variants = [x for x in [
  621. TestVariant('interpreted', extra_flags + [
  622. '-maxInterpretCount:1', '-maxSimpleJitRunCount:1', '-bgjit-',
  623. '-dynamicprofilecache:profile.dpl.${id}'
  624. ], [
  625. 'require_disable_jit'
  626. ]),
  627. TestVariant('dynapogo', extra_flags + [
  628. '-forceNative', '-off:simpleJit', '-bgJitDelay:0',
  629. '-dynamicprofileinput:profile.dpl.${id}'
  630. ], [
  631. 'require_disable_jit'
  632. ]),
  633. TestVariant('disable_jit', extra_flags + [
  634. '-nonative'
  635. ], [
  636. 'exclude_interpreted', 'fails_interpreted', 'require_backend'
  637. ])
  638. ] if x.name in args.variants]
  639. print('############# ChakraCore Test Suite #############')
  640. print('Testing {} build'.format('Test' if flavor == 'Test' else 'Debug'))
  641. print('Using {} threads'.format(processcount))
  642. # run each variant
  643. pool, sequential_pool = Pool(processcount), Pool(1)
  644. start_time = datetime.now()
  645. for variant in variants:
  646. variant.run(testLoader, pool, sequential_pool)
  647. elapsed_time = datetime.now() - start_time
  648. failed = any(variant.test_result.fail_count > 0 for variant in variants)
  649. print('[{} seconds] {}'.format(
  650. round(elapsed_time.total_seconds(),2), 'Success!' if not failed else 'Failed!'))
  651. # rm profile.dpl.*
  652. for f in glob.glob(test_root + '/*/profile.dpl.*'):
  653. os.remove(f)
  654. return 1 if failed else 0
  655. if __name__ == '__main__':
  656. sys.exit(main())