Home | History | Annotate | Download | only in test
      1 #===----------------------------------------------------------------------===##
      2 #
      3 #                     The LLVM Compiler Infrastructure
      4 #
      5 # This file is dual licensed under the MIT and the University of Illinois Open
      6 # Source Licenses. See LICENSE.TXT for details.
      7 #
      8 #===----------------------------------------------------------------------===##
      9 
     10 import copy
     11 import errno
     12 import os
     13 import time
     14 import random
     15 
     16 import lit.Test        # pylint: disable=import-error
     17 import lit.TestRunner  # pylint: disable=import-error
     18 from lit.TestRunner import ParserKind, IntegratedTestKeywordParser  \
     19     # pylint: disable=import-error
     20 
     21 from libcxx.test.executor import LocalExecutor as LocalExecutor
     22 import libcxx.util
     23 
     24 
     25 class LibcxxTestFormat(object):
     26     """
     27     Custom test format handler for use with the test format use by libc++.
     28 
     29     Tests fall into two categories:
     30       FOO.pass.cpp - Executable test which should compile, run, and exit with
     31                      code 0.
     32       FOO.fail.cpp - Negative test case which is expected to fail compilation.
     33       FOO.sh.cpp   - A test that uses LIT's ShTest format.
     34     """
     35 
     36     def __init__(self, cxx, use_verify_for_fail, execute_external,
     37                  executor, exec_env):
     38         self.cxx = copy.deepcopy(cxx)
     39         self.use_verify_for_fail = use_verify_for_fail
     40         self.execute_external = execute_external
     41         self.executor = executor
     42         self.exec_env = dict(exec_env)
     43 
     44     @staticmethod
     45     def _make_custom_parsers():
     46         return [
     47             IntegratedTestKeywordParser('FLAKY_TEST.', ParserKind.TAG,
     48                                         initial_value=False),
     49             IntegratedTestKeywordParser('MODULES_DEFINES:', ParserKind.LIST,
     50                                         initial_value=[])
     51         ]
     52 
     53     @staticmethod
     54     def _get_parser(key, parsers):
     55         for p in parsers:
     56             if p.keyword == key:
     57                 return p
     58         assert False and "parser not found"
     59 
     60     # TODO: Move this into lit's FileBasedTest
     61     def getTestsInDirectory(self, testSuite, path_in_suite,
     62                             litConfig, localConfig):
     63         source_path = testSuite.getSourcePath(path_in_suite)
     64         for filename in os.listdir(source_path):
     65             # Ignore dot files and excluded tests.
     66             if filename.startswith('.') or filename in localConfig.excludes:
     67                 continue
     68 
     69             filepath = os.path.join(source_path, filename)
     70             if not os.path.isdir(filepath):
     71                 if any([filename.endswith(ext)
     72                         for ext in localConfig.suffixes]):
     73                     yield lit.Test.Test(testSuite, path_in_suite + (filename,),
     74                                         localConfig)
     75 
     76     def execute(self, test, lit_config):
     77         while True:
     78             try:
     79                 return self._execute(test, lit_config)
     80             except OSError as oe:
     81                 if oe.errno != errno.ETXTBSY:
     82                     raise
     83                 time.sleep(0.1)
     84 
     85     def _execute(self, test, lit_config):
     86         name = test.path_in_suite[-1]
     87         name_root, name_ext = os.path.splitext(name)
     88         is_libcxx_test = test.path_in_suite[0] == 'libcxx'
     89         is_sh_test = name_root.endswith('.sh')
     90         is_pass_test = name.endswith('.pass.cpp')
     91         is_fail_test = name.endswith('.fail.cpp')
     92         assert is_sh_test or name_ext == '.cpp', 'non-cpp file must be sh test'
     93 
     94         if test.config.unsupported:
     95             return (lit.Test.UNSUPPORTED,
     96                     "A lit.local.cfg marked this unsupported")
     97 
     98         parsers = self._make_custom_parsers()
     99         script = lit.TestRunner.parseIntegratedTestScript(
    100             test, additional_parsers=parsers, require_script=is_sh_test)
    101         # Check if a result for the test was returned. If so return that
    102         # result.
    103         if isinstance(script, lit.Test.Result):
    104             return script
    105         if lit_config.noExecute:
    106             return lit.Test.Result(lit.Test.PASS)
    107 
    108         # Check that we don't have run lines on tests that don't support them.
    109         if not is_sh_test and len(script) != 0:
    110             lit_config.fatal('Unsupported RUN line found in test %s' % name)
    111 
    112         tmpDir, tmpBase = lit.TestRunner.getTempPaths(test)
    113         substitutions = lit.TestRunner.getDefaultSubstitutions(test, tmpDir,
    114                                                                tmpBase)
    115         script = lit.TestRunner.applySubstitutions(script, substitutions)
    116 
    117         test_cxx = copy.deepcopy(self.cxx)
    118         if is_fail_test:
    119             test_cxx.useCCache(False)
    120             test_cxx.useWarnings(False)
    121         extra_modules_defines = self._get_parser('MODULES_DEFINES:',
    122                                                  parsers).getValue()
    123         if '-fmodules' in test.config.available_features:
    124             test_cxx.compile_flags += [('-D%s' % mdef.strip()) for
    125                                        mdef in extra_modules_defines]
    126             test_cxx.addWarningFlagIfSupported('-Wno-macro-redefined')
    127             # FIXME: libc++ debug tests #define _LIBCPP_ASSERT to override it
    128             # If we see this we need to build the test against uniquely built
    129             # modules.
    130             if is_libcxx_test:
    131                 with open(test.getSourcePath(), 'r') as f:
    132                     contents = f.read()
    133                 if '#define _LIBCPP_ASSERT' in contents:
    134                     test_cxx.useModules(False)
    135 
    136         # Dispatch the test based on its suffix.
    137         if is_sh_test:
    138             if not isinstance(self.executor, LocalExecutor):
    139                 # We can't run ShTest tests with a executor yet.
    140                 # For now, bail on trying to run them
    141                 return lit.Test.UNSUPPORTED, 'ShTest format not yet supported'
    142             test.config.enviroment = dict(self.exec_env)
    143             return lit.TestRunner._runShTest(test, lit_config,
    144                                              self.execute_external, script,
    145                                              tmpBase)
    146         elif is_fail_test:
    147             return self._evaluate_fail_test(test, test_cxx, parsers)
    148         elif is_pass_test:
    149             return self._evaluate_pass_test(test, tmpBase, lit_config,
    150                                             test_cxx, parsers)
    151         else:
    152             # No other test type is supported
    153             assert False
    154 
    155     def _clean(self, exec_path):  # pylint: disable=no-self-use
    156         libcxx.util.cleanFile(exec_path)
    157 
    158     def _evaluate_pass_test(self, test, tmpBase, lit_config,
    159                             test_cxx, parsers):
    160         execDir = os.path.dirname(test.getExecPath())
    161         source_path = test.getSourcePath()
    162         exec_path = tmpBase + '.exe'
    163         object_path = tmpBase + '.o'
    164         # Create the output directory if it does not already exist.
    165         libcxx.util.mkdir_p(os.path.dirname(tmpBase))
    166         try:
    167             # Compile the test
    168             cmd, out, err, rc = test_cxx.compileLinkTwoSteps(
    169                 source_path, out=exec_path, object_file=object_path,
    170                 cwd=execDir)
    171             compile_cmd = cmd
    172             if rc != 0:
    173                 report = libcxx.util.makeReport(cmd, out, err, rc)
    174                 report += "Compilation failed unexpectedly!"
    175                 return lit.Test.FAIL, report
    176             # Run the test
    177             local_cwd = os.path.dirname(source_path)
    178             env = None
    179             if self.exec_env:
    180                 env = self.exec_env
    181             # TODO: Only list actually needed files in file_deps.
    182             # Right now we just mark all of the .dat files in the same
    183             # directory as dependencies, but it's likely less than that. We
    184             # should add a `// FILE-DEP: foo.dat` to each test to track this.
    185             data_files = [os.path.join(local_cwd, f)
    186                           for f in os.listdir(local_cwd) if f.endswith('.dat')]
    187             is_flaky = self._get_parser('FLAKY_TEST.', parsers).getValue()
    188             max_retry = 3 if is_flaky else 1
    189             for retry_count in range(max_retry):
    190                 cmd, out, err, rc = self.executor.run(exec_path, [exec_path],
    191                                                       local_cwd, data_files,
    192                                                       env)
    193                 if rc == 0:
    194                     res = lit.Test.PASS if retry_count == 0 else lit.Test.FLAKYPASS
    195                     return res, ''
    196                 elif rc != 0 and retry_count + 1 == max_retry:
    197                     report = libcxx.util.makeReport(cmd, out, err, rc)
    198                     report = "Compiled With: %s\n%s" % (compile_cmd, report)
    199                     report += "Compiled test failed unexpectedly!"
    200                     return lit.Test.FAIL, report
    201 
    202             assert False # Unreachable
    203         finally:
    204             # Note that cleanup of exec_file happens in `_clean()`. If you
    205             # override this, cleanup is your reponsibility.
    206             libcxx.util.cleanFile(object_path)
    207             self._clean(exec_path)
    208 
    209     def _evaluate_fail_test(self, test, test_cxx, parsers):
    210         source_path = test.getSourcePath()
    211         # FIXME: lift this detection into LLVM/LIT.
    212         with open(source_path, 'r') as f:
    213             contents = f.read()
    214         verify_tags = ['expected-note', 'expected-remark', 'expected-warning',
    215                        'expected-error', 'expected-no-diagnostics']
    216         use_verify = self.use_verify_for_fail and \
    217                      any([tag in contents for tag in verify_tags])
    218         # FIXME(EricWF): GCC 5 does not evaluate static assertions that
    219         # are dependant on a template parameter when '-fsyntax-only' is passed.
    220         # This is fixed in GCC 6. However for now we only pass "-fsyntax-only"
    221         # when using Clang.
    222         if test_cxx.type != 'gcc':
    223             test_cxx.flags += ['-fsyntax-only']
    224         if use_verify:
    225             test_cxx.useVerify()
    226             test_cxx.useWarnings()
    227             if '-Wuser-defined-warnings' in test_cxx.warning_flags:
    228                 test_cxx.warning_flags += ['-Wno-error=user-defined-warnings']
    229 
    230         cmd, out, err, rc = test_cxx.compile(source_path, out=os.devnull)
    231         expected_rc = 0 if use_verify else 1
    232         if rc == expected_rc:
    233             return lit.Test.PASS, ''
    234         else:
    235             report = libcxx.util.makeReport(cmd, out, err, rc)
    236             report_msg = ('Expected compilation to fail!' if not use_verify else
    237                           'Expected compilation using verify to pass!')
    238             return lit.Test.FAIL, report + report_msg + '\n'
    239