[lit] Use py2&3 compatible exec() syntax.
[oota-llvm.git] / utils / lit / lit / TestFormats.py
1 from __future__ import absolute_import
2 import os
3 import sys
4
5 import lit.Test
6 import lit.TestRunner
7 import lit.Util
8
9 kIsWindows = sys.platform in ['win32', 'cygwin']
10
11 class GoogleTest(object):
12     def __init__(self, test_sub_dir, test_suffix):
13         self.test_sub_dir = os.path.normcase(str(test_sub_dir)).split(';')
14         self.test_suffix = str(test_suffix)
15
16         # On Windows, assume tests will also end in '.exe'.
17         if kIsWindows:
18             self.test_suffix += '.exe'
19
20     def getGTestTests(self, path, litConfig, localConfig):
21         """getGTestTests(path) - [name]
22
23         Return the tests available in gtest executable.
24
25         Args:
26           path: String path to a gtest executable
27           litConfig: LitConfig instance
28           localConfig: TestingConfig instance"""
29
30         try:
31             lines = lit.Util.capture([path, '--gtest_list_tests'],
32                                      env=localConfig.environment)
33             if kIsWindows:
34               lines = lines.replace('\r', '')
35             lines = lines.split('\n')
36         except:
37             litConfig.error("unable to discover google-tests in %r" % path)
38             raise StopIteration
39
40         nested_tests = []
41         for ln in lines:
42             if not ln.strip():
43                 continue
44
45             prefix = ''
46             index = 0
47             while ln[index*2:index*2+2] == '  ':
48                 index += 1
49             while len(nested_tests) > index:
50                 nested_tests.pop()
51
52             ln = ln[index*2:]
53             if ln.endswith('.'):
54                 nested_tests.append(ln)
55             else:
56                 yield ''.join(nested_tests) + ln
57
58     # Note: path_in_suite should not include the executable name.
59     def getTestsInExecutable(self, testSuite, path_in_suite, execpath,
60                              litConfig, localConfig):
61         if not execpath.endswith(self.test_suffix):
62             return
63         (dirname, basename) = os.path.split(execpath)
64         # Discover the tests in this executable.
65         for testname in self.getGTestTests(execpath, litConfig, localConfig):
66             testPath = path_in_suite + (basename, testname)
67             yield lit.Test.Test(testSuite, testPath, localConfig)
68
69     def getTestsInDirectory(self, testSuite, path_in_suite,
70                             litConfig, localConfig):
71         source_path = testSuite.getSourcePath(path_in_suite)
72         for filename in os.listdir(source_path):
73             filepath = os.path.join(source_path, filename)
74             if os.path.isdir(filepath):
75                 # Iterate over executables in a directory.
76                 if not os.path.normcase(filename) in self.test_sub_dir:
77                     continue
78                 dirpath_in_suite = path_in_suite + (filename, )
79                 for subfilename in os.listdir(filepath):
80                     execpath = os.path.join(filepath, subfilename)
81                     for test in self.getTestsInExecutable(
82                             testSuite, dirpath_in_suite, execpath,
83                             litConfig, localConfig):
84                       yield test
85             elif ('.' in self.test_sub_dir):
86                 for test in self.getTestsInExecutable(
87                         testSuite, path_in_suite, filepath,
88                         litConfig, localConfig):
89                     yield test
90
91     def execute(self, test, litConfig):
92         testPath,testName = os.path.split(test.getSourcePath())
93         while not os.path.exists(testPath):
94             # Handle GTest parametrized and typed tests, whose name includes
95             # some '/'s.
96             testPath, namePrefix = os.path.split(testPath)
97             testName = os.path.join(namePrefix, testName)
98
99         cmd = [testPath, '--gtest_filter=' + testName]
100         if litConfig.useValgrind:
101             cmd = litConfig.valgrindArgs + cmd
102
103         out, err, exitCode = lit.TestRunner.executeCommand(
104             cmd, env=test.config.environment)
105
106         if not exitCode:
107             return lit.Test.PASS,''
108
109         return lit.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 lit.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 lit.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 = lit.Test.Test(
185                     testSuite, 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 (lit.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 = lit.TestRunner.executeCommand(cmd)
213
214         diags = out + err
215         if not exitCode and not diags.strip():
216             return lit.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 lit.Test.FAIL, report