runtests.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  1. #!/usr/bin/env python
  2. #-------------------------------------------------------------------------------------------------------
  3. # Copyright (C) Microsoft. All rights reserved.
  4. # Copyright (c) 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_simd')
  158. else:
  159. not_tags.add('exclude_windows')
  160. # exclude tests that depend on features not supported on a platform
  161. if arch == 'arm' or arch == 'arm64':
  162. not_tags.add('require_asmjs')
  163. # exclude tests known to fail under certain sanitizers
  164. if args.sanitize != None:
  165. not_tags.add('exclude_sanitize_'+args.sanitize)
  166. if sys.platform == 'darwin':
  167. not_tags.add('exclude_mac')
  168. if 'require_icu' in not_tags or 'exclude_noicu' in not_tags:
  169. not_tags.add('Intl')
  170. not_compile_flags = None
  171. # use -j flag to specify number of parallel processes
  172. processcount = cpu_count()
  173. if args.processcount != None:
  174. processcount = int(args.processcount)
  175. # handle warn on timeout
  176. warn_on_timeout = False
  177. if args.warn_on_timeout == True:
  178. warn_on_timeout = True
  179. # handle limiting test result analysis to return codes
  180. return_code_only = False
  181. if args.orc == True:
  182. return_code_only = True
  183. # use tags/not_tags/not_compile_flags as case-insensitive
  184. def lower_set(s):
  185. return set([x.lower() for x in s] if s else [])
  186. tags = lower_set(tags)
  187. not_tags = lower_set(not_tags)
  188. not_compile_flags = lower_set(not_compile_flags)
  189. # split tags text into tags set
  190. _empty_set = set()
  191. def split_tags(text):
  192. return set(x.strip() for x in text.lower().split(',')) if text \
  193. else _empty_set
  194. # remove carriage returns at end of line to avoid platform difference
  195. def normalize_new_line(text):
  196. return re.sub(b'[\r]+\n', b'\n', text)
  197. # A test simply contains a collection of test attributes.
  198. # Misc attributes added by test run:
  199. # id unique counter to identify a test
  200. # filename full path of test file
  201. # elapsed_time elapsed time when running the test
  202. #
  203. class Test(dict):
  204. __setattr__ = dict.__setitem__
  205. __delattr__ = dict.__delitem__
  206. # support dot syntax for normal attribute access
  207. def __getattr__(self, key):
  208. return super(Test, self).__getattr__(key) if key.startswith('__') \
  209. else self.get(key)
  210. # mark start of this test run, to compute elapsed_time
  211. def start(self):
  212. self.start_time = datetime.now()
  213. # mark end of this test run, compute elapsed_time
  214. def done(self):
  215. if not self.elapsed_time:
  216. self.elapsed_time = (datetime.now() - self.start_time)\
  217. .total_seconds()
  218. # records pass_count/fail_count
  219. class PassFailCount(object):
  220. def __init__(self):
  221. self.pass_count = 0
  222. self.fail_count = 0
  223. def __str__(self):
  224. return 'passed {}, failed {}'.format(self.pass_count, self.fail_count)
  225. def total_count(self):
  226. return self.pass_count + self.fail_count
  227. # records total and individual folder's pass_count/fail_count
  228. class TestResult(PassFailCount):
  229. def __init__(self):
  230. super(self.__class__, self).__init__()
  231. self.folders = {}
  232. def _get_folder_result(self, folder):
  233. r = self.folders.get(folder)
  234. if not r:
  235. r = PassFailCount()
  236. self.folders[folder] = r
  237. return r
  238. def log(self, filename, fail=False):
  239. folder = os.path.basename(os.path.dirname(filename))
  240. r = self._get_folder_result(folder)
  241. if fail:
  242. r.fail_count += 1
  243. self.fail_count += 1
  244. else:
  245. r.pass_count += 1
  246. self.pass_count += 1
  247. # test variants:
  248. # interpreted: -maxInterpretCount:1 -maxSimpleJitRunCount:1 -bgjit-
  249. # dynapogo: -forceNative -off:simpleJit -bgJitDelay:0
  250. class TestVariant(object):
  251. def __init__(self, name, compile_flags=[], variant_not_tags=[]):
  252. self.name = name
  253. self.compile_flags = \
  254. ['-ExtendedErrorStackForTestHost',
  255. '-BaselineMode'] + compile_flags
  256. self._compile_flags_has_expansion = self._has_expansion(compile_flags)
  257. self.tags = tags.copy()
  258. self.not_tags = not_tags.union(variant_not_tags).union(
  259. ['{}_{}'.format(x, name) for x in ('fails','exclude')])
  260. self.msg_queue = Manager().Queue() # messages from multi processes
  261. self.test_result = TestResult()
  262. self.test_count = 0
  263. self._print_lines = [] # _print lines buffer
  264. self._last_len = 0
  265. if verbose:
  266. print("Added variant {0}:".format(name))
  267. print("Flags: " + ", ".join(self.compile_flags))
  268. print("Tags: " + ", ".join(self.tags))
  269. print("NotTags: " + ", ".join(self.not_tags))
  270. @staticmethod
  271. def _has_expansion(flags):
  272. return any(re.match(r'.*\${.*}', f) for f in flags)
  273. @staticmethod
  274. def _expand(flag, test):
  275. return re.sub(r'\${id}', str(test.id), flag)
  276. def _expand_compile_flags(self, test):
  277. if self._compile_flags_has_expansion:
  278. return [self._expand(flag, test) for flag in self.compile_flags]
  279. return self.compile_flags
  280. # check if this test variant should run a given test
  281. def _should_test(self, test):
  282. tags = split_tags(test.get('tags'))
  283. if not tags.isdisjoint(self.not_tags):
  284. return False
  285. if self.tags and not self.tags.issubset(tags):
  286. return False
  287. if not_compile_flags: # exclude unsupported compile-flags if any
  288. flags = test.get('compile-flags')
  289. if flags and \
  290. not not_compile_flags.isdisjoint(flags.lower().split()):
  291. return False
  292. return True
  293. # print output from multi-process run, to be sent with result message
  294. def _print(self, line):
  295. self._print_lines.append(line)
  296. # queue a test result from multi-process runs
  297. def _log_result(self, test, fail):
  298. if fail or show_passes:
  299. output = ''
  300. for line in self._print_lines:
  301. output = output + line + '\n' # collect buffered _print output
  302. else:
  303. output = ''
  304. self._print_lines = []
  305. self.msg_queue.put((test.filename, fail, test.elapsed_time, output))
  306. # (on main process) process one queued message
  307. def _process_msg(self, msg):
  308. filename, fail, elapsed_time, output = msg
  309. self.test_result.log(filename, fail=fail)
  310. if fail or show_passes:
  311. line = '[{}/{} {:4.2f}] {} -> {}'.format(
  312. self.test_result.total_count(),
  313. self.test_count,
  314. elapsed_time,
  315. 'Failed' if fail else 'Passed',
  316. self._short_name(filename))
  317. padding = self._last_len - len(line)
  318. print(line + ' ' * padding, end='\n' if fail else '\r')
  319. self._last_len = len(line) if not fail else 0
  320. if len(output) > 0:
  321. print(output)
  322. # get a shorter test file path for display only
  323. def _short_name(self, filename):
  324. folder = os.path.basename(os.path.dirname(filename))
  325. return os.path.join(folder, os.path.basename(filename))
  326. # (on main process) wait and process one queued message
  327. def _process_one_msg(self):
  328. self._process_msg(self.msg_queue.get())
  329. # log a failed test with details
  330. def _show_failed(self, test, flags, exit_code, output,
  331. expected_output=None, timedout=False):
  332. if timedout:
  333. if warn_on_timeout:
  334. self._print('WARNING: Test timed out!')
  335. else:
  336. self._print('ERROR: Test timed out!')
  337. self._print('{} {} {}'.format(binary, ' '.join(flags), test.filename))
  338. if not return_code_only:
  339. if expected_output == None or timedout:
  340. self._print("\nOutput:")
  341. self._print("----------------------------")
  342. self._print(output.decode('utf-8'))
  343. self._print("----------------------------")
  344. else:
  345. lst_output = output.split(b'\n')
  346. lst_expected = expected_output.split(b'\n')
  347. ln = min(len(lst_output), len(lst_expected))
  348. for i in range(0, ln):
  349. if lst_output[i] != lst_expected[i]:
  350. self._print("Output: (at line " + str(i+1) + ")")
  351. self._print("----------------------------")
  352. self._print(lst_output[i].decode('utf-8'))
  353. self._print("----------------------------")
  354. self._print("Expected Output:")
  355. self._print("----------------------------")
  356. self._print(lst_expected[i].decode('utf-8'))
  357. self._print("----------------------------")
  358. break
  359. self._print("exit code: {}".format(exit_code))
  360. if warn_on_timeout and timedout:
  361. self._log_result(test, fail=False)
  362. else:
  363. self._log_result(test, fail=True)
  364. # temp: try find real file name on hard drive if case mismatch
  365. def _check_file(self, folder, filename):
  366. path = os.path.join(folder, filename)
  367. if os.path.isfile(path):
  368. return path # file exists on disk
  369. filename_lower = filename.lower()
  370. files = os.listdir(folder)
  371. for i in range(len(files)):
  372. if files[i].lower() == filename_lower:
  373. self._print('\nWARNING: {} should be {}\n'.format(
  374. path, files[i]))
  375. return os.path.join(folder, files[i])
  376. # can't find the file, just return the path and let it error out
  377. return path
  378. # run one test under this variant
  379. def test_one(self, test):
  380. try:
  381. test.start()
  382. self._run_one_test(test)
  383. except Exception:
  384. test.done()
  385. self._print(traceback.format_exc())
  386. self._log_result(test, fail=True)
  387. # internally perform one test run
  388. def _run_one_test(self, test):
  389. folder = test.folder
  390. js_file = test.filename = self._check_file(folder, test.files)
  391. js_output = b''
  392. working_path = os.path.dirname(js_file)
  393. flags = test.get('compile-flags') or ''
  394. flags = self._expand_compile_flags(test) + \
  395. args.flags.split() + \
  396. flags.split()
  397. if test.get('custom-config-file') != None:
  398. flags = ['-CustomConfigFile:' + test.get('custom-config-file')]
  399. if args.lldb == None:
  400. cmd = [binary] + flags + [os.path.basename(js_file)]
  401. else:
  402. lldb_file = open(working_path + '/' + os.path.basename(js_file) + '.lldb.cmd', 'w')
  403. lldb_command = ['run'] + flags + [os.path.basename(js_file)]
  404. lldb_file.write(' '.join([str(s) for s in lldb_command]));
  405. lldb_file.close()
  406. cmd = ['lldb'] + [binary] + ['-s'] + [os.path.basename(js_file) + '.lldb.cmd'] + ['-o bt'] + ['-b']
  407. test.start()
  408. proc = SP.Popen(cmd, stdout=SP.PIPE, stderr=SP.STDOUT, cwd=working_path)
  409. timeout_data = [proc, False]
  410. def timeout_func(timeout_data):
  411. timeout_data[0].kill()
  412. timeout_data[1] = True
  413. timeout = test.get('timeout', args.timeout) # test override or default
  414. timer = Timer(timeout, timeout_func, [timeout_data])
  415. skip_baseline_match = False
  416. try:
  417. timer.start()
  418. js_output = normalize_new_line(proc.communicate()[0])
  419. exit_code = proc.wait()
  420. # if -lldb was set; check if test was crashed before corrupting the output
  421. search_for = " exited with status = 0 (0x00000000)"
  422. if args.lldb != None and exit_code == 0 and js_output.index(search_for) > 0:
  423. js_output = js_output[0:js_output.index(search_for)]
  424. exit_pos = js_output.rfind('\nProcess ')
  425. if exit_pos > len(js_output) - 20: # if [Process ????? <seach for>]
  426. if 'baseline' not in test:
  427. js_output = "pass"
  428. else:
  429. skip_baseline_match = True
  430. finally:
  431. timer.cancel()
  432. test.done()
  433. # shared _show_failed args
  434. fail_args = { 'test': test, 'flags': flags,
  435. 'exit_code': exit_code, 'output': js_output }
  436. # check timed out
  437. if (timeout_data[1]):
  438. return self._show_failed(timedout=True, **fail_args)
  439. # check ch failed
  440. if exit_code != 0:
  441. return self._show_failed(**fail_args)
  442. if not return_code_only:
  443. # check output
  444. if 'baseline' not in test:
  445. # output lines must be 'pass' or 'passed' or empty with at least 1 not empty
  446. passes = 0
  447. for line in js_output.split(b'\n'):
  448. if line !=b'':
  449. low = line.lower()
  450. if low == b'pass' or low == b'passed':
  451. passes = 1
  452. else:
  453. return self._show_failed(**fail_args)
  454. if passes == 0:
  455. return self._show_failed(**fail_args)
  456. else:
  457. baseline = test.get('baseline')
  458. if not skip_baseline_match and baseline:
  459. # perform baseline comparison
  460. baseline = self._check_file(folder, baseline)
  461. with open(baseline, 'rb') as bs_file:
  462. baseline_output = bs_file.read()
  463. # Clean up carriage return
  464. # todo: remove carriage return at the end of the line
  465. # or better fix ch to output same on all platforms
  466. expected_output = normalize_new_line(baseline_output)
  467. if expected_output != js_output:
  468. return self._show_failed(
  469. expected_output=expected_output, **fail_args)
  470. # passed
  471. if verbose:
  472. self._print('{} {} {}'.format(binary, ' '.join(flags), test.filename))
  473. self._log_result(test, fail=False)
  474. # run tests under this variant, using given multiprocessing Pool
  475. def _run(self, tests, pool):
  476. # filter tests to run
  477. tests = [x for x in tests if self._should_test(x)]
  478. self.test_count += len(tests)
  479. # run tests in parallel
  480. pool.map_async(run_one, [(self,test) for test in tests])
  481. while self.test_result.total_count() != self.test_count:
  482. self._process_one_msg()
  483. # print test result summary
  484. def print_summary(self, time):
  485. print('\n############ Results for {} tests ###########'\
  486. .format(self.name))
  487. for folder, result in sorted(self.test_result.folders.items()):
  488. print('{}: {}'.format(folder, result))
  489. print("----------------------------")
  490. print('Total: {}'.format(self.test_result))
  491. print('Time taken for {} tests: {} seconds\n'.format(self.name, round(time.total_seconds(),2)))
  492. sys.stdout.flush()
  493. # run all tests from testLoader
  494. def run(self, testLoader, pool, sequential_pool):
  495. print('\n############# Starting {} tests #############'\
  496. .format(self.name))
  497. if self.tags:
  498. print(' tags: {}'.format(self.tags))
  499. for x in self.not_tags:
  500. print(' exclude: {}'.format(x))
  501. sys.stdout.flush()
  502. start_time = datetime.now()
  503. tests, sequential_tests = [], []
  504. for folder in testLoader.folders():
  505. if folder.tags.isdisjoint(self.not_tags):
  506. dest = tests if not folder.is_sequential else sequential_tests
  507. dest += folder.tests
  508. if tests:
  509. self._run(tests, pool)
  510. if sequential_tests:
  511. self._run(sequential_tests, sequential_pool)
  512. self.print_summary(datetime.now() - start_time)
  513. # global run one test function for multiprocessing, used by TestVariant
  514. def run_one(data):
  515. try:
  516. variant, test = data
  517. variant.test_one(test)
  518. except Exception:
  519. print('ERROR: Unhandled exception!!!')
  520. traceback.print_exc()
  521. # A test folder contains a list of tests and maybe some tags.
  522. class TestFolder(object):
  523. def __init__(self, tests, tags=_empty_set):
  524. self.tests = tests
  525. self.tags = tags
  526. self.is_sequential = 'sequential' in tags
  527. # TestLoader loads all tests
  528. class TestLoader(object):
  529. def __init__(self, paths):
  530. self._folder_tags = self._load_folder_tags()
  531. self._test_id = 0
  532. self._folders = []
  533. for path in paths:
  534. if os.path.isfile(path):
  535. folder, file = os.path.dirname(path), os.path.basename(path)
  536. else:
  537. folder, file = path, None
  538. ftags = self._get_folder_tags(folder)
  539. if ftags != None: # Only honor entries listed in rlexedirs.xml
  540. tests = self._load_tests(folder, file)
  541. self._folders.append(TestFolder(tests, ftags))
  542. def folders(self):
  543. return self._folders
  544. # load folder/tags info from test_root/rlexedirs.xml
  545. @staticmethod
  546. def _load_folder_tags():
  547. xmlpath = os.path.join(test_root, 'rlexedirs.xml')
  548. try:
  549. xml = ET.parse(xmlpath).getroot()
  550. except IOError:
  551. print('ERROR: failed to read {}'.format(xmlpath))
  552. exit(-1)
  553. folder_tags = {}
  554. for x in xml:
  555. d = x.find('default')
  556. key = d.find('files').text.lower() # avoid case mismatch
  557. tags = d.find('tags')
  558. folder_tags[key] = \
  559. split_tags(tags.text) if tags != None else _empty_set
  560. return folder_tags
  561. # get folder tags if any
  562. def _get_folder_tags(self, folder):
  563. key = os.path.basename(os.path.normpath(folder)).lower()
  564. return self._folder_tags.get(key)
  565. def _next_test_id(self):
  566. self._test_id += 1
  567. return self._test_id
  568. # load all tests in folder using rlexe.xml file
  569. def _load_tests(self, folder, file):
  570. try:
  571. xmlpath = os.path.join(folder, 'rlexe.xml')
  572. xml = ET.parse(xmlpath).getroot()
  573. except IOError:
  574. return []
  575. def test_override(condition, check_tag, check_value, test):
  576. target = condition.find(check_tag)
  577. if target != None and target.text == check_value:
  578. for override in condition.find('override'):
  579. test[override.tag] = override.text
  580. def load_test(testXml):
  581. test = Test(folder=folder)
  582. for c in testXml.find('default'):
  583. if c.tag == 'timeout': # timeout seconds
  584. test[c.tag] = int(c.text)
  585. elif c.tag == 'tags' and c.tag in test: # merge multiple <tags>
  586. test[c.tag] = test[c.tag] + ',' + c.text
  587. else:
  588. test[c.tag] = c.text
  589. condition = testXml.find('condition')
  590. if condition != None:
  591. test_override(condition, 'target', arch_alias, test)
  592. return test
  593. tests = [load_test(x) for x in xml]
  594. if file != None:
  595. tests = [x for x in tests if x.files == file]
  596. if len(tests) == 0 and self.is_jsfile(file):
  597. tests = [Test(folder=folder, files=file, baseline='')]
  598. for test in tests: # assign unique test.id
  599. test.id = self._next_test_id()
  600. return tests
  601. @staticmethod
  602. def is_jsfile(path):
  603. return os.path.splitext(path)[1] == '.js'
  604. def main():
  605. # Set the right timezone, the tests need Pacific Standard Time
  606. # TODO: Windows. time.tzset only supports Unix
  607. if hasattr(time, 'tzset'):
  608. os.environ['TZ'] = 'America/Los_Angeles'
  609. time.tzset()
  610. elif sys.platform == 'win32':
  611. os.system('tzutil /s "Pacific Standard time"')
  612. # By default run all tests
  613. if len(args.folders) == 0:
  614. files = (os.path.join(test_root, x) for x in os.listdir(test_root))
  615. args.folders = [f for f in sorted(files) if not os.path.isfile(f)]
  616. # load all tests
  617. testLoader = TestLoader(args.folders)
  618. # test variants
  619. variants = [x for x in [
  620. TestVariant('interpreted', extra_flags + [
  621. '-maxInterpretCount:1', '-maxSimpleJitRunCount:1', '-bgjit-',
  622. '-dynamicprofilecache:profile.dpl.${id}'
  623. ], [
  624. 'require_disable_jit'
  625. ]),
  626. TestVariant('dynapogo', extra_flags + [
  627. '-forceNative', '-off:simpleJit', '-bgJitDelay:0',
  628. '-dynamicprofileinput:profile.dpl.${id}'
  629. ], [
  630. 'require_disable_jit'
  631. ]),
  632. TestVariant('disable_jit', extra_flags + [
  633. '-nonative'
  634. ], [
  635. 'exclude_interpreted', 'fails_interpreted', 'require_backend'
  636. ])
  637. ] if x.name in args.variants]
  638. print('############# ChakraCore Test Suite #############')
  639. print('Testing {} build'.format('Test' if flavor == 'Test' else 'Debug'))
  640. print('Using {} threads'.format(processcount))
  641. # run each variant
  642. pool, sequential_pool = Pool(processcount), Pool(1)
  643. start_time = datetime.now()
  644. for variant in variants:
  645. variant.run(testLoader, pool, sequential_pool)
  646. elapsed_time = datetime.now() - start_time
  647. failed = any(variant.test_result.fail_count > 0 for variant in variants)
  648. print('[{} seconds] {}'.format(
  649. round(elapsed_time.total_seconds(),2), 'Success!' if not failed else 'Failed!'))
  650. # rm profile.dpl.*
  651. for f in glob.glob(test_root + '/*/profile.dpl.*'):
  652. os.remove(f)
  653. return 1 if failed else 0
  654. if __name__ == '__main__':
  655. sys.exit(main())