Make lit's gtest support honor config.environment.
[oota-llvm.git] / utils / lit / lit / TestFormats.py
1 import os
2
3 import Test
4 import TestRunner
5 import Util
6
7 class GoogleTest(object):
8     def __init__(self, test_sub_dir, test_suffix):
9         self.test_sub_dir = str(test_sub_dir)
10         self.test_suffix = str(test_suffix)
11
12     def getGTestTests(self, path, litConfig, localConfig):
13         """getGTestTests(path) - [name]
14
15         Return the tests available in gtest executable.
16
17         Args:
18           path: String path to a gtest executable
19           litConfig: LitConfig instance
20           localConfig: TestingConfig instance"""
21
22         try:
23             lines = Util.capture([path, '--gtest_list_tests'],
24                                  env=localConfig.environment).split('\n')
25         except:
26             litConfig.error("unable to discover google-tests in %r" % path)
27             raise StopIteration
28
29         nested_tests = []
30         for ln in lines:
31             if not ln.strip():
32                 continue
33
34             prefix = ''
35             index = 0
36             while ln[index*2:index*2+2] == '  ':
37                 index += 1
38             while len(nested_tests) > index:
39                 nested_tests.pop()
40             
41             ln = ln[index*2:]
42             if ln.endswith('.'):
43                 nested_tests.append(ln)
44             else:
45                 yield ''.join(nested_tests) + ln
46
47     def getTestsInDirectory(self, testSuite, path_in_suite,
48                             litConfig, localConfig):
49         source_path = testSuite.getSourcePath(path_in_suite)
50         for filename in os.listdir(source_path):
51             # Check for the one subdirectory (build directory) tests will be in.
52             if filename != self.test_sub_dir:
53                 continue
54
55             filepath = os.path.join(source_path, filename)
56             for subfilename in os.listdir(filepath):
57                 if subfilename.endswith(self.test_suffix):
58                     execpath = os.path.join(filepath, subfilename)
59
60                     # Discover the tests in this executable.
61                     for name in self.getGTestTests(execpath, litConfig,
62                                                    localConfig):
63                         testPath = path_in_suite + (filename, subfilename, name)
64                         yield Test.Test(testSuite, testPath, localConfig)
65
66     def execute(self, test, litConfig):
67         testPath,testName = os.path.split(test.getSourcePath())
68         while not os.path.exists(testPath):
69             # Handle GTest parametrized and typed tests, whose name includes
70             # some '/'s.
71             testPath, namePrefix = os.path.split(testPath)
72             testName = os.path.join(namePrefix, testName)
73
74         cmd = [testPath, '--gtest_filter=' + testName]
75         out, err, exitCode = TestRunner.executeCommand(
76             cmd, env=test.config.environment)
77             
78         if not exitCode:
79             return Test.PASS,''
80
81         return Test.FAIL, out + err
82
83 ###
84
85 class FileBasedTest(object):
86     def getTestsInDirectory(self, testSuite, path_in_suite,
87                             litConfig, localConfig):
88         source_path = testSuite.getSourcePath(path_in_suite)
89         for filename in os.listdir(source_path):
90             filepath = os.path.join(source_path, filename)
91             if not os.path.isdir(filepath):
92                 base,ext = os.path.splitext(filename)
93                 if ext in localConfig.suffixes:
94                     yield Test.Test(testSuite, path_in_suite + (filename,),
95                                     localConfig)
96
97 class ShTest(FileBasedTest):
98     def __init__(self, execute_external = False):
99         self.execute_external = execute_external
100
101     def execute(self, test, litConfig):
102         return TestRunner.executeShTest(test, litConfig,
103                                         self.execute_external)
104
105 class TclTest(FileBasedTest):
106     def execute(self, test, litConfig):
107         return TestRunner.executeTclTest(test, litConfig)
108
109 ###
110
111 import re
112 import tempfile
113
114 class OneCommandPerFileTest:
115     # FIXME: Refactor into generic test for running some command on a directory
116     # of inputs.
117
118     def __init__(self, command, dir, recursive=False,
119                  pattern=".*", useTempInput=False):
120         if isinstance(command, str):
121             self.command = [command]
122         else:
123             self.command = list(command)
124         self.dir = str(dir)
125         self.recursive = bool(recursive)
126         self.pattern = re.compile(pattern)
127         self.useTempInput = useTempInput
128
129     def getTestsInDirectory(self, testSuite, path_in_suite,
130                             litConfig, localConfig):
131         for dirname,subdirs,filenames in os.walk(self.dir):
132             if not self.recursive:
133                 subdirs[:] = []
134
135             subdirs[:] = [d for d in subdirs
136                           if (d != '.svn' and
137                               d not in localConfig.excludes)]
138
139             for filename in filenames:
140                 if (not self.pattern.match(filename) or
141                     filename in localConfig.excludes):
142                     continue
143
144                 path = os.path.join(dirname,filename)
145                 suffix = path[len(self.dir):]
146                 if suffix.startswith(os.sep):
147                     suffix = suffix[1:]
148                 test = Test.Test(testSuite,
149                                  path_in_suite + tuple(suffix.split(os.sep)),
150                                  localConfig)
151                 # FIXME: Hack?
152                 test.source_path = path
153                 yield test
154
155     def createTempInput(self, tmp, test):
156         abstract
157
158     def execute(self, test, litConfig):
159         if test.config.unsupported:
160             return (Test.UNSUPPORTED, 'Test is unsupported')
161
162         cmd = list(self.command)
163
164         # If using temp input, create a temporary file and hand it to the
165         # subclass.
166         if self.useTempInput:
167             tmp = tempfile.NamedTemporaryFile(suffix='.cpp')
168             self.createTempInput(tmp, test)
169             tmp.flush()
170             cmd.append(tmp.name)
171         else:
172             cmd.append(test.source_path)
173
174         out, err, exitCode = TestRunner.executeCommand(cmd)
175
176         diags = out + err
177         if not exitCode and not diags.strip():
178             return Test.PASS,''
179
180         # Try to include some useful information.
181         report = """Command: %s\n""" % ' '.join(["'%s'" % a
182                                                  for a in cmd])
183         if self.useTempInput:
184             report += """Temporary File: %s\n""" % tmp.name
185             report += "--\n%s--\n""" % open(tmp.name).read()
186         report += """Output:\n--\n%s--""" % diags
187
188         return Test.FAIL, report
189
190 class SyntaxCheckTest(OneCommandPerFileTest):
191     def __init__(self, compiler, dir, extra_cxx_args=[], *args, **kwargs):
192         cmd = [compiler, '-x', 'c++', '-fsyntax-only'] + extra_cxx_args
193         OneCommandPerFileTest.__init__(self, cmd, dir,
194                                        useTempInput=1, *args, **kwargs)
195
196     def createTempInput(self, tmp, test):
197         print >>tmp, '#include "%s"' % test.source_path