#!/usr/bin/python from __future__ import print_function from functools import partial from multiprocessing import Pool from os import listdir, environ from os.path import isfile, join, splitext from pybin.tools import * from pybin.test_run import * import argparse import multiprocessing import os import re import signal import sys ################################################################################ # help functions ################################################################################ def list_expected(): expected = [] def step(_, dirname, names): for name in names: path = os.path.join(dirname, name) match = re.search("(\.[\w\/\-_]*)\/.expect\/([\w\-_]+)(\.[\w\-_]+)?\.txt", path) if match : test = Test() test.name = match.group(2) test.path = match.group(1) test.arch = match.group(3)[1:] if match.group(3) else None expected.append(test) # Start the walk os.path.walk('.', step, '') return expected # reads the directory ./.expect and indentifies the tests def listTests( includes, excludes ): includes = [os.path.normpath( os.path.join('.',i) ) for i in includes] if includes else None excludes = [os.path.normpath( os.path.join('.',i) ) for i in excludes] if excludes else None # tests directly in the .expect folder will always be processed test_list = list_expected() # if we have a limited number of includes, filter by them if includes: test_list = [x for x in test_list if os.path.normpath( x.path ).startswith( tuple(includes) ) ] # # if we have a folders to excludes, filter by them if excludes: test_list = [x for x in test_list if not os.path.normpath( x.path ).startswith( tuple(excludes) ) ] return test_list # from the found tests, filter all the valid tests/desired tests def validTests( options ): tests = [] # if we are regenerating the tests we need to find the information of the # already existing tests and create new info for the new tests if options.regenerate_expected : for testname in options.tests : if testname.endswith( (".c", ".cc", ".cpp") ): print('ERROR: "%s", tests are not allowed to end with a C/C++/CFA extension, ignoring it' % testname, file=sys.stderr) else : found = [test for test in allTests if test.name == testname] tests.append( found[0] if len(found) == 1 else Test(testname, testname) ) else : # otherwise we only need to validate that all tests are present in the complete list for testname in options.tests: test = [t for t in allTests if os.path.normpath( t.target() ) == os.path.normpath( testname )] if len(test) != 0 : tests.append( test[0] ) else : print('ERROR: No expected file for test %s, ignoring it' % testname, file=sys.stderr) # make sure we have at least some test to run if len(tests) == 0 : print('ERROR: No valid test to run', file=sys.stderr) sys.exit(1) return tests class TestResult: SUCCESS = 0 FAILURE = 1 TIMEOUT = 124 # parses the option def getOptions(): # create a parser with the arguments for the tests script parser = argparse.ArgumentParser(description='Script which runs cforall tests') parser.add_argument('--debug', help='Run all tests in debug or release', type=yes_no, default='no') parser.add_argument('--arch', help='Test for specific architecture', type=str, default=getMachineType()) parser.add_argument('--dry-run', help='Don\'t run the tests, only output the commands', action='store_true') parser.add_argument('--list', help='List all test available', action='store_true') parser.add_argument('--all', help='Run all test available', action='store_true') parser.add_argument('--regenerate-expected', help='Regenerate the .expect by running the specified tets, can be used with --all option', action='store_true') parser.add_argument('-j', '--jobs', help='Number of tests to run simultaneously', type=int, default='8') parser.add_argument('--list-comp', help='List all valide arguments', action='store_true') parser.add_argument('-I','--include', help='Directory of test to include, can be used multiple time, All if omitted', action='append') parser.add_argument('-E','--exclude', help='Directory of test to exclude, can be used multiple time, None if omitted', action='append') parser.add_argument('tests', metavar='test', type=str, nargs='*', help='a list of tests to run') options = parser.parse_args() # script must have at least some tests to run or be listing listing = options.list or options.list_comp all_tests = options.all some_tests = len(options.tests) > 0 some_dirs = len(options.include) > 0 if options.include else 0 # check that exactly one of the booleans is set to true if not sum( (listing, all_tests, some_tests, some_dirs) ) > 0 : print('ERROR: must have option \'--all\', \'--list\', \'--include\', \'-I\' or non-empty test list', file=sys.stderr) parser.print_help() sys.exit(1) return options def jobCount( options ): # check if the user already passed in a number of jobs for multi-threading make_flags = environ.get('MAKEFLAGS') make_jobs_fds = re.search("--jobserver-(auth|fds)=\s*([0-9]+),([0-9]+)", make_flags) if make_flags else None if make_jobs_fds : tokens = os.read(int(make_jobs_fds.group(2)), 1024) options.jobs = len(tokens) os.write(int(make_jobs_fds.group(3)), tokens) else : options.jobs = multiprocessing.cpu_count() # make sure we have a valid number of jobs that corresponds to user input if options.jobs <= 0 : print('ERROR: Invalid number of jobs', file=sys.stderr) sys.exit(1) return min( options.jobs, len(tests) ), True if make_flags else False ################################################################################ # running test functions ################################################################################ # logic to run a single test and return the result (No handling of printing or other test framework logic) def run_single_test(test, generate, dry_run, debug): # find the output file based on the test name and options flag out_file = test.output_file() if not generate else test.expect_file() err_file = test.error_file() cmp_file = test.expect_file() in_file = test.input_file() # prepare the proper directories test.prepare( dry_run ) # remove any outputs from the previous tests to prevent side effects rm( (out_file, err_file, test.target()), dry_run ) options = "-debug" if debug else "-nodebug" # build, skipping to next test on error make_ret, _ = sh("""%s DEBUG_FLAGS="%s" %s test="%s" 2> %s 1> /dev/null""" % (make_cmd, options, test.target(), err_file, out_file), dry_run) retcode = 0 error = None # if the make command succeds continue otherwise skip to diff if make_ret == 0 or dry_run: # fetch optional input stdinput = "< %s" % in_file if isfile(in_file) else "" if dry_run or fileIsExecutable(test.target()) : # run test retcode, _ = sh("timeout 60 ./%s %s > %s 2>&1" % (test.target(), stdinput, out_file), dry_run) else : # simply cat the result into the output sh("cat %s > %s" % (test.target(), out_file), dry_run) else: sh("mv %s %s" % (err_file, out_file), dry_run) if retcode == 0: if generate : # if we are ounly generating the output we still need to check that the test actually exists if not dry_run and fileContainsOnly(out_file, "make: *** No rule to make target `%s'. Stop." % test.target()) : retcode = 1; error = "\t\tNo make target for test %s!" % test.target() sh("rm %s" % out_file, False) else : # fetch return code and error from the diff command retcode, error = diff(cmp_file, out_file, dry_run) else: with open (out_file, "r") as myfile: error = myfile.read() # clean the executable sh("rm -f %s > /dev/null 2>&1" % test.target(), dry_run) return retcode, error # run a single test and handle the errors, outputs, printing, exception handling, etc. def run_test_worker(t, generate, dry_run, debug) : signal.signal(signal.SIGINT, signal.SIG_DFL) # print formated name name_txt = "%20s " % t.name retcode, error = run_single_test(t, generate, dry_run, debug) # update output based on current action if generate : if retcode == TestResult.SUCCESS: result_txt = "Done" elif retcode == TestResult.TIMEOUT: result_txt = "TIMEOUT" else : result_txt = "ERROR code %d" % retcode else : if retcode == TestResult.SUCCESS: result_txt = "PASSED" elif retcode == TestResult.TIMEOUT: result_txt = "TIMEOUT" else : result_txt = "FAILED with code %d" % retcode #print result with error if needed text = name_txt + result_txt out = sys.stdout if error : text = text + "\n" + error out = sys.stderr print(text, file = out) sys.stdout.flush() sys.stderr.flush() signal.signal(signal.SIGINT, signal.SIG_IGN) return retcode != TestResult.SUCCESS # run the given list of tests with the given parameters def run_tests(tests, generate, dry_run, jobs, debug) : # clean the sandbox from previous commands sh("%s clean > /dev/null 2>&1" % make_cmd, dry_run) if generate : print( "Regenerate tests for: " ) # create the executor for our jobs and handle the signal properly original_sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN) pool = Pool(jobs) signal.signal(signal.SIGINT, original_sigint_handler) # for each test to run try : results = pool.map_async(partial(run_test_worker, generate=generate, dry_run=dry_run, debug=debug), tests, chunksize = 1 ).get(7200) except KeyboardInterrupt: pool.terminate() print("Tests interrupted by user") sys.exit(1) # clean the workspace sh("%s clean > /dev/null 2>&1" % make_cmd, dry_run) for failed in results: if failed : return 1 return 0 ################################################################################ # main loop ################################################################################ if __name__ == "__main__": #always run from same folder chdir() # parse the command line arguments options = getOptions() # fetch the liest of all valid tests allTests = listTests( options.include, options.exclude ) # if user wants all tests than no other treatement of the test list is required if options.all or options.list or options.list_comp or options.include : tests = allTests else : #otherwise we need to validate that the test list that was entered is valid tests = validTests( options ) # sort the test alphabetically for convenience tests.sort(key=lambda t: os.path.join(t.path, t.name)) # users may want to simply list the tests if options.list_comp : print("-h --help --debug --dry-run --list --all --regenerate-expected -j --jobs ", end='') print(" ".join(map(lambda t: "%s" % (t.target()), tests))) elif options.list : print("Listing for %s:%s"% (options.arch, "debug" if options.debug else "no debug")) print("\n".join(map(lambda t: "%s" % (t.toString()), tests))) else : options.jobs, forceJobs = jobCount( options ) print('Running (%s:%s) on %i cores' % (options.arch, "debug" if options.debug else "no debug", options.jobs)) make_cmd = "make" if forceJobs else ("make -j%i" % options.jobs) # otherwise run all tests and make sure to return the correct error code sys.exit( run_tests(tests, options.regenerate_expected, options.dry_run, options.jobs, options.debug) )