blob: 1e412ff9cb94832ef2b2fbac6eb63770c9d488ad [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 Chen2891bb02011-09-16 01:04:26 +000024import subprocess
Johnny Chen75e28f92010-08-05 23:42:46 +000025import unittest2
Johnny Chen9707bb62010-06-25 21:14:08 +000026
Johnny Chen26901c82011-03-11 19:47:23 +000027def is_exe(fpath):
Johnny Chenf2c7b282011-04-26 23:10:51 +000028 """Returns true if fpath is an executable."""
Johnny Chen26901c82011-03-11 19:47:23 +000029 return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
30
Johnny Chen26901c82011-03-11 19:47:23 +000031def which(program):
Johnny Chenf2c7b282011-04-26 23:10:51 +000032 """Returns the full path to a program; None otherwise."""
Johnny Chen26901c82011-03-11 19:47:23 +000033 fpath, fname = os.path.split(program)
34 if fpath:
35 if is_exe(program):
36 return program
37 else:
38 for path in os.environ["PATH"].split(os.pathsep):
39 exe_file = os.path.join(path, program)
40 if is_exe(exe_file):
41 return exe_file
42 return None
43
Johnny Chen877c7e42010-08-07 00:16:07 +000044class _WritelnDecorator(object):
45 """Used to decorate file-like objects with a handy 'writeln' method"""
46 def __init__(self,stream):
47 self.stream = stream
48
49 def __getattr__(self, attr):
50 if attr in ('stream', '__getstate__'):
51 raise AttributeError(attr)
52 return getattr(self.stream,attr)
53
54 def writeln(self, arg=None):
55 if arg:
56 self.write(arg)
57 self.write('\n') # text-mode streams translate to \r\n if needed
58
Johnny Chen9707bb62010-06-25 21:14:08 +000059#
60# Global variables:
61#
62
63# The test suite.
Johnny Chen75e28f92010-08-05 23:42:46 +000064suite = unittest2.TestSuite()
Johnny Chen9707bb62010-06-25 21:14:08 +000065
Johnny Chen4f93bf12010-12-10 00:51:23 +000066# By default, both command line and Python API tests are performed.
Johnny Chen3ebdacc2010-12-10 18:52:10 +000067# Use @python_api_test decorator, defined in lldbtest.py, to mark a test as
68# a Python API test.
Johnny Chen4f93bf12010-12-10 00:51:23 +000069dont_do_python_api_test = False
70
71# By default, both command line and Python API tests are performed.
Johnny Chen4f93bf12010-12-10 00:51:23 +000072just_do_python_api_test = False
73
Johnny Chen82ccf402011-07-30 01:39:58 +000074# By default, benchmarks tests are not run.
75just_do_benchmarks_test = False
76
Johnny Chen82e6b1e2010-12-01 22:47:54 +000077# The blacklist is optional (-b blacklistFile) and allows a central place to skip
78# testclass's and/or testclass.testmethod's.
79blacklist = None
80
81# The dictionary as a result of sourcing blacklistFile.
82blacklistConfig = {}
83
Johnny Chen9fdb0a92010-09-18 00:16:47 +000084# The config file is optional.
85configFile = None
86
Johnny Chend2acdb32010-11-16 22:42:58 +000087# Test suite repeat count. Can be overwritten with '-# count'.
88count = 1
89
Johnny Chenb40056b2010-09-21 00:09:27 +000090# The dictionary as a result of sourcing configFile.
91config = {}
92
Johnny Chen1a4d5e72011-03-04 01:35:22 +000093# The 'archs' and 'compilers' can be specified via either command line or configFile,
94# with the command line overriding the configFile. When specified, they should be
95# of the list type. For example, "-A x86_64^i386" => archs=['x86_64', 'i386'] and
96# "-C gcc^clang" => compilers=['gcc', 'clang'].
97archs = None
98compilers = None
99
Johnny Chen91960d32010-09-08 20:56:16 +0000100# Delay startup in order for the debugger to attach.
101delay = False
102
Johnny Chend5362332011-01-29 01:21:04 +0000103# Dump the Python sys.path variable. Use '-D' to dump sys.path.
Johnny Chen50bc6382011-01-29 01:16:52 +0000104dumpSysPath = False
105
Johnny Chene00c9302011-10-10 22:03:44 +0000106# Full path of the benchmark executable, as specified by the '-e' option.
107bmExecutable = None
108# The breakpoint specification of bmExecutable, as specified by the '-x' option.
109bmBreakpointSpec = None
110
Johnny Chen7d6d8442010-12-03 19:59:35 +0000111# By default, failfast is False. Use '-F' to overwrite it.
112failfast = False
113
Johnny Chenc5fa0052011-07-29 22:54:56 +0000114# The filters (testclass.testmethod) used to admit tests into our test suite.
115filters = []
Johnny Chenb62436b2010-10-06 20:40:56 +0000116
Johnny Chen38f823c2011-10-11 01:30:27 +0000117# The runhooks is a list of lldb commands specifically for the debugger.
118# Use '-k' to specify a runhook.
119runHooks = []
120
Johnny Chena224cd12010-11-08 01:21:03 +0000121# If '-g' is specified, the filterspec is not exclusive. If a test module does
122# not contain testclass.testmethod which matches the filterspec, the whole test
123# module is still admitted into our test suite. fs4all flag defaults to True.
124fs4all = True
Johnny Chenb62436b2010-10-06 20:40:56 +0000125
Johnny Chenaf149a02010-09-16 17:11:30 +0000126# Ignore the build search path relative to this script to locate the lldb.py module.
127ignore = False
128
Johnny Chen548aefd2010-10-11 22:25:46 +0000129# By default, we skip long running test case. Use '-l' option to override.
Johnny Chen41998192010-10-01 22:59:49 +0000130skipLongRunningTest = True
131
Johnny Chen7c52ff12010-09-27 23:29:54 +0000132# The regular expression pattern to match against eligible filenames as our test cases.
133regexp = None
134
Johnny Chen548aefd2010-10-11 22:25:46 +0000135# By default, tests are executed in place and cleanups are performed afterwards.
136# Use '-r dir' option to relocate the tests and their intermediate files to a
137# different directory and to forgo any cleanups. The directory specified must
138# not exist yet.
139rdir = None
140
Johnny Chen125fc2b2010-10-21 16:55:35 +0000141# By default, recorded session info for errored/failed test are dumped into its
142# own file under a session directory named after the timestamp of the test suite
143# run. Use '-s session-dir-name' to specify a specific dir name.
144sdir_name = None
145
Johnny Chen63c2cba2010-10-29 22:20:36 +0000146# Set this flag if there is any session info dumped during the test run.
147sdir_has_content = False
148
Johnny Chenb5fe80c2011-05-17 22:58:50 +0000149# svn_info stores the output from 'svn info lldb.base.dir'.
150svn_info = ''
151
Johnny Chen9707bb62010-06-25 21:14:08 +0000152# Default verbosity is 0.
153verbose = 0
154
Peter Collingbourne61aca482011-06-20 19:06:29 +0000155# By default, search from the script directory.
156testdirs = [ sys.path[0] ]
Johnny Chen9707bb62010-06-25 21:14:08 +0000157
Johnny Chen877c7e42010-08-07 00:16:07 +0000158# Separator string.
159separator = '-' * 70
160
Johnny Chen9707bb62010-06-25 21:14:08 +0000161
162def usage():
163 print """
164Usage: dotest.py [option] [args]
165where options:
Jim Ingham4f347cb2011-04-13 21:11:41 +0000166-h : print this help message and exit. Add '-v' for more detailed help.
Johnny Chen1a4d5e72011-03-04 01:35:22 +0000167-A : specify the architecture(s) to launch for the inferior process
168 -A i386 => launch inferior with i386 architecture
169 -A x86_64^i386 => launch inferior with x86_64 and i386 architectures
170-C : specify the compiler(s) used to build the inferior executable
171 -C clang => build debuggee using clang compiler
172 -C clang^gcc => build debuggee using clang and gcc compilers
Johnny Chen50bc6382011-01-29 01:16:52 +0000173-D : dump the Python sys.path variable
Johnny Chen4f93bf12010-12-10 00:51:23 +0000174-a : don't do lldb Python API tests
175 use @python_api_test to decorate a test case as lldb Python API test
Johnny Chen3ebdacc2010-12-10 18:52:10 +0000176+a : just do lldb Python API tests
Johnny Chencc659ad2010-12-10 19:02:23 +0000177 do not specify both '-a' and '+a' at the same time
Johnny Chen82ccf402011-07-30 01:39:58 +0000178+b : just do benchmark tests
179 use @benchmark_test to decorate a test case as such
Johnny Chen82e6b1e2010-12-01 22:47:54 +0000180-b : read a blacklist file specified after this option
Johnny Chen9fdb0a92010-09-18 00:16:47 +0000181-c : read a config file specified after this option
Johnny Chen1a4d5e72011-03-04 01:35:22 +0000182 the architectures and compilers (note the plurals) specified via '-A' and '-C'
183 will override those specified via a config file
Johnny Chenb40056b2010-09-21 00:09:27 +0000184 (see also lldb-trunk/example/test/usage-config)
Johnny Chen91960d32010-09-08 20:56:16 +0000185-d : delay startup for 10 seconds (in order for the debugger to attach)
Johnny Chene00c9302011-10-10 22:03:44 +0000186-e : specify the full path of an executable used for benchmark purpose;
187 see also '-x', which provides the breakpoint sepcification
Johnny Chen7d6d8442010-12-03 19:59:35 +0000188-F : failfast, stop the test suite on the first error/failure
Johnny Chen46be75d2010-10-11 16:19:48 +0000189-f : specify a filter, which consists of the test class name, a dot, followed by
Johnny Chen1a6e92a2010-11-08 20:17:04 +0000190 the test method, to only admit such test into the test suite
Johnny Chenb62436b2010-10-06 20:40:56 +0000191 e.g., -f 'ClassTypesTestCase.test_with_dwarf_and_python_api'
Johnny Chena224cd12010-11-08 01:21:03 +0000192-g : if specified, the filterspec by -f is not exclusive, i.e., if a test module
193 does not match the filterspec (testclass.testmethod), the whole module is
194 still admitted to the test suite
Johnny Chenaf149a02010-09-16 17:11:30 +0000195-i : ignore (don't bailout) if 'lldb.py' module cannot be located in the build
196 tree relative to this script; use PYTHONPATH to locate the module
Johnny Chen38f823c2011-10-11 01:30:27 +0000197-k : specify a runhook, which is an lldb command to be executed by the debugger;
198 '-k' option can occur multiple times, the commands are executed one after the
199 other to bring the debugger to a desired state, so that, for example, further
200 benchmarking can be done
Johnny Chen41998192010-10-01 22:59:49 +0000201-l : don't skip long running test
Johnny Chen7c52ff12010-09-27 23:29:54 +0000202-p : specify a regexp filename pattern for inclusion in the test suite
Johnny Chen548aefd2010-10-11 22:25:46 +0000203-r : specify a dir to relocate the tests and their intermediate files to;
204 the directory must not exist before running this test driver;
205 no cleanup of intermediate test files is performed in this case
Johnny Chen125fc2b2010-10-21 16:55:35 +0000206-s : specify the name of the dir created to store the session files of tests
207 with errored or failed status; if not specified, the test driver uses the
208 timestamp as the session dir name
Johnny Chena2486f22011-04-21 20:48:32 +0000209-t : turn on tracing of lldb command and other detailed test executions
210-v : do verbose mode of unittest framework (print out each test case invocation)
Johnny Chene00c9302011-10-10 22:03:44 +0000211-x : specify the breakpoint specification for the benchmark executable;
212 see also '-e', which provides the full path of the executable
Johnny Chene47649c2010-10-07 02:04:14 +0000213-w : insert some wait time (currently 0.5 sec) between consecutive test cases
Johnny Chend2acdb32010-11-16 22:42:58 +0000214-# : Repeat the test suite for a specified number of times
Johnny Chen9707bb62010-06-25 21:14:08 +0000215
216and:
Johnny Chen9656ab22010-10-22 19:00:18 +0000217args : specify a list of directory names to search for test modules named after
218 Test*.py (test discovery)
Peter Collingbourne5f2b5d62011-06-14 03:55:45 +0000219 if empty, search from the current working directory, instead
Jim Ingham4f347cb2011-04-13 21:11:41 +0000220"""
Johnny Chen58f93922010-06-29 23:10:39 +0000221
Jim Ingham4f347cb2011-04-13 21:11:41 +0000222 if verbose > 0:
223 print """
Johnny Chen9656ab22010-10-22 19:00:18 +0000224Examples:
225
Johnny Chena224cd12010-11-08 01:21:03 +0000226This is an example of using the -f option to pinpoint to a specfic test class
227and test method to be run:
Johnny Chen6ad7e5e2010-10-21 00:47:52 +0000228
Johnny Chena224cd12010-11-08 01:21:03 +0000229$ ./dotest.py -f ClassTypesTestCase.test_with_dsym_and_run_command
Johnny Chen6ad7e5e2010-10-21 00:47:52 +0000230----------------------------------------------------------------------
231Collected 1 test
232
233test_with_dsym_and_run_command (TestClassTypes.ClassTypesTestCase)
234Test 'frame variable this' when stopped on a class constructor. ... ok
235
236----------------------------------------------------------------------
237Ran 1 test in 1.396s
238
239OK
Johnny Chen9656ab22010-10-22 19:00:18 +0000240
241And this is an example of using the -p option to run a single file (the filename
242matches the pattern 'ObjC' and it happens to be 'TestObjCMethods.py'):
243
244$ ./dotest.py -v -p ObjC
245----------------------------------------------------------------------
246Collected 4 tests
247
248test_break_with_dsym (TestObjCMethods.FoundationTestCase)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000249Test setting objc breakpoints using '_regexp-break' and 'breakpoint set'. ... ok
Johnny Chen9656ab22010-10-22 19:00:18 +0000250test_break_with_dwarf (TestObjCMethods.FoundationTestCase)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000251Test setting objc breakpoints using '_regexp-break' and 'breakpoint set'. ... ok
Johnny Chen9656ab22010-10-22 19:00:18 +0000252test_data_type_and_expr_with_dsym (TestObjCMethods.FoundationTestCase)
253Lookup objective-c data types and evaluate expressions. ... ok
254test_data_type_and_expr_with_dwarf (TestObjCMethods.FoundationTestCase)
255Lookup objective-c data types and evaluate expressions. ... ok
256
257----------------------------------------------------------------------
258Ran 4 tests in 16.661s
259
260OK
Johnny Chen6ad7e5e2010-10-21 00:47:52 +0000261
Johnny Chen58f93922010-06-29 23:10:39 +0000262Running of this script also sets up the LLDB_TEST environment variable so that
Johnny Chenaf149a02010-09-16 17:11:30 +0000263individual test cases can locate their supporting files correctly. The script
264tries to set up Python's search paths for modules by looking at the build tree
Johnny Chena85859f2010-11-11 22:14:56 +0000265relative to this script. See also the '-i' option in the following example.
266
267Finally, this is an example of using the lldb.py module distributed/installed by
268Xcode4 to run against the tests under the 'forward' directory, and with the '-w'
269option to add some delay between two tests. It uses ARCH=x86_64 to specify that
270as the architecture and CC=clang to specify the compiler used for the test run:
271
272$ PYTHONPATH=/Xcode4/Library/PrivateFrameworks/LLDB.framework/Versions/A/Resources/Python ARCH=x86_64 CC=clang ./dotest.py -v -w -i forward
273
274Session logs for test failures/errors will go into directory '2010-11-11-13_56_16'
275----------------------------------------------------------------------
276Collected 2 tests
277
278test_with_dsym_and_run_command (TestForwardDeclaration.ForwardDeclarationTestCase)
279Display *bar_ptr when stopped on a function with forward declaration of struct bar. ... ok
280test_with_dwarf_and_run_command (TestForwardDeclaration.ForwardDeclarationTestCase)
281Display *bar_ptr when stopped on a function with forward declaration of struct bar. ... ok
282
283----------------------------------------------------------------------
284Ran 2 tests in 5.659s
285
286OK
287
288The 'Session ...' verbiage is recently introduced (see also the '-s' option) to
289notify the directory containing the session logs for test failures or errors.
290In case there is any test failure/error, a similar message is appended at the
291end of the stderr output for your convenience.
Johnny Chenfde69bc2010-09-14 22:01:40 +0000292
293Environment variables related to loggings:
294
295o LLDB_LOG: if defined, specifies the log file pathname for the 'lldb' subsystem
296 with a default option of 'event process' if LLDB_LOG_OPTION is not defined.
297
298o GDB_REMOTE_LOG: if defined, specifies the log file pathname for the
299 'process.gdb-remote' subsystem with a default option of 'packets' if
300 GDB_REMOTE_LOG_OPTION is not defined.
Johnny Chen9707bb62010-06-25 21:14:08 +0000301"""
Johnny Chen9fdb0a92010-09-18 00:16:47 +0000302 sys.exit(0)
Johnny Chen9707bb62010-06-25 21:14:08 +0000303
304
Johnny Chenaf149a02010-09-16 17:11:30 +0000305def parseOptionsAndInitTestdirs():
306 """Initialize the list of directories containing our unittest scripts.
307
308 '-h/--help as the first option prints out usage info and exit the program.
309 """
310
Johnny Chen4f93bf12010-12-10 00:51:23 +0000311 global dont_do_python_api_test
312 global just_do_python_api_test
Johnny Chen82ccf402011-07-30 01:39:58 +0000313 global just_do_benchmarks_test
Johnny Chen82e6b1e2010-12-01 22:47:54 +0000314 global blacklist
315 global blacklistConfig
Johnny Chen9fdb0a92010-09-18 00:16:47 +0000316 global configFile
Johnny Chen1a4d5e72011-03-04 01:35:22 +0000317 global archs
318 global compilers
Johnny Chend2acdb32010-11-16 22:42:58 +0000319 global count
Johnny Chenaf149a02010-09-16 17:11:30 +0000320 global delay
Johnny Chen50bc6382011-01-29 01:16:52 +0000321 global dumpSysPath
Johnny Chene00c9302011-10-10 22:03:44 +0000322 global bmExecutable
323 global bmBreakpointSpec
Johnny Chen7d6d8442010-12-03 19:59:35 +0000324 global failfast
Johnny Chenc5fa0052011-07-29 22:54:56 +0000325 global filters
Johnny Chenb62436b2010-10-06 20:40:56 +0000326 global fs4all
Johnny Chen7c52ff12010-09-27 23:29:54 +0000327 global ignore
Johnny Chen38f823c2011-10-11 01:30:27 +0000328 global runHooks
Johnny Chen41998192010-10-01 22:59:49 +0000329 global skipLongRunningTest
Johnny Chen7c52ff12010-09-27 23:29:54 +0000330 global regexp
Johnny Chen548aefd2010-10-11 22:25:46 +0000331 global rdir
Johnny Chen125fc2b2010-10-21 16:55:35 +0000332 global sdir_name
Johnny Chenaf149a02010-09-16 17:11:30 +0000333 global verbose
334 global testdirs
335
Jim Ingham4f347cb2011-04-13 21:11:41 +0000336 do_help = False
337
Johnny Chenaf149a02010-09-16 17:11:30 +0000338 if len(sys.argv) == 1:
339 return
340
341 # Process possible trace and/or verbose flag, among other things.
342 index = 1
Johnny Chence2212c2010-10-07 15:41:55 +0000343 while index < len(sys.argv):
Johnny Chen4f93bf12010-12-10 00:51:23 +0000344 if sys.argv[index].startswith('-') or sys.argv[index].startswith('+'):
345 # We should continue processing...
346 pass
347 else:
Johnny Chenaf149a02010-09-16 17:11:30 +0000348 # End of option processing.
349 break
350
351 if sys.argv[index].find('-h') != -1:
Jim Ingham4f347cb2011-04-13 21:11:41 +0000352 index += 1
353 do_help = True
Johnny Chen012cba12011-01-26 19:07:42 +0000354 elif sys.argv[index].startswith('-A'):
355 # Increment by 1 to fetch the ARCH spec.
356 index += 1
357 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
358 usage()
Johnny Cheneee9b862011-04-26 20:45:00 +0000359 archs = sys.argv[index].split('^')
Johnny Chen012cba12011-01-26 19:07:42 +0000360 index += 1
361 elif sys.argv[index].startswith('-C'):
362 # Increment by 1 to fetch the CC spec.
363 index += 1
364 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
365 usage()
Johnny Cheneee9b862011-04-26 20:45:00 +0000366 compilers = sys.argv[index].split('^')
Johnny Chen012cba12011-01-26 19:07:42 +0000367 index += 1
Johnny Chen50bc6382011-01-29 01:16:52 +0000368 elif sys.argv[index].startswith('-D'):
369 dumpSysPath = True
370 index += 1
Johnny Chen4f93bf12010-12-10 00:51:23 +0000371 elif sys.argv[index].startswith('-a'):
372 dont_do_python_api_test = True
373 index += 1
374 elif sys.argv[index].startswith('+a'):
375 just_do_python_api_test = True
376 index += 1
Johnny Chen82ccf402011-07-30 01:39:58 +0000377 elif sys.argv[index].startswith('+b'):
378 just_do_benchmarks_test = True
379 index += 1
Johnny Chen82e6b1e2010-12-01 22:47:54 +0000380 elif sys.argv[index].startswith('-b'):
381 # Increment by 1 to fetch the blacklist file name option argument.
382 index += 1
383 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
384 usage()
385 blacklistFile = sys.argv[index]
386 if not os.path.isfile(blacklistFile):
387 print "Blacklist file:", blacklistFile, "does not exist!"
388 usage()
389 index += 1
390 # Now read the blacklist contents and assign it to blacklist.
391 execfile(blacklistFile, globals(), blacklistConfig)
392 blacklist = blacklistConfig.get('blacklist')
Johnny Chen9fdb0a92010-09-18 00:16:47 +0000393 elif sys.argv[index].startswith('-c'):
394 # Increment by 1 to fetch the config file name option argument.
395 index += 1
396 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
397 usage()
398 configFile = sys.argv[index]
399 if not os.path.isfile(configFile):
400 print "Config file:", configFile, "does not exist!"
401 usage()
402 index += 1
Johnny Chenaf149a02010-09-16 17:11:30 +0000403 elif sys.argv[index].startswith('-d'):
404 delay = True
405 index += 1
Johnny Chene00c9302011-10-10 22:03:44 +0000406 elif sys.argv[index].startswith('-e'):
407 # Increment by 1 to fetch the full path of the benchmark executable.
408 index += 1
409 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
410 usage()
411 bmExecutable = sys.argv[index]
412 if not is_exe(bmExecutable):
413 usage()
414 index += 1
Johnny Chen7d6d8442010-12-03 19:59:35 +0000415 elif sys.argv[index].startswith('-F'):
416 failfast = True
417 index += 1
Johnny Chenb62436b2010-10-06 20:40:56 +0000418 elif sys.argv[index].startswith('-f'):
419 # Increment by 1 to fetch the filter spec.
420 index += 1
421 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
422 usage()
Johnny Chenc5fa0052011-07-29 22:54:56 +0000423 filters.append(sys.argv[index])
Johnny Chenb62436b2010-10-06 20:40:56 +0000424 index += 1
425 elif sys.argv[index].startswith('-g'):
Johnny Chena224cd12010-11-08 01:21:03 +0000426 fs4all = False
Johnny Chenb62436b2010-10-06 20:40:56 +0000427 index += 1
Johnny Chenaf149a02010-09-16 17:11:30 +0000428 elif sys.argv[index].startswith('-i'):
429 ignore = True
430 index += 1
Johnny Chen38f823c2011-10-11 01:30:27 +0000431 elif sys.argv[index].startswith('-k'):
432 # Increment by 1 to fetch the runhook lldb command.
433 index += 1
434 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
435 usage()
436 runHooks.append(sys.argv[index])
437 index += 1
Johnny Chen41998192010-10-01 22:59:49 +0000438 elif sys.argv[index].startswith('-l'):
439 skipLongRunningTest = False
440 index += 1
Johnny Chen7c52ff12010-09-27 23:29:54 +0000441 elif sys.argv[index].startswith('-p'):
442 # Increment by 1 to fetch the reg exp pattern argument.
443 index += 1
444 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
445 usage()
446 regexp = sys.argv[index]
447 index += 1
Johnny Chen548aefd2010-10-11 22:25:46 +0000448 elif sys.argv[index].startswith('-r'):
449 # Increment by 1 to fetch the relocated directory argument.
450 index += 1
451 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
452 usage()
453 rdir = os.path.abspath(sys.argv[index])
454 if os.path.exists(rdir):
455 print "Relocated directory:", rdir, "must not exist!"
456 usage()
457 index += 1
Johnny Chen125fc2b2010-10-21 16:55:35 +0000458 elif sys.argv[index].startswith('-s'):
459 # Increment by 1 to fetch the session dir name.
460 index += 1
461 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
462 usage()
463 sdir_name = sys.argv[index]
464 index += 1
Johnny Chenaf149a02010-09-16 17:11:30 +0000465 elif sys.argv[index].startswith('-t'):
466 os.environ["LLDB_COMMAND_TRACE"] = "YES"
467 index += 1
468 elif sys.argv[index].startswith('-v'):
469 verbose = 2
470 index += 1
Johnny Chene47649c2010-10-07 02:04:14 +0000471 elif sys.argv[index].startswith('-w'):
472 os.environ["LLDB_WAIT_BETWEEN_TEST_CASES"] = 'YES'
473 index += 1
Johnny Chene00c9302011-10-10 22:03:44 +0000474 elif sys.argv[index].startswith('-x'):
475 # Increment by 1 to fetch the breakpoint specification of the benchmark executable.
476 index += 1
477 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
478 usage()
479 bmBreakpointSpec = sys.argv[index]
480 index += 1
Johnny Chend2acdb32010-11-16 22:42:58 +0000481 elif sys.argv[index].startswith('-#'):
482 # Increment by 1 to fetch the repeat count argument.
483 index += 1
484 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
485 usage()
486 count = int(sys.argv[index])
487 index += 1
Johnny Chenaf149a02010-09-16 17:11:30 +0000488 else:
489 print "Unknown option: ", sys.argv[index]
490 usage()
Johnny Chenaf149a02010-09-16 17:11:30 +0000491
Jim Ingham4f347cb2011-04-13 21:11:41 +0000492 if do_help == True:
493 usage()
494
Johnny Chencc659ad2010-12-10 19:02:23 +0000495 # Do not specify both '-a' and '+a' at the same time.
496 if dont_do_python_api_test and just_do_python_api_test:
497 usage()
498
Johnny Chenaf149a02010-09-16 17:11:30 +0000499 # Gather all the dirs passed on the command line.
500 if len(sys.argv) > index:
501 testdirs = map(os.path.abspath, sys.argv[index:])
502
Johnny Chen548aefd2010-10-11 22:25:46 +0000503 # If '-r dir' is specified, the tests should be run under the relocated
504 # directory. Let's copy the testdirs over.
505 if rdir:
506 from shutil import copytree, ignore_patterns
507
508 tmpdirs = []
509 for srcdir in testdirs:
510 dstdir = os.path.join(rdir, os.path.basename(srcdir))
511 # Don't copy the *.pyc and .svn stuffs.
512 copytree(srcdir, dstdir, ignore=ignore_patterns('*.pyc', '.svn'))
513 tmpdirs.append(dstdir)
514
515 # This will be our modified testdirs.
516 testdirs = tmpdirs
517
518 # With '-r dir' specified, there's no cleanup of intermediate test files.
519 os.environ["LLDB_DO_CLEANUP"] = 'NO'
520
521 # If testdirs is ['test'], the make directory has already been copied
522 # recursively and is contained within the rdir/test dir. For anything
523 # else, we would need to copy over the make directory and its contents,
524 # so that, os.listdir(rdir) looks like, for example:
525 #
526 # array_types conditional_break make
527 #
528 # where the make directory contains the Makefile.rules file.
529 if len(testdirs) != 1 or os.path.basename(testdirs[0]) != 'test':
530 # Don't copy the .svn stuffs.
531 copytree('make', os.path.join(rdir, 'make'),
532 ignore=ignore_patterns('.svn'))
533
534 #print "testdirs:", testdirs
535
Johnny Chenb40056b2010-09-21 00:09:27 +0000536 # Source the configFile if specified.
537 # The side effect, if any, will be felt from this point on. An example
538 # config file may be these simple two lines:
539 #
540 # sys.stderr = open("/tmp/lldbtest-stderr", "w")
541 # sys.stdout = open("/tmp/lldbtest-stdout", "w")
542 #
543 # which will reassign the two file objects to sys.stderr and sys.stdout,
544 # respectively.
545 #
546 # See also lldb-trunk/example/test/usage-config.
547 global config
548 if configFile:
549 # Pass config (a dictionary) as the locals namespace for side-effect.
550 execfile(configFile, globals(), config)
551 #print "config:", config
552 #print "sys.stderr:", sys.stderr
553 #print "sys.stdout:", sys.stdout
554
Johnny Chenaf149a02010-09-16 17:11:30 +0000555
Johnny Chen9707bb62010-06-25 21:14:08 +0000556def setupSysPath():
Johnny Chen8a3c0432011-03-11 20:13:06 +0000557 """
558 Add LLDB.framework/Resources/Python to the search paths for modules.
559 As a side effect, we also discover the 'lldb' executable and export it here.
560 """
Johnny Chen9707bb62010-06-25 21:14:08 +0000561
Johnny Chen548aefd2010-10-11 22:25:46 +0000562 global rdir
563 global testdirs
Johnny Chen50bc6382011-01-29 01:16:52 +0000564 global dumpSysPath
Johnny Chenb5fe80c2011-05-17 22:58:50 +0000565 global svn_info
Johnny Chen548aefd2010-10-11 22:25:46 +0000566
Johnny Chen9707bb62010-06-25 21:14:08 +0000567 # Get the directory containing the current script.
Johnny Chen4d162e52011-08-12 18:54:11 +0000568 if ("DOTEST_PROFILE" in os.environ or "DOTEST_PDB" in os.environ) and "DOTEST_SCRIPT_DIR" in os.environ:
Johnny Chen0de6ab52011-01-19 02:10:40 +0000569 scriptPath = os.environ["DOTEST_SCRIPT_DIR"]
570 else:
571 scriptPath = sys.path[0]
Johnny Chena1affab2010-07-03 03:41:59 +0000572 if not scriptPath.endswith('test'):
Johnny Chen9707bb62010-06-25 21:14:08 +0000573 print "This script expects to reside in lldb's test directory."
574 sys.exit(-1)
575
Johnny Chen548aefd2010-10-11 22:25:46 +0000576 if rdir:
577 # Set up the LLDB_TEST environment variable appropriately, so that the
578 # individual tests can be located relatively.
579 #
580 # See also lldbtest.TestBase.setUpClass(cls).
581 if len(testdirs) == 1 and os.path.basename(testdirs[0]) == 'test':
582 os.environ["LLDB_TEST"] = os.path.join(rdir, 'test')
583 else:
584 os.environ["LLDB_TEST"] = rdir
585 else:
586 os.environ["LLDB_TEST"] = scriptPath
Peter Collingbournef6c3de82011-06-20 19:06:45 +0000587
588 # Set up the LLDB_SRC environment variable, so that the tests can locate
589 # the LLDB source code.
590 os.environ["LLDB_SRC"] = os.path.join(sys.path[0], os.pardir)
591
Johnny Chen9de4ede2010-08-31 17:42:54 +0000592 pluginPath = os.path.join(scriptPath, 'plugins')
Johnny Chen8a3c0432011-03-11 20:13:06 +0000593 pexpectPath = os.path.join(scriptPath, 'pexpect-2.4')
Johnny Chen58f93922010-06-29 23:10:39 +0000594
Johnny Chen8a3c0432011-03-11 20:13:06 +0000595 # Append script dir, plugin dir, and pexpect dir to the sys.path.
Johnny Chenaf149a02010-09-16 17:11:30 +0000596 sys.path.append(scriptPath)
597 sys.path.append(pluginPath)
Johnny Chen8a3c0432011-03-11 20:13:06 +0000598 sys.path.append(pexpectPath)
Johnny Chenaf149a02010-09-16 17:11:30 +0000599
Johnny Chen26901c82011-03-11 19:47:23 +0000600 # This is our base name component.
Johnny Chena1affab2010-07-03 03:41:59 +0000601 base = os.path.abspath(os.path.join(scriptPath, os.pardir))
Johnny Chen6a564a42011-02-15 18:50:19 +0000602
Johnny Chen26901c82011-03-11 19:47:23 +0000603 # These are for xcode build directories.
Johnny Chen6a564a42011-02-15 18:50:19 +0000604 xcode3_build_dir = ['build']
605 xcode4_build_dir = ['build', 'lldb', 'Build', 'Products']
606 dbg = ['Debug']
607 rel = ['Release']
608 bai = ['BuildAndIntegration']
609 python_resource_dir = ['LLDB.framework', 'Resources', 'Python']
Johnny Chen26901c82011-03-11 19:47:23 +0000610
611 # Some of the tests can invoke the 'lldb' command directly.
612 # We'll try to locate the appropriate executable right here.
613
Johnny Chen6033bed2011-08-26 00:00:01 +0000614 # First, you can define an environment variable LLDB_EXEC specifying the
615 # full pathname of the lldb executable.
616 if "LLDB_EXEC" in os.environ and is_exe(os.environ["LLDB_EXEC"]):
617 lldbExec = os.environ["LLDB_EXEC"]
618 else:
619 lldbExec = None
620
Johnny Chen26901c82011-03-11 19:47:23 +0000621 executable = ['lldb']
622 dbgExec = os.path.join(base, *(xcode3_build_dir + dbg + executable))
623 dbgExec2 = os.path.join(base, *(xcode4_build_dir + dbg + executable))
624 relExec = os.path.join(base, *(xcode3_build_dir + rel + executable))
625 relExec2 = os.path.join(base, *(xcode4_build_dir + rel + executable))
626 baiExec = os.path.join(base, *(xcode3_build_dir + bai + executable))
627 baiExec2 = os.path.join(base, *(xcode4_build_dir + bai + executable))
628
Johnny Chen6033bed2011-08-26 00:00:01 +0000629 # The 'lldb' executable built here in the source tree.
630 lldbHere = None
Johnny Chen26901c82011-03-11 19:47:23 +0000631 if is_exe(dbgExec):
Johnny Chen6033bed2011-08-26 00:00:01 +0000632 lldbHere = dbgExec
Johnny Chen26901c82011-03-11 19:47:23 +0000633 elif is_exe(dbgExec2):
Johnny Chen6033bed2011-08-26 00:00:01 +0000634 lldbHere = dbgExec2
Johnny Chen26901c82011-03-11 19:47:23 +0000635 elif is_exe(relExec):
Johnny Chen6033bed2011-08-26 00:00:01 +0000636 lldbHere = relExec
Johnny Chen26901c82011-03-11 19:47:23 +0000637 elif is_exe(relExec2):
Johnny Chen6033bed2011-08-26 00:00:01 +0000638 lldbHere = relExec2
Johnny Chen26901c82011-03-11 19:47:23 +0000639 elif is_exe(baiExec):
Johnny Chen6033bed2011-08-26 00:00:01 +0000640 lldbHere = baiExec
Johnny Chen26901c82011-03-11 19:47:23 +0000641 elif is_exe(baiExec2):
Johnny Chen6033bed2011-08-26 00:00:01 +0000642 lldbHere = baiExec2
Johnny Chen26901c82011-03-11 19:47:23 +0000643
Johnny Chen6033bed2011-08-26 00:00:01 +0000644 if lldbHere:
645 os.environ["LLDB_HERE"] = lldbHere
646 if not lldbExec:
647 lldbExec = lldbHere
Johnny Chen62d527e2011-08-04 18:17:16 +0000648 os.environ["LLDB_BUILD_DIR"] = os.path.split(lldbExec)[0]
Johnny Chen6a4e0872011-09-16 17:50:44 +0000649 print "LLDB build dir:", os.environ["LLDB_BUILD_DIR"]
Johnny Chen62d527e2011-08-04 18:17:16 +0000650
Johnny Chen6033bed2011-08-26 00:00:01 +0000651 # One last chance to locate the 'lldb' executable.
Johnny Chen26901c82011-03-11 19:47:23 +0000652 if not lldbExec:
Johnny Chen6033bed2011-08-26 00:00:01 +0000653 if lldbHere:
654 lldbExec = lldbHere
655 else:
656 lldbExec = which('lldb')
Johnny Chen26901c82011-03-11 19:47:23 +0000657
658 if not lldbExec:
659 print "The 'lldb' executable cannot be located. Some of the tests may not be run as a result."
660 else:
661 os.environ["LLDB_EXEC"] = lldbExec
Johnny Chend7931462011-03-17 00:38:22 +0000662 #print "The 'lldb' executable path is", lldbExec
663 os.system('%s -v' % lldbExec)
664
Johnny Chenb264c9b2011-06-24 22:52:05 +0000665 if os.path.isdir(os.path.join(base, '.svn')):
666 pipe = subprocess.Popen(["svn", "info", base], stdout = subprocess.PIPE)
667 svn_info = pipe.stdout.read()
668 elif os.path.isdir(os.path.join(base, '.git')):
669 pipe = subprocess.Popen(["git", "svn", "info", base], stdout = subprocess.PIPE)
670 svn_info = pipe.stdout.read()
Johnny Chenb5fe80c2011-05-17 22:58:50 +0000671 print svn_info
Johnny Chen26901c82011-03-11 19:47:23 +0000672
673 global ignore
674
675 # The '-i' option is used to skip looking for lldb.py in the build tree.
676 if ignore:
677 return
678
Johnny Chen6a564a42011-02-15 18:50:19 +0000679 dbgPath = os.path.join(base, *(xcode3_build_dir + dbg + python_resource_dir))
680 dbgPath2 = os.path.join(base, *(xcode4_build_dir + dbg + python_resource_dir))
681 relPath = os.path.join(base, *(xcode3_build_dir + rel + python_resource_dir))
682 relPath2 = os.path.join(base, *(xcode4_build_dir + rel + python_resource_dir))
683 baiPath = os.path.join(base, *(xcode3_build_dir + bai + python_resource_dir))
684 baiPath2 = os.path.join(base, *(xcode4_build_dir + bai + python_resource_dir))
Johnny Chen9707bb62010-06-25 21:14:08 +0000685
686 lldbPath = None
687 if os.path.isfile(os.path.join(dbgPath, 'lldb.py')):
688 lldbPath = dbgPath
Greg Claytond9846b02011-02-14 21:17:06 +0000689 elif os.path.isfile(os.path.join(dbgPath2, 'lldb.py')):
690 lldbPath = dbgPath2
Johnny Chen9707bb62010-06-25 21:14:08 +0000691 elif os.path.isfile(os.path.join(relPath, 'lldb.py')):
692 lldbPath = relPath
Greg Claytond9846b02011-02-14 21:17:06 +0000693 elif os.path.isfile(os.path.join(relPath2, 'lldb.py')):
694 lldbPath = relPath2
Johnny Chenc202c462010-09-15 18:11:19 +0000695 elif os.path.isfile(os.path.join(baiPath, 'lldb.py')):
696 lldbPath = baiPath
Greg Claytond9846b02011-02-14 21:17:06 +0000697 elif os.path.isfile(os.path.join(baiPath2, 'lldb.py')):
698 lldbPath = baiPath2
Johnny Chen9707bb62010-06-25 21:14:08 +0000699
700 if not lldbPath:
Johnny Chenc202c462010-09-15 18:11:19 +0000701 print 'This script requires lldb.py to be in either ' + dbgPath + ',',
702 print relPath + ', or ' + baiPath
Johnny Chen9707bb62010-06-25 21:14:08 +0000703 sys.exit(-1)
704
Johnny Chenaf149a02010-09-16 17:11:30 +0000705 # This is to locate the lldb.py module. Insert it right after sys.path[0].
706 sys.path[1:1] = [lldbPath]
Johnny Chen50bc6382011-01-29 01:16:52 +0000707 if dumpSysPath:
708 print "sys.path:", sys.path
Johnny Chen9707bb62010-06-25 21:14:08 +0000709
Johnny Chen9707bb62010-06-25 21:14:08 +0000710
Johnny Chencd0279d2010-09-20 18:07:50 +0000711def doDelay(delta):
712 """Delaying startup for delta-seconds to facilitate debugger attachment."""
713 def alarm_handler(*args):
714 raise Exception("timeout")
715
716 signal.signal(signal.SIGALRM, alarm_handler)
717 signal.alarm(delta)
718 sys.stdout.write("pid=%d\n" % os.getpid())
719 sys.stdout.write("Enter RET to proceed (or timeout after %d seconds):" %
720 delta)
721 sys.stdout.flush()
722 try:
723 text = sys.stdin.readline()
724 except:
725 text = ""
726 signal.alarm(0)
727 sys.stdout.write("proceeding...\n")
728 pass
729
730
Johnny Chen9707bb62010-06-25 21:14:08 +0000731def visit(prefix, dir, names):
732 """Visitor function for os.path.walk(path, visit, arg)."""
733
734 global suite
Johnny Chen7c52ff12010-09-27 23:29:54 +0000735 global regexp
Johnny Chenc5fa0052011-07-29 22:54:56 +0000736 global filters
Johnny Chenb62436b2010-10-06 20:40:56 +0000737 global fs4all
Johnny Chen9707bb62010-06-25 21:14:08 +0000738
739 for name in names:
740 if os.path.isdir(os.path.join(dir, name)):
741 continue
742
743 if '.py' == os.path.splitext(name)[1] and name.startswith(prefix):
Johnny Chen7c52ff12010-09-27 23:29:54 +0000744 # Try to match the regexp pattern, if specified.
745 if regexp:
746 import re
747 if re.search(regexp, name):
748 #print "Filename: '%s' matches pattern: '%s'" % (name, regexp)
749 pass
750 else:
751 #print "Filename: '%s' does not match pattern: '%s'" % (name, regexp)
752 continue
753
Johnny Chen953864a2010-10-12 21:35:54 +0000754 # We found a match for our test. Add it to the suite.
Johnny Chen79723352010-10-12 15:53:22 +0000755
756 # Update the sys.path first.
Johnny Chena85d7ee2010-06-26 00:19:32 +0000757 if not sys.path.count(dir):
Johnny Chen548aefd2010-10-11 22:25:46 +0000758 sys.path.insert(0, dir)
Johnny Chen9707bb62010-06-25 21:14:08 +0000759 base = os.path.splitext(name)[0]
Johnny Chenb62436b2010-10-06 20:40:56 +0000760
761 # Thoroughly check the filterspec against the base module and admit
762 # the (base, filterspec) combination only when it makes sense.
Johnny Chenc5fa0052011-07-29 22:54:56 +0000763 filterspec = None
764 for filterspec in filters:
Johnny Chenb62436b2010-10-06 20:40:56 +0000765 # Optimistically set the flag to True.
766 filtered = True
767 module = __import__(base)
768 parts = filterspec.split('.')
769 obj = module
770 for part in parts:
771 try:
772 parent, obj = obj, getattr(obj, part)
773 except AttributeError:
774 # The filterspec has failed.
775 filtered = False
776 break
Johnny Chenc5fa0052011-07-29 22:54:56 +0000777
Johnny Chendb4be602011-08-12 23:55:07 +0000778 # If filtered, we have a good filterspec. Add it.
Johnny Chenc5fa0052011-07-29 22:54:56 +0000779 if filtered:
Johnny Chendb4be602011-08-12 23:55:07 +0000780 #print "adding filter spec %s to module %s" % (filterspec, module)
781 suite.addTests(
782 unittest2.defaultTestLoader.loadTestsFromName(filterspec, module))
783 continue
Johnny Chenc5fa0052011-07-29 22:54:56 +0000784
785 # Forgo this module if the (base, filterspec) combo is invalid
786 # and no '-g' option is specified
787 if filters and fs4all and not filtered:
788 continue
Johnny Chenb62436b2010-10-06 20:40:56 +0000789
Johnny Chendb4be602011-08-12 23:55:07 +0000790 # Add either the filtered test case(s) (which is done before) or the entire test class.
791 if not filterspec or not filtered:
Johnny Chenb62436b2010-10-06 20:40:56 +0000792 # A simple case of just the module name. Also the failover case
793 # from the filterspec branch when the (base, filterspec) combo
794 # doesn't make sense.
795 suite.addTests(unittest2.defaultTestLoader.loadTestsFromName(base))
Johnny Chen9707bb62010-06-25 21:14:08 +0000796
797
Johnny Chencd0279d2010-09-20 18:07:50 +0000798def lldbLoggings():
799 """Check and do lldb loggings if necessary."""
800
801 # Turn on logging for debugging purposes if ${LLDB_LOG} environment variable is
802 # defined. Use ${LLDB_LOG} to specify the log file.
803 ci = lldb.DBG.GetCommandInterpreter()
804 res = lldb.SBCommandReturnObject()
805 if ("LLDB_LOG" in os.environ):
806 if ("LLDB_LOG_OPTION" in os.environ):
807 lldb_log_option = os.environ["LLDB_LOG_OPTION"]
808 else:
Johnny Chen8fd886c2010-12-08 01:25:21 +0000809 lldb_log_option = "event process expr state api"
Johnny Chencd0279d2010-09-20 18:07:50 +0000810 ci.HandleCommand(
Greg Clayton940b1032011-02-23 00:35:02 +0000811 "log enable -n -f " + os.environ["LLDB_LOG"] + " lldb " + lldb_log_option,
Johnny Chencd0279d2010-09-20 18:07:50 +0000812 res)
813 if not res.Succeeded():
814 raise Exception('log enable failed (check LLDB_LOG env variable.')
815 # Ditto for gdb-remote logging if ${GDB_REMOTE_LOG} environment variable is defined.
816 # Use ${GDB_REMOTE_LOG} to specify the log file.
817 if ("GDB_REMOTE_LOG" in os.environ):
818 if ("GDB_REMOTE_LOG_OPTION" in os.environ):
819 gdb_remote_log_option = os.environ["GDB_REMOTE_LOG_OPTION"]
820 else:
Johnny Chen7ab8c852010-12-02 18:35:13 +0000821 gdb_remote_log_option = "packets process"
Johnny Chencd0279d2010-09-20 18:07:50 +0000822 ci.HandleCommand(
Johnny Chenc935a892011-06-21 19:25:45 +0000823 "log enable -n -f " + os.environ["GDB_REMOTE_LOG"] + " gdb-remote "
Johnny Chencd0279d2010-09-20 18:07:50 +0000824 + gdb_remote_log_option,
825 res)
826 if not res.Succeeded():
827 raise Exception('log enable failed (check GDB_REMOTE_LOG env variable.')
828
Johnny Chen067022b2011-01-19 19:31:46 +0000829def getMyCommandLine():
Johnny Chen067022b2011-01-19 19:31:46 +0000830 ps = subprocess.Popen(['ps', '-o', "command=CMD", str(os.getpid())], stdout=subprocess.PIPE).communicate()[0]
831 lines = ps.split('\n')
832 cmd_line = lines[1]
833 return cmd_line
Johnny Chencd0279d2010-09-20 18:07:50 +0000834
Johnny Chend96b5682010-11-05 17:30:53 +0000835# ======================================== #
Johnny Chencd0279d2010-09-20 18:07:50 +0000836# #
837# Execution of the test driver starts here #
838# #
Johnny Chend96b5682010-11-05 17:30:53 +0000839# ======================================== #
Johnny Chencd0279d2010-09-20 18:07:50 +0000840
Johnny Chen2891bb02011-09-16 01:04:26 +0000841def checkDsymForUUIDIsNotOn():
Johnny Chen6a4e0872011-09-16 17:50:44 +0000842 cmd = ["defaults", "read", "com.apple.DebugSymbols"]
843 pipe = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
844 cmd_output = pipe.stdout.read()
Johnny Chen178c8d92011-09-16 18:03:19 +0000845 if cmd_output and "DBGFileMappedPaths = " in cmd_output:
Johnny Chen6a451482011-09-16 18:09:45 +0000846 print "%s =>" % ' '.join(cmd)
Johnny Chen6a4e0872011-09-16 17:50:44 +0000847 print cmd_output
Johnny Chen2891bb02011-09-16 01:04:26 +0000848 print "Disable automatic lookup and caching of dSYMs before running the test suite!"
849 print "Exiting..."
850 sys.exit(0)
851
852# On MacOS X, check to make sure that domain for com.apple.DebugSymbols defaults
853# does not exist before proceeding to running the test suite.
854if sys.platform.startswith("darwin"):
855 checkDsymForUUIDIsNotOn()
856
Johnny Chen9707bb62010-06-25 21:14:08 +0000857#
Johnny Chenaf149a02010-09-16 17:11:30 +0000858# Start the actions by first parsing the options while setting up the test
859# directories, followed by setting up the search paths for lldb utilities;
860# then, we walk the directory trees and collect the tests into our test suite.
Johnny Chen9707bb62010-06-25 21:14:08 +0000861#
Johnny Chenaf149a02010-09-16 17:11:30 +0000862parseOptionsAndInitTestdirs()
Johnny Chen9707bb62010-06-25 21:14:08 +0000863setupSysPath()
Johnny Chen91960d32010-09-08 20:56:16 +0000864
865#
866# If '-d' is specified, do a delay of 10 seconds for the debugger to attach.
867#
868if delay:
Johnny Chencd0279d2010-09-20 18:07:50 +0000869 doDelay(10)
Johnny Chen91960d32010-09-08 20:56:16 +0000870
Johnny Chen49f2f7a2010-09-20 17:25:45 +0000871#
Johnny Chen41998192010-10-01 22:59:49 +0000872# If '-l' is specified, do not skip the long running tests.
873if not skipLongRunningTest:
874 os.environ["LLDB_SKIP_LONG_RUNNING_TEST"] = "NO"
875
876#
Johnny Chen79723352010-10-12 15:53:22 +0000877# Walk through the testdirs while collecting tests.
Johnny Chen49f2f7a2010-09-20 17:25:45 +0000878#
Johnny Chen9707bb62010-06-25 21:14:08 +0000879for testdir in testdirs:
880 os.path.walk(testdir, visit, 'Test')
881
Johnny Chenb40056b2010-09-21 00:09:27 +0000882#
Johnny Chen9707bb62010-06-25 21:14:08 +0000883# Now that we have loaded all the test cases, run the whole test suite.
Johnny Chenb40056b2010-09-21 00:09:27 +0000884#
Johnny Chencd0279d2010-09-20 18:07:50 +0000885
Johnny Chen1bfbd412010-06-29 19:44:16 +0000886# For the time being, let's bracket the test runner within the
887# lldb.SBDebugger.Initialize()/Terminate() pair.
Johnny Chen01f2a6a2010-08-10 20:23:55 +0000888import lldb, atexit
Johnny Chen6b6f5ba2010-10-14 16:36:49 +0000889# Update: the act of importing lldb now executes lldb.SBDebugger.Initialize(),
890# there's no need to call it a second time.
891#lldb.SBDebugger.Initialize()
Johnny Chen01f2a6a2010-08-10 20:23:55 +0000892atexit.register(lambda: lldb.SBDebugger.Terminate())
Johnny Chen1bfbd412010-06-29 19:44:16 +0000893
Johnny Chen909e5a62010-07-01 22:52:57 +0000894# Create a singleton SBDebugger in the lldb namespace.
895lldb.DBG = lldb.SBDebugger.Create()
896
Johnny Chen4f93bf12010-12-10 00:51:23 +0000897# Put the blacklist in the lldb namespace, to be used by lldb.TestBase.
Johnny Chen82e6b1e2010-12-01 22:47:54 +0000898lldb.blacklist = blacklist
899
Johnny Chene00c9302011-10-10 22:03:44 +0000900# Put dont/just_do_python_api_test in the lldb namespace.
Johnny Chen4f93bf12010-12-10 00:51:23 +0000901lldb.dont_do_python_api_test = dont_do_python_api_test
902lldb.just_do_python_api_test = just_do_python_api_test
Johnny Chen82ccf402011-07-30 01:39:58 +0000903lldb.just_do_benchmarks_test = just_do_benchmarks_test
Johnny Chen4f93bf12010-12-10 00:51:23 +0000904
Johnny Chene00c9302011-10-10 22:03:44 +0000905# Put bmExecutable and bmBreakpointSpec into the lldb namespace, too.
906lldb.bmExecutable = bmExecutable
907lldb.bmBreakpointSpec = bmBreakpointSpec
908
Johnny Chen38f823c2011-10-11 01:30:27 +0000909# And don't forget the runHooks!
910lldb.runHooks = runHooks
911
Johnny Chencd0279d2010-09-20 18:07:50 +0000912# Turn on lldb loggings if necessary.
913lldbLoggings()
Johnny Chen909e5a62010-07-01 22:52:57 +0000914
Johnny Chen7987ac92010-08-09 20:40:52 +0000915# Install the control-c handler.
916unittest2.signals.installHandler()
917
Johnny Chen125fc2b2010-10-21 16:55:35 +0000918# If sdir_name is not specified through the '-s sdir_name' option, get a
919# timestamp string and export it as LLDB_SESSION_DIR environment var. This will
920# be used when/if we want to dump the session info of individual test cases
921# later on.
Johnny Chence681462010-10-19 00:25:01 +0000922#
923# See also TestBase.dumpSessionInfo() in lldbtest.py.
Johnny Chen125fc2b2010-10-21 16:55:35 +0000924if not sdir_name:
925 import datetime
Johnny Chen41fae812010-10-29 22:26:38 +0000926 # The windows platforms don't like ':' in the pathname.
Johnny Chen76bd0102010-10-28 16:32:13 +0000927 timestamp = datetime.datetime.now().strftime("%Y-%m-%d-%H_%M_%S")
Johnny Chen125fc2b2010-10-21 16:55:35 +0000928 sdir_name = timestamp
Peter Collingbourne132476f2011-06-20 23:55:53 +0000929os.environ["LLDB_SESSION_DIRNAME"] = os.path.join(os.getcwd(), sdir_name)
Johnny Chen067022b2011-01-19 19:31:46 +0000930
Johnny Chenab2f0662011-05-06 20:30:22 +0000931sys.stderr.write("\nSession logs for test failures/errors/unexpected successes"
932 " will go into directory '%s'\n" % sdir_name)
Johnny Chen067022b2011-01-19 19:31:46 +0000933sys.stderr.write("Command invoked: %s\n" % getMyCommandLine())
Johnny Chence681462010-10-19 00:25:01 +0000934
Johnny Chenb5fe80c2011-05-17 22:58:50 +0000935if not os.path.isdir(sdir_name):
936 os.mkdir(sdir_name)
937fname = os.path.join(sdir_name, "svn-info")
938with open(fname, "w") as f:
939 print >> f, svn_info
940 print >> f, "Command invoked: %s\n" % getMyCommandLine()
941
Johnny Chenb40056b2010-09-21 00:09:27 +0000942#
943# Invoke the default TextTestRunner to run the test suite, possibly iterating
944# over different configurations.
945#
946
Johnny Chenb40056b2010-09-21 00:09:27 +0000947iterArchs = False
Johnny Chenf032d902010-09-21 00:16:09 +0000948iterCompilers = False
Johnny Chenb40056b2010-09-21 00:09:27 +0000949
Johnny Chen1a4d5e72011-03-04 01:35:22 +0000950if not archs and "archs" in config:
Johnny Chenb40056b2010-09-21 00:09:27 +0000951 archs = config["archs"]
Johnny Chen1a4d5e72011-03-04 01:35:22 +0000952
953if isinstance(archs, list) and len(archs) >= 1:
954 iterArchs = True
955
956if not compilers and "compilers" in config:
Johnny Chenb40056b2010-09-21 00:09:27 +0000957 compilers = config["compilers"]
Johnny Chen1a4d5e72011-03-04 01:35:22 +0000958
959if isinstance(compilers, list) and len(compilers) >= 1:
960 iterCompilers = True
Johnny Chenb40056b2010-09-21 00:09:27 +0000961
Johnny Chen953864a2010-10-12 21:35:54 +0000962# Make a shallow copy of sys.path, we need to manipulate the search paths later.
963# This is only necessary if we are relocated and with different configurations.
Johnny Chen1a4d5e72011-03-04 01:35:22 +0000964if rdir:
Johnny Chen953864a2010-10-12 21:35:54 +0000965 old_sys_path = sys.path[:]
Johnny Chen1a4d5e72011-03-04 01:35:22 +0000966# If we iterate on archs or compilers, there is a chance we want to split stderr/stdout.
967if iterArchs or iterCompilers:
Johnny Chen953864a2010-10-12 21:35:54 +0000968 old_stderr = sys.stderr
969 old_stdout = sys.stdout
970 new_stderr = None
971 new_stdout = None
972
Johnny Chend96b5682010-11-05 17:30:53 +0000973# Iterating over all possible architecture and compiler combinations.
Johnny Chenb40056b2010-09-21 00:09:27 +0000974for ia in range(len(archs) if iterArchs else 1):
975 archConfig = ""
976 if iterArchs:
Johnny Chen18a921f2010-09-30 17:11:58 +0000977 os.environ["ARCH"] = archs[ia]
Johnny Chenb40056b2010-09-21 00:09:27 +0000978 archConfig = "arch=%s" % archs[ia]
979 for ic in range(len(compilers) if iterCompilers else 1):
980 if iterCompilers:
Johnny Chen18a921f2010-09-30 17:11:58 +0000981 os.environ["CC"] = compilers[ic]
Johnny Chenb40056b2010-09-21 00:09:27 +0000982 configString = "%s compiler=%s" % (archConfig, compilers[ic])
983 else:
984 configString = archConfig
985
Johnny Chenb40056b2010-09-21 00:09:27 +0000986 if iterArchs or iterCompilers:
Johnny Chen1a4d5e72011-03-04 01:35:22 +0000987 # Translate ' ' to '-' for pathname component.
988 from string import maketrans
989 tbl = maketrans(' ', '-')
990 configPostfix = configString.translate(tbl)
991
992 # Check whether we need to split stderr/stdout into configuration
993 # specific files.
994 if old_stderr.name != '<stderr>' and config.get('split_stderr'):
995 if new_stderr:
996 new_stderr.close()
997 new_stderr = open("%s.%s" % (old_stderr.name, configPostfix), "w")
998 sys.stderr = new_stderr
999 if old_stdout.name != '<stdout>' and config.get('split_stdout'):
1000 if new_stdout:
1001 new_stdout.close()
1002 new_stdout = open("%s.%s" % (old_stdout.name, configPostfix), "w")
1003 sys.stdout = new_stdout
1004
Johnny Chen953864a2010-10-12 21:35:54 +00001005 # If we specified a relocated directory to run the test suite, do
1006 # the extra housekeeping to copy the testdirs to a configStringified
1007 # directory and to update sys.path before invoking the test runner.
1008 # The purpose is to separate the configuration-specific directories
1009 # from each other.
1010 if rdir:
Johnny Chen953864a2010-10-12 21:35:54 +00001011 from shutil import copytree, ignore_patterns
1012
Johnny Chen953864a2010-10-12 21:35:54 +00001013 newrdir = "%s.%s" % (rdir, configPostfix)
1014
1015 # Copy the tree to a new directory with postfix name configPostfix.
1016 copytree(rdir, newrdir, ignore=ignore_patterns('*.pyc', '*.o', '*.d'))
1017
Johnny Chen1a4d5e72011-03-04 01:35:22 +00001018 # Update the LLDB_TEST environment variable to reflect new top
Johnny Chen953864a2010-10-12 21:35:54 +00001019 # level test directory.
1020 #
1021 # See also lldbtest.TestBase.setUpClass(cls).
1022 if len(testdirs) == 1 and os.path.basename(testdirs[0]) == 'test':
1023 os.environ["LLDB_TEST"] = os.path.join(newrdir, 'test')
1024 else:
1025 os.environ["LLDB_TEST"] = newrdir
1026
1027 # And update the Python search paths for modules.
1028 sys.path = [x.replace(rdir, newrdir, 1) for x in old_sys_path]
1029
1030 # Output the configuration.
Johnny Chenb40056b2010-09-21 00:09:27 +00001031 sys.stderr.write("\nConfiguration: " + configString + "\n")
Johnny Chen953864a2010-10-12 21:35:54 +00001032
1033 #print "sys.stderr name is", sys.stderr.name
1034 #print "sys.stdout name is", sys.stdout.name
1035
1036 # First, write out the number of collected test cases.
1037 sys.stderr.write(separator + "\n")
1038 sys.stderr.write("Collected %d test%s\n\n"
1039 % (suite.countTestCases(),
1040 suite.countTestCases() != 1 and "s" or ""))
1041
Johnny Chen84a6d6f2010-10-15 01:18:29 +00001042 class LLDBTestResult(unittest2.TextTestResult):
1043 """
Johnny Chen26be4532010-11-09 23:56:14 +00001044 Enforce a singleton pattern to allow introspection of test progress.
1045
1046 Overwrite addError(), addFailure(), and addExpectedFailure() methods
1047 to enable each test instance to track its failure/error status. It
1048 is used in the LLDB test framework to emit detailed trace messages
1049 to a log file for easier human inspection of test failres/errors.
Johnny Chen84a6d6f2010-10-15 01:18:29 +00001050 """
1051 __singleton__ = None
Johnny Chen360dd372010-11-29 17:50:10 +00001052 __ignore_singleton__ = False
Johnny Chen84a6d6f2010-10-15 01:18:29 +00001053
1054 def __init__(self, *args):
Johnny Chen360dd372010-11-29 17:50:10 +00001055 if not LLDBTestResult.__ignore_singleton__ and LLDBTestResult.__singleton__:
Johnny Chend2acdb32010-11-16 22:42:58 +00001056 raise Exception("LLDBTestResult instantiated more than once")
Johnny Chen84a6d6f2010-10-15 01:18:29 +00001057 super(LLDBTestResult, self).__init__(*args)
1058 LLDBTestResult.__singleton__ = self
1059 # Now put this singleton into the lldb module namespace.
1060 lldb.test_result = self
Johnny Chen810042e2011-01-05 20:24:11 +00001061 # Computes the format string for displaying the counter.
1062 global suite
1063 counterWidth = len(str(suite.countTestCases()))
1064 self.fmt = "%" + str(counterWidth) + "d: "
Johnny Chenc87fd492011-01-05 22:50:11 +00001065 self.indentation = ' ' * (counterWidth + 2)
Johnny Chen810042e2011-01-05 20:24:11 +00001066 # This counts from 1 .. suite.countTestCases().
1067 self.counter = 0
1068
Johnny Chenc87fd492011-01-05 22:50:11 +00001069 def getDescription(self, test):
1070 doc_first_line = test.shortDescription()
1071 if self.descriptions and doc_first_line:
1072 return '\n'.join((str(test), self.indentation + doc_first_line))
1073 else:
1074 return str(test)
1075
Johnny Chen810042e2011-01-05 20:24:11 +00001076 def startTest(self, test):
1077 self.counter += 1
1078 if self.showAll:
1079 self.stream.write(self.fmt % self.counter)
1080 super(LLDBTestResult, self).startTest(test)
Johnny Chen84a6d6f2010-10-15 01:18:29 +00001081
Johnny Chence681462010-10-19 00:25:01 +00001082 def addError(self, test, err):
Johnny Chen63c2cba2010-10-29 22:20:36 +00001083 global sdir_has_content
1084 sdir_has_content = True
Johnny Chence681462010-10-19 00:25:01 +00001085 super(LLDBTestResult, self).addError(test, err)
1086 method = getattr(test, "markError", None)
1087 if method:
1088 method()
1089
Johnny Chen84a6d6f2010-10-15 01:18:29 +00001090 def addFailure(self, test, err):
Johnny Chen63c2cba2010-10-29 22:20:36 +00001091 global sdir_has_content
1092 sdir_has_content = True
Johnny Chen84a6d6f2010-10-15 01:18:29 +00001093 super(LLDBTestResult, self).addFailure(test, err)
1094 method = getattr(test, "markFailure", None)
1095 if method:
1096 method()
Johnny Chen84a6d6f2010-10-15 01:18:29 +00001097
Johnny Chendd2bb2c2010-11-03 18:17:03 +00001098 def addExpectedFailure(self, test, err):
1099 global sdir_has_content
1100 sdir_has_content = True
1101 super(LLDBTestResult, self).addExpectedFailure(test, err)
1102 method = getattr(test, "markExpectedFailure", None)
1103 if method:
1104 method()
1105
Johnny Chenf5b89092011-08-15 23:09:08 +00001106 def addSkip(self, test, reason):
1107 global sdir_has_content
1108 sdir_has_content = True
1109 super(LLDBTestResult, self).addSkip(test, reason)
1110 method = getattr(test, "markSkippedTest", None)
1111 if method:
1112 method()
1113
Johnny Chenab2f0662011-05-06 20:30:22 +00001114 def addUnexpectedSuccess(self, test):
1115 global sdir_has_content
1116 sdir_has_content = True
1117 super(LLDBTestResult, self).addUnexpectedSuccess(test)
1118 method = getattr(test, "markUnexpectedSuccess", None)
1119 if method:
1120 method()
1121
Johnny Chen26be4532010-11-09 23:56:14 +00001122 # Invoke the test runner.
Johnny Chend2acdb32010-11-16 22:42:58 +00001123 if count == 1:
Johnny Chen7d6d8442010-12-03 19:59:35 +00001124 result = unittest2.TextTestRunner(stream=sys.stderr,
1125 verbosity=verbose,
1126 failfast=failfast,
Johnny Chend2acdb32010-11-16 22:42:58 +00001127 resultclass=LLDBTestResult).run(suite)
1128 else:
Johnny Chend6e7ca22010-11-29 17:52:43 +00001129 # We are invoking the same test suite more than once. In this case,
1130 # mark __ignore_singleton__ flag as True so the signleton pattern is
1131 # not enforced.
Johnny Chen360dd372010-11-29 17:50:10 +00001132 LLDBTestResult.__ignore_singleton__ = True
Johnny Chend2acdb32010-11-16 22:42:58 +00001133 for i in range(count):
Johnny Chen7d6d8442010-12-03 19:59:35 +00001134 result = unittest2.TextTestRunner(stream=sys.stderr,
1135 verbosity=verbose,
1136 failfast=failfast,
Johnny Chen360dd372010-11-29 17:50:10 +00001137 resultclass=LLDBTestResult).run(suite)
Johnny Chenb40056b2010-09-21 00:09:27 +00001138
Johnny Chen1bfbd412010-06-29 19:44:16 +00001139
Johnny Chen63c2cba2010-10-29 22:20:36 +00001140if sdir_has_content:
Johnny Chenab2f0662011-05-06 20:30:22 +00001141 sys.stderr.write("Session logs for test failures/errors/unexpected successes"
1142 " can be found in directory '%s'\n" % sdir_name)
Johnny Chen63c2cba2010-10-29 22:20:36 +00001143
Johnny Chencd0279d2010-09-20 18:07:50 +00001144# Terminate the test suite if ${LLDB_TESTSUITE_FORCE_FINISH} is defined.
1145# This should not be necessary now.
Johnny Chen83f6e512010-08-13 22:58:44 +00001146if ("LLDB_TESTSUITE_FORCE_FINISH" in os.environ):
Johnny Chen83f6e512010-08-13 22:58:44 +00001147 print "Terminating Test suite..."
1148 subprocess.Popen(["/bin/sh", "-c", "kill %s; exit 0" % (os.getpid())])
1149
Johnny Chen01f2a6a2010-08-10 20:23:55 +00001150# Exiting.
1151sys.exit(not result.wasSuccessful)