regression.py
author Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
Sat, 04 Jul 2009 08:15:48 +0200
changeset 4654 2eaebe77d66b
parent 4584 7f4ee7f84b19
permissions -rw-r--r--
Added tag ns-3.5 for changeset c975274c9707
     1 # python lib modules
     2 import os
     3 import sys
     4 import shutil
     5 import pproc as subprocess
     6 import errno
     7 
     8 # WAF modules
     9 import Options
    10 import Utils
    11 import Task
    12 
    13 # local modules
    14 import wutils
    15 
    16 
    17 def dev_null():
    18     if sys.platform == 'win32':
    19         return open("NUL:", "w")
    20     else:
    21         return open("/dev/null", "w")
    22 
    23 
    24 def _find_tests(testdir):
    25     """Return a list of test modules in the test directory
    26 
    27     Arguments:
    28     testdir -- the directory to look in for tests
    29     """
    30     names = os.listdir(testdir)
    31     tests = []
    32     for name in names:
    33         if name[:5] == "test-" and name[-3:] == ".py":
    34             testname = name[:-3]
    35             tests.append(testname)
    36     tests.sort()
    37     return tests
    38 
    39 def diff(dir1, dir2, verbose):
    40     import filecmp
    41     comp = filecmp.dircmp(dir1, dir2)
    42     differ = (comp.left_only or comp.right_only or comp.diff_files)
    43 
    44     if differ:
    45         # ok, stupid binary comparison reports differences, but maybe
    46         # only text files differ, in which case we should compare
    47         # again while ignoring newline differences between
    48         # windows/mac/unix.
    49         if not comp.left_only and not comp.right_only:
    50             for diff_fname in comp.diff_files:
    51                 if not (diff_fname.endswith(".tr") or diff_fname.endswith(".mob")):
    52                     # doesn't look like a text file; it has to differ
    53                     break
    54                 diff_file1 = open(os.path.join(dir1, diff_fname), "rtU").readlines()
    55                 diff_file2 = open(os.path.join(dir2, diff_fname), "rtU").readlines()
    56                 if diff_file1 != diff_file2:
    57                     break
    58                 #else:
    59                 #    print ">>>>>>>> %s file does not really differ!" % (diff_fname)
    60             else:
    61                 differ = False
    62 
    63     if differ:
    64         if verbose:
    65             comp.report()
    66             import difflib
    67             for diff_fname in comp.diff_files:
    68                 if not (diff_fname.endswith(".tr") or diff_fname.endswith(".mob")):
    69                     print "The different file %r does not sound like a text file, not compared." % (diff_fname,)
    70                 diff_file1 = open(os.path.join(dir1, diff_fname), "rt").readlines()
    71                 diff_file2 = open(os.path.join(dir2, diff_fname), "rt").readlines()
    72                 diff = difflib.unified_diff(diff_file1, diff_file2)
    73                 count = 0
    74                 print "Differences in file %r" % (diff_fname,)
    75                 for line in diff:
    76                     print line
    77                     count += 1
    78                     if count > 100:
    79                         break
    80         return 1
    81     else:
    82         return 0
    83 
    84 class regression_test_task(Task.TaskBase):
    85     after = 'cc cxx cc_link cxx_link'
    86     color = 'BLUE'
    87 
    88     def __init__(self, bld, env, test_name, test_scripts_dir, build_traces_dir, reference_traces):
    89         self.bld = bld
    90         self.generator = self
    91         self.env = env
    92         super(regression_test_task, self).__init__(generator=self, env=env)
    93         self.test_name = test_name
    94         self.test_scripts_dir = test_scripts_dir
    95         self.build_traces_dir = build_traces_dir
    96         self.reference_traces_dir = reference_traces
    97 
    98     def __str__(self):
    99         return 'regression-test (%s)\n' % self.test_name
   100 
   101     def runnable_status(self):
   102         return Task.RUN_ME
   103 
   104     def run(self):
   105         """Run a single test"""
   106         sys.path.insert(0, self.test_scripts_dir)
   107         try:
   108             mod = __import__(self.test_name, globals(), locals(), [])
   109         finally:
   110             sys.path.remove(self.test_scripts_dir)
   111 
   112         assert self.test_name.startswith('test-')
   113         short_name = self.test_name[len('test-'):]
   114 
   115         trace_dir_name = getattr(mod, "trace_dir_name", None)
   116         if trace_dir_name is None:
   117             trace_dir_name = "%s.ref" % short_name
   118         trace_output_path = os.path.join(self.build_traces_dir, trace_dir_name)
   119         reference_traces_path = os.path.join(self.reference_traces_dir, trace_dir_name)
   120 
   121         if hasattr(mod, 'get_arguments'):
   122             arguments = mod.get_arguments(self.env, '..')
   123         else:
   124             arguments = getattr(mod, "arguments", [])
   125 
   126         pyscript = getattr(mod, "pyscript", None)
   127         if pyscript:
   128             is_pyscript = True
   129             program = pyscript
   130         else:
   131             is_pyscript = False
   132             program = getattr(mod, "program", short_name)
   133 
   134         if hasattr(mod, 'may_run'):
   135             reason_cannot_run = mod.may_run(self.env, Options.options)
   136         else:
   137             reason_cannot_run = None
   138         if reason_cannot_run:
   139             print "SKIP %s (%s)" % (self.test_name, reason_cannot_run)
   140             self.result = None
   141             return 0
   142 
   143         if Options.options.regression_generate:
   144             # clean the target dir
   145             try:
   146                 shutil.rmtree(reference_traces_path)
   147             except OSError, ex:
   148                 if ex.errno not in [errno.ENOENT]:
   149                     raise
   150             os.makedirs(reference_traces_path)
   151             result = self.run_reference_generate(reference_traces_path, program, arguments, is_pyscript)
   152             if result == 0:
   153                 print "GENERATE " + self.test_name
   154             else:
   155                 print "GENERATE FAIL " + self.test_name
   156         else:
   157             # clean the target dir
   158             try:
   159                 shutil.rmtree(trace_output_path)
   160             except OSError, ex:
   161                 if ex.errno not in [errno.ENOENT]:
   162                     raise
   163             os.makedirs(trace_output_path)
   164             # run it
   165             #print "self.run_reference_test:(%r, %r, %r, %r, %r)" \
   166             #    % (reference_traces_path, trace_output_path, program, arguments, is_pyscript)
   167             result = self.run_reference_test(reference_traces_path, trace_output_path, program, arguments, is_pyscript)
   168             if result == 0:
   169                 print "PASS " + self.test_name
   170             else:
   171                 print "FAIL " + self.test_name
   172         self.result = result
   173         return 0
   174 
   175     def run_reference_test(self, reference_traces_path, trace_output_path, program, arguments, is_pyscript):
   176         if not os.path.exists(reference_traces_path):
   177             print "Cannot locate reference traces in " + reference_traces_path
   178             return 1
   179 
   180         if is_pyscript:
   181             script = os.path.abspath(os.path.join('..', *os.path.split(program)))
   182             argv = [self.env['PYTHON'], script] + arguments
   183             try:
   184                 wutils.run_argv(argv, self.env, cwd=trace_output_path, force_no_valgrind=True)
   185             except Utils.WafError, ex:
   186                 print >> sys.stderr, ex
   187                 return 1
   188         else:
   189             try:
   190                 wutils.run_program(program, self.env,
   191                                    command_template=wutils.get_command_template(self.env, arguments),
   192                                    cwd=trace_output_path)
   193             except Utils.WafError, ex:
   194                 print >> sys.stderr, ex
   195                 return 1
   196 
   197         rc = diff(trace_output_path, reference_traces_path, Options.options.verbose)
   198         if rc:
   199             print "----------"
   200             print "Traces differ in test: ", self.test_name
   201             print "Reference traces in directory: " + reference_traces_path
   202             print "Traces in directory: " + trace_output_path
   203             print "Run the following command for details:"
   204             print "\tdiff -u %s %s" % (reference_traces_path, trace_output_path)
   205             if not Options.options.verbose:
   206                 print "Or re-run regression testing with option -v"
   207             print "----------"
   208         return rc
   209 
   210 
   211     def run_reference_generate(self, trace_output_path, program, arguments, is_pyscript):
   212         if is_pyscript:
   213             script = os.path.abspath(os.path.join('..', *os.path.split(program)))
   214             argv = [self.env['PYTHON'], script] + arguments
   215             try:
   216                 retval = wutils.run_argv(argv, self.env, cwd=trace_output_path, force_no_valgrind=True)
   217             except Utils.WafError, ex:
   218                 print >> sys.stderr, ex
   219                 return 1
   220         else:
   221             try:
   222                 retval = wutils.run_program(program, self.env,
   223                                             command_template=wutils.get_command_template(self.env, arguments),
   224                                             cwd=trace_output_path)
   225             except Utils.WafError, ex:
   226                 print >> sys.stderr, ex
   227                 return 1
   228         return retval
   229 
   230 
   231 class regression_test_collector_task(Task.TaskBase):
   232     after = 'regression_test_task'
   233     color = 'BLUE'
   234 
   235     def __init__(self, bld, test_tasks):
   236         self.bld = bld
   237         super(regression_test_collector_task, self).__init__(generator=self)
   238         self.test_tasks = test_tasks
   239 
   240     def __str__(self):
   241         return 'regression-test-collector\n'
   242 
   243     def runnable_status(self):
   244         return Task.RUN_ME
   245 
   246     def run(self):
   247         failed_tests = [test for test in self.test_tasks if test.result is not None and test.result != 0]
   248         skipped_tests = [test for test in self.test_tasks if test.result is None]
   249         print "Regression testing summary:"
   250         if skipped_tests:
   251             print "SKIP: %i of %i tests have been skipped (%s)" % (
   252                 len(skipped_tests), len(self.test_tasks),
   253                 ', '.join([test.test_name for test in skipped_tests]))
   254         if failed_tests:
   255             print "FAIL: %i of %i tests have failed (%s)" % (
   256                 len(failed_tests), len(self.test_tasks),
   257                 ', '.join([test.test_name for test in failed_tests]))
   258             return 1
   259         else:
   260             print "PASS: %i of %i tests passed" % (len(self.test_tasks) - len(skipped_tests),
   261                                                    len(self.test_tasks))
   262             return 0
   263 
   264 def run_regression(bld, reference_traces):
   265     """Execute regression tests.  Called with cwd set to the 'regression' subdir of ns-3.
   266 
   267     @param reference_traces: reference traces directory.
   268 
   269     """
   270 
   271     testdir = os.path.join("regression", "tests")
   272     if not os.path.exists(testdir):
   273         print "Tests directory does not exist"
   274         sys.exit(3)
   275 
   276     if Options.options.regression_tests:
   277         tests = Options.options.regression_tests.split(',')
   278     else:
   279         tests = _find_tests(testdir)
   280 
   281     if not os.path.exists(reference_traces):
   282         print "Reference traces directory (%s) does not exist" % reference_traces
   283         return 3
   284     
   285     test_scripts_dir = bld.path.find_dir('regression/tests').abspath()
   286     build_traces_dir = bld.path.find_or_declare('regression/traces').abspath(bld.env)
   287     tasks = []
   288     for test in tests:
   289         task = regression_test_task(bld, bld.env, test, test_scripts_dir, build_traces_dir, reference_traces)
   290         #bld.task_manager.add_task(task)
   291         tasks.append(task)
   292     regression_test_collector_task(bld, tasks)