runtests.py 26 KB

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