blob: 86fb7373940a10c0828635ebf16bbc16a17257e1 [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.
15"""
16
Johnny Chen91960d32010-09-08 20:56:16 +000017import os, signal, sys, time
Johnny Chen75e28f92010-08-05 23:42:46 +000018import unittest2
Johnny Chen9707bb62010-06-25 21:14:08 +000019
Johnny Chen877c7e42010-08-07 00:16:07 +000020class _WritelnDecorator(object):
21 """Used to decorate file-like objects with a handy 'writeln' method"""
22 def __init__(self,stream):
23 self.stream = stream
24
25 def __getattr__(self, attr):
26 if attr in ('stream', '__getstate__'):
27 raise AttributeError(attr)
28 return getattr(self.stream,attr)
29
30 def writeln(self, arg=None):
31 if arg:
32 self.write(arg)
33 self.write('\n') # text-mode streams translate to \r\n if needed
34
Johnny Chen9707bb62010-06-25 21:14:08 +000035#
36# Global variables:
37#
38
39# The test suite.
Johnny Chen75e28f92010-08-05 23:42:46 +000040suite = unittest2.TestSuite()
Johnny Chen9707bb62010-06-25 21:14:08 +000041
Johnny Chen91960d32010-09-08 20:56:16 +000042# Delay startup in order for the debugger to attach.
43delay = False
44
Johnny Chen9707bb62010-06-25 21:14:08 +000045# Default verbosity is 0.
46verbose = 0
47
48# By default, search from the current working directory.
49testdirs = [ os.getcwd() ]
50
Johnny Chen877c7e42010-08-07 00:16:07 +000051# Separator string.
52separator = '-' * 70
53
Johnny Chen840d8e32010-08-17 23:00:13 +000054# Decorated sys.stderr for our consumption.
55err = _WritelnDecorator(sys.stderr)
Johnny Chen877c7e42010-08-07 00:16:07 +000056
Johnny Chen9707bb62010-06-25 21:14:08 +000057
58def usage():
59 print """
60Usage: dotest.py [option] [args]
61where options:
62-h : print this help message and exit (also --help)
Johnny Chen91960d32010-09-08 20:56:16 +000063-d : delay startup for 10 seconds (in order for the debugger to attach)
Johnny Chend0c24b22010-08-23 17:10:44 +000064-t : trace lldb command execution and result
Johnny Chen9707bb62010-06-25 21:14:08 +000065-v : do verbose mode of unittest framework
66
67and:
68args : specify a list of directory names to search for python Test*.py scripts
69 if empty, search from the curret working directory, instead
Johnny Chen58f93922010-06-29 23:10:39 +000070
71Running of this script also sets up the LLDB_TEST environment variable so that
72individual test cases can locate their supporting files correctly.
Johnny Chenfde69bc2010-09-14 22:01:40 +000073
74Environment variables related to loggings:
75
76o LLDB_LOG: if defined, specifies the log file pathname for the 'lldb' subsystem
77 with a default option of 'event process' if LLDB_LOG_OPTION is not defined.
78
79o GDB_REMOTE_LOG: if defined, specifies the log file pathname for the
80 'process.gdb-remote' subsystem with a default option of 'packets' if
81 GDB_REMOTE_LOG_OPTION is not defined.
Johnny Chen9707bb62010-06-25 21:14:08 +000082"""
83
84
85def setupSysPath():
86 """Add LLDB.framework/Resources/Python to the search paths for modules."""
87
88 # Get the directory containing the current script.
Johnny Chena1affab2010-07-03 03:41:59 +000089 scriptPath = sys.path[0]
90 if not scriptPath.endswith('test'):
Johnny Chen9707bb62010-06-25 21:14:08 +000091 print "This script expects to reside in lldb's test directory."
92 sys.exit(-1)
93
Johnny Chena1affab2010-07-03 03:41:59 +000094 os.environ["LLDB_TEST"] = scriptPath
Johnny Chen9de4ede2010-08-31 17:42:54 +000095 pluginPath = os.path.join(scriptPath, 'plugins')
Johnny Chen58f93922010-06-29 23:10:39 +000096
Johnny Chena1affab2010-07-03 03:41:59 +000097 base = os.path.abspath(os.path.join(scriptPath, os.pardir))
Johnny Chen9707bb62010-06-25 21:14:08 +000098 dbgPath = os.path.join(base, 'build', 'Debug', 'LLDB.framework',
99 'Resources', 'Python')
100 relPath = os.path.join(base, 'build', 'Release', 'LLDB.framework',
101 'Resources', 'Python')
Johnny Chenc202c462010-09-15 18:11:19 +0000102 baiPath = os.path.join(base, 'build', 'BuildAndIntegration',
103 'LLDB.framework', 'Resources', 'Python')
Johnny Chen9707bb62010-06-25 21:14:08 +0000104
105 lldbPath = None
106 if os.path.isfile(os.path.join(dbgPath, 'lldb.py')):
107 lldbPath = dbgPath
108 elif os.path.isfile(os.path.join(relPath, 'lldb.py')):
109 lldbPath = relPath
Johnny Chenc202c462010-09-15 18:11:19 +0000110 elif os.path.isfile(os.path.join(baiPath, 'lldb.py')):
111 lldbPath = baiPath
Johnny Chen9707bb62010-06-25 21:14:08 +0000112
113 if not lldbPath:
Johnny Chenc202c462010-09-15 18:11:19 +0000114 print 'This script requires lldb.py to be in either ' + dbgPath + ',',
115 print relPath + ', or ' + baiPath
Johnny Chen9707bb62010-06-25 21:14:08 +0000116 sys.exit(-1)
117
118 sys.path.append(lldbPath)
Johnny Chena1affab2010-07-03 03:41:59 +0000119 sys.path.append(scriptPath)
Johnny Chen9de4ede2010-08-31 17:42:54 +0000120 sys.path.append(pluginPath)
Johnny Chen9707bb62010-06-25 21:14:08 +0000121
122
123def initTestdirs():
124 """Initialize the list of directories containing our unittest scripts.
125
126 '-h/--help as the first option prints out usage info and exit the program.
127 """
128
Johnny Chen91960d32010-09-08 20:56:16 +0000129 global delay
Johnny Chen9707bb62010-06-25 21:14:08 +0000130 global verbose
131 global testdirs
132
133 if len(sys.argv) == 1:
134 pass
135 elif sys.argv[1].find('-h') != -1:
136 # Print usage info and exit.
137 usage()
138 sys.exit(0)
139 else:
Johnny Chend0c24b22010-08-23 17:10:44 +0000140 # Process possible trace and/or verbose flag.
Johnny Chen9707bb62010-06-25 21:14:08 +0000141 index = 1
Johnny Chenfde69bc2010-09-14 22:01:40 +0000142 for i in range(1, len(sys.argv)):
143 if not sys.argv[index].startswith('-'):
144 # End of option processing.
145 break
146
Johnny Chen91960d32010-09-08 20:56:16 +0000147 if sys.argv[index].startswith('-d'):
148 delay = True
149 index += 1
Johnny Chenfde69bc2010-09-14 22:01:40 +0000150 elif sys.argv[index].startswith('-t'):
Johnny Chend0c24b22010-08-23 17:10:44 +0000151 os.environ["LLDB_COMMAND_TRACE"] = "YES"
152 index += 1
Johnny Chenfde69bc2010-09-14 22:01:40 +0000153 elif sys.argv[index].startswith('-v'):
Johnny Chend0c24b22010-08-23 17:10:44 +0000154 verbose = 2
155 index += 1
Johnny Chen9707bb62010-06-25 21:14:08 +0000156
157 # Gather all the dirs passed on the command line.
158 if len(sys.argv) > index:
159 testdirs = map(os.path.abspath, sys.argv[index:])
160
Johnny Chen9707bb62010-06-25 21:14:08 +0000161
162def visit(prefix, dir, names):
163 """Visitor function for os.path.walk(path, visit, arg)."""
164
165 global suite
166
167 for name in names:
168 if os.path.isdir(os.path.join(dir, name)):
169 continue
170
171 if '.py' == os.path.splitext(name)[1] and name.startswith(prefix):
172 # We found a pattern match for our test case. Add it to the suite.
Johnny Chena85d7ee2010-06-26 00:19:32 +0000173 if not sys.path.count(dir):
174 sys.path.append(dir)
Johnny Chen9707bb62010-06-25 21:14:08 +0000175 base = os.path.splitext(name)[0]
Johnny Chen75e28f92010-08-05 23:42:46 +0000176 suite.addTests(unittest2.defaultTestLoader.loadTestsFromName(base))
Johnny Chen9707bb62010-06-25 21:14:08 +0000177
178
179#
180# Start the actions by first setting up the module search path for lldb,
181# followed by initializing the test directories, and then walking the directory
182# trees, while collecting the tests into our test suite.
183#
184setupSysPath()
185initTestdirs()
Johnny Chen91960d32010-09-08 20:56:16 +0000186
187#
188# If '-d' is specified, do a delay of 10 seconds for the debugger to attach.
189#
190if delay:
191 def alarm_handler(*args):
192 raise Exception("timeout")
193
194 signal.signal(signal.SIGALRM, alarm_handler)
195 signal.alarm(10)
196 sys.stdout.write("pid=" + str(os.getpid()) + '\n')
197 sys.stdout.write("Enter RET to proceed (or timeout after 10 seconds):")
198 sys.stdout.flush()
199 try:
200 text = sys.stdin.readline()
201 except:
202 text = ""
203 signal.alarm(0)
204 sys.stdout.write("proceeding...\n")
205 pass
206
Johnny Chen9707bb62010-06-25 21:14:08 +0000207for testdir in testdirs:
208 os.path.walk(testdir, visit, 'Test')
209
210# Now that we have loaded all the test cases, run the whole test suite.
Johnny Chen840d8e32010-08-17 23:00:13 +0000211err.writeln(separator)
212err.writeln("Collected %d test%s" % (suite.countTestCases(),
Johnny Chen877c7e42010-08-07 00:16:07 +0000213 suite.countTestCases() != 1 and "s" or ""))
Johnny Chen840d8e32010-08-17 23:00:13 +0000214err.writeln()
Johnny Chen1bfbd412010-06-29 19:44:16 +0000215
216# For the time being, let's bracket the test runner within the
217# lldb.SBDebugger.Initialize()/Terminate() pair.
Johnny Chen01f2a6a2010-08-10 20:23:55 +0000218import lldb, atexit
Johnny Chen1bfbd412010-06-29 19:44:16 +0000219lldb.SBDebugger.Initialize()
Johnny Chen01f2a6a2010-08-10 20:23:55 +0000220atexit.register(lambda: lldb.SBDebugger.Terminate())
Johnny Chen1bfbd412010-06-29 19:44:16 +0000221
Johnny Chen909e5a62010-07-01 22:52:57 +0000222# Create a singleton SBDebugger in the lldb namespace.
223lldb.DBG = lldb.SBDebugger.Create()
224
225# Turn on logging for debugging purposes if ${LLDB_LOG} environment variable is
Johnny Chen1a437262010-08-16 22:37:45 +0000226# defined. Use ${LLDB_LOG} to specify the log file.
Johnny Chen909e5a62010-07-01 22:52:57 +0000227ci = lldb.DBG.GetCommandInterpreter()
228res = lldb.SBCommandReturnObject()
229if ("LLDB_LOG" in os.environ):
Johnny Chen4e6c8882010-08-17 21:36:09 +0000230 if ("LLDB_LOG_OPTION" in os.environ):
231 lldb_log_option = os.environ["LLDB_LOG_OPTION"]
232 else:
233 lldb_log_option = "event process"
Johnny Chen909e5a62010-07-01 22:52:57 +0000234 ci.HandleCommand(
Johnny Chen4e6c8882010-08-17 21:36:09 +0000235 "log enable -f " + os.environ["LLDB_LOG"] + " lldb " + lldb_log_option,
236 res)
Johnny Chen797674b2010-07-02 20:35:23 +0000237 if not res.Succeeded():
Johnny Chen4e6c8882010-08-17 21:36:09 +0000238 raise Exception('log enable failed (check LLDB_LOG env variable.')
Johnny Chenfde69bc2010-09-14 22:01:40 +0000239# Ditto for gdb-remote logging if ${GDB_REMOTE_LOG} environment variable is defined.
Johnny Chen1a437262010-08-16 22:37:45 +0000240# Use ${GDB_REMOTE_LOG} to specify the log file.
241if ("GDB_REMOTE_LOG" in os.environ):
Johnny Chen4e6c8882010-08-17 21:36:09 +0000242 if ("GDB_REMOTE_LOG_OPTION" in os.environ):
243 gdb_remote_log_option = os.environ["GDB_REMOTE_LOG_OPTION"]
244 else:
245 gdb_remote_log_option = "packets"
Johnny Chen1a437262010-08-16 22:37:45 +0000246 ci.HandleCommand(
Johnny Chen4e6c8882010-08-17 21:36:09 +0000247 "log enable -f " + os.environ["GDB_REMOTE_LOG"] + " process.gdb-remote "
248 + gdb_remote_log_option,
249 res)
Johnny Chen1a437262010-08-16 22:37:45 +0000250 if not res.Succeeded():
Johnny Chen4e6c8882010-08-17 21:36:09 +0000251 raise Exception('log enable failed (check GDB_REMOTE_LOG env variable.')
Johnny Chen909e5a62010-07-01 22:52:57 +0000252
Johnny Chen7987ac92010-08-09 20:40:52 +0000253# Install the control-c handler.
254unittest2.signals.installHandler()
255
256# Invoke the default TextTestRunner to run the test suite.
Johnny Chen01f2a6a2010-08-10 20:23:55 +0000257result = unittest2.TextTestRunner(verbosity=verbose).run(suite)
Johnny Chen1bfbd412010-06-29 19:44:16 +0000258
Johnny Chen83f6e512010-08-13 22:58:44 +0000259if ("LLDB_TESTSUITE_FORCE_FINISH" in os.environ):
260 import subprocess
261 print "Terminating Test suite..."
262 subprocess.Popen(["/bin/sh", "-c", "kill %s; exit 0" % (os.getpid())])
263
Johnny Chen01f2a6a2010-08-10 20:23:55 +0000264# Exiting.
265sys.exit(not result.wasSuccessful)