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