Fixed bug when tests in executable partially used absolute paths.
[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     # Note: path_in_suite should not include the executable name.
58     def getTestsInExecutable(self, testSuite, path_in_suite, execpath,
59                              litConfig, localConfig):
60         if not execpath.endswith(self.test_suffix):
61             return
62         (dirname, basename) = os.path.split(execpath)
63         # Discover the tests in this executable.
64         for testname in self.getGTestTests(execpath, litConfig, localConfig):
65             testPath = path_in_suite + (basename, testname)
66             yield Test.Test(testSuite, testPath, localConfig)
67
68     def getTestsInDirectory(self, testSuite, path_in_suite,
69                             litConfig, localConfig):
70         source_path = testSuite.getSourcePath(path_in_suite)
71         for filename in os.listdir(source_path):
72             filepath = os.path.join(source_path, filename)
73             if os.path.isdir(filepath):
74                 # Iterate over executables in a directory.
75                 if not os.path.normcase(filename) in self.test_sub_dir:
76                     continue
77                 dirpath_in_suite = path_in_suite + (filename, )
78                 for subfilename in os.listdir(filepath):
79                     execpath = os.path.join(filepath, subfilename)
80                     for test in self.getTestsInExecutable(
81                             testSuite, dirpath_in_suite, execpath,
82                             litConfig, localConfig):
83                       yield test
84             elif ('.' in self.test_sub_dir):
85                 for test in self.getTestsInExecutable(
86                         testSuite, path_in_suite, filepath,
87                         litConfig, localConfig):
88                     yield test
89
90     def execute(self, test, litConfig):
91         testPath,testName = os.path.split(test.getSourcePath())
92         while not os.path.exists(testPath):
93             # Handle GTest parametrized and typed tests, whose name includes
94             # some '/'s.
95             testPath, namePrefix = os.path.split(testPath)
96             testName = os.path.join(namePrefix, testName)
97
98         cmd = [testPath, '--gtest_filter=' + testName]
99         if litConfig.useValgrind:
100             cmd = litConfig.valgrindArgs + cmd
101
102         if litConfig.noExecute:
103             return Test.PASS, ''
104
105         out, err, exitCode = TestRunner.executeCommand(
106             cmd, env=test.config.environment)
107
108         if not exitCode:
109             return Test.PASS,''
110
111         return Test.FAIL, out + err
112
113 ###
114
115 class FileBasedTest(object):
116     def getTestsInDirectory(self, testSuite, path_in_suite,
117                             litConfig, localConfig):
118         source_path = testSuite.getSourcePath(path_in_suite)
119         for filename in os.listdir(source_path):
120             # Ignore dot files and excluded tests.
121             if (filename.startswith('.') or
122                 filename in localConfig.excludes):
123                 continue
124
125             filepath = os.path.join(source_path, filename)
126             if not os.path.isdir(filepath):
127                 base,ext = os.path.splitext(filename)
128                 if ext in localConfig.suffixes:
129                     yield Test.Test(testSuite, path_in_suite + (filename,),
130                                     localConfig)
131
132 class ShTest(FileBasedTest):
133     def __init__(self, execute_external = False):
134         self.execute_external = execute_external
135
136     def execute(self, test, litConfig):
137         return TestRunner.executeShTest(test, litConfig,
138                                         self.execute_external)
139
140 ###
141
142 import re
143 import tempfile
144
145 class OneCommandPerFileTest:
146     # FIXME: Refactor into generic test for running some command on a directory
147     # of inputs.
148
149     def __init__(self, command, dir, recursive=False,
150                  pattern=".*", useTempInput=False):
151         if isinstance(command, str):
152             self.command = [command]
153         else:
154             self.command = list(command)
155         if dir is not None:
156             dir = str(dir)
157         self.dir = dir
158         self.recursive = bool(recursive)
159         self.pattern = re.compile(pattern)
160         self.useTempInput = useTempInput
161
162     def getTestsInDirectory(self, testSuite, path_in_suite,
163                             litConfig, localConfig):
164         dir = self.dir
165         if dir is None:
166             dir = testSuite.getSourcePath(path_in_suite)
167
168         for dirname,subdirs,filenames in os.walk(dir):
169             if not self.recursive:
170                 subdirs[:] = []
171
172             subdirs[:] = [d for d in subdirs
173                           if (d != '.svn' and
174                               d not in localConfig.excludes)]
175
176             for filename in filenames:
177                 if (filename.startswith('.') or
178                     not self.pattern.match(filename) or
179                     filename in localConfig.excludes):
180                     continue
181
182                 path = os.path.join(dirname,filename)
183                 suffix = path[len(dir):]
184                 if suffix.startswith(os.sep):
185                     suffix = suffix[1:]
186                 test = Test.Test(testSuite,
187                                  path_in_suite + tuple(suffix.split(os.sep)),
188                                  localConfig)
189                 # FIXME: Hack?
190                 test.source_path = path
191                 yield test
192
193     def createTempInput(self, tmp, test):
194         abstract
195
196     def execute(self, test, litConfig):
197         if test.config.unsupported:
198             return (Test.UNSUPPORTED, 'Test is unsupported')
199
200         cmd = list(self.command)
201
202         # If using temp input, create a temporary file and hand it to the
203         # subclass.
204         if self.useTempInput:
205             tmp = tempfile.NamedTemporaryFile(suffix='.cpp')
206             self.createTempInput(tmp, test)
207             tmp.flush()
208             cmd.append(tmp.name)
209         elif hasattr(test, 'source_path'):
210             cmd.append(test.source_path)
211         else:
212             cmd.append(test.getSourcePath())
213
214         out, err, exitCode = TestRunner.executeCommand(cmd)
215
216         diags = out + err
217         if not exitCode and not diags.strip():
218             return Test.PASS,''
219
220         # Try to include some useful information.
221         report = """Command: %s\n""" % ' '.join(["'%s'" % a
222                                                  for a in cmd])
223         if self.useTempInput:
224             report += """Temporary File: %s\n""" % tmp.name
225             report += "--\n%s--\n""" % open(tmp.name).read()
226         report += """Output:\n--\n%s--""" % diags
227
228         return Test.FAIL, report