blob: 7634c2a2a2d025add32967db145e7aa701b190be [file] [log] [blame]
Johnny Chen9707bb62010-06-25 21:14:08 +00001#!/usr/bin/env python
2
3"""
4A simple testing framework for lldb using python's unit testing framework.
5
6Tests for lldb are written as python scripts which take advantage of the script
7bridging provided by LLDB.framework to interact with lldb core.
8
9A specific naming pattern is followed by the .py script to be recognized as
10a module which implements a test scenario, namely, Test*.py.
11
12To specify the directories where "Test*.py" python test scripts are located,
13you need to pass in a list of directory names. By default, the current
14working directory is searched if nothing is specified on the command line.
Johnny Chen872aee12010-09-16 15:44:23 +000015
16Type:
17
18./dotest.py -h
19
20for available options.
Johnny Chen9707bb62010-06-25 21:14:08 +000021"""
22
Johnny Chen91960d32010-09-08 20:56:16 +000023import os, signal, sys, time
Johnny Chen75e28f92010-08-05 23:42:46 +000024import unittest2
Johnny Chen9707bb62010-06-25 21:14:08 +000025
Johnny Chen877c7e42010-08-07 00:16:07 +000026class _WritelnDecorator(object):
27 """Used to decorate file-like objects with a handy 'writeln' method"""
28 def __init__(self,stream):
29 self.stream = stream
30
31 def __getattr__(self, attr):
32 if attr in ('stream', '__getstate__'):
33 raise AttributeError(attr)
34 return getattr(self.stream,attr)
35
36 def writeln(self, arg=None):
37 if arg:
38 self.write(arg)
39 self.write('\n') # text-mode streams translate to \r\n if needed
40
Johnny Chen9707bb62010-06-25 21:14:08 +000041#
42# Global variables:
43#
44
45# The test suite.
Johnny Chen75e28f92010-08-05 23:42:46 +000046suite = unittest2.TestSuite()
Johnny Chen9707bb62010-06-25 21:14:08 +000047
Johnny Chen82e6b1e2010-12-01 22:47:54 +000048# The blacklist is optional (-b blacklistFile) and allows a central place to skip
49# testclass's and/or testclass.testmethod's.
50blacklist = None
51
52# The dictionary as a result of sourcing blacklistFile.
53blacklistConfig = {}
54
Johnny Chen9fdb0a92010-09-18 00:16:47 +000055# The config file is optional.
56configFile = None
57
Johnny Chend2acdb32010-11-16 22:42:58 +000058# Test suite repeat count. Can be overwritten with '-# count'.
59count = 1
60
Johnny Chenb40056b2010-09-21 00:09:27 +000061# The dictionary as a result of sourcing configFile.
62config = {}
63
Johnny Chen91960d32010-09-08 20:56:16 +000064# Delay startup in order for the debugger to attach.
65delay = False
66
Johnny Chen7d6d8442010-12-03 19:59:35 +000067# By default, failfast is False. Use '-F' to overwrite it.
68failfast = False
69
Johnny Chena224cd12010-11-08 01:21:03 +000070# The filter (testclass.testmethod) used to admit tests into our test suite.
Johnny Chenb62436b2010-10-06 20:40:56 +000071filterspec = None
72
Johnny Chena224cd12010-11-08 01:21:03 +000073# If '-g' is specified, the filterspec is not exclusive. If a test module does
74# not contain testclass.testmethod which matches the filterspec, the whole test
75# module is still admitted into our test suite. fs4all flag defaults to True.
76fs4all = True
Johnny Chenb62436b2010-10-06 20:40:56 +000077
Johnny Chenaf149a02010-09-16 17:11:30 +000078# Ignore the build search path relative to this script to locate the lldb.py module.
79ignore = False
80
Johnny Chen548aefd2010-10-11 22:25:46 +000081# By default, we skip long running test case. Use '-l' option to override.
Johnny Chen41998192010-10-01 22:59:49 +000082skipLongRunningTest = True
83
Johnny Chen7c52ff12010-09-27 23:29:54 +000084# The regular expression pattern to match against eligible filenames as our test cases.
85regexp = None
86
Johnny Chen548aefd2010-10-11 22:25:46 +000087# By default, tests are executed in place and cleanups are performed afterwards.
88# Use '-r dir' option to relocate the tests and their intermediate files to a
89# different directory and to forgo any cleanups. The directory specified must
90# not exist yet.
91rdir = None
92
Johnny Chen125fc2b2010-10-21 16:55:35 +000093# By default, recorded session info for errored/failed test are dumped into its
94# own file under a session directory named after the timestamp of the test suite
95# run. Use '-s session-dir-name' to specify a specific dir name.
96sdir_name = None
97
Johnny Chen63c2cba2010-10-29 22:20:36 +000098# Set this flag if there is any session info dumped during the test run.
99sdir_has_content = False
100
Johnny Chen9707bb62010-06-25 21:14:08 +0000101# Default verbosity is 0.
102verbose = 0
103
104# By default, search from the current working directory.
105testdirs = [ os.getcwd() ]
106
Johnny Chen877c7e42010-08-07 00:16:07 +0000107# Separator string.
108separator = '-' * 70
109
Johnny Chen9707bb62010-06-25 21:14:08 +0000110
111def usage():
112 print """
113Usage: dotest.py [option] [args]
114where options:
115-h : print this help message and exit (also --help)
Johnny Chen82e6b1e2010-12-01 22:47:54 +0000116-b : read a blacklist file specified after this option
Johnny Chen9fdb0a92010-09-18 00:16:47 +0000117-c : read a config file specified after this option
Johnny Chenb40056b2010-09-21 00:09:27 +0000118 (see also lldb-trunk/example/test/usage-config)
Johnny Chen91960d32010-09-08 20:56:16 +0000119-d : delay startup for 10 seconds (in order for the debugger to attach)
Johnny Chen7d6d8442010-12-03 19:59:35 +0000120-F : failfast, stop the test suite on the first error/failure
Johnny Chen46be75d2010-10-11 16:19:48 +0000121-f : specify a filter, which consists of the test class name, a dot, followed by
Johnny Chen1a6e92a2010-11-08 20:17:04 +0000122 the test method, to only admit such test into the test suite
Johnny Chenb62436b2010-10-06 20:40:56 +0000123 e.g., -f 'ClassTypesTestCase.test_with_dwarf_and_python_api'
Johnny Chena224cd12010-11-08 01:21:03 +0000124-g : if specified, the filterspec by -f is not exclusive, i.e., if a test module
125 does not match the filterspec (testclass.testmethod), the whole module is
126 still admitted to the test suite
Johnny Chenaf149a02010-09-16 17:11:30 +0000127-i : ignore (don't bailout) if 'lldb.py' module cannot be located in the build
128 tree relative to this script; use PYTHONPATH to locate the module
Johnny Chen41998192010-10-01 22:59:49 +0000129-l : don't skip long running test
Johnny Chen7c52ff12010-09-27 23:29:54 +0000130-p : specify a regexp filename pattern for inclusion in the test suite
Johnny Chen548aefd2010-10-11 22:25:46 +0000131-r : specify a dir to relocate the tests and their intermediate files to;
132 the directory must not exist before running this test driver;
133 no cleanup of intermediate test files is performed in this case
Johnny Chen125fc2b2010-10-21 16:55:35 +0000134-s : specify the name of the dir created to store the session files of tests
135 with errored or failed status; if not specified, the test driver uses the
136 timestamp as the session dir name
Johnny Chend0c24b22010-08-23 17:10:44 +0000137-t : trace lldb command execution and result
Johnny Chen9707bb62010-06-25 21:14:08 +0000138-v : do verbose mode of unittest framework
Johnny Chene47649c2010-10-07 02:04:14 +0000139-w : insert some wait time (currently 0.5 sec) between consecutive test cases
Johnny Chend2acdb32010-11-16 22:42:58 +0000140-# : Repeat the test suite for a specified number of times
Johnny Chen9707bb62010-06-25 21:14:08 +0000141
142and:
Johnny Chen9656ab22010-10-22 19:00:18 +0000143args : specify a list of directory names to search for test modules named after
144 Test*.py (test discovery)
Johnny Chen9707bb62010-06-25 21:14:08 +0000145 if empty, search from the curret working directory, instead
Johnny Chen58f93922010-06-29 23:10:39 +0000146
Johnny Chen9656ab22010-10-22 19:00:18 +0000147Examples:
148
Johnny Chena224cd12010-11-08 01:21:03 +0000149This is an example of using the -f option to pinpoint to a specfic test class
150and test method to be run:
Johnny Chen6ad7e5e2010-10-21 00:47:52 +0000151
Johnny Chena224cd12010-11-08 01:21:03 +0000152$ ./dotest.py -f ClassTypesTestCase.test_with_dsym_and_run_command
Johnny Chen6ad7e5e2010-10-21 00:47:52 +0000153----------------------------------------------------------------------
154Collected 1 test
155
156test_with_dsym_and_run_command (TestClassTypes.ClassTypesTestCase)
157Test 'frame variable this' when stopped on a class constructor. ... ok
158
159----------------------------------------------------------------------
160Ran 1 test in 1.396s
161
162OK
Johnny Chen9656ab22010-10-22 19:00:18 +0000163
164And this is an example of using the -p option to run a single file (the filename
165matches the pattern 'ObjC' and it happens to be 'TestObjCMethods.py'):
166
167$ ./dotest.py -v -p ObjC
168----------------------------------------------------------------------
169Collected 4 tests
170
171test_break_with_dsym (TestObjCMethods.FoundationTestCase)
172Test setting objc breakpoints using 'regexp-break' and 'breakpoint set'. ... ok
173test_break_with_dwarf (TestObjCMethods.FoundationTestCase)
174Test setting objc breakpoints using 'regexp-break' and 'breakpoint set'. ... ok
175test_data_type_and_expr_with_dsym (TestObjCMethods.FoundationTestCase)
176Lookup objective-c data types and evaluate expressions. ... ok
177test_data_type_and_expr_with_dwarf (TestObjCMethods.FoundationTestCase)
178Lookup objective-c data types and evaluate expressions. ... ok
179
180----------------------------------------------------------------------
181Ran 4 tests in 16.661s
182
183OK
Johnny Chen6ad7e5e2010-10-21 00:47:52 +0000184
Johnny Chen58f93922010-06-29 23:10:39 +0000185Running of this script also sets up the LLDB_TEST environment variable so that
Johnny Chenaf149a02010-09-16 17:11:30 +0000186individual test cases can locate their supporting files correctly. The script
187tries to set up Python's search paths for modules by looking at the build tree
Johnny Chena85859f2010-11-11 22:14:56 +0000188relative to this script. See also the '-i' option in the following example.
189
190Finally, this is an example of using the lldb.py module distributed/installed by
191Xcode4 to run against the tests under the 'forward' directory, and with the '-w'
192option to add some delay between two tests. It uses ARCH=x86_64 to specify that
193as the architecture and CC=clang to specify the compiler used for the test run:
194
195$ PYTHONPATH=/Xcode4/Library/PrivateFrameworks/LLDB.framework/Versions/A/Resources/Python ARCH=x86_64 CC=clang ./dotest.py -v -w -i forward
196
197Session logs for test failures/errors will go into directory '2010-11-11-13_56_16'
198----------------------------------------------------------------------
199Collected 2 tests
200
201test_with_dsym_and_run_command (TestForwardDeclaration.ForwardDeclarationTestCase)
202Display *bar_ptr when stopped on a function with forward declaration of struct bar. ... ok
203test_with_dwarf_and_run_command (TestForwardDeclaration.ForwardDeclarationTestCase)
204Display *bar_ptr when stopped on a function with forward declaration of struct bar. ... ok
205
206----------------------------------------------------------------------
207Ran 2 tests in 5.659s
208
209OK
210
211The 'Session ...' verbiage is recently introduced (see also the '-s' option) to
212notify the directory containing the session logs for test failures or errors.
213In case there is any test failure/error, a similar message is appended at the
214end of the stderr output for your convenience.
Johnny Chenfde69bc2010-09-14 22:01:40 +0000215
216Environment variables related to loggings:
217
218o LLDB_LOG: if defined, specifies the log file pathname for the 'lldb' subsystem
219 with a default option of 'event process' if LLDB_LOG_OPTION is not defined.
220
221o GDB_REMOTE_LOG: if defined, specifies the log file pathname for the
222 'process.gdb-remote' subsystem with a default option of 'packets' if
223 GDB_REMOTE_LOG_OPTION is not defined.
Johnny Chen9707bb62010-06-25 21:14:08 +0000224"""
Johnny Chen9fdb0a92010-09-18 00:16:47 +0000225 sys.exit(0)
Johnny Chen9707bb62010-06-25 21:14:08 +0000226
227
Johnny Chenaf149a02010-09-16 17:11:30 +0000228def parseOptionsAndInitTestdirs():
229 """Initialize the list of directories containing our unittest scripts.
230
231 '-h/--help as the first option prints out usage info and exit the program.
232 """
233
Johnny Chen82e6b1e2010-12-01 22:47:54 +0000234 global blacklist
235 global blacklistConfig
Johnny Chen9fdb0a92010-09-18 00:16:47 +0000236 global configFile
Johnny Chend2acdb32010-11-16 22:42:58 +0000237 global count
Johnny Chenaf149a02010-09-16 17:11:30 +0000238 global delay
Johnny Chen7d6d8442010-12-03 19:59:35 +0000239 global failfast
Johnny Chenb62436b2010-10-06 20:40:56 +0000240 global filterspec
241 global fs4all
Johnny Chen7c52ff12010-09-27 23:29:54 +0000242 global ignore
Johnny Chen41998192010-10-01 22:59:49 +0000243 global skipLongRunningTest
Johnny Chen7c52ff12010-09-27 23:29:54 +0000244 global regexp
Johnny Chen548aefd2010-10-11 22:25:46 +0000245 global rdir
Johnny Chen125fc2b2010-10-21 16:55:35 +0000246 global sdir_name
Johnny Chenaf149a02010-09-16 17:11:30 +0000247 global verbose
248 global testdirs
249
250 if len(sys.argv) == 1:
251 return
252
253 # Process possible trace and/or verbose flag, among other things.
254 index = 1
Johnny Chence2212c2010-10-07 15:41:55 +0000255 while index < len(sys.argv):
Johnny Chenaf149a02010-09-16 17:11:30 +0000256 if not sys.argv[index].startswith('-'):
257 # End of option processing.
258 break
259
260 if sys.argv[index].find('-h') != -1:
261 usage()
Johnny Chen82e6b1e2010-12-01 22:47:54 +0000262 elif sys.argv[index].startswith('-b'):
263 # Increment by 1 to fetch the blacklist file name option argument.
264 index += 1
265 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
266 usage()
267 blacklistFile = sys.argv[index]
268 if not os.path.isfile(blacklistFile):
269 print "Blacklist file:", blacklistFile, "does not exist!"
270 usage()
271 index += 1
272 # Now read the blacklist contents and assign it to blacklist.
273 execfile(blacklistFile, globals(), blacklistConfig)
274 blacklist = blacklistConfig.get('blacklist')
Johnny Chen9fdb0a92010-09-18 00:16:47 +0000275 elif sys.argv[index].startswith('-c'):
276 # Increment by 1 to fetch the config file name option argument.
277 index += 1
278 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
279 usage()
280 configFile = sys.argv[index]
281 if not os.path.isfile(configFile):
282 print "Config file:", configFile, "does not exist!"
283 usage()
284 index += 1
Johnny Chenaf149a02010-09-16 17:11:30 +0000285 elif sys.argv[index].startswith('-d'):
286 delay = True
287 index += 1
Johnny Chen7d6d8442010-12-03 19:59:35 +0000288 elif sys.argv[index].startswith('-F'):
289 failfast = True
290 index += 1
Johnny Chenb62436b2010-10-06 20:40:56 +0000291 elif sys.argv[index].startswith('-f'):
292 # Increment by 1 to fetch the filter spec.
293 index += 1
294 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
295 usage()
296 filterspec = sys.argv[index]
297 index += 1
298 elif sys.argv[index].startswith('-g'):
Johnny Chena224cd12010-11-08 01:21:03 +0000299 fs4all = False
Johnny Chenb62436b2010-10-06 20:40:56 +0000300 index += 1
Johnny Chenaf149a02010-09-16 17:11:30 +0000301 elif sys.argv[index].startswith('-i'):
302 ignore = True
303 index += 1
Johnny Chen41998192010-10-01 22:59:49 +0000304 elif sys.argv[index].startswith('-l'):
305 skipLongRunningTest = False
306 index += 1
Johnny Chen7c52ff12010-09-27 23:29:54 +0000307 elif sys.argv[index].startswith('-p'):
308 # Increment by 1 to fetch the reg exp pattern argument.
309 index += 1
310 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
311 usage()
312 regexp = sys.argv[index]
313 index += 1
Johnny Chen548aefd2010-10-11 22:25:46 +0000314 elif sys.argv[index].startswith('-r'):
315 # Increment by 1 to fetch the relocated directory argument.
316 index += 1
317 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
318 usage()
319 rdir = os.path.abspath(sys.argv[index])
320 if os.path.exists(rdir):
321 print "Relocated directory:", rdir, "must not exist!"
322 usage()
323 index += 1
Johnny Chen125fc2b2010-10-21 16:55:35 +0000324 elif sys.argv[index].startswith('-s'):
325 # Increment by 1 to fetch the session dir name.
326 index += 1
327 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
328 usage()
329 sdir_name = sys.argv[index]
330 index += 1
Johnny Chenaf149a02010-09-16 17:11:30 +0000331 elif sys.argv[index].startswith('-t'):
332 os.environ["LLDB_COMMAND_TRACE"] = "YES"
333 index += 1
334 elif sys.argv[index].startswith('-v'):
335 verbose = 2
336 index += 1
Johnny Chene47649c2010-10-07 02:04:14 +0000337 elif sys.argv[index].startswith('-w'):
338 os.environ["LLDB_WAIT_BETWEEN_TEST_CASES"] = 'YES'
339 index += 1
Johnny Chend2acdb32010-11-16 22:42:58 +0000340 elif sys.argv[index].startswith('-#'):
341 # Increment by 1 to fetch the repeat count argument.
342 index += 1
343 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
344 usage()
345 count = int(sys.argv[index])
346 index += 1
Johnny Chenaf149a02010-09-16 17:11:30 +0000347 else:
348 print "Unknown option: ", sys.argv[index]
349 usage()
Johnny Chenaf149a02010-09-16 17:11:30 +0000350
351 # Gather all the dirs passed on the command line.
352 if len(sys.argv) > index:
353 testdirs = map(os.path.abspath, sys.argv[index:])
354
Johnny Chen548aefd2010-10-11 22:25:46 +0000355 # If '-r dir' is specified, the tests should be run under the relocated
356 # directory. Let's copy the testdirs over.
357 if rdir:
358 from shutil import copytree, ignore_patterns
359
360 tmpdirs = []
361 for srcdir in testdirs:
362 dstdir = os.path.join(rdir, os.path.basename(srcdir))
363 # Don't copy the *.pyc and .svn stuffs.
364 copytree(srcdir, dstdir, ignore=ignore_patterns('*.pyc', '.svn'))
365 tmpdirs.append(dstdir)
366
367 # This will be our modified testdirs.
368 testdirs = tmpdirs
369
370 # With '-r dir' specified, there's no cleanup of intermediate test files.
371 os.environ["LLDB_DO_CLEANUP"] = 'NO'
372
373 # If testdirs is ['test'], the make directory has already been copied
374 # recursively and is contained within the rdir/test dir. For anything
375 # else, we would need to copy over the make directory and its contents,
376 # so that, os.listdir(rdir) looks like, for example:
377 #
378 # array_types conditional_break make
379 #
380 # where the make directory contains the Makefile.rules file.
381 if len(testdirs) != 1 or os.path.basename(testdirs[0]) != 'test':
382 # Don't copy the .svn stuffs.
383 copytree('make', os.path.join(rdir, 'make'),
384 ignore=ignore_patterns('.svn'))
385
386 #print "testdirs:", testdirs
387
Johnny Chenb40056b2010-09-21 00:09:27 +0000388 # Source the configFile if specified.
389 # The side effect, if any, will be felt from this point on. An example
390 # config file may be these simple two lines:
391 #
392 # sys.stderr = open("/tmp/lldbtest-stderr", "w")
393 # sys.stdout = open("/tmp/lldbtest-stdout", "w")
394 #
395 # which will reassign the two file objects to sys.stderr and sys.stdout,
396 # respectively.
397 #
398 # See also lldb-trunk/example/test/usage-config.
399 global config
400 if configFile:
401 # Pass config (a dictionary) as the locals namespace for side-effect.
402 execfile(configFile, globals(), config)
403 #print "config:", config
404 #print "sys.stderr:", sys.stderr
405 #print "sys.stdout:", sys.stdout
406
Johnny Chenaf149a02010-09-16 17:11:30 +0000407
Johnny Chen9707bb62010-06-25 21:14:08 +0000408def setupSysPath():
409 """Add LLDB.framework/Resources/Python to the search paths for modules."""
410
Johnny Chen548aefd2010-10-11 22:25:46 +0000411 global rdir
412 global testdirs
413
Johnny Chen9707bb62010-06-25 21:14:08 +0000414 # Get the directory containing the current script.
Johnny Chena1affab2010-07-03 03:41:59 +0000415 scriptPath = sys.path[0]
416 if not scriptPath.endswith('test'):
Johnny Chen9707bb62010-06-25 21:14:08 +0000417 print "This script expects to reside in lldb's test directory."
418 sys.exit(-1)
419
Johnny Chen548aefd2010-10-11 22:25:46 +0000420 if rdir:
421 # Set up the LLDB_TEST environment variable appropriately, so that the
422 # individual tests can be located relatively.
423 #
424 # See also lldbtest.TestBase.setUpClass(cls).
425 if len(testdirs) == 1 and os.path.basename(testdirs[0]) == 'test':
426 os.environ["LLDB_TEST"] = os.path.join(rdir, 'test')
427 else:
428 os.environ["LLDB_TEST"] = rdir
429 else:
430 os.environ["LLDB_TEST"] = scriptPath
Johnny Chen9de4ede2010-08-31 17:42:54 +0000431 pluginPath = os.path.join(scriptPath, 'plugins')
Johnny Chen58f93922010-06-29 23:10:39 +0000432
Johnny Chenaf149a02010-09-16 17:11:30 +0000433 # Append script dir and plugin dir to the sys.path.
434 sys.path.append(scriptPath)
435 sys.path.append(pluginPath)
436
437 global ignore
438
439 # The '-i' option is used to skip looking for lldb.py in the build tree.
440 if ignore:
441 return
442
Johnny Chena1affab2010-07-03 03:41:59 +0000443 base = os.path.abspath(os.path.join(scriptPath, os.pardir))
Johnny Chen9707bb62010-06-25 21:14:08 +0000444 dbgPath = os.path.join(base, 'build', 'Debug', 'LLDB.framework',
445 'Resources', 'Python')
446 relPath = os.path.join(base, 'build', 'Release', 'LLDB.framework',
447 'Resources', 'Python')
Johnny Chenc202c462010-09-15 18:11:19 +0000448 baiPath = os.path.join(base, 'build', 'BuildAndIntegration',
449 'LLDB.framework', 'Resources', 'Python')
Johnny Chen9707bb62010-06-25 21:14:08 +0000450
451 lldbPath = None
452 if os.path.isfile(os.path.join(dbgPath, 'lldb.py')):
453 lldbPath = dbgPath
454 elif os.path.isfile(os.path.join(relPath, 'lldb.py')):
455 lldbPath = relPath
Johnny Chenc202c462010-09-15 18:11:19 +0000456 elif os.path.isfile(os.path.join(baiPath, 'lldb.py')):
457 lldbPath = baiPath
Johnny Chen9707bb62010-06-25 21:14:08 +0000458
459 if not lldbPath:
Johnny Chenc202c462010-09-15 18:11:19 +0000460 print 'This script requires lldb.py to be in either ' + dbgPath + ',',
461 print relPath + ', or ' + baiPath
Johnny Chen9707bb62010-06-25 21:14:08 +0000462 sys.exit(-1)
463
Johnny Chenaf149a02010-09-16 17:11:30 +0000464 # This is to locate the lldb.py module. Insert it right after sys.path[0].
465 sys.path[1:1] = [lldbPath]
Johnny Chen9707bb62010-06-25 21:14:08 +0000466
Johnny Chen9707bb62010-06-25 21:14:08 +0000467
Johnny Chencd0279d2010-09-20 18:07:50 +0000468def doDelay(delta):
469 """Delaying startup for delta-seconds to facilitate debugger attachment."""
470 def alarm_handler(*args):
471 raise Exception("timeout")
472
473 signal.signal(signal.SIGALRM, alarm_handler)
474 signal.alarm(delta)
475 sys.stdout.write("pid=%d\n" % os.getpid())
476 sys.stdout.write("Enter RET to proceed (or timeout after %d seconds):" %
477 delta)
478 sys.stdout.flush()
479 try:
480 text = sys.stdin.readline()
481 except:
482 text = ""
483 signal.alarm(0)
484 sys.stdout.write("proceeding...\n")
485 pass
486
487
Johnny Chen9707bb62010-06-25 21:14:08 +0000488def visit(prefix, dir, names):
489 """Visitor function for os.path.walk(path, visit, arg)."""
490
491 global suite
Johnny Chen7c52ff12010-09-27 23:29:54 +0000492 global regexp
Johnny Chenb62436b2010-10-06 20:40:56 +0000493 global filterspec
494 global fs4all
Johnny Chen9707bb62010-06-25 21:14:08 +0000495
496 for name in names:
497 if os.path.isdir(os.path.join(dir, name)):
498 continue
499
500 if '.py' == os.path.splitext(name)[1] and name.startswith(prefix):
Johnny Chen7c52ff12010-09-27 23:29:54 +0000501 # Try to match the regexp pattern, if specified.
502 if regexp:
503 import re
504 if re.search(regexp, name):
505 #print "Filename: '%s' matches pattern: '%s'" % (name, regexp)
506 pass
507 else:
508 #print "Filename: '%s' does not match pattern: '%s'" % (name, regexp)
509 continue
510
Johnny Chen953864a2010-10-12 21:35:54 +0000511 # We found a match for our test. Add it to the suite.
Johnny Chen79723352010-10-12 15:53:22 +0000512
513 # Update the sys.path first.
Johnny Chena85d7ee2010-06-26 00:19:32 +0000514 if not sys.path.count(dir):
Johnny Chen548aefd2010-10-11 22:25:46 +0000515 sys.path.insert(0, dir)
Johnny Chen9707bb62010-06-25 21:14:08 +0000516 base = os.path.splitext(name)[0]
Johnny Chenb62436b2010-10-06 20:40:56 +0000517
518 # Thoroughly check the filterspec against the base module and admit
519 # the (base, filterspec) combination only when it makes sense.
520 if filterspec:
521 # Optimistically set the flag to True.
522 filtered = True
523 module = __import__(base)
524 parts = filterspec.split('.')
525 obj = module
526 for part in parts:
527 try:
528 parent, obj = obj, getattr(obj, part)
529 except AttributeError:
530 # The filterspec has failed.
531 filtered = False
532 break
533 # Forgo this module if the (base, filterspec) combo is invalid
Johnny Chena224cd12010-11-08 01:21:03 +0000534 # and no '-g' option is specified
Johnny Chenb62436b2010-10-06 20:40:56 +0000535 if fs4all and not filtered:
536 continue
537
Johnny Chen953864a2010-10-12 21:35:54 +0000538 # Add either the filtered test case or the entire test class.
Johnny Chenb62436b2010-10-06 20:40:56 +0000539 if filterspec and filtered:
540 suite.addTests(
541 unittest2.defaultTestLoader.loadTestsFromName(filterspec, module))
542 else:
543 # A simple case of just the module name. Also the failover case
544 # from the filterspec branch when the (base, filterspec) combo
545 # doesn't make sense.
546 suite.addTests(unittest2.defaultTestLoader.loadTestsFromName(base))
Johnny Chen9707bb62010-06-25 21:14:08 +0000547
548
Johnny Chencd0279d2010-09-20 18:07:50 +0000549def lldbLoggings():
550 """Check and do lldb loggings if necessary."""
551
552 # Turn on logging for debugging purposes if ${LLDB_LOG} environment variable is
553 # defined. Use ${LLDB_LOG} to specify the log file.
554 ci = lldb.DBG.GetCommandInterpreter()
555 res = lldb.SBCommandReturnObject()
556 if ("LLDB_LOG" in os.environ):
557 if ("LLDB_LOG_OPTION" in os.environ):
558 lldb_log_option = os.environ["LLDB_LOG_OPTION"]
559 else:
Johnny Chen8fd886c2010-12-08 01:25:21 +0000560 lldb_log_option = "event process expr state api"
Johnny Chencd0279d2010-09-20 18:07:50 +0000561 ci.HandleCommand(
Johnny Chen58bf3442010-12-02 23:31:02 +0000562 "log enable -T -n -f " + os.environ["LLDB_LOG"] + " lldb " + lldb_log_option,
Johnny Chencd0279d2010-09-20 18:07:50 +0000563 res)
564 if not res.Succeeded():
565 raise Exception('log enable failed (check LLDB_LOG env variable.')
566 # Ditto for gdb-remote logging if ${GDB_REMOTE_LOG} environment variable is defined.
567 # Use ${GDB_REMOTE_LOG} to specify the log file.
568 if ("GDB_REMOTE_LOG" in os.environ):
569 if ("GDB_REMOTE_LOG_OPTION" in os.environ):
570 gdb_remote_log_option = os.environ["GDB_REMOTE_LOG_OPTION"]
571 else:
Johnny Chen7ab8c852010-12-02 18:35:13 +0000572 gdb_remote_log_option = "packets process"
Johnny Chencd0279d2010-09-20 18:07:50 +0000573 ci.HandleCommand(
Johnny Chen58bf3442010-12-02 23:31:02 +0000574 "log enable -T -n -f " + os.environ["GDB_REMOTE_LOG"] + " process.gdb-remote "
Johnny Chencd0279d2010-09-20 18:07:50 +0000575 + gdb_remote_log_option,
576 res)
577 if not res.Succeeded():
578 raise Exception('log enable failed (check GDB_REMOTE_LOG env variable.')
579
580
Johnny Chend96b5682010-11-05 17:30:53 +0000581# ======================================== #
Johnny Chencd0279d2010-09-20 18:07:50 +0000582# #
583# Execution of the test driver starts here #
584# #
Johnny Chend96b5682010-11-05 17:30:53 +0000585# ======================================== #
Johnny Chencd0279d2010-09-20 18:07:50 +0000586
Johnny Chen9707bb62010-06-25 21:14:08 +0000587#
Johnny Chenaf149a02010-09-16 17:11:30 +0000588# Start the actions by first parsing the options while setting up the test
589# directories, followed by setting up the search paths for lldb utilities;
590# then, we walk the directory trees and collect the tests into our test suite.
Johnny Chen9707bb62010-06-25 21:14:08 +0000591#
Johnny Chenaf149a02010-09-16 17:11:30 +0000592parseOptionsAndInitTestdirs()
Johnny Chen9707bb62010-06-25 21:14:08 +0000593setupSysPath()
Johnny Chen91960d32010-09-08 20:56:16 +0000594
595#
596# If '-d' is specified, do a delay of 10 seconds for the debugger to attach.
597#
598if delay:
Johnny Chencd0279d2010-09-20 18:07:50 +0000599 doDelay(10)
Johnny Chen91960d32010-09-08 20:56:16 +0000600
Johnny Chen49f2f7a2010-09-20 17:25:45 +0000601#
Johnny Chen41998192010-10-01 22:59:49 +0000602# If '-l' is specified, do not skip the long running tests.
603if not skipLongRunningTest:
604 os.environ["LLDB_SKIP_LONG_RUNNING_TEST"] = "NO"
605
606#
Johnny Chen79723352010-10-12 15:53:22 +0000607# Walk through the testdirs while collecting tests.
Johnny Chen49f2f7a2010-09-20 17:25:45 +0000608#
Johnny Chen9707bb62010-06-25 21:14:08 +0000609for testdir in testdirs:
610 os.path.walk(testdir, visit, 'Test')
611
Johnny Chenb40056b2010-09-21 00:09:27 +0000612#
Johnny Chen9707bb62010-06-25 21:14:08 +0000613# Now that we have loaded all the test cases, run the whole test suite.
Johnny Chenb40056b2010-09-21 00:09:27 +0000614#
Johnny Chencd0279d2010-09-20 18:07:50 +0000615
Johnny Chen1bfbd412010-06-29 19:44:16 +0000616# For the time being, let's bracket the test runner within the
617# lldb.SBDebugger.Initialize()/Terminate() pair.
Johnny Chen01f2a6a2010-08-10 20:23:55 +0000618import lldb, atexit
Johnny Chen6b6f5ba2010-10-14 16:36:49 +0000619# Update: the act of importing lldb now executes lldb.SBDebugger.Initialize(),
620# there's no need to call it a second time.
621#lldb.SBDebugger.Initialize()
Johnny Chen01f2a6a2010-08-10 20:23:55 +0000622atexit.register(lambda: lldb.SBDebugger.Terminate())
Johnny Chen1bfbd412010-06-29 19:44:16 +0000623
Johnny Chen909e5a62010-07-01 22:52:57 +0000624# Create a singleton SBDebugger in the lldb namespace.
625lldb.DBG = lldb.SBDebugger.Create()
626
Johnny Chen82e6b1e2010-12-01 22:47:54 +0000627# And put the blacklist in the lldb namespace, to be used by lldb.TestBase.
628lldb.blacklist = blacklist
629
Johnny Chencd0279d2010-09-20 18:07:50 +0000630# Turn on lldb loggings if necessary.
631lldbLoggings()
Johnny Chen909e5a62010-07-01 22:52:57 +0000632
Johnny Chen7987ac92010-08-09 20:40:52 +0000633# Install the control-c handler.
634unittest2.signals.installHandler()
635
Johnny Chen125fc2b2010-10-21 16:55:35 +0000636# If sdir_name is not specified through the '-s sdir_name' option, get a
637# timestamp string and export it as LLDB_SESSION_DIR environment var. This will
638# be used when/if we want to dump the session info of individual test cases
639# later on.
Johnny Chence681462010-10-19 00:25:01 +0000640#
641# See also TestBase.dumpSessionInfo() in lldbtest.py.
Johnny Chen125fc2b2010-10-21 16:55:35 +0000642if not sdir_name:
643 import datetime
Johnny Chen41fae812010-10-29 22:26:38 +0000644 # The windows platforms don't like ':' in the pathname.
Johnny Chen76bd0102010-10-28 16:32:13 +0000645 timestamp = datetime.datetime.now().strftime("%Y-%m-%d-%H_%M_%S")
Johnny Chen125fc2b2010-10-21 16:55:35 +0000646 sdir_name = timestamp
647os.environ["LLDB_SESSION_DIRNAME"] = sdir_name
Johnny Chen47c47c42010-11-09 23:42:00 +0000648sys.stderr.write("\nSession logs for test failures/errors will go into directory '%s'\n" % sdir_name)
Johnny Chence681462010-10-19 00:25:01 +0000649
Johnny Chenb40056b2010-09-21 00:09:27 +0000650#
651# Invoke the default TextTestRunner to run the test suite, possibly iterating
652# over different configurations.
653#
654
Johnny Chenb40056b2010-09-21 00:09:27 +0000655iterArchs = False
Johnny Chenf032d902010-09-21 00:16:09 +0000656iterCompilers = False
Johnny Chenb40056b2010-09-21 00:09:27 +0000657
658from types import *
659if "archs" in config:
660 archs = config["archs"]
661 if type(archs) is ListType and len(archs) >= 1:
662 iterArchs = True
663if "compilers" in config:
664 compilers = config["compilers"]
665 if type(compilers) is ListType and len(compilers) >= 1:
666 iterCompilers = True
667
Johnny Chen953864a2010-10-12 21:35:54 +0000668# Make a shallow copy of sys.path, we need to manipulate the search paths later.
669# This is only necessary if we are relocated and with different configurations.
670if rdir and (iterArchs or iterCompilers):
671 old_sys_path = sys.path[:]
672 old_stderr = sys.stderr
673 old_stdout = sys.stdout
674 new_stderr = None
675 new_stdout = None
676
Johnny Chend96b5682010-11-05 17:30:53 +0000677# Iterating over all possible architecture and compiler combinations.
Johnny Chenb40056b2010-09-21 00:09:27 +0000678for ia in range(len(archs) if iterArchs else 1):
679 archConfig = ""
680 if iterArchs:
Johnny Chen18a921f2010-09-30 17:11:58 +0000681 os.environ["ARCH"] = archs[ia]
Johnny Chenb40056b2010-09-21 00:09:27 +0000682 archConfig = "arch=%s" % archs[ia]
683 for ic in range(len(compilers) if iterCompilers else 1):
684 if iterCompilers:
Johnny Chen18a921f2010-09-30 17:11:58 +0000685 os.environ["CC"] = compilers[ic]
Johnny Chenb40056b2010-09-21 00:09:27 +0000686 configString = "%s compiler=%s" % (archConfig, compilers[ic])
687 else:
688 configString = archConfig
689
Johnny Chenb40056b2010-09-21 00:09:27 +0000690 if iterArchs or iterCompilers:
Johnny Chen953864a2010-10-12 21:35:54 +0000691 # If we specified a relocated directory to run the test suite, do
692 # the extra housekeeping to copy the testdirs to a configStringified
693 # directory and to update sys.path before invoking the test runner.
694 # The purpose is to separate the configuration-specific directories
695 # from each other.
696 if rdir:
697 from string import maketrans
698 from shutil import copytree, ignore_patterns
699
700 # Translate ' ' to '-' for dir name.
701 tbl = maketrans(' ', '-')
702 configPostfix = configString.translate(tbl)
703 newrdir = "%s.%s" % (rdir, configPostfix)
704
705 # Copy the tree to a new directory with postfix name configPostfix.
706 copytree(rdir, newrdir, ignore=ignore_patterns('*.pyc', '*.o', '*.d'))
707
708 # Check whether we need to split stderr/stdout into configuration
709 # specific files.
710 if old_stderr.name != '<stderr>' and config.get('split_stderr'):
711 if new_stderr:
712 new_stderr.close()
713 new_stderr = open("%s.%s" % (old_stderr.name, configPostfix), "w")
714 sys.stderr = new_stderr
Johnny Chen4b6630e2010-10-12 21:50:36 +0000715 if old_stdout.name != '<stdout>' and config.get('split_stdout'):
Johnny Chen953864a2010-10-12 21:35:54 +0000716 if new_stdout:
717 new_stdout.close()
718 new_stdout = open("%s.%s" % (old_stdout.name, configPostfix), "w")
719 sys.stdout = new_stdout
720
721 # Update the LLDB_TEST environment variable to reflect new top
722 # level test directory.
723 #
724 # See also lldbtest.TestBase.setUpClass(cls).
725 if len(testdirs) == 1 and os.path.basename(testdirs[0]) == 'test':
726 os.environ["LLDB_TEST"] = os.path.join(newrdir, 'test')
727 else:
728 os.environ["LLDB_TEST"] = newrdir
729
730 # And update the Python search paths for modules.
731 sys.path = [x.replace(rdir, newrdir, 1) for x in old_sys_path]
732
733 # Output the configuration.
Johnny Chenb40056b2010-09-21 00:09:27 +0000734 sys.stderr.write("\nConfiguration: " + configString + "\n")
Johnny Chen953864a2010-10-12 21:35:54 +0000735
736 #print "sys.stderr name is", sys.stderr.name
737 #print "sys.stdout name is", sys.stdout.name
738
739 # First, write out the number of collected test cases.
740 sys.stderr.write(separator + "\n")
741 sys.stderr.write("Collected %d test%s\n\n"
742 % (suite.countTestCases(),
743 suite.countTestCases() != 1 and "s" or ""))
744
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000745 class LLDBTestResult(unittest2.TextTestResult):
746 """
Johnny Chen26be4532010-11-09 23:56:14 +0000747 Enforce a singleton pattern to allow introspection of test progress.
748
749 Overwrite addError(), addFailure(), and addExpectedFailure() methods
750 to enable each test instance to track its failure/error status. It
751 is used in the LLDB test framework to emit detailed trace messages
752 to a log file for easier human inspection of test failres/errors.
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000753 """
754 __singleton__ = None
Johnny Chen360dd372010-11-29 17:50:10 +0000755 __ignore_singleton__ = False
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000756
757 def __init__(self, *args):
Johnny Chen360dd372010-11-29 17:50:10 +0000758 if not LLDBTestResult.__ignore_singleton__ and LLDBTestResult.__singleton__:
Johnny Chend2acdb32010-11-16 22:42:58 +0000759 raise Exception("LLDBTestResult instantiated more than once")
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000760 super(LLDBTestResult, self).__init__(*args)
761 LLDBTestResult.__singleton__ = self
762 # Now put this singleton into the lldb module namespace.
763 lldb.test_result = self
764
Johnny Chence681462010-10-19 00:25:01 +0000765 def addError(self, test, err):
Johnny Chen63c2cba2010-10-29 22:20:36 +0000766 global sdir_has_content
767 sdir_has_content = True
Johnny Chence681462010-10-19 00:25:01 +0000768 super(LLDBTestResult, self).addError(test, err)
769 method = getattr(test, "markError", None)
770 if method:
771 method()
772
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000773 def addFailure(self, test, err):
Johnny Chen63c2cba2010-10-29 22:20:36 +0000774 global sdir_has_content
775 sdir_has_content = True
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000776 super(LLDBTestResult, self).addFailure(test, err)
777 method = getattr(test, "markFailure", None)
778 if method:
779 method()
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000780
Johnny Chendd2bb2c2010-11-03 18:17:03 +0000781 def addExpectedFailure(self, test, err):
782 global sdir_has_content
783 sdir_has_content = True
784 super(LLDBTestResult, self).addExpectedFailure(test, err)
785 method = getattr(test, "markExpectedFailure", None)
786 if method:
787 method()
788
Johnny Chen26be4532010-11-09 23:56:14 +0000789 # Invoke the test runner.
Johnny Chend2acdb32010-11-16 22:42:58 +0000790 if count == 1:
Johnny Chen7d6d8442010-12-03 19:59:35 +0000791 result = unittest2.TextTestRunner(stream=sys.stderr,
792 verbosity=verbose,
793 failfast=failfast,
Johnny Chend2acdb32010-11-16 22:42:58 +0000794 resultclass=LLDBTestResult).run(suite)
795 else:
Johnny Chend6e7ca22010-11-29 17:52:43 +0000796 # We are invoking the same test suite more than once. In this case,
797 # mark __ignore_singleton__ flag as True so the signleton pattern is
798 # not enforced.
Johnny Chen360dd372010-11-29 17:50:10 +0000799 LLDBTestResult.__ignore_singleton__ = True
Johnny Chend2acdb32010-11-16 22:42:58 +0000800 for i in range(count):
Johnny Chen7d6d8442010-12-03 19:59:35 +0000801 result = unittest2.TextTestRunner(stream=sys.stderr,
802 verbosity=verbose,
803 failfast=failfast,
Johnny Chen360dd372010-11-29 17:50:10 +0000804 resultclass=LLDBTestResult).run(suite)
Johnny Chenb40056b2010-09-21 00:09:27 +0000805
Johnny Chen1bfbd412010-06-29 19:44:16 +0000806
Johnny Chen63c2cba2010-10-29 22:20:36 +0000807if sdir_has_content:
Johnny Chen47c47c42010-11-09 23:42:00 +0000808 sys.stderr.write("Session logs for test failures/errors can be found in directory '%s'\n" % sdir_name)
Johnny Chen63c2cba2010-10-29 22:20:36 +0000809
Johnny Chencd0279d2010-09-20 18:07:50 +0000810# Terminate the test suite if ${LLDB_TESTSUITE_FORCE_FINISH} is defined.
811# This should not be necessary now.
Johnny Chen83f6e512010-08-13 22:58:44 +0000812if ("LLDB_TESTSUITE_FORCE_FINISH" in os.environ):
813 import subprocess
814 print "Terminating Test suite..."
815 subprocess.Popen(["/bin/sh", "-c", "kill %s; exit 0" % (os.getpid())])
816
Johnny Chen01f2a6a2010-08-10 20:23:55 +0000817# Exiting.
818sys.exit(not result.wasSuccessful)