blob: 14c0017b2312a72f83e77530bfca3b944c7a206b [file] [log] [blame]
Johnny Chen9707bb62010-06-25 21:14:08 +00001#!/usr/bin/env python
2
3"""
4A simple testing framework for lldb using python's unit testing framework.
5
6Tests for lldb are written as python scripts which take advantage of the script
7bridging provided by LLDB.framework to interact with lldb core.
8
9A specific naming pattern is followed by the .py script to be recognized as
10a module which implements a test scenario, namely, Test*.py.
11
12To specify the directories where "Test*.py" python test scripts are located,
13you need to pass in a list of directory names. By default, the current
14working directory is searched if nothing is specified on the command line.
Johnny Chen872aee12010-09-16 15:44:23 +000015
16Type:
17
18./dotest.py -h
19
20for available options.
Johnny Chen9707bb62010-06-25 21:14:08 +000021"""
22
Johnny Chen91960d32010-09-08 20:56:16 +000023import os, signal, sys, time
Johnny Chen75e28f92010-08-05 23:42:46 +000024import unittest2
Johnny Chen9707bb62010-06-25 21:14:08 +000025
Johnny Chen877c7e42010-08-07 00:16:07 +000026class _WritelnDecorator(object):
27 """Used to decorate file-like objects with a handy 'writeln' method"""
28 def __init__(self,stream):
29 self.stream = stream
30
31 def __getattr__(self, attr):
32 if attr in ('stream', '__getstate__'):
33 raise AttributeError(attr)
34 return getattr(self.stream,attr)
35
36 def writeln(self, arg=None):
37 if arg:
38 self.write(arg)
39 self.write('\n') # text-mode streams translate to \r\n if needed
40
Johnny Chen9707bb62010-06-25 21:14:08 +000041#
42# Global variables:
43#
44
45# The test suite.
Johnny Chen75e28f92010-08-05 23:42:46 +000046suite = unittest2.TestSuite()
Johnny Chen9707bb62010-06-25 21:14:08 +000047
Johnny Chen4f93bf12010-12-10 00:51:23 +000048# By default, both command line and Python API tests are performed.
Johnny Chen3ebdacc2010-12-10 18:52:10 +000049# Use @python_api_test decorator, defined in lldbtest.py, to mark a test as
50# a Python API test.
Johnny Chen4f93bf12010-12-10 00:51:23 +000051dont_do_python_api_test = False
52
53# By default, both command line and Python API tests are performed.
Johnny Chen4f93bf12010-12-10 00:51:23 +000054just_do_python_api_test = False
55
Johnny Chen82e6b1e2010-12-01 22:47:54 +000056# The blacklist is optional (-b blacklistFile) and allows a central place to skip
57# testclass's and/or testclass.testmethod's.
58blacklist = None
59
60# The dictionary as a result of sourcing blacklistFile.
61blacklistConfig = {}
62
Johnny Chen9fdb0a92010-09-18 00:16:47 +000063# The config file is optional.
64configFile = None
65
Johnny Chend2acdb32010-11-16 22:42:58 +000066# Test suite repeat count. Can be overwritten with '-# count'.
67count = 1
68
Johnny Chenb40056b2010-09-21 00:09:27 +000069# The dictionary as a result of sourcing configFile.
70config = {}
71
Johnny Chen91960d32010-09-08 20:56:16 +000072# Delay startup in order for the debugger to attach.
73delay = False
74
Johnny Chen7d6d8442010-12-03 19:59:35 +000075# By default, failfast is False. Use '-F' to overwrite it.
76failfast = False
77
Johnny Chena224cd12010-11-08 01:21:03 +000078# The filter (testclass.testmethod) used to admit tests into our test suite.
Johnny Chenb62436b2010-10-06 20:40:56 +000079filterspec = None
80
Johnny Chena224cd12010-11-08 01:21:03 +000081# If '-g' is specified, the filterspec is not exclusive. If a test module does
82# not contain testclass.testmethod which matches the filterspec, the whole test
83# module is still admitted into our test suite. fs4all flag defaults to True.
84fs4all = True
Johnny Chenb62436b2010-10-06 20:40:56 +000085
Johnny Chenaf149a02010-09-16 17:11:30 +000086# Ignore the build search path relative to this script to locate the lldb.py module.
87ignore = False
88
Johnny Chen548aefd2010-10-11 22:25:46 +000089# By default, we skip long running test case. Use '-l' option to override.
Johnny Chen41998192010-10-01 22:59:49 +000090skipLongRunningTest = True
91
Johnny Chen7c52ff12010-09-27 23:29:54 +000092# The regular expression pattern to match against eligible filenames as our test cases.
93regexp = None
94
Johnny Chen548aefd2010-10-11 22:25:46 +000095# By default, tests are executed in place and cleanups are performed afterwards.
96# Use '-r dir' option to relocate the tests and their intermediate files to a
97# different directory and to forgo any cleanups. The directory specified must
98# not exist yet.
99rdir = None
100
Johnny Chen125fc2b2010-10-21 16:55:35 +0000101# By default, recorded session info for errored/failed test are dumped into its
102# own file under a session directory named after the timestamp of the test suite
103# run. Use '-s session-dir-name' to specify a specific dir name.
104sdir_name = None
105
Johnny Chen63c2cba2010-10-29 22:20:36 +0000106# Set this flag if there is any session info dumped during the test run.
107sdir_has_content = False
108
Johnny Chen9707bb62010-06-25 21:14:08 +0000109# Default verbosity is 0.
110verbose = 0
111
112# By default, search from the current working directory.
113testdirs = [ os.getcwd() ]
114
Johnny Chen877c7e42010-08-07 00:16:07 +0000115# Separator string.
116separator = '-' * 70
117
Johnny Chen9707bb62010-06-25 21:14:08 +0000118
119def usage():
120 print """
121Usage: dotest.py [option] [args]
122where options:
123-h : print this help message and exit (also --help)
Johnny Chen4f93bf12010-12-10 00:51:23 +0000124-a : don't do lldb Python API tests
125 use @python_api_test to decorate a test case as lldb Python API test
Johnny Chen3ebdacc2010-12-10 18:52:10 +0000126+a : just do lldb Python API tests
Johnny Chencc659ad2010-12-10 19:02:23 +0000127 do not specify both '-a' and '+a' at the same time
Johnny Chen82e6b1e2010-12-01 22:47:54 +0000128-b : read a blacklist file specified after this option
Johnny Chen9fdb0a92010-09-18 00:16:47 +0000129-c : read a config file specified after this option
Johnny Chenb40056b2010-09-21 00:09:27 +0000130 (see also lldb-trunk/example/test/usage-config)
Johnny Chen91960d32010-09-08 20:56:16 +0000131-d : delay startup for 10 seconds (in order for the debugger to attach)
Johnny Chen7d6d8442010-12-03 19:59:35 +0000132-F : failfast, stop the test suite on the first error/failure
Johnny Chen46be75d2010-10-11 16:19:48 +0000133-f : specify a filter, which consists of the test class name, a dot, followed by
Johnny Chen1a6e92a2010-11-08 20:17:04 +0000134 the test method, to only admit such test into the test suite
Johnny Chenb62436b2010-10-06 20:40:56 +0000135 e.g., -f 'ClassTypesTestCase.test_with_dwarf_and_python_api'
Johnny Chena224cd12010-11-08 01:21:03 +0000136-g : if specified, the filterspec by -f is not exclusive, i.e., if a test module
137 does not match the filterspec (testclass.testmethod), the whole module is
138 still admitted to the test suite
Johnny Chenaf149a02010-09-16 17:11:30 +0000139-i : ignore (don't bailout) if 'lldb.py' module cannot be located in the build
140 tree relative to this script; use PYTHONPATH to locate the module
Johnny Chen41998192010-10-01 22:59:49 +0000141-l : don't skip long running test
Johnny Chen7c52ff12010-09-27 23:29:54 +0000142-p : specify a regexp filename pattern for inclusion in the test suite
Johnny Chen548aefd2010-10-11 22:25:46 +0000143-r : specify a dir to relocate the tests and their intermediate files to;
144 the directory must not exist before running this test driver;
145 no cleanup of intermediate test files is performed in this case
Johnny Chen125fc2b2010-10-21 16:55:35 +0000146-s : specify the name of the dir created to store the session files of tests
147 with errored or failed status; if not specified, the test driver uses the
148 timestamp as the session dir name
Johnny Chend0c24b22010-08-23 17:10:44 +0000149-t : trace lldb command execution and result
Johnny Chen9707bb62010-06-25 21:14:08 +0000150-v : do verbose mode of unittest framework
Johnny Chene47649c2010-10-07 02:04:14 +0000151-w : insert some wait time (currently 0.5 sec) between consecutive test cases
Johnny Chend2acdb32010-11-16 22:42:58 +0000152-# : Repeat the test suite for a specified number of times
Johnny Chen9707bb62010-06-25 21:14:08 +0000153
154and:
Johnny Chen9656ab22010-10-22 19:00:18 +0000155args : specify a list of directory names to search for test modules named after
156 Test*.py (test discovery)
Johnny Chen9707bb62010-06-25 21:14:08 +0000157 if empty, search from the curret working directory, instead
Johnny Chen58f93922010-06-29 23:10:39 +0000158
Johnny Chen9656ab22010-10-22 19:00:18 +0000159Examples:
160
Johnny Chena224cd12010-11-08 01:21:03 +0000161This is an example of using the -f option to pinpoint to a specfic test class
162and test method to be run:
Johnny Chen6ad7e5e2010-10-21 00:47:52 +0000163
Johnny Chena224cd12010-11-08 01:21:03 +0000164$ ./dotest.py -f ClassTypesTestCase.test_with_dsym_and_run_command
Johnny Chen6ad7e5e2010-10-21 00:47:52 +0000165----------------------------------------------------------------------
166Collected 1 test
167
168test_with_dsym_and_run_command (TestClassTypes.ClassTypesTestCase)
169Test 'frame variable this' when stopped on a class constructor. ... ok
170
171----------------------------------------------------------------------
172Ran 1 test in 1.396s
173
174OK
Johnny Chen9656ab22010-10-22 19:00:18 +0000175
176And this is an example of using the -p option to run a single file (the filename
177matches the pattern 'ObjC' and it happens to be 'TestObjCMethods.py'):
178
179$ ./dotest.py -v -p ObjC
180----------------------------------------------------------------------
181Collected 4 tests
182
183test_break_with_dsym (TestObjCMethods.FoundationTestCase)
184Test setting objc breakpoints using 'regexp-break' and 'breakpoint set'. ... ok
185test_break_with_dwarf (TestObjCMethods.FoundationTestCase)
186Test setting objc breakpoints using 'regexp-break' and 'breakpoint set'. ... ok
187test_data_type_and_expr_with_dsym (TestObjCMethods.FoundationTestCase)
188Lookup objective-c data types and evaluate expressions. ... ok
189test_data_type_and_expr_with_dwarf (TestObjCMethods.FoundationTestCase)
190Lookup objective-c data types and evaluate expressions. ... ok
191
192----------------------------------------------------------------------
193Ran 4 tests in 16.661s
194
195OK
Johnny Chen6ad7e5e2010-10-21 00:47:52 +0000196
Johnny Chen58f93922010-06-29 23:10:39 +0000197Running of this script also sets up the LLDB_TEST environment variable so that
Johnny Chenaf149a02010-09-16 17:11:30 +0000198individual test cases can locate their supporting files correctly. The script
199tries to set up Python's search paths for modules by looking at the build tree
Johnny Chena85859f2010-11-11 22:14:56 +0000200relative to this script. See also the '-i' option in the following example.
201
202Finally, this is an example of using the lldb.py module distributed/installed by
203Xcode4 to run against the tests under the 'forward' directory, and with the '-w'
204option to add some delay between two tests. It uses ARCH=x86_64 to specify that
205as the architecture and CC=clang to specify the compiler used for the test run:
206
207$ PYTHONPATH=/Xcode4/Library/PrivateFrameworks/LLDB.framework/Versions/A/Resources/Python ARCH=x86_64 CC=clang ./dotest.py -v -w -i forward
208
209Session logs for test failures/errors will go into directory '2010-11-11-13_56_16'
210----------------------------------------------------------------------
211Collected 2 tests
212
213test_with_dsym_and_run_command (TestForwardDeclaration.ForwardDeclarationTestCase)
214Display *bar_ptr when stopped on a function with forward declaration of struct bar. ... ok
215test_with_dwarf_and_run_command (TestForwardDeclaration.ForwardDeclarationTestCase)
216Display *bar_ptr when stopped on a function with forward declaration of struct bar. ... ok
217
218----------------------------------------------------------------------
219Ran 2 tests in 5.659s
220
221OK
222
223The 'Session ...' verbiage is recently introduced (see also the '-s' option) to
224notify the directory containing the session logs for test failures or errors.
225In case there is any test failure/error, a similar message is appended at the
226end of the stderr output for your convenience.
Johnny Chenfde69bc2010-09-14 22:01:40 +0000227
228Environment variables related to loggings:
229
230o LLDB_LOG: if defined, specifies the log file pathname for the 'lldb' subsystem
231 with a default option of 'event process' if LLDB_LOG_OPTION is not defined.
232
233o GDB_REMOTE_LOG: if defined, specifies the log file pathname for the
234 'process.gdb-remote' subsystem with a default option of 'packets' if
235 GDB_REMOTE_LOG_OPTION is not defined.
Johnny Chen9707bb62010-06-25 21:14:08 +0000236"""
Johnny Chen9fdb0a92010-09-18 00:16:47 +0000237 sys.exit(0)
Johnny Chen9707bb62010-06-25 21:14:08 +0000238
239
Johnny Chenaf149a02010-09-16 17:11:30 +0000240def parseOptionsAndInitTestdirs():
241 """Initialize the list of directories containing our unittest scripts.
242
243 '-h/--help as the first option prints out usage info and exit the program.
244 """
245
Johnny Chen4f93bf12010-12-10 00:51:23 +0000246 global dont_do_python_api_test
247 global just_do_python_api_test
Johnny Chen82e6b1e2010-12-01 22:47:54 +0000248 global blacklist
249 global blacklistConfig
Johnny Chen9fdb0a92010-09-18 00:16:47 +0000250 global configFile
Johnny Chend2acdb32010-11-16 22:42:58 +0000251 global count
Johnny Chenaf149a02010-09-16 17:11:30 +0000252 global delay
Johnny Chen7d6d8442010-12-03 19:59:35 +0000253 global failfast
Johnny Chenb62436b2010-10-06 20:40:56 +0000254 global filterspec
255 global fs4all
Johnny Chen7c52ff12010-09-27 23:29:54 +0000256 global ignore
Johnny Chen41998192010-10-01 22:59:49 +0000257 global skipLongRunningTest
Johnny Chen7c52ff12010-09-27 23:29:54 +0000258 global regexp
Johnny Chen548aefd2010-10-11 22:25:46 +0000259 global rdir
Johnny Chen125fc2b2010-10-21 16:55:35 +0000260 global sdir_name
Johnny Chenaf149a02010-09-16 17:11:30 +0000261 global verbose
262 global testdirs
263
264 if len(sys.argv) == 1:
265 return
266
267 # Process possible trace and/or verbose flag, among other things.
268 index = 1
Johnny Chence2212c2010-10-07 15:41:55 +0000269 while index < len(sys.argv):
Johnny Chen4f93bf12010-12-10 00:51:23 +0000270 if sys.argv[index].startswith('-') or sys.argv[index].startswith('+'):
271 # We should continue processing...
272 pass
273 else:
Johnny Chenaf149a02010-09-16 17:11:30 +0000274 # End of option processing.
275 break
276
277 if sys.argv[index].find('-h') != -1:
278 usage()
Johnny Chen4f93bf12010-12-10 00:51:23 +0000279 elif sys.argv[index].startswith('-a'):
280 dont_do_python_api_test = True
281 index += 1
282 elif sys.argv[index].startswith('+a'):
283 just_do_python_api_test = True
284 index += 1
Johnny Chen82e6b1e2010-12-01 22:47:54 +0000285 elif sys.argv[index].startswith('-b'):
286 # Increment by 1 to fetch the blacklist file name option argument.
287 index += 1
288 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
289 usage()
290 blacklistFile = sys.argv[index]
291 if not os.path.isfile(blacklistFile):
292 print "Blacklist file:", blacklistFile, "does not exist!"
293 usage()
294 index += 1
295 # Now read the blacklist contents and assign it to blacklist.
296 execfile(blacklistFile, globals(), blacklistConfig)
297 blacklist = blacklistConfig.get('blacklist')
Johnny Chen9fdb0a92010-09-18 00:16:47 +0000298 elif sys.argv[index].startswith('-c'):
299 # Increment by 1 to fetch the config file name option argument.
300 index += 1
301 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
302 usage()
303 configFile = sys.argv[index]
304 if not os.path.isfile(configFile):
305 print "Config file:", configFile, "does not exist!"
306 usage()
307 index += 1
Johnny Chenaf149a02010-09-16 17:11:30 +0000308 elif sys.argv[index].startswith('-d'):
309 delay = True
310 index += 1
Johnny Chen7d6d8442010-12-03 19:59:35 +0000311 elif sys.argv[index].startswith('-F'):
312 failfast = True
313 index += 1
Johnny Chenb62436b2010-10-06 20:40:56 +0000314 elif sys.argv[index].startswith('-f'):
315 # Increment by 1 to fetch the filter spec.
316 index += 1
317 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
318 usage()
319 filterspec = sys.argv[index]
320 index += 1
321 elif sys.argv[index].startswith('-g'):
Johnny Chena224cd12010-11-08 01:21:03 +0000322 fs4all = False
Johnny Chenb62436b2010-10-06 20:40:56 +0000323 index += 1
Johnny Chenaf149a02010-09-16 17:11:30 +0000324 elif sys.argv[index].startswith('-i'):
325 ignore = True
326 index += 1
Johnny Chen41998192010-10-01 22:59:49 +0000327 elif sys.argv[index].startswith('-l'):
328 skipLongRunningTest = False
329 index += 1
Johnny Chen7c52ff12010-09-27 23:29:54 +0000330 elif sys.argv[index].startswith('-p'):
331 # Increment by 1 to fetch the reg exp pattern argument.
332 index += 1
333 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
334 usage()
335 regexp = sys.argv[index]
336 index += 1
Johnny Chen548aefd2010-10-11 22:25:46 +0000337 elif sys.argv[index].startswith('-r'):
338 # Increment by 1 to fetch the relocated directory argument.
339 index += 1
340 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
341 usage()
342 rdir = os.path.abspath(sys.argv[index])
343 if os.path.exists(rdir):
344 print "Relocated directory:", rdir, "must not exist!"
345 usage()
346 index += 1
Johnny Chen125fc2b2010-10-21 16:55:35 +0000347 elif sys.argv[index].startswith('-s'):
348 # Increment by 1 to fetch the session dir name.
349 index += 1
350 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
351 usage()
352 sdir_name = sys.argv[index]
353 index += 1
Johnny Chenaf149a02010-09-16 17:11:30 +0000354 elif sys.argv[index].startswith('-t'):
355 os.environ["LLDB_COMMAND_TRACE"] = "YES"
356 index += 1
357 elif sys.argv[index].startswith('-v'):
358 verbose = 2
359 index += 1
Johnny Chene47649c2010-10-07 02:04:14 +0000360 elif sys.argv[index].startswith('-w'):
361 os.environ["LLDB_WAIT_BETWEEN_TEST_CASES"] = 'YES'
362 index += 1
Johnny Chend2acdb32010-11-16 22:42:58 +0000363 elif sys.argv[index].startswith('-#'):
364 # Increment by 1 to fetch the repeat count argument.
365 index += 1
366 if index >= len(sys.argv) or sys.argv[index].startswith('-'):
367 usage()
368 count = int(sys.argv[index])
369 index += 1
Johnny Chenaf149a02010-09-16 17:11:30 +0000370 else:
371 print "Unknown option: ", sys.argv[index]
372 usage()
Johnny Chenaf149a02010-09-16 17:11:30 +0000373
Johnny Chencc659ad2010-12-10 19:02:23 +0000374 # Do not specify both '-a' and '+a' at the same time.
375 if dont_do_python_api_test and just_do_python_api_test:
376 usage()
377
Johnny Chenaf149a02010-09-16 17:11:30 +0000378 # Gather all the dirs passed on the command line.
379 if len(sys.argv) > index:
380 testdirs = map(os.path.abspath, sys.argv[index:])
381
Johnny Chen548aefd2010-10-11 22:25:46 +0000382 # If '-r dir' is specified, the tests should be run under the relocated
383 # directory. Let's copy the testdirs over.
384 if rdir:
385 from shutil import copytree, ignore_patterns
386
387 tmpdirs = []
388 for srcdir in testdirs:
389 dstdir = os.path.join(rdir, os.path.basename(srcdir))
390 # Don't copy the *.pyc and .svn stuffs.
391 copytree(srcdir, dstdir, ignore=ignore_patterns('*.pyc', '.svn'))
392 tmpdirs.append(dstdir)
393
394 # This will be our modified testdirs.
395 testdirs = tmpdirs
396
397 # With '-r dir' specified, there's no cleanup of intermediate test files.
398 os.environ["LLDB_DO_CLEANUP"] = 'NO'
399
400 # If testdirs is ['test'], the make directory has already been copied
401 # recursively and is contained within the rdir/test dir. For anything
402 # else, we would need to copy over the make directory and its contents,
403 # so that, os.listdir(rdir) looks like, for example:
404 #
405 # array_types conditional_break make
406 #
407 # where the make directory contains the Makefile.rules file.
408 if len(testdirs) != 1 or os.path.basename(testdirs[0]) != 'test':
409 # Don't copy the .svn stuffs.
410 copytree('make', os.path.join(rdir, 'make'),
411 ignore=ignore_patterns('.svn'))
412
413 #print "testdirs:", testdirs
414
Johnny Chenb40056b2010-09-21 00:09:27 +0000415 # Source the configFile if specified.
416 # The side effect, if any, will be felt from this point on. An example
417 # config file may be these simple two lines:
418 #
419 # sys.stderr = open("/tmp/lldbtest-stderr", "w")
420 # sys.stdout = open("/tmp/lldbtest-stdout", "w")
421 #
422 # which will reassign the two file objects to sys.stderr and sys.stdout,
423 # respectively.
424 #
425 # See also lldb-trunk/example/test/usage-config.
426 global config
427 if configFile:
428 # Pass config (a dictionary) as the locals namespace for side-effect.
429 execfile(configFile, globals(), config)
430 #print "config:", config
431 #print "sys.stderr:", sys.stderr
432 #print "sys.stdout:", sys.stdout
433
Johnny Chenaf149a02010-09-16 17:11:30 +0000434
Johnny Chen9707bb62010-06-25 21:14:08 +0000435def setupSysPath():
436 """Add LLDB.framework/Resources/Python to the search paths for modules."""
437
Johnny Chen548aefd2010-10-11 22:25:46 +0000438 global rdir
439 global testdirs
440
Johnny Chen9707bb62010-06-25 21:14:08 +0000441 # Get the directory containing the current script.
Johnny Chen0de6ab52011-01-19 02:10:40 +0000442 if "DOTEST_PROFILE" in os.environ and "DOTEST_SCRIPT_DIR" in os.environ:
443 scriptPath = os.environ["DOTEST_SCRIPT_DIR"]
444 else:
445 scriptPath = sys.path[0]
Johnny Chena1affab2010-07-03 03:41:59 +0000446 if not scriptPath.endswith('test'):
Johnny Chen9707bb62010-06-25 21:14:08 +0000447 print "This script expects to reside in lldb's test directory."
448 sys.exit(-1)
449
Johnny Chen548aefd2010-10-11 22:25:46 +0000450 if rdir:
451 # Set up the LLDB_TEST environment variable appropriately, so that the
452 # individual tests can be located relatively.
453 #
454 # See also lldbtest.TestBase.setUpClass(cls).
455 if len(testdirs) == 1 and os.path.basename(testdirs[0]) == 'test':
456 os.environ["LLDB_TEST"] = os.path.join(rdir, 'test')
457 else:
458 os.environ["LLDB_TEST"] = rdir
459 else:
460 os.environ["LLDB_TEST"] = scriptPath
Johnny Chen9de4ede2010-08-31 17:42:54 +0000461 pluginPath = os.path.join(scriptPath, 'plugins')
Johnny Chen58f93922010-06-29 23:10:39 +0000462
Johnny Chenaf149a02010-09-16 17:11:30 +0000463 # Append script dir and plugin dir to the sys.path.
464 sys.path.append(scriptPath)
465 sys.path.append(pluginPath)
466
467 global ignore
468
469 # The '-i' option is used to skip looking for lldb.py in the build tree.
470 if ignore:
471 return
472
Johnny Chena1affab2010-07-03 03:41:59 +0000473 base = os.path.abspath(os.path.join(scriptPath, os.pardir))
Johnny Chen9707bb62010-06-25 21:14:08 +0000474 dbgPath = os.path.join(base, 'build', 'Debug', 'LLDB.framework',
475 'Resources', 'Python')
476 relPath = os.path.join(base, 'build', 'Release', 'LLDB.framework',
477 'Resources', 'Python')
Johnny Chenc202c462010-09-15 18:11:19 +0000478 baiPath = os.path.join(base, 'build', 'BuildAndIntegration',
479 'LLDB.framework', 'Resources', 'Python')
Johnny Chen9707bb62010-06-25 21:14:08 +0000480
481 lldbPath = None
482 if os.path.isfile(os.path.join(dbgPath, 'lldb.py')):
483 lldbPath = dbgPath
484 elif os.path.isfile(os.path.join(relPath, 'lldb.py')):
485 lldbPath = relPath
Johnny Chenc202c462010-09-15 18:11:19 +0000486 elif os.path.isfile(os.path.join(baiPath, 'lldb.py')):
487 lldbPath = baiPath
Johnny Chen9707bb62010-06-25 21:14:08 +0000488
489 if not lldbPath:
Johnny Chenc202c462010-09-15 18:11:19 +0000490 print 'This script requires lldb.py to be in either ' + dbgPath + ',',
491 print relPath + ', or ' + baiPath
Johnny Chen9707bb62010-06-25 21:14:08 +0000492 sys.exit(-1)
493
Johnny Chenaf149a02010-09-16 17:11:30 +0000494 # This is to locate the lldb.py module. Insert it right after sys.path[0].
495 sys.path[1:1] = [lldbPath]
Johnny Chen9707bb62010-06-25 21:14:08 +0000496
Johnny Chen9707bb62010-06-25 21:14:08 +0000497
Johnny Chencd0279d2010-09-20 18:07:50 +0000498def doDelay(delta):
499 """Delaying startup for delta-seconds to facilitate debugger attachment."""
500 def alarm_handler(*args):
501 raise Exception("timeout")
502
503 signal.signal(signal.SIGALRM, alarm_handler)
504 signal.alarm(delta)
505 sys.stdout.write("pid=%d\n" % os.getpid())
506 sys.stdout.write("Enter RET to proceed (or timeout after %d seconds):" %
507 delta)
508 sys.stdout.flush()
509 try:
510 text = sys.stdin.readline()
511 except:
512 text = ""
513 signal.alarm(0)
514 sys.stdout.write("proceeding...\n")
515 pass
516
517
Johnny Chen9707bb62010-06-25 21:14:08 +0000518def visit(prefix, dir, names):
519 """Visitor function for os.path.walk(path, visit, arg)."""
520
521 global suite
Johnny Chen7c52ff12010-09-27 23:29:54 +0000522 global regexp
Johnny Chenb62436b2010-10-06 20:40:56 +0000523 global filterspec
524 global fs4all
Johnny Chen9707bb62010-06-25 21:14:08 +0000525
526 for name in names:
527 if os.path.isdir(os.path.join(dir, name)):
528 continue
529
530 if '.py' == os.path.splitext(name)[1] and name.startswith(prefix):
Johnny Chen7c52ff12010-09-27 23:29:54 +0000531 # Try to match the regexp pattern, if specified.
532 if regexp:
533 import re
534 if re.search(regexp, name):
535 #print "Filename: '%s' matches pattern: '%s'" % (name, regexp)
536 pass
537 else:
538 #print "Filename: '%s' does not match pattern: '%s'" % (name, regexp)
539 continue
540
Johnny Chen953864a2010-10-12 21:35:54 +0000541 # We found a match for our test. Add it to the suite.
Johnny Chen79723352010-10-12 15:53:22 +0000542
543 # Update the sys.path first.
Johnny Chena85d7ee2010-06-26 00:19:32 +0000544 if not sys.path.count(dir):
Johnny Chen548aefd2010-10-11 22:25:46 +0000545 sys.path.insert(0, dir)
Johnny Chen9707bb62010-06-25 21:14:08 +0000546 base = os.path.splitext(name)[0]
Johnny Chenb62436b2010-10-06 20:40:56 +0000547
548 # Thoroughly check the filterspec against the base module and admit
549 # the (base, filterspec) combination only when it makes sense.
550 if filterspec:
551 # Optimistically set the flag to True.
552 filtered = True
553 module = __import__(base)
554 parts = filterspec.split('.')
555 obj = module
556 for part in parts:
557 try:
558 parent, obj = obj, getattr(obj, part)
559 except AttributeError:
560 # The filterspec has failed.
561 filtered = False
562 break
563 # Forgo this module if the (base, filterspec) combo is invalid
Johnny Chena224cd12010-11-08 01:21:03 +0000564 # and no '-g' option is specified
Johnny Chenb62436b2010-10-06 20:40:56 +0000565 if fs4all and not filtered:
566 continue
567
Johnny Chen953864a2010-10-12 21:35:54 +0000568 # Add either the filtered test case or the entire test class.
Johnny Chenb62436b2010-10-06 20:40:56 +0000569 if filterspec and filtered:
570 suite.addTests(
571 unittest2.defaultTestLoader.loadTestsFromName(filterspec, module))
572 else:
573 # A simple case of just the module name. Also the failover case
574 # from the filterspec branch when the (base, filterspec) combo
575 # doesn't make sense.
576 suite.addTests(unittest2.defaultTestLoader.loadTestsFromName(base))
Johnny Chen9707bb62010-06-25 21:14:08 +0000577
578
Johnny Chencd0279d2010-09-20 18:07:50 +0000579def lldbLoggings():
580 """Check and do lldb loggings if necessary."""
581
582 # Turn on logging for debugging purposes if ${LLDB_LOG} environment variable is
583 # defined. Use ${LLDB_LOG} to specify the log file.
584 ci = lldb.DBG.GetCommandInterpreter()
585 res = lldb.SBCommandReturnObject()
586 if ("LLDB_LOG" in os.environ):
587 if ("LLDB_LOG_OPTION" in os.environ):
588 lldb_log_option = os.environ["LLDB_LOG_OPTION"]
589 else:
Johnny Chen8fd886c2010-12-08 01:25:21 +0000590 lldb_log_option = "event process expr state api"
Johnny Chencd0279d2010-09-20 18:07:50 +0000591 ci.HandleCommand(
Johnny Chen58bf3442010-12-02 23:31:02 +0000592 "log enable -T -n -f " + os.environ["LLDB_LOG"] + " lldb " + lldb_log_option,
Johnny Chencd0279d2010-09-20 18:07:50 +0000593 res)
594 if not res.Succeeded():
595 raise Exception('log enable failed (check LLDB_LOG env variable.')
596 # Ditto for gdb-remote logging if ${GDB_REMOTE_LOG} environment variable is defined.
597 # Use ${GDB_REMOTE_LOG} to specify the log file.
598 if ("GDB_REMOTE_LOG" in os.environ):
599 if ("GDB_REMOTE_LOG_OPTION" in os.environ):
600 gdb_remote_log_option = os.environ["GDB_REMOTE_LOG_OPTION"]
601 else:
Johnny Chen7ab8c852010-12-02 18:35:13 +0000602 gdb_remote_log_option = "packets process"
Johnny Chencd0279d2010-09-20 18:07:50 +0000603 ci.HandleCommand(
Johnny Chen58bf3442010-12-02 23:31:02 +0000604 "log enable -T -n -f " + os.environ["GDB_REMOTE_LOG"] + " process.gdb-remote "
Johnny Chencd0279d2010-09-20 18:07:50 +0000605 + gdb_remote_log_option,
606 res)
607 if not res.Succeeded():
608 raise Exception('log enable failed (check GDB_REMOTE_LOG env variable.')
609
Johnny Chen067022b2011-01-19 19:31:46 +0000610def getMyCommandLine():
611 import subprocess
612 ps = subprocess.Popen(['ps', '-o', "command=CMD", str(os.getpid())], stdout=subprocess.PIPE).communicate()[0]
613 lines = ps.split('\n')
614 cmd_line = lines[1]
615 return cmd_line
Johnny Chencd0279d2010-09-20 18:07:50 +0000616
Johnny Chend96b5682010-11-05 17:30:53 +0000617# ======================================== #
Johnny Chencd0279d2010-09-20 18:07:50 +0000618# #
619# Execution of the test driver starts here #
620# #
Johnny Chend96b5682010-11-05 17:30:53 +0000621# ======================================== #
Johnny Chencd0279d2010-09-20 18:07:50 +0000622
Johnny Chen9707bb62010-06-25 21:14:08 +0000623#
Johnny Chenaf149a02010-09-16 17:11:30 +0000624# Start the actions by first parsing the options while setting up the test
625# directories, followed by setting up the search paths for lldb utilities;
626# then, we walk the directory trees and collect the tests into our test suite.
Johnny Chen9707bb62010-06-25 21:14:08 +0000627#
Johnny Chenaf149a02010-09-16 17:11:30 +0000628parseOptionsAndInitTestdirs()
Johnny Chen9707bb62010-06-25 21:14:08 +0000629setupSysPath()
Johnny Chen91960d32010-09-08 20:56:16 +0000630
631#
632# If '-d' is specified, do a delay of 10 seconds for the debugger to attach.
633#
634if delay:
Johnny Chencd0279d2010-09-20 18:07:50 +0000635 doDelay(10)
Johnny Chen91960d32010-09-08 20:56:16 +0000636
Johnny Chen49f2f7a2010-09-20 17:25:45 +0000637#
Johnny Chen41998192010-10-01 22:59:49 +0000638# If '-l' is specified, do not skip the long running tests.
639if not skipLongRunningTest:
640 os.environ["LLDB_SKIP_LONG_RUNNING_TEST"] = "NO"
641
642#
Johnny Chen79723352010-10-12 15:53:22 +0000643# Walk through the testdirs while collecting tests.
Johnny Chen49f2f7a2010-09-20 17:25:45 +0000644#
Johnny Chen9707bb62010-06-25 21:14:08 +0000645for testdir in testdirs:
646 os.path.walk(testdir, visit, 'Test')
647
Johnny Chenb40056b2010-09-21 00:09:27 +0000648#
Johnny Chen9707bb62010-06-25 21:14:08 +0000649# Now that we have loaded all the test cases, run the whole test suite.
Johnny Chenb40056b2010-09-21 00:09:27 +0000650#
Johnny Chencd0279d2010-09-20 18:07:50 +0000651
Johnny Chen1bfbd412010-06-29 19:44:16 +0000652# For the time being, let's bracket the test runner within the
653# lldb.SBDebugger.Initialize()/Terminate() pair.
Johnny Chen01f2a6a2010-08-10 20:23:55 +0000654import lldb, atexit
Johnny Chen6b6f5ba2010-10-14 16:36:49 +0000655# Update: the act of importing lldb now executes lldb.SBDebugger.Initialize(),
656# there's no need to call it a second time.
657#lldb.SBDebugger.Initialize()
Johnny Chen01f2a6a2010-08-10 20:23:55 +0000658atexit.register(lambda: lldb.SBDebugger.Terminate())
Johnny Chen1bfbd412010-06-29 19:44:16 +0000659
Johnny Chen909e5a62010-07-01 22:52:57 +0000660# Create a singleton SBDebugger in the lldb namespace.
661lldb.DBG = lldb.SBDebugger.Create()
662
Johnny Chen4f93bf12010-12-10 00:51:23 +0000663# Put the blacklist in the lldb namespace, to be used by lldb.TestBase.
Johnny Chen82e6b1e2010-12-01 22:47:54 +0000664lldb.blacklist = blacklist
665
Johnny Chen4f93bf12010-12-10 00:51:23 +0000666# Put dont/just_do_python_api_test in the lldb namespace, too.
667lldb.dont_do_python_api_test = dont_do_python_api_test
668lldb.just_do_python_api_test = just_do_python_api_test
669
Johnny Chencd0279d2010-09-20 18:07:50 +0000670# Turn on lldb loggings if necessary.
671lldbLoggings()
Johnny Chen909e5a62010-07-01 22:52:57 +0000672
Johnny Chen7987ac92010-08-09 20:40:52 +0000673# Install the control-c handler.
674unittest2.signals.installHandler()
675
Johnny Chen125fc2b2010-10-21 16:55:35 +0000676# If sdir_name is not specified through the '-s sdir_name' option, get a
677# timestamp string and export it as LLDB_SESSION_DIR environment var. This will
678# be used when/if we want to dump the session info of individual test cases
679# later on.
Johnny Chence681462010-10-19 00:25:01 +0000680#
681# See also TestBase.dumpSessionInfo() in lldbtest.py.
Johnny Chen125fc2b2010-10-21 16:55:35 +0000682if not sdir_name:
683 import datetime
Johnny Chen41fae812010-10-29 22:26:38 +0000684 # The windows platforms don't like ':' in the pathname.
Johnny Chen76bd0102010-10-28 16:32:13 +0000685 timestamp = datetime.datetime.now().strftime("%Y-%m-%d-%H_%M_%S")
Johnny Chen125fc2b2010-10-21 16:55:35 +0000686 sdir_name = timestamp
687os.environ["LLDB_SESSION_DIRNAME"] = sdir_name
Johnny Chen067022b2011-01-19 19:31:46 +0000688
Johnny Chen47c47c42010-11-09 23:42:00 +0000689sys.stderr.write("\nSession logs for test failures/errors will go into directory '%s'\n" % sdir_name)
Johnny Chen067022b2011-01-19 19:31:46 +0000690sys.stderr.write("Command invoked: %s\n" % getMyCommandLine())
Johnny Chence681462010-10-19 00:25:01 +0000691
Johnny Chenb40056b2010-09-21 00:09:27 +0000692#
693# Invoke the default TextTestRunner to run the test suite, possibly iterating
694# over different configurations.
695#
696
Johnny Chenb40056b2010-09-21 00:09:27 +0000697iterArchs = False
Johnny Chenf032d902010-09-21 00:16:09 +0000698iterCompilers = False
Johnny Chenb40056b2010-09-21 00:09:27 +0000699
700from types import *
701if "archs" in config:
702 archs = config["archs"]
703 if type(archs) is ListType and len(archs) >= 1:
704 iterArchs = True
705if "compilers" in config:
706 compilers = config["compilers"]
707 if type(compilers) is ListType and len(compilers) >= 1:
708 iterCompilers = True
709
Johnny Chen953864a2010-10-12 21:35:54 +0000710# Make a shallow copy of sys.path, we need to manipulate the search paths later.
711# This is only necessary if we are relocated and with different configurations.
712if rdir and (iterArchs or iterCompilers):
713 old_sys_path = sys.path[:]
714 old_stderr = sys.stderr
715 old_stdout = sys.stdout
716 new_stderr = None
717 new_stdout = None
718
Johnny Chend96b5682010-11-05 17:30:53 +0000719# Iterating over all possible architecture and compiler combinations.
Johnny Chenb40056b2010-09-21 00:09:27 +0000720for ia in range(len(archs) if iterArchs else 1):
721 archConfig = ""
722 if iterArchs:
Johnny Chen18a921f2010-09-30 17:11:58 +0000723 os.environ["ARCH"] = archs[ia]
Johnny Chenb40056b2010-09-21 00:09:27 +0000724 archConfig = "arch=%s" % archs[ia]
725 for ic in range(len(compilers) if iterCompilers else 1):
726 if iterCompilers:
Johnny Chen18a921f2010-09-30 17:11:58 +0000727 os.environ["CC"] = compilers[ic]
Johnny Chenb40056b2010-09-21 00:09:27 +0000728 configString = "%s compiler=%s" % (archConfig, compilers[ic])
729 else:
730 configString = archConfig
731
Johnny Chenb40056b2010-09-21 00:09:27 +0000732 if iterArchs or iterCompilers:
Johnny Chen953864a2010-10-12 21:35:54 +0000733 # If we specified a relocated directory to run the test suite, do
734 # the extra housekeeping to copy the testdirs to a configStringified
735 # directory and to update sys.path before invoking the test runner.
736 # The purpose is to separate the configuration-specific directories
737 # from each other.
738 if rdir:
739 from string import maketrans
740 from shutil import copytree, ignore_patterns
741
742 # Translate ' ' to '-' for dir name.
743 tbl = maketrans(' ', '-')
744 configPostfix = configString.translate(tbl)
745 newrdir = "%s.%s" % (rdir, configPostfix)
746
747 # Copy the tree to a new directory with postfix name configPostfix.
748 copytree(rdir, newrdir, ignore=ignore_patterns('*.pyc', '*.o', '*.d'))
749
750 # Check whether we need to split stderr/stdout into configuration
751 # specific files.
752 if old_stderr.name != '<stderr>' and config.get('split_stderr'):
753 if new_stderr:
754 new_stderr.close()
755 new_stderr = open("%s.%s" % (old_stderr.name, configPostfix), "w")
756 sys.stderr = new_stderr
Johnny Chen4b6630e2010-10-12 21:50:36 +0000757 if old_stdout.name != '<stdout>' and config.get('split_stdout'):
Johnny Chen953864a2010-10-12 21:35:54 +0000758 if new_stdout:
759 new_stdout.close()
760 new_stdout = open("%s.%s" % (old_stdout.name, configPostfix), "w")
761 sys.stdout = new_stdout
762
763 # Update the LLDB_TEST environment variable to reflect new top
764 # level test directory.
765 #
766 # See also lldbtest.TestBase.setUpClass(cls).
767 if len(testdirs) == 1 and os.path.basename(testdirs[0]) == 'test':
768 os.environ["LLDB_TEST"] = os.path.join(newrdir, 'test')
769 else:
770 os.environ["LLDB_TEST"] = newrdir
771
772 # And update the Python search paths for modules.
773 sys.path = [x.replace(rdir, newrdir, 1) for x in old_sys_path]
774
775 # Output the configuration.
Johnny Chenb40056b2010-09-21 00:09:27 +0000776 sys.stderr.write("\nConfiguration: " + configString + "\n")
Johnny Chen953864a2010-10-12 21:35:54 +0000777
778 #print "sys.stderr name is", sys.stderr.name
779 #print "sys.stdout name is", sys.stdout.name
780
781 # First, write out the number of collected test cases.
782 sys.stderr.write(separator + "\n")
783 sys.stderr.write("Collected %d test%s\n\n"
784 % (suite.countTestCases(),
785 suite.countTestCases() != 1 and "s" or ""))
786
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000787 class LLDBTestResult(unittest2.TextTestResult):
788 """
Johnny Chen26be4532010-11-09 23:56:14 +0000789 Enforce a singleton pattern to allow introspection of test progress.
790
791 Overwrite addError(), addFailure(), and addExpectedFailure() methods
792 to enable each test instance to track its failure/error status. It
793 is used in the LLDB test framework to emit detailed trace messages
794 to a log file for easier human inspection of test failres/errors.
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000795 """
796 __singleton__ = None
Johnny Chen360dd372010-11-29 17:50:10 +0000797 __ignore_singleton__ = False
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000798
799 def __init__(self, *args):
Johnny Chen360dd372010-11-29 17:50:10 +0000800 if not LLDBTestResult.__ignore_singleton__ and LLDBTestResult.__singleton__:
Johnny Chend2acdb32010-11-16 22:42:58 +0000801 raise Exception("LLDBTestResult instantiated more than once")
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000802 super(LLDBTestResult, self).__init__(*args)
803 LLDBTestResult.__singleton__ = self
804 # Now put this singleton into the lldb module namespace.
805 lldb.test_result = self
Johnny Chen810042e2011-01-05 20:24:11 +0000806 # Computes the format string for displaying the counter.
807 global suite
808 counterWidth = len(str(suite.countTestCases()))
809 self.fmt = "%" + str(counterWidth) + "d: "
Johnny Chenc87fd492011-01-05 22:50:11 +0000810 self.indentation = ' ' * (counterWidth + 2)
Johnny Chen810042e2011-01-05 20:24:11 +0000811 # This counts from 1 .. suite.countTestCases().
812 self.counter = 0
813
Johnny Chenc87fd492011-01-05 22:50:11 +0000814 def getDescription(self, test):
815 doc_first_line = test.shortDescription()
816 if self.descriptions and doc_first_line:
817 return '\n'.join((str(test), self.indentation + doc_first_line))
818 else:
819 return str(test)
820
Johnny Chen810042e2011-01-05 20:24:11 +0000821 def startTest(self, test):
822 self.counter += 1
823 if self.showAll:
824 self.stream.write(self.fmt % self.counter)
825 super(LLDBTestResult, self).startTest(test)
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000826
Johnny Chence681462010-10-19 00:25:01 +0000827 def addError(self, test, err):
Johnny Chen63c2cba2010-10-29 22:20:36 +0000828 global sdir_has_content
829 sdir_has_content = True
Johnny Chence681462010-10-19 00:25:01 +0000830 super(LLDBTestResult, self).addError(test, err)
831 method = getattr(test, "markError", None)
832 if method:
833 method()
834
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000835 def addFailure(self, test, err):
Johnny Chen63c2cba2010-10-29 22:20:36 +0000836 global sdir_has_content
837 sdir_has_content = True
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000838 super(LLDBTestResult, self).addFailure(test, err)
839 method = getattr(test, "markFailure", None)
840 if method:
841 method()
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000842
Johnny Chendd2bb2c2010-11-03 18:17:03 +0000843 def addExpectedFailure(self, test, err):
844 global sdir_has_content
845 sdir_has_content = True
846 super(LLDBTestResult, self).addExpectedFailure(test, err)
847 method = getattr(test, "markExpectedFailure", None)
848 if method:
849 method()
850
Johnny Chen26be4532010-11-09 23:56:14 +0000851 # Invoke the test runner.
Johnny Chend2acdb32010-11-16 22:42:58 +0000852 if count == 1:
Johnny Chen7d6d8442010-12-03 19:59:35 +0000853 result = unittest2.TextTestRunner(stream=sys.stderr,
854 verbosity=verbose,
855 failfast=failfast,
Johnny Chend2acdb32010-11-16 22:42:58 +0000856 resultclass=LLDBTestResult).run(suite)
857 else:
Johnny Chend6e7ca22010-11-29 17:52:43 +0000858 # We are invoking the same test suite more than once. In this case,
859 # mark __ignore_singleton__ flag as True so the signleton pattern is
860 # not enforced.
Johnny Chen360dd372010-11-29 17:50:10 +0000861 LLDBTestResult.__ignore_singleton__ = True
Johnny Chend2acdb32010-11-16 22:42:58 +0000862 for i in range(count):
Johnny Chen7d6d8442010-12-03 19:59:35 +0000863 result = unittest2.TextTestRunner(stream=sys.stderr,
864 verbosity=verbose,
865 failfast=failfast,
Johnny Chen360dd372010-11-29 17:50:10 +0000866 resultclass=LLDBTestResult).run(suite)
Johnny Chenb40056b2010-09-21 00:09:27 +0000867
Johnny Chen1bfbd412010-06-29 19:44:16 +0000868
Johnny Chen63c2cba2010-10-29 22:20:36 +0000869if sdir_has_content:
Johnny Chen47c47c42010-11-09 23:42:00 +0000870 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 +0000871
Johnny Chencd0279d2010-09-20 18:07:50 +0000872# Terminate the test suite if ${LLDB_TESTSUITE_FORCE_FINISH} is defined.
873# This should not be necessary now.
Johnny Chen83f6e512010-08-13 22:58:44 +0000874if ("LLDB_TESTSUITE_FORCE_FINISH" in os.environ):
875 import subprocess
876 print "Terminating Test suite..."
877 subprocess.Popen(["/bin/sh", "-c", "kill %s; exit 0" % (os.getpid())])
878
Johnny Chen01f2a6a2010-08-10 20:23:55 +0000879# Exiting.
880sys.exit(not result.wasSuccessful)