blob: 87af0a65f9fe190cb44f10cb98f197564a256501 [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 Chen26901c82011-03-11 19:47:23 +000026def is_exe(fpath):
27 return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
28
29# Find the full path to a program, or return None.
30def which(program):
31 fpath, fname = os.path.split(program)
32 if fpath:
33 if is_exe(program):
34 return program
35 else:
36 for path in os.environ["PATH"].split(os.pathsep):
37 exe_file = os.path.join(path, program)
38 if is_exe(exe_file):
39 return exe_file
40 return None
41
Johnny Chen877c7e42010-08-07 00:16:07 +000042class _WritelnDecorator(object):
43 """Used to decorate file-like objects with a handy 'writeln' method"""
44 def __init__(self,stream):
45 self.stream = stream
46
47 def __getattr__(self, attr):
48 if attr in ('stream', '__getstate__'):
49 raise AttributeError(attr)
50 return getattr(self.stream,attr)
51
52 def writeln(self, arg=None):
53 if arg:
54 self.write(arg)
55 self.write('\n') # text-mode streams translate to \r\n if needed
56
Johnny Chen9707bb62010-06-25 21:14:08 +000057#
58# Global variables:
59#
60
61# The test suite.
Johnny Chen75e28f92010-08-05 23:42:46 +000062suite = unittest2.TestSuite()
Johnny Chen9707bb62010-06-25 21:14:08 +000063
Johnny Chen4f93bf12010-12-10 00:51:23 +000064# By default, both command line and Python API tests are performed.
Johnny Chen3ebdacc2010-12-10 18:52:10 +000065# Use @python_api_test decorator, defined in lldbtest.py, to mark a test as
66# a Python API test.
Johnny Chen4f93bf12010-12-10 00:51:23 +000067dont_do_python_api_test = False
68
69# By default, both command line and Python API tests are performed.
Johnny Chen4f93bf12010-12-10 00:51:23 +000070just_do_python_api_test = False
71
Johnny Chen82e6b1e2010-12-01 22:47:54 +000072# The blacklist is optional (-b blacklistFile) and allows a central place to skip
73# testclass's and/or testclass.testmethod's.
74blacklist = None
75
76# The dictionary as a result of sourcing blacklistFile.
77blacklistConfig = {}
78
Johnny Chen9fdb0a92010-09-18 00:16:47 +000079# The config file is optional.
80configFile = None
81
Johnny Chend2acdb32010-11-16 22:42:58 +000082# Test suite repeat count. Can be overwritten with '-# count'.
83count = 1
84
Johnny Chenb40056b2010-09-21 00:09:27 +000085# The dictionary as a result of sourcing configFile.
86config = {}
87
Johnny Chen1a4d5e72011-03-04 01:35:22 +000088# The 'archs' and 'compilers' can be specified via either command line or configFile,
89# with the command line overriding the configFile. When specified, they should be
90# of the list type. For example, "-A x86_64^i386" => archs=['x86_64', 'i386'] and
91# "-C gcc^clang" => compilers=['gcc', 'clang'].
92archs = None
93compilers = None
94
Johnny Chen91960d32010-09-08 20:56:16 +000095# Delay startup in order for the debugger to attach.
96delay = False
97
Johnny Chend5362332011-01-29 01:21:04 +000098# Dump the Python sys.path variable. Use '-D' to dump sys.path.
Johnny Chen50bc6382011-01-29 01:16:52 +000099dumpSysPath = False
100
Johnny Chen7d6d8442010-12-03 19:59:35 +0000101# By default, failfast is False. Use '-F' to overwrite it.
102failfast = False
103
Johnny Chena224cd12010-11-08 01:21:03 +0000104# The filter (testclass.testmethod) used to admit tests into our test suite.
Johnny Chenb62436b2010-10-06 20:40:56 +0000105filterspec = None
106
Johnny Chena224cd12010-11-08 01:21:03 +0000107# If '-g' is specified, the filterspec is not exclusive. If a test module does
108# not contain testclass.testmethod which matches the filterspec, the whole test
109# module is still admitted into our test suite. fs4all flag defaults to True.
110fs4all = True
Johnny Chenb62436b2010-10-06 20:40:56 +0000111
Johnny Chenaf149a02010-09-16 17:11:30 +0000112# Ignore the build search path relative to this script to locate the lldb.py module.
113ignore = False
114
Johnny Chen548aefd2010-10-11 22:25:46 +0000115# By default, we skip long running test case. Use '-l' option to override.
Johnny Chen41998192010-10-01 22:59:49 +0000116skipLongRunningTest = True
117
Johnny Chen7c52ff12010-09-27 23:29:54 +0000118# The regular expression pattern to match against eligible filenames as our test cases.
119regexp = None
120
Johnny Chen548aefd2010-10-11 22:25:46 +0000121# By default, tests are executed in place and cleanups are performed afterwards.
122# Use '-r dir' option to relocate the tests and their intermediate files to a
123# different directory and to forgo any cleanups. The directory specified must
124# not exist yet.
125rdir = None
126
Johnny Chen125fc2b2010-10-21 16:55:35 +0000127# By default, recorded session info for errored/failed test are dumped into its
128# own file under a session directory named after the timestamp of the test suite
129# run. Use '-s session-dir-name' to specify a specific dir name.
130sdir_name = None
131
Johnny Chen63c2cba2010-10-29 22:20:36 +0000132# Set this flag if there is any session info dumped during the test run.
133sdir_has_content = False
134
Johnny Chen9707bb62010-06-25 21:14:08 +0000135# Default verbosity is 0.
136verbose = 0
137
138# By default, search from the current working directory.
139testdirs = [ os.getcwd() ]
140
Johnny Chen877c7e42010-08-07 00:16:07 +0000141# Separator string.
142separator = '-' * 70
143
Johnny Chen9707bb62010-06-25 21:14:08 +0000144
145def usage():
146 print """
147Usage: dotest.py [option] [args]
148where options:
Jim Ingham4f347cb2011-04-13 21:11:41 +0000149-h : print this help message and exit. Add '-v' for more detailed help.
Johnny Chen1a4d5e72011-03-04 01:35:22 +0000150-A : specify the architecture(s) to launch for the inferior process
151 -A i386 => launch inferior with i386 architecture
152 -A x86_64^i386 => launch inferior with x86_64 and i386 architectures
153-C : specify the compiler(s) used to build the inferior executable
154 -C clang => build debuggee using clang compiler
155 -C clang^gcc => build debuggee using clang and gcc compilers
Johnny Chen50bc6382011-01-29 01:16:52 +0000156-D : dump the Python sys.path variable
Johnny Chen4f93bf12010-12-10 00:51:23 +0000157-a : don't do lldb Python API tests
158 use @python_api_test to decorate a test case as lldb Python API test
Johnny Chen3ebdacc2010-12-10 18:52:10 +0000159+a : just do lldb Python API tests
Johnny Chencc659ad2010-12-10 19:02:23 +0000160 do not specify both '-a' and '+a' at the same time
Johnny Chen82e6b1e2010-12-01 22:47:54 +0000161-b : read a blacklist file specified after this option
Johnny Chen9fdb0a92010-09-18 00:16:47 +0000162-c : read a config file specified after this option
Johnny Chen1a4d5e72011-03-04 01:35:22 +0000163 the architectures and compilers (note the plurals) specified via '-A' and '-C'
164 will override those specified via a config file
Johnny Chenb40056b2010-09-21 00:09:27 +0000165 (see also lldb-trunk/example/test/usage-config)
Johnny Chen91960d32010-09-08 20:56:16 +0000166-d : delay startup for 10 seconds (in order for the debugger to attach)
Johnny Chen7d6d8442010-12-03 19:59:35 +0000167-F : failfast, stop the test suite on the first error/failure
Johnny Chen46be75d2010-10-11 16:19:48 +0000168-f : specify a filter, which consists of the test class name, a dot, followed by
Johnny Chen1a6e92a2010-11-08 20:17:04 +0000169 the test method, to only admit such test into the test suite
Johnny Chenb62436b2010-10-06 20:40:56 +0000170 e.g., -f 'ClassTypesTestCase.test_with_dwarf_and_python_api'
Johnny Chena224cd12010-11-08 01:21:03 +0000171-g : if specified, the filterspec by -f is not exclusive, i.e., if a test module
172 does not match the filterspec (testclass.testmethod), the whole module is
173 still admitted to the test suite
Johnny Chenaf149a02010-09-16 17:11:30 +0000174-i : ignore (don't bailout) if 'lldb.py' module cannot be located in the build
175 tree relative to this script; use PYTHONPATH to locate the module
Johnny Chen41998192010-10-01 22:59:49 +0000176-l : don't skip long running test
Johnny Chen7c52ff12010-09-27 23:29:54 +0000177-p : specify a regexp filename pattern for inclusion in the test suite
Johnny Chen548aefd2010-10-11 22:25:46 +0000178-r : specify a dir to relocate the tests and their intermediate files to;
179 the directory must not exist before running this test driver;
180 no cleanup of intermediate test files is performed in this case
Johnny Chen125fc2b2010-10-21 16:55:35 +0000181-s : specify the name of the dir created to store the session files of tests
182 with errored or failed status; if not specified, the test driver uses the
183 timestamp as the session dir name
Johnny Chena2486f22011-04-21 20:48:32 +0000184-t : turn on tracing of lldb command and other detailed test executions
185-v : do verbose mode of unittest framework (print out each test case invocation)
Johnny Chene47649c2010-10-07 02:04:14 +0000186-w : insert some wait time (currently 0.5 sec) between consecutive test cases
Johnny Chend2acdb32010-11-16 22:42:58 +0000187-# : Repeat the test suite for a specified number of times
Johnny Chen9707bb62010-06-25 21:14:08 +0000188
189and:
Johnny Chen9656ab22010-10-22 19:00:18 +0000190args : specify a list of directory names to search for test modules named after
191 Test*.py (test discovery)
Johnny Chen9707bb62010-06-25 21:14:08 +0000192 if empty, search from the curret working directory, instead
Jim Ingham4f347cb2011-04-13 21:11:41 +0000193"""
Johnny Chen58f93922010-06-29 23:10:39 +0000194
Jim Ingham4f347cb2011-04-13 21:11:41 +0000195 if verbose > 0:
196 print """
Johnny Chen9656ab22010-10-22 19:00:18 +0000197Examples:
198
Johnny Chena224cd12010-11-08 01:21:03 +0000199This is an example of using the -f option to pinpoint to a specfic test class
200and test method to be run:
Johnny Chen6ad7e5e2010-10-21 00:47:52 +0000201
Johnny Chena224cd12010-11-08 01:21:03 +0000202$ ./dotest.py -f ClassTypesTestCase.test_with_dsym_and_run_command
Johnny Chen6ad7e5e2010-10-21 00:47:52 +0000203----------------------------------------------------------------------
204Collected 1 test
205
206test_with_dsym_and_run_command (TestClassTypes.ClassTypesTestCase)
207Test 'frame variable this' when stopped on a class constructor. ... ok
208
209----------------------------------------------------------------------
210Ran 1 test in 1.396s
211
212OK
Johnny Chen9656ab22010-10-22 19:00:18 +0000213
214And this is an example of using the -p option to run a single file (the filename
215matches the pattern 'ObjC' and it happens to be 'TestObjCMethods.py'):
216
217$ ./dotest.py -v -p ObjC
218----------------------------------------------------------------------
219Collected 4 tests
220
221test_break_with_dsym (TestObjCMethods.FoundationTestCase)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000222Test setting objc breakpoints using '_regexp-break' and 'breakpoint set'. ... ok
Johnny Chen9656ab22010-10-22 19:00:18 +0000223test_break_with_dwarf (TestObjCMethods.FoundationTestCase)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000224Test setting objc breakpoints using '_regexp-break' and 'breakpoint set'. ... ok
Johnny Chen9656ab22010-10-22 19:00:18 +0000225test_data_type_and_expr_with_dsym (TestObjCMethods.FoundationTestCase)
226Lookup objective-c data types and evaluate expressions. ... ok
227test_data_type_and_expr_with_dwarf (TestObjCMethods.FoundationTestCase)
228Lookup objective-c data types and evaluate expressions. ... ok
229
230----------------------------------------------------------------------
231Ran 4 tests in 16.661s
232
233OK
Johnny Chen6ad7e5e2010-10-21 00:47:52 +0000234
Johnny Chen58f93922010-06-29 23:10:39 +0000235Running of this script also sets up the LLDB_TEST environment variable so that
Johnny Chenaf149a02010-09-16 17:11:30 +0000236individual test cases can locate their supporting files correctly. The script
237tries to set up Python's search paths for modules by looking at the build tree
Johnny Chena85859f2010-11-11 22:14:56 +0000238relative to this script. See also the '-i' option in the following example.
239
240Finally, this is an example of using the lldb.py module distributed/installed by
241Xcode4 to run against the tests under the 'forward' directory, and with the '-w'
242option to add some delay between two tests. It uses ARCH=x86_64 to specify that
243as the architecture and CC=clang to specify the compiler used for the test run:
244
245$ PYTHONPATH=/Xcode4/Library/PrivateFrameworks/LLDB.framework/Versions/A/Resources/Python ARCH=x86_64 CC=clang ./dotest.py -v -w -i forward
246
247Session logs for test failures/errors will go into directory '2010-11-11-13_56_16'
248----------------------------------------------------------------------
249Collected 2 tests
250
251test_with_dsym_and_run_command (TestForwardDeclaration.ForwardDeclarationTestCase)
252Display *bar_ptr when stopped on a function with forward declaration of struct bar. ... ok
253test_with_dwarf_and_run_command (TestForwardDeclaration.ForwardDeclarationTestCase)
254Display *bar_ptr when stopped on a function with forward declaration of struct bar. ... ok
255
256----------------------------------------------------------------------
257Ran 2 tests in 5.659s
258
259OK
260
261The 'Session ...' verbiage is recently introduced (see also the '-s' option) to
262notify the directory containing the session logs for test failures or errors.
263In case there is any test failure/error, a similar message is appended at the
264end of the stderr output for your convenience.
Johnny Chenfde69bc2010-09-14 22:01:40 +0000265
266Environment variables related to loggings:
267
268o LLDB_LOG: if defined, specifies the log file pathname for the 'lldb' subsystem
269 with a default option of 'event process' if LLDB_LOG_OPTION is not defined.
270
271o GDB_REMOTE_LOG: if defined, specifies the log file pathname for the
272 'process.gdb-remote' subsystem with a default option of 'packets' if
273 GDB_REMOTE_LOG_OPTION is not defined.
Johnny Chen9707bb62010-06-25 21:14:08 +0000274"""
Johnny Chen9fdb0a92010-09-18 00:16:47 +0000275 sys.exit(0)
Johnny Chen9707bb62010-06-25 21:14:08 +0000276
277
Johnny Chenaf149a02010-09-16 17:11:30 +0000278def parseOptionsAndInitTestdirs():
279 """Initialize the list of directories containing our unittest scripts.
280
281 '-h/--help as the first option prints out usage info and exit the program.
282 """
283
Johnny Chen4f93bf12010-12-10 00:51:23 +0000284 global dont_do_python_api_test
285 global just_do_python_api_test
Johnny Chen82e6b1e2010-12-01 22:47:54 +0000286 global blacklist
287 global blacklistConfig
Johnny Chen9fdb0a92010-09-18 00:16:47 +0000288 global configFile
Johnny Chen1a4d5e72011-03-04 01:35:22 +0000289 global archs
290 global compilers
Johnny Chend2acdb32010-11-16 22:42:58 +0000291 global count
Johnny Chenaf149a02010-09-16 17:11:30 +0000292 global delay
Johnny Chen50bc6382011-01-29 01:16:52 +0000293 global dumpSysPath
Johnny Chen7d6d8442010-12-03 19:59:35 +0000294 global failfast
Johnny Chenb62436b2010-10-06 20:40:56 +0000295 global filterspec
296 global fs4all
Johnny Chen7c52ff12010-09-27 23:29:54 +0000297 global ignore
Johnny Chen41998192010-10-01 22:59:49 +0000298 global skipLongRunningTest
Johnny Chen7c52ff12010-09-27 23:29:54 +0000299 global regexp
Johnny Chen548aefd2010-10-11 22:25:46 +0000300 global rdir
Johnny Chen125fc2b2010-10-21 16:55:35 +0000301 global sdir_name
Johnny Chenaf149a02010-09-16 17:11:30 +0000302 global verbose
303 global testdirs
304
Jim Ingham4f347cb2011-04-13 21:11:41 +0000305 do_help = False
306
Johnny Chenaf149a02010-09-16 17:11:30 +0000307 if len(sys.argv) == 1:
308 return
309
310 # Process possible trace and/or verbose flag, among other things.
311 index = 1
Johnny Chence2212c2010-10-07 15:41:55 +0000312 while index < len(sys.argv):
Johnny Chen4f93bf12010-12-10 00:51:23 +0000313 if sys.argv[index].startswith('-') or sys.argv[index].startswith('+'):
314 # We should continue processing...
315 pass
316 else:
Johnny Chenaf149a02010-09-16 17:11:30 +0000317 # End of option processing.
318 break
319
320 if sys.argv[index].find('-h') != -1:
Jim Ingham4f347cb2011-04-13 21:11:41 +0000321 index += 1
322 do_help = True
Johnny Chen012cba12011-01-26 19:07:42 +0000323 elif sys.argv[index].startswith('-A'):
324 # Increment by 1 to fetch the ARCH spec.
325 index += 1
326 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
327 usage()
Johnny Cheneee9b862011-04-26 20:45:00 +0000328 archs = sys.argv[index].split('^')
Johnny Chen012cba12011-01-26 19:07:42 +0000329 index += 1
330 elif sys.argv[index].startswith('-C'):
331 # Increment by 1 to fetch the CC spec.
332 index += 1
333 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
334 usage()
Johnny Cheneee9b862011-04-26 20:45:00 +0000335 compilers = sys.argv[index].split('^')
Johnny Chen012cba12011-01-26 19:07:42 +0000336 index += 1
Johnny Chen50bc6382011-01-29 01:16:52 +0000337 elif sys.argv[index].startswith('-D'):
338 dumpSysPath = True
339 index += 1
Johnny Chen4f93bf12010-12-10 00:51:23 +0000340 elif sys.argv[index].startswith('-a'):
341 dont_do_python_api_test = True
342 index += 1
343 elif sys.argv[index].startswith('+a'):
344 just_do_python_api_test = True
345 index += 1
Johnny Chen82e6b1e2010-12-01 22:47:54 +0000346 elif sys.argv[index].startswith('-b'):
347 # Increment by 1 to fetch the blacklist file name option argument.
348 index += 1
349 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
350 usage()
351 blacklistFile = sys.argv[index]
352 if not os.path.isfile(blacklistFile):
353 print "Blacklist file:", blacklistFile, "does not exist!"
354 usage()
355 index += 1
356 # Now read the blacklist contents and assign it to blacklist.
357 execfile(blacklistFile, globals(), blacklistConfig)
358 blacklist = blacklistConfig.get('blacklist')
Johnny Chen9fdb0a92010-09-18 00:16:47 +0000359 elif sys.argv[index].startswith('-c'):
360 # Increment by 1 to fetch the config file name option argument.
361 index += 1
362 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
363 usage()
364 configFile = sys.argv[index]
365 if not os.path.isfile(configFile):
366 print "Config file:", configFile, "does not exist!"
367 usage()
368 index += 1
Johnny Chenaf149a02010-09-16 17:11:30 +0000369 elif sys.argv[index].startswith('-d'):
370 delay = True
371 index += 1
Johnny Chen7d6d8442010-12-03 19:59:35 +0000372 elif sys.argv[index].startswith('-F'):
373 failfast = True
374 index += 1
Johnny Chenb62436b2010-10-06 20:40:56 +0000375 elif sys.argv[index].startswith('-f'):
376 # Increment by 1 to fetch the filter spec.
377 index += 1
378 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
379 usage()
380 filterspec = sys.argv[index]
381 index += 1
382 elif sys.argv[index].startswith('-g'):
Johnny Chena224cd12010-11-08 01:21:03 +0000383 fs4all = False
Johnny Chenb62436b2010-10-06 20:40:56 +0000384 index += 1
Johnny Chenaf149a02010-09-16 17:11:30 +0000385 elif sys.argv[index].startswith('-i'):
386 ignore = True
387 index += 1
Johnny Chen41998192010-10-01 22:59:49 +0000388 elif sys.argv[index].startswith('-l'):
389 skipLongRunningTest = False
390 index += 1
Johnny Chen7c52ff12010-09-27 23:29:54 +0000391 elif sys.argv[index].startswith('-p'):
392 # Increment by 1 to fetch the reg exp pattern argument.
393 index += 1
394 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
395 usage()
396 regexp = sys.argv[index]
397 index += 1
Johnny Chen548aefd2010-10-11 22:25:46 +0000398 elif sys.argv[index].startswith('-r'):
399 # Increment by 1 to fetch the relocated directory argument.
400 index += 1
401 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
402 usage()
403 rdir = os.path.abspath(sys.argv[index])
404 if os.path.exists(rdir):
405 print "Relocated directory:", rdir, "must not exist!"
406 usage()
407 index += 1
Johnny Chen125fc2b2010-10-21 16:55:35 +0000408 elif sys.argv[index].startswith('-s'):
409 # Increment by 1 to fetch the session dir name.
410 index += 1
411 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
412 usage()
413 sdir_name = sys.argv[index]
414 index += 1
Johnny Chenaf149a02010-09-16 17:11:30 +0000415 elif sys.argv[index].startswith('-t'):
416 os.environ["LLDB_COMMAND_TRACE"] = "YES"
417 index += 1
418 elif sys.argv[index].startswith('-v'):
419 verbose = 2
420 index += 1
Johnny Chene47649c2010-10-07 02:04:14 +0000421 elif sys.argv[index].startswith('-w'):
422 os.environ["LLDB_WAIT_BETWEEN_TEST_CASES"] = 'YES'
423 index += 1
Johnny Chend2acdb32010-11-16 22:42:58 +0000424 elif sys.argv[index].startswith('-#'):
425 # Increment by 1 to fetch the repeat count argument.
426 index += 1
427 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
428 usage()
429 count = int(sys.argv[index])
430 index += 1
Johnny Chenaf149a02010-09-16 17:11:30 +0000431 else:
432 print "Unknown option: ", sys.argv[index]
433 usage()
Johnny Chenaf149a02010-09-16 17:11:30 +0000434
Jim Ingham4f347cb2011-04-13 21:11:41 +0000435 if do_help == True:
436 usage()
437
Johnny Chencc659ad2010-12-10 19:02:23 +0000438 # Do not specify both '-a' and '+a' at the same time.
439 if dont_do_python_api_test and just_do_python_api_test:
440 usage()
441
Johnny Chenaf149a02010-09-16 17:11:30 +0000442 # Gather all the dirs passed on the command line.
443 if len(sys.argv) > index:
444 testdirs = map(os.path.abspath, sys.argv[index:])
445
Johnny Chen548aefd2010-10-11 22:25:46 +0000446 # If '-r dir' is specified, the tests should be run under the relocated
447 # directory. Let's copy the testdirs over.
448 if rdir:
449 from shutil import copytree, ignore_patterns
450
451 tmpdirs = []
452 for srcdir in testdirs:
453 dstdir = os.path.join(rdir, os.path.basename(srcdir))
454 # Don't copy the *.pyc and .svn stuffs.
455 copytree(srcdir, dstdir, ignore=ignore_patterns('*.pyc', '.svn'))
456 tmpdirs.append(dstdir)
457
458 # This will be our modified testdirs.
459 testdirs = tmpdirs
460
461 # With '-r dir' specified, there's no cleanup of intermediate test files.
462 os.environ["LLDB_DO_CLEANUP"] = 'NO'
463
464 # If testdirs is ['test'], the make directory has already been copied
465 # recursively and is contained within the rdir/test dir. For anything
466 # else, we would need to copy over the make directory and its contents,
467 # so that, os.listdir(rdir) looks like, for example:
468 #
469 # array_types conditional_break make
470 #
471 # where the make directory contains the Makefile.rules file.
472 if len(testdirs) != 1 or os.path.basename(testdirs[0]) != 'test':
473 # Don't copy the .svn stuffs.
474 copytree('make', os.path.join(rdir, 'make'),
475 ignore=ignore_patterns('.svn'))
476
477 #print "testdirs:", testdirs
478
Johnny Chenb40056b2010-09-21 00:09:27 +0000479 # Source the configFile if specified.
480 # The side effect, if any, will be felt from this point on. An example
481 # config file may be these simple two lines:
482 #
483 # sys.stderr = open("/tmp/lldbtest-stderr", "w")
484 # sys.stdout = open("/tmp/lldbtest-stdout", "w")
485 #
486 # which will reassign the two file objects to sys.stderr and sys.stdout,
487 # respectively.
488 #
489 # See also lldb-trunk/example/test/usage-config.
490 global config
491 if configFile:
492 # Pass config (a dictionary) as the locals namespace for side-effect.
493 execfile(configFile, globals(), config)
494 #print "config:", config
495 #print "sys.stderr:", sys.stderr
496 #print "sys.stdout:", sys.stdout
497
Johnny Chenaf149a02010-09-16 17:11:30 +0000498
Johnny Chen9707bb62010-06-25 21:14:08 +0000499def setupSysPath():
Johnny Chen8a3c0432011-03-11 20:13:06 +0000500 """
501 Add LLDB.framework/Resources/Python to the search paths for modules.
502 As a side effect, we also discover the 'lldb' executable and export it here.
503 """
Johnny Chen9707bb62010-06-25 21:14:08 +0000504
Johnny Chen548aefd2010-10-11 22:25:46 +0000505 global rdir
506 global testdirs
Johnny Chen50bc6382011-01-29 01:16:52 +0000507 global dumpSysPath
Johnny Chen548aefd2010-10-11 22:25:46 +0000508
Johnny Chen9707bb62010-06-25 21:14:08 +0000509 # Get the directory containing the current script.
Johnny Chen0de6ab52011-01-19 02:10:40 +0000510 if "DOTEST_PROFILE" in os.environ and "DOTEST_SCRIPT_DIR" in os.environ:
511 scriptPath = os.environ["DOTEST_SCRIPT_DIR"]
512 else:
513 scriptPath = sys.path[0]
Johnny Chena1affab2010-07-03 03:41:59 +0000514 if not scriptPath.endswith('test'):
Johnny Chen9707bb62010-06-25 21:14:08 +0000515 print "This script expects to reside in lldb's test directory."
516 sys.exit(-1)
517
Johnny Chen548aefd2010-10-11 22:25:46 +0000518 if rdir:
519 # Set up the LLDB_TEST environment variable appropriately, so that the
520 # individual tests can be located relatively.
521 #
522 # See also lldbtest.TestBase.setUpClass(cls).
523 if len(testdirs) == 1 and os.path.basename(testdirs[0]) == 'test':
524 os.environ["LLDB_TEST"] = os.path.join(rdir, 'test')
525 else:
526 os.environ["LLDB_TEST"] = rdir
527 else:
528 os.environ["LLDB_TEST"] = scriptPath
Johnny Chen9de4ede2010-08-31 17:42:54 +0000529 pluginPath = os.path.join(scriptPath, 'plugins')
Johnny Chen8a3c0432011-03-11 20:13:06 +0000530 pexpectPath = os.path.join(scriptPath, 'pexpect-2.4')
Johnny Chen58f93922010-06-29 23:10:39 +0000531
Johnny Chen8a3c0432011-03-11 20:13:06 +0000532 # Append script dir, plugin dir, and pexpect dir to the sys.path.
Johnny Chenaf149a02010-09-16 17:11:30 +0000533 sys.path.append(scriptPath)
534 sys.path.append(pluginPath)
Johnny Chen8a3c0432011-03-11 20:13:06 +0000535 sys.path.append(pexpectPath)
Johnny Chenaf149a02010-09-16 17:11:30 +0000536
Johnny Chen26901c82011-03-11 19:47:23 +0000537 # This is our base name component.
Johnny Chena1affab2010-07-03 03:41:59 +0000538 base = os.path.abspath(os.path.join(scriptPath, os.pardir))
Johnny Chen6a564a42011-02-15 18:50:19 +0000539
Johnny Chen26901c82011-03-11 19:47:23 +0000540 # These are for xcode build directories.
Johnny Chen6a564a42011-02-15 18:50:19 +0000541 xcode3_build_dir = ['build']
542 xcode4_build_dir = ['build', 'lldb', 'Build', 'Products']
543 dbg = ['Debug']
544 rel = ['Release']
545 bai = ['BuildAndIntegration']
546 python_resource_dir = ['LLDB.framework', 'Resources', 'Python']
Johnny Chen26901c82011-03-11 19:47:23 +0000547
548 # Some of the tests can invoke the 'lldb' command directly.
549 # We'll try to locate the appropriate executable right here.
550
551 executable = ['lldb']
552 dbgExec = os.path.join(base, *(xcode3_build_dir + dbg + executable))
553 dbgExec2 = os.path.join(base, *(xcode4_build_dir + dbg + executable))
554 relExec = os.path.join(base, *(xcode3_build_dir + rel + executable))
555 relExec2 = os.path.join(base, *(xcode4_build_dir + rel + executable))
556 baiExec = os.path.join(base, *(xcode3_build_dir + bai + executable))
557 baiExec2 = os.path.join(base, *(xcode4_build_dir + bai + executable))
558
559 lldbExec = None
560 if is_exe(dbgExec):
561 lldbExec = dbgExec
562 elif is_exe(dbgExec2):
563 lldbExec = dbgExec2
564 elif is_exe(relExec):
565 lldbExec = relExec
566 elif is_exe(relExec2):
567 lldbExec = relExec2
568 elif is_exe(baiExec):
569 lldbExec = baiExec
570 elif is_exe(baiExec2):
571 lldbExec = baiExec2
572
573 if not lldbExec:
574 lldbExec = which('lldb')
575
576 if not lldbExec:
577 print "The 'lldb' executable cannot be located. Some of the tests may not be run as a result."
578 else:
579 os.environ["LLDB_EXEC"] = lldbExec
Johnny Chend7931462011-03-17 00:38:22 +0000580 #print "The 'lldb' executable path is", lldbExec
581 os.system('%s -v' % lldbExec)
582
583 os.system('svn info %s' % base)
Johnny Chen26901c82011-03-11 19:47:23 +0000584
585 global ignore
586
587 # The '-i' option is used to skip looking for lldb.py in the build tree.
588 if ignore:
589 return
590
Johnny Chen6a564a42011-02-15 18:50:19 +0000591 dbgPath = os.path.join(base, *(xcode3_build_dir + dbg + python_resource_dir))
592 dbgPath2 = os.path.join(base, *(xcode4_build_dir + dbg + python_resource_dir))
593 relPath = os.path.join(base, *(xcode3_build_dir + rel + python_resource_dir))
594 relPath2 = os.path.join(base, *(xcode4_build_dir + rel + python_resource_dir))
595 baiPath = os.path.join(base, *(xcode3_build_dir + bai + python_resource_dir))
596 baiPath2 = os.path.join(base, *(xcode4_build_dir + bai + python_resource_dir))
Johnny Chen9707bb62010-06-25 21:14:08 +0000597
598 lldbPath = None
599 if os.path.isfile(os.path.join(dbgPath, 'lldb.py')):
600 lldbPath = dbgPath
Greg Claytond9846b02011-02-14 21:17:06 +0000601 elif os.path.isfile(os.path.join(dbgPath2, 'lldb.py')):
602 lldbPath = dbgPath2
Johnny Chen9707bb62010-06-25 21:14:08 +0000603 elif os.path.isfile(os.path.join(relPath, 'lldb.py')):
604 lldbPath = relPath
Greg Claytond9846b02011-02-14 21:17:06 +0000605 elif os.path.isfile(os.path.join(relPath2, 'lldb.py')):
606 lldbPath = relPath2
Johnny Chenc202c462010-09-15 18:11:19 +0000607 elif os.path.isfile(os.path.join(baiPath, 'lldb.py')):
608 lldbPath = baiPath
Greg Claytond9846b02011-02-14 21:17:06 +0000609 elif os.path.isfile(os.path.join(baiPath2, 'lldb.py')):
610 lldbPath = baiPath2
Johnny Chen9707bb62010-06-25 21:14:08 +0000611
612 if not lldbPath:
Johnny Chenc202c462010-09-15 18:11:19 +0000613 print 'This script requires lldb.py to be in either ' + dbgPath + ',',
614 print relPath + ', or ' + baiPath
Johnny Chen9707bb62010-06-25 21:14:08 +0000615 sys.exit(-1)
616
Johnny Chenaf149a02010-09-16 17:11:30 +0000617 # This is to locate the lldb.py module. Insert it right after sys.path[0].
618 sys.path[1:1] = [lldbPath]
Johnny Chen50bc6382011-01-29 01:16:52 +0000619 if dumpSysPath:
620 print "sys.path:", sys.path
Johnny Chen9707bb62010-06-25 21:14:08 +0000621
Johnny Chen9707bb62010-06-25 21:14:08 +0000622
Johnny Chencd0279d2010-09-20 18:07:50 +0000623def doDelay(delta):
624 """Delaying startup for delta-seconds to facilitate debugger attachment."""
625 def alarm_handler(*args):
626 raise Exception("timeout")
627
628 signal.signal(signal.SIGALRM, alarm_handler)
629 signal.alarm(delta)
630 sys.stdout.write("pid=%d\n" % os.getpid())
631 sys.stdout.write("Enter RET to proceed (or timeout after %d seconds):" %
632 delta)
633 sys.stdout.flush()
634 try:
635 text = sys.stdin.readline()
636 except:
637 text = ""
638 signal.alarm(0)
639 sys.stdout.write("proceeding...\n")
640 pass
641
642
Johnny Chen9707bb62010-06-25 21:14:08 +0000643def visit(prefix, dir, names):
644 """Visitor function for os.path.walk(path, visit, arg)."""
645
646 global suite
Johnny Chen7c52ff12010-09-27 23:29:54 +0000647 global regexp
Johnny Chenb62436b2010-10-06 20:40:56 +0000648 global filterspec
649 global fs4all
Johnny Chen9707bb62010-06-25 21:14:08 +0000650
651 for name in names:
652 if os.path.isdir(os.path.join(dir, name)):
653 continue
654
655 if '.py' == os.path.splitext(name)[1] and name.startswith(prefix):
Johnny Chen7c52ff12010-09-27 23:29:54 +0000656 # Try to match the regexp pattern, if specified.
657 if regexp:
658 import re
659 if re.search(regexp, name):
660 #print "Filename: '%s' matches pattern: '%s'" % (name, regexp)
661 pass
662 else:
663 #print "Filename: '%s' does not match pattern: '%s'" % (name, regexp)
664 continue
665
Johnny Chen953864a2010-10-12 21:35:54 +0000666 # We found a match for our test. Add it to the suite.
Johnny Chen79723352010-10-12 15:53:22 +0000667
668 # Update the sys.path first.
Johnny Chena85d7ee2010-06-26 00:19:32 +0000669 if not sys.path.count(dir):
Johnny Chen548aefd2010-10-11 22:25:46 +0000670 sys.path.insert(0, dir)
Johnny Chen9707bb62010-06-25 21:14:08 +0000671 base = os.path.splitext(name)[0]
Johnny Chenb62436b2010-10-06 20:40:56 +0000672
673 # Thoroughly check the filterspec against the base module and admit
674 # the (base, filterspec) combination only when it makes sense.
675 if filterspec:
676 # Optimistically set the flag to True.
677 filtered = True
678 module = __import__(base)
679 parts = filterspec.split('.')
680 obj = module
681 for part in parts:
682 try:
683 parent, obj = obj, getattr(obj, part)
684 except AttributeError:
685 # The filterspec has failed.
686 filtered = False
687 break
688 # Forgo this module if the (base, filterspec) combo is invalid
Johnny Chena224cd12010-11-08 01:21:03 +0000689 # and no '-g' option is specified
Johnny Chenb62436b2010-10-06 20:40:56 +0000690 if fs4all and not filtered:
691 continue
692
Johnny Chen953864a2010-10-12 21:35:54 +0000693 # Add either the filtered test case or the entire test class.
Johnny Chenb62436b2010-10-06 20:40:56 +0000694 if filterspec and filtered:
695 suite.addTests(
696 unittest2.defaultTestLoader.loadTestsFromName(filterspec, module))
697 else:
698 # A simple case of just the module name. Also the failover case
699 # from the filterspec branch when the (base, filterspec) combo
700 # doesn't make sense.
701 suite.addTests(unittest2.defaultTestLoader.loadTestsFromName(base))
Johnny Chen9707bb62010-06-25 21:14:08 +0000702
703
Johnny Chencd0279d2010-09-20 18:07:50 +0000704def lldbLoggings():
705 """Check and do lldb loggings if necessary."""
706
707 # Turn on logging for debugging purposes if ${LLDB_LOG} environment variable is
708 # defined. Use ${LLDB_LOG} to specify the log file.
709 ci = lldb.DBG.GetCommandInterpreter()
710 res = lldb.SBCommandReturnObject()
711 if ("LLDB_LOG" in os.environ):
712 if ("LLDB_LOG_OPTION" in os.environ):
713 lldb_log_option = os.environ["LLDB_LOG_OPTION"]
714 else:
Johnny Chen8fd886c2010-12-08 01:25:21 +0000715 lldb_log_option = "event process expr state api"
Johnny Chencd0279d2010-09-20 18:07:50 +0000716 ci.HandleCommand(
Greg Clayton940b1032011-02-23 00:35:02 +0000717 "log enable -n -f " + os.environ["LLDB_LOG"] + " lldb " + lldb_log_option,
Johnny Chencd0279d2010-09-20 18:07:50 +0000718 res)
719 if not res.Succeeded():
720 raise Exception('log enable failed (check LLDB_LOG env variable.')
721 # Ditto for gdb-remote logging if ${GDB_REMOTE_LOG} environment variable is defined.
722 # Use ${GDB_REMOTE_LOG} to specify the log file.
723 if ("GDB_REMOTE_LOG" in os.environ):
724 if ("GDB_REMOTE_LOG_OPTION" in os.environ):
725 gdb_remote_log_option = os.environ["GDB_REMOTE_LOG_OPTION"]
726 else:
Johnny Chen7ab8c852010-12-02 18:35:13 +0000727 gdb_remote_log_option = "packets process"
Johnny Chencd0279d2010-09-20 18:07:50 +0000728 ci.HandleCommand(
Greg Clayton940b1032011-02-23 00:35:02 +0000729 "log enable -n -f " + os.environ["GDB_REMOTE_LOG"] + " process.gdb-remote "
Johnny Chencd0279d2010-09-20 18:07:50 +0000730 + gdb_remote_log_option,
731 res)
732 if not res.Succeeded():
733 raise Exception('log enable failed (check GDB_REMOTE_LOG env variable.')
734
Johnny Chen067022b2011-01-19 19:31:46 +0000735def getMyCommandLine():
736 import subprocess
737 ps = subprocess.Popen(['ps', '-o', "command=CMD", str(os.getpid())], stdout=subprocess.PIPE).communicate()[0]
738 lines = ps.split('\n')
739 cmd_line = lines[1]
740 return cmd_line
Johnny Chencd0279d2010-09-20 18:07:50 +0000741
Johnny Chend96b5682010-11-05 17:30:53 +0000742# ======================================== #
Johnny Chencd0279d2010-09-20 18:07:50 +0000743# #
744# Execution of the test driver starts here #
745# #
Johnny Chend96b5682010-11-05 17:30:53 +0000746# ======================================== #
Johnny Chencd0279d2010-09-20 18:07:50 +0000747
Johnny Chen9707bb62010-06-25 21:14:08 +0000748#
Johnny Chenaf149a02010-09-16 17:11:30 +0000749# Start the actions by first parsing the options while setting up the test
750# directories, followed by setting up the search paths for lldb utilities;
751# then, we walk the directory trees and collect the tests into our test suite.
Johnny Chen9707bb62010-06-25 21:14:08 +0000752#
Johnny Chenaf149a02010-09-16 17:11:30 +0000753parseOptionsAndInitTestdirs()
Johnny Chen9707bb62010-06-25 21:14:08 +0000754setupSysPath()
Johnny Chen91960d32010-09-08 20:56:16 +0000755
756#
757# If '-d' is specified, do a delay of 10 seconds for the debugger to attach.
758#
759if delay:
Johnny Chencd0279d2010-09-20 18:07:50 +0000760 doDelay(10)
Johnny Chen91960d32010-09-08 20:56:16 +0000761
Johnny Chen49f2f7a2010-09-20 17:25:45 +0000762#
Johnny Chen41998192010-10-01 22:59:49 +0000763# If '-l' is specified, do not skip the long running tests.
764if not skipLongRunningTest:
765 os.environ["LLDB_SKIP_LONG_RUNNING_TEST"] = "NO"
766
767#
Johnny Chen79723352010-10-12 15:53:22 +0000768# Walk through the testdirs while collecting tests.
Johnny Chen49f2f7a2010-09-20 17:25:45 +0000769#
Johnny Chen9707bb62010-06-25 21:14:08 +0000770for testdir in testdirs:
771 os.path.walk(testdir, visit, 'Test')
772
Johnny Chenb40056b2010-09-21 00:09:27 +0000773#
Johnny Chen9707bb62010-06-25 21:14:08 +0000774# Now that we have loaded all the test cases, run the whole test suite.
Johnny Chenb40056b2010-09-21 00:09:27 +0000775#
Johnny Chencd0279d2010-09-20 18:07:50 +0000776
Johnny Chen1bfbd412010-06-29 19:44:16 +0000777# For the time being, let's bracket the test runner within the
778# lldb.SBDebugger.Initialize()/Terminate() pair.
Johnny Chen01f2a6a2010-08-10 20:23:55 +0000779import lldb, atexit
Johnny Chen6b6f5ba2010-10-14 16:36:49 +0000780# Update: the act of importing lldb now executes lldb.SBDebugger.Initialize(),
781# there's no need to call it a second time.
782#lldb.SBDebugger.Initialize()
Johnny Chen01f2a6a2010-08-10 20:23:55 +0000783atexit.register(lambda: lldb.SBDebugger.Terminate())
Johnny Chen1bfbd412010-06-29 19:44:16 +0000784
Johnny Chen909e5a62010-07-01 22:52:57 +0000785# Create a singleton SBDebugger in the lldb namespace.
786lldb.DBG = lldb.SBDebugger.Create()
787
Johnny Chen4f93bf12010-12-10 00:51:23 +0000788# Put the blacklist in the lldb namespace, to be used by lldb.TestBase.
Johnny Chen82e6b1e2010-12-01 22:47:54 +0000789lldb.blacklist = blacklist
790
Johnny Chen4f93bf12010-12-10 00:51:23 +0000791# Put dont/just_do_python_api_test in the lldb namespace, too.
792lldb.dont_do_python_api_test = dont_do_python_api_test
793lldb.just_do_python_api_test = just_do_python_api_test
794
Johnny Chencd0279d2010-09-20 18:07:50 +0000795# Turn on lldb loggings if necessary.
796lldbLoggings()
Johnny Chen909e5a62010-07-01 22:52:57 +0000797
Johnny Chen7987ac92010-08-09 20:40:52 +0000798# Install the control-c handler.
799unittest2.signals.installHandler()
800
Johnny Chen125fc2b2010-10-21 16:55:35 +0000801# If sdir_name is not specified through the '-s sdir_name' option, get a
802# timestamp string and export it as LLDB_SESSION_DIR environment var. This will
803# be used when/if we want to dump the session info of individual test cases
804# later on.
Johnny Chence681462010-10-19 00:25:01 +0000805#
806# See also TestBase.dumpSessionInfo() in lldbtest.py.
Johnny Chen125fc2b2010-10-21 16:55:35 +0000807if not sdir_name:
808 import datetime
Johnny Chen41fae812010-10-29 22:26:38 +0000809 # The windows platforms don't like ':' in the pathname.
Johnny Chen76bd0102010-10-28 16:32:13 +0000810 timestamp = datetime.datetime.now().strftime("%Y-%m-%d-%H_%M_%S")
Johnny Chen125fc2b2010-10-21 16:55:35 +0000811 sdir_name = timestamp
812os.environ["LLDB_SESSION_DIRNAME"] = sdir_name
Johnny Chen067022b2011-01-19 19:31:46 +0000813
Johnny Chen47c47c42010-11-09 23:42:00 +0000814sys.stderr.write("\nSession logs for test failures/errors will go into directory '%s'\n" % sdir_name)
Johnny Chen067022b2011-01-19 19:31:46 +0000815sys.stderr.write("Command invoked: %s\n" % getMyCommandLine())
Johnny Chence681462010-10-19 00:25:01 +0000816
Johnny Chenb40056b2010-09-21 00:09:27 +0000817#
818# Invoke the default TextTestRunner to run the test suite, possibly iterating
819# over different configurations.
820#
821
Johnny Chenb40056b2010-09-21 00:09:27 +0000822iterArchs = False
Johnny Chenf032d902010-09-21 00:16:09 +0000823iterCompilers = False
Johnny Chenb40056b2010-09-21 00:09:27 +0000824
Johnny Chen1a4d5e72011-03-04 01:35:22 +0000825if not archs and "archs" in config:
Johnny Chenb40056b2010-09-21 00:09:27 +0000826 archs = config["archs"]
Johnny Chen1a4d5e72011-03-04 01:35:22 +0000827
828if isinstance(archs, list) and len(archs) >= 1:
829 iterArchs = True
830
831if not compilers and "compilers" in config:
Johnny Chenb40056b2010-09-21 00:09:27 +0000832 compilers = config["compilers"]
Johnny Chen1a4d5e72011-03-04 01:35:22 +0000833
834if isinstance(compilers, list) and len(compilers) >= 1:
835 iterCompilers = True
Johnny Chenb40056b2010-09-21 00:09:27 +0000836
Johnny Chen953864a2010-10-12 21:35:54 +0000837# Make a shallow copy of sys.path, we need to manipulate the search paths later.
838# This is only necessary if we are relocated and with different configurations.
Johnny Chen1a4d5e72011-03-04 01:35:22 +0000839if rdir:
Johnny Chen953864a2010-10-12 21:35:54 +0000840 old_sys_path = sys.path[:]
Johnny Chen1a4d5e72011-03-04 01:35:22 +0000841# If we iterate on archs or compilers, there is a chance we want to split stderr/stdout.
842if iterArchs or iterCompilers:
Johnny Chen953864a2010-10-12 21:35:54 +0000843 old_stderr = sys.stderr
844 old_stdout = sys.stdout
845 new_stderr = None
846 new_stdout = None
847
Johnny Chend96b5682010-11-05 17:30:53 +0000848# Iterating over all possible architecture and compiler combinations.
Johnny Chenb40056b2010-09-21 00:09:27 +0000849for ia in range(len(archs) if iterArchs else 1):
850 archConfig = ""
851 if iterArchs:
Johnny Chen18a921f2010-09-30 17:11:58 +0000852 os.environ["ARCH"] = archs[ia]
Johnny Chenb40056b2010-09-21 00:09:27 +0000853 archConfig = "arch=%s" % archs[ia]
854 for ic in range(len(compilers) if iterCompilers else 1):
855 if iterCompilers:
Johnny Chen18a921f2010-09-30 17:11:58 +0000856 os.environ["CC"] = compilers[ic]
Johnny Chenb40056b2010-09-21 00:09:27 +0000857 configString = "%s compiler=%s" % (archConfig, compilers[ic])
858 else:
859 configString = archConfig
860
Johnny Chenb40056b2010-09-21 00:09:27 +0000861 if iterArchs or iterCompilers:
Johnny Chen1a4d5e72011-03-04 01:35:22 +0000862 # Translate ' ' to '-' for pathname component.
863 from string import maketrans
864 tbl = maketrans(' ', '-')
865 configPostfix = configString.translate(tbl)
866
867 # Check whether we need to split stderr/stdout into configuration
868 # specific files.
869 if old_stderr.name != '<stderr>' and config.get('split_stderr'):
870 if new_stderr:
871 new_stderr.close()
872 new_stderr = open("%s.%s" % (old_stderr.name, configPostfix), "w")
873 sys.stderr = new_stderr
874 if old_stdout.name != '<stdout>' and config.get('split_stdout'):
875 if new_stdout:
876 new_stdout.close()
877 new_stdout = open("%s.%s" % (old_stdout.name, configPostfix), "w")
878 sys.stdout = new_stdout
879
Johnny Chen953864a2010-10-12 21:35:54 +0000880 # If we specified a relocated directory to run the test suite, do
881 # the extra housekeeping to copy the testdirs to a configStringified
882 # directory and to update sys.path before invoking the test runner.
883 # The purpose is to separate the configuration-specific directories
884 # from each other.
885 if rdir:
Johnny Chen953864a2010-10-12 21:35:54 +0000886 from shutil import copytree, ignore_patterns
887
Johnny Chen953864a2010-10-12 21:35:54 +0000888 newrdir = "%s.%s" % (rdir, configPostfix)
889
890 # Copy the tree to a new directory with postfix name configPostfix.
891 copytree(rdir, newrdir, ignore=ignore_patterns('*.pyc', '*.o', '*.d'))
892
Johnny Chen1a4d5e72011-03-04 01:35:22 +0000893 # Update the LLDB_TEST environment variable to reflect new top
Johnny Chen953864a2010-10-12 21:35:54 +0000894 # level test directory.
895 #
896 # See also lldbtest.TestBase.setUpClass(cls).
897 if len(testdirs) == 1 and os.path.basename(testdirs[0]) == 'test':
898 os.environ["LLDB_TEST"] = os.path.join(newrdir, 'test')
899 else:
900 os.environ["LLDB_TEST"] = newrdir
901
902 # And update the Python search paths for modules.
903 sys.path = [x.replace(rdir, newrdir, 1) for x in old_sys_path]
904
905 # Output the configuration.
Johnny Chenb40056b2010-09-21 00:09:27 +0000906 sys.stderr.write("\nConfiguration: " + configString + "\n")
Johnny Chen953864a2010-10-12 21:35:54 +0000907
908 #print "sys.stderr name is", sys.stderr.name
909 #print "sys.stdout name is", sys.stdout.name
910
911 # First, write out the number of collected test cases.
912 sys.stderr.write(separator + "\n")
913 sys.stderr.write("Collected %d test%s\n\n"
914 % (suite.countTestCases(),
915 suite.countTestCases() != 1 and "s" or ""))
916
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000917 class LLDBTestResult(unittest2.TextTestResult):
918 """
Johnny Chen26be4532010-11-09 23:56:14 +0000919 Enforce a singleton pattern to allow introspection of test progress.
920
921 Overwrite addError(), addFailure(), and addExpectedFailure() methods
922 to enable each test instance to track its failure/error status. It
923 is used in the LLDB test framework to emit detailed trace messages
924 to a log file for easier human inspection of test failres/errors.
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000925 """
926 __singleton__ = None
Johnny Chen360dd372010-11-29 17:50:10 +0000927 __ignore_singleton__ = False
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000928
929 def __init__(self, *args):
Johnny Chen360dd372010-11-29 17:50:10 +0000930 if not LLDBTestResult.__ignore_singleton__ and LLDBTestResult.__singleton__:
Johnny Chend2acdb32010-11-16 22:42:58 +0000931 raise Exception("LLDBTestResult instantiated more than once")
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000932 super(LLDBTestResult, self).__init__(*args)
933 LLDBTestResult.__singleton__ = self
934 # Now put this singleton into the lldb module namespace.
935 lldb.test_result = self
Johnny Chen810042e2011-01-05 20:24:11 +0000936 # Computes the format string for displaying the counter.
937 global suite
938 counterWidth = len(str(suite.countTestCases()))
939 self.fmt = "%" + str(counterWidth) + "d: "
Johnny Chenc87fd492011-01-05 22:50:11 +0000940 self.indentation = ' ' * (counterWidth + 2)
Johnny Chen810042e2011-01-05 20:24:11 +0000941 # This counts from 1 .. suite.countTestCases().
942 self.counter = 0
943
Johnny Chenc87fd492011-01-05 22:50:11 +0000944 def getDescription(self, test):
945 doc_first_line = test.shortDescription()
946 if self.descriptions and doc_first_line:
947 return '\n'.join((str(test), self.indentation + doc_first_line))
948 else:
949 return str(test)
950
Johnny Chen810042e2011-01-05 20:24:11 +0000951 def startTest(self, test):
952 self.counter += 1
953 if self.showAll:
954 self.stream.write(self.fmt % self.counter)
955 super(LLDBTestResult, self).startTest(test)
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000956
Johnny Chence681462010-10-19 00:25:01 +0000957 def addError(self, test, err):
Johnny Chen63c2cba2010-10-29 22:20:36 +0000958 global sdir_has_content
959 sdir_has_content = True
Johnny Chence681462010-10-19 00:25:01 +0000960 super(LLDBTestResult, self).addError(test, err)
961 method = getattr(test, "markError", None)
962 if method:
963 method()
964
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000965 def addFailure(self, test, err):
Johnny Chen63c2cba2010-10-29 22:20:36 +0000966 global sdir_has_content
967 sdir_has_content = True
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000968 super(LLDBTestResult, self).addFailure(test, err)
969 method = getattr(test, "markFailure", None)
970 if method:
971 method()
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000972
Johnny Chendd2bb2c2010-11-03 18:17:03 +0000973 def addExpectedFailure(self, test, err):
974 global sdir_has_content
975 sdir_has_content = True
976 super(LLDBTestResult, self).addExpectedFailure(test, err)
977 method = getattr(test, "markExpectedFailure", None)
978 if method:
979 method()
980
Johnny Chen26be4532010-11-09 23:56:14 +0000981 # Invoke the test runner.
Johnny Chend2acdb32010-11-16 22:42:58 +0000982 if count == 1:
Johnny Chen7d6d8442010-12-03 19:59:35 +0000983 result = unittest2.TextTestRunner(stream=sys.stderr,
984 verbosity=verbose,
985 failfast=failfast,
Johnny Chend2acdb32010-11-16 22:42:58 +0000986 resultclass=LLDBTestResult).run(suite)
987 else:
Johnny Chend6e7ca22010-11-29 17:52:43 +0000988 # We are invoking the same test suite more than once. In this case,
989 # mark __ignore_singleton__ flag as True so the signleton pattern is
990 # not enforced.
Johnny Chen360dd372010-11-29 17:50:10 +0000991 LLDBTestResult.__ignore_singleton__ = True
Johnny Chend2acdb32010-11-16 22:42:58 +0000992 for i in range(count):
Johnny Chen7d6d8442010-12-03 19:59:35 +0000993 result = unittest2.TextTestRunner(stream=sys.stderr,
994 verbosity=verbose,
995 failfast=failfast,
Johnny Chen360dd372010-11-29 17:50:10 +0000996 resultclass=LLDBTestResult).run(suite)
Johnny Chenb40056b2010-09-21 00:09:27 +0000997
Johnny Chen1bfbd412010-06-29 19:44:16 +0000998
Johnny Chen63c2cba2010-10-29 22:20:36 +0000999if sdir_has_content:
Johnny Chen47c47c42010-11-09 23:42:00 +00001000 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 +00001001
Johnny Chencd0279d2010-09-20 18:07:50 +00001002# Terminate the test suite if ${LLDB_TESTSUITE_FORCE_FINISH} is defined.
1003# This should not be necessary now.
Johnny Chen83f6e512010-08-13 22:58:44 +00001004if ("LLDB_TESTSUITE_FORCE_FINISH" in os.environ):
1005 import subprocess
1006 print "Terminating Test suite..."
1007 subprocess.Popen(["/bin/sh", "-c", "kill %s; exit 0" % (os.getpid())])
1008
Johnny Chen01f2a6a2010-08-10 20:23:55 +00001009# Exiting.
1010sys.exit(not result.wasSuccessful)