lit: Ignore dot files when scanning for tests (e.g., editor temprary files,
[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             # Ignore dot files.
91             if filename.startswith('.'):
92                 continue
93
94             filepath = os.path.join(source_path, filename)
95             if not os.path.isdir(filepath):
96                 base,ext = os.path.splitext(filename)
97                 if ext in localConfig.suffixes:
98                     yield Test.Test(testSuite, path_in_suite + (filename,),
99                                     localConfig)
100
101 class ShTest(FileBasedTest):
102     def __init__(self, execute_external = False):
103         self.execute_external = execute_external
104
105     def execute(self, test, litConfig):
106         return TestRunner.executeShTest(test, litConfig,
107                                         self.execute_external)
108
109 class TclTest(FileBasedTest):
110     def execute(self, test, litConfig):
111         return TestRunner.executeTclTest(test, litConfig)
112
113 ###
114
115 import re
116 import tempfile
117
118 class OneCommandPerFileTest:
119     # FIXME: Refactor into generic test for running some command on a directory
120     # of inputs.
121
122     def __init__(self, command, dir, recursive=False,
123                  pattern=".*", useTempInput=False):
124         if isinstance(command, str):
125             self.command = [command]
126         else:
127             self.command = list(command)
128         self.dir = str(dir)
129         self.recursive = bool(recursive)
130         self.pattern = re.compile(pattern)
131         self.useTempInput = useTempInput
132
133     def getTestsInDirectory(self, testSuite, path_in_suite,
134                             litConfig, localConfig):
135         for dirname,subdirs,filenames in os.walk(self.dir):
136             if not self.recursive:
137                 subdirs[:] = []
138
139             subdirs[:] = [d for d in subdirs
140                           if (d != '.svn' and
141                               d not in localConfig.excludes)]
142
143             for filename in filenames:
144                 if (filename.startswith('.') or
145                     not self.pattern.match(filename) or
146                     filename in localConfig.excludes):
147                     continue
148
149                 path = os.path.join(dirname,filename)
150                 suffix = path[len(self.dir):]
151                 if suffix.startswith(os.sep):
152                     suffix = suffix[1:]
153                 test = Test.Test(testSuite,
154                                  path_in_suite + tuple(suffix.split(os.sep)),
155                                  localConfig)
156                 # FIXME: Hack?
157                 test.source_path = path
158                 yield test
159
160     def createTempInput(self, tmp, test):
161         abstract
162
163     def execute(self, test, litConfig):
164         if test.config.unsupported:
165             return (Test.UNSUPPORTED, 'Test is unsupported')
166
167         cmd = list(self.command)
168
169         # If using temp input, create a temporary file and hand it to the
170         # subclass.
171         if self.useTempInput:
172             tmp = tempfile.NamedTemporaryFile(suffix='.cpp')
173             self.createTempInput(tmp, test)
174             tmp.flush()
175             cmd.append(tmp.name)
176         else:
177             cmd.append(test.source_path)
178
179         out, err, exitCode = TestRunner.executeCommand(cmd)
180
181         diags = out + err
182         if not exitCode and not diags.strip():
183             return Test.PASS,''
184
185         # Try to include some useful information.
186         report = """Command: %s\n""" % ' '.join(["'%s'" % a
187                                                  for a in cmd])
188         if self.useTempInput:
189             report += """Temporary File: %s\n""" % tmp.name
190             report += "--\n%s--\n""" % open(tmp.name).read()
191         report += """Output:\n--\n%s--""" % diags
192
193         return Test.FAIL, report
194
195 class SyntaxCheckTest(OneCommandPerFileTest):
196     def __init__(self, compiler, dir, extra_cxx_args=[], *args, **kwargs):
197         cmd = [compiler, '-x', 'c++', '-fsyntax-only'] + extra_cxx_args
198         OneCommandPerFileTest.__init__(self, cmd, dir,
199                                        useTempInput=1, *args, **kwargs)
200
201     def createTempInput(self, tmp, test):
202         print >>tmp, '#include "%s"' % test.source_path