blob: 9a2e4bd778f12809fcf990e5186c0acea80e4c21 [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')
102
103 lldbPath = None
104 if os.path.isfile(os.path.join(dbgPath, 'lldb.py')):
105 lldbPath = dbgPath
106 elif os.path.isfile(os.path.join(relPath, 'lldb.py')):
107 lldbPath = relPath
108
109 if not lldbPath:
110 print 'This script requires lldb.py to be in either ' + dbgPath,
111 print ' or' + relPath
112 sys.exit(-1)
113
114 sys.path.append(lldbPath)
Johnny Chena1affab2010-07-03 03:41:59 +0000115 sys.path.append(scriptPath)
Johnny Chen9de4ede2010-08-31 17:42:54 +0000116 sys.path.append(pluginPath)
Johnny Chen9707bb62010-06-25 21:14:08 +0000117
118
119def initTestdirs():
120 """Initialize the list of directories containing our unittest scripts.
121
122 '-h/--help as the first option prints out usage info and exit the program.
123 """
124
Johnny Chen91960d32010-09-08 20:56:16 +0000125 global delay
Johnny Chen9707bb62010-06-25 21:14:08 +0000126 global verbose
127 global testdirs
128
129 if len(sys.argv) == 1:
130 pass
131 elif sys.argv[1].find('-h') != -1:
132 # Print usage info and exit.
133 usage()
134 sys.exit(0)
135 else:
Johnny Chend0c24b22010-08-23 17:10:44 +0000136 # Process possible trace and/or verbose flag.
Johnny Chen9707bb62010-06-25 21:14:08 +0000137 index = 1
Johnny Chenfde69bc2010-09-14 22:01:40 +0000138 for i in range(1, len(sys.argv)):
139 if not sys.argv[index].startswith('-'):
140 # End of option processing.
141 break
142
Johnny Chen91960d32010-09-08 20:56:16 +0000143 if sys.argv[index].startswith('-d'):
144 delay = True
145 index += 1
Johnny Chenfde69bc2010-09-14 22:01:40 +0000146 elif sys.argv[index].startswith('-t'):
Johnny Chend0c24b22010-08-23 17:10:44 +0000147 os.environ["LLDB_COMMAND_TRACE"] = "YES"
148 index += 1
Johnny Chenfde69bc2010-09-14 22:01:40 +0000149 elif sys.argv[index].startswith('-v'):
Johnny Chend0c24b22010-08-23 17:10:44 +0000150 verbose = 2
151 index += 1
Johnny Chen9707bb62010-06-25 21:14:08 +0000152
153 # Gather all the dirs passed on the command line.
154 if len(sys.argv) > index:
155 testdirs = map(os.path.abspath, sys.argv[index:])
156
Johnny Chen9707bb62010-06-25 21:14:08 +0000157
158def visit(prefix, dir, names):
159 """Visitor function for os.path.walk(path, visit, arg)."""
160
161 global suite
162
163 for name in names:
164 if os.path.isdir(os.path.join(dir, name)):
165 continue
166
167 if '.py' == os.path.splitext(name)[1] and name.startswith(prefix):
168 # We found a pattern match for our test case. Add it to the suite.
Johnny Chena85d7ee2010-06-26 00:19:32 +0000169 if not sys.path.count(dir):
170 sys.path.append(dir)
Johnny Chen9707bb62010-06-25 21:14:08 +0000171 base = os.path.splitext(name)[0]
Johnny Chen75e28f92010-08-05 23:42:46 +0000172 suite.addTests(unittest2.defaultTestLoader.loadTestsFromName(base))
Johnny Chen9707bb62010-06-25 21:14:08 +0000173
174
175#
176# Start the actions by first setting up the module search path for lldb,
177# followed by initializing the test directories, and then walking the directory
178# trees, while collecting the tests into our test suite.
179#
180setupSysPath()
181initTestdirs()
Johnny Chen91960d32010-09-08 20:56:16 +0000182
183#
184# If '-d' is specified, do a delay of 10 seconds for the debugger to attach.
185#
186if delay:
187 def alarm_handler(*args):
188 raise Exception("timeout")
189
190 signal.signal(signal.SIGALRM, alarm_handler)
191 signal.alarm(10)
192 sys.stdout.write("pid=" + str(os.getpid()) + '\n')
193 sys.stdout.write("Enter RET to proceed (or timeout after 10 seconds):")
194 sys.stdout.flush()
195 try:
196 text = sys.stdin.readline()
197 except:
198 text = ""
199 signal.alarm(0)
200 sys.stdout.write("proceeding...\n")
201 pass
202
Johnny Chen9707bb62010-06-25 21:14:08 +0000203for testdir in testdirs:
204 os.path.walk(testdir, visit, 'Test')
205
206# Now that we have loaded all the test cases, run the whole test suite.
Johnny Chen840d8e32010-08-17 23:00:13 +0000207err.writeln(separator)
208err.writeln("Collected %d test%s" % (suite.countTestCases(),
Johnny Chen877c7e42010-08-07 00:16:07 +0000209 suite.countTestCases() != 1 and "s" or ""))
Johnny Chen840d8e32010-08-17 23:00:13 +0000210err.writeln()
Johnny Chen1bfbd412010-06-29 19:44:16 +0000211
212# For the time being, let's bracket the test runner within the
213# lldb.SBDebugger.Initialize()/Terminate() pair.
Johnny Chen01f2a6a2010-08-10 20:23:55 +0000214import lldb, atexit
Johnny Chen1bfbd412010-06-29 19:44:16 +0000215lldb.SBDebugger.Initialize()
Johnny Chen01f2a6a2010-08-10 20:23:55 +0000216atexit.register(lambda: lldb.SBDebugger.Terminate())
Johnny Chen1bfbd412010-06-29 19:44:16 +0000217
Johnny Chen909e5a62010-07-01 22:52:57 +0000218# Create a singleton SBDebugger in the lldb namespace.
219lldb.DBG = lldb.SBDebugger.Create()
220
221# Turn on logging for debugging purposes if ${LLDB_LOG} environment variable is
Johnny Chen1a437262010-08-16 22:37:45 +0000222# defined. Use ${LLDB_LOG} to specify the log file.
Johnny Chen909e5a62010-07-01 22:52:57 +0000223ci = lldb.DBG.GetCommandInterpreter()
224res = lldb.SBCommandReturnObject()
225if ("LLDB_LOG" in os.environ):
Johnny Chen4e6c8882010-08-17 21:36:09 +0000226 if ("LLDB_LOG_OPTION" in os.environ):
227 lldb_log_option = os.environ["LLDB_LOG_OPTION"]
228 else:
229 lldb_log_option = "event process"
Johnny Chen909e5a62010-07-01 22:52:57 +0000230 ci.HandleCommand(
Johnny Chen4e6c8882010-08-17 21:36:09 +0000231 "log enable -f " + os.environ["LLDB_LOG"] + " lldb " + lldb_log_option,
232 res)
Johnny Chen797674b2010-07-02 20:35:23 +0000233 if not res.Succeeded():
Johnny Chen4e6c8882010-08-17 21:36:09 +0000234 raise Exception('log enable failed (check LLDB_LOG env variable.')
Johnny Chenfde69bc2010-09-14 22:01:40 +0000235# Ditto for gdb-remote logging if ${GDB_REMOTE_LOG} environment variable is defined.
Johnny Chen1a437262010-08-16 22:37:45 +0000236# Use ${GDB_REMOTE_LOG} to specify the log file.
237if ("GDB_REMOTE_LOG" in os.environ):
Johnny Chen4e6c8882010-08-17 21:36:09 +0000238 if ("GDB_REMOTE_LOG_OPTION" in os.environ):
239 gdb_remote_log_option = os.environ["GDB_REMOTE_LOG_OPTION"]
240 else:
241 gdb_remote_log_option = "packets"
Johnny Chen1a437262010-08-16 22:37:45 +0000242 ci.HandleCommand(
Johnny Chen4e6c8882010-08-17 21:36:09 +0000243 "log enable -f " + os.environ["GDB_REMOTE_LOG"] + " process.gdb-remote "
244 + gdb_remote_log_option,
245 res)
Johnny Chen1a437262010-08-16 22:37:45 +0000246 if not res.Succeeded():
Johnny Chen4e6c8882010-08-17 21:36:09 +0000247 raise Exception('log enable failed (check GDB_REMOTE_LOG env variable.')
Johnny Chen909e5a62010-07-01 22:52:57 +0000248
Johnny Chen7987ac92010-08-09 20:40:52 +0000249# Install the control-c handler.
250unittest2.signals.installHandler()
251
252# Invoke the default TextTestRunner to run the test suite.
Johnny Chen01f2a6a2010-08-10 20:23:55 +0000253result = unittest2.TextTestRunner(verbosity=verbose).run(suite)
Johnny Chen1bfbd412010-06-29 19:44:16 +0000254
Johnny Chen83f6e512010-08-13 22:58:44 +0000255if ("LLDB_TESTSUITE_FORCE_FINISH" in os.environ):
256 import subprocess
257 print "Terminating Test suite..."
258 subprocess.Popen(["/bin/sh", "-c", "kill %s; exit 0" % (os.getpid())])
259
Johnny Chen01f2a6a2010-08-10 20:23:55 +0000260# Exiting.
261sys.exit(not result.wasSuccessful)