blob: a4fceca2d0c159882c37896530043d06efb20de1 [file] [log] [blame]
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001"""
2LLDB module which provides the abstract base class of lldb test case.
3
4The concrete subclass can override lldbtest.TesBase in order to inherit the
5common behavior for unitest.TestCase.setUp/tearDown implemented in this file.
6
7The subclass should override the attribute mydir in order for the python runtime
8to locate the individual test cases when running as part of a large test suite
9or when running each test case as a separate python invocation.
10
11./dotest.py provides a test driver which sets up the environment to run the
12entire test suite. Users who want to run a test case on its own can specify the
13LLDB_TEST and PYTHONPATH environment variables, for example:
14
15$ export LLDB_TEST=$PWD
Johnny Chen4533dad2011-05-31 23:21:42 +000016$ export PYTHONPATH=/Volumes/data/lldb/svn/trunk/build/Debug/LLDB.framework/Resources/Python:$LLDB_TEST:$LLDB_TEST/plugins:$LLDB_TEST/pexpect-2.4
Johnny Chenbf6ffa32010-07-03 03:41:59 +000017$ echo $LLDB_TEST
18/Volumes/data/lldb/svn/trunk/test
19$ echo $PYTHONPATH
Johnny Chen8d55a342010-08-31 17:42:54 +000020/Volumes/data/lldb/svn/trunk/build/Debug/LLDB.framework/Resources/Python:/Volumes/data/lldb/svn/trunk/test:/Volumes/data/lldb/svn/trunk/test/plugins
Johnny Chenbf6ffa32010-07-03 03:41:59 +000021$ python function_types/TestFunctionTypes.py
22.
23----------------------------------------------------------------------
24Ran 1 test in 0.363s
25
26OK
Johnny Chend0190a62010-08-23 17:10:44 +000027$ LLDB_COMMAND_TRACE=YES python array_types/TestArrayTypes.py
Johnny Chen57b47382010-09-02 22:25:47 +000028
29...
Johnny Chend0190a62010-08-23 17:10:44 +000030
31runCmd: breakpoint set -f main.c -l 42
32output: Breakpoint created: 1: file ='main.c', line = 42, locations = 1
33
34runCmd: run
35output: Launching '/Volumes/data/lldb/svn/trunk/test/array_types/a.out' (x86_64)
36
Johnny Chen57b47382010-09-02 22:25:47 +000037...
Johnny Chend0190a62010-08-23 17:10:44 +000038
Johnny Chen57b47382010-09-02 22:25:47 +000039runCmd: frame variable strings
Johnny Chend0190a62010-08-23 17:10:44 +000040output: (char *[4]) strings = {
41 (char *) strings[0] = 0x0000000100000f0c "Hello",
42 (char *) strings[1] = 0x0000000100000f12 "Hola",
43 (char *) strings[2] = 0x0000000100000f17 "Bonjour",
44 (char *) strings[3] = 0x0000000100000f1f "Guten Tag"
45}
46
Johnny Chen57b47382010-09-02 22:25:47 +000047runCmd: frame variable char_16
Johnny Chend0190a62010-08-23 17:10:44 +000048output: (char [16]) char_16 = {
49 (char) char_16[0] = 'H',
50 (char) char_16[1] = 'e',
51 (char) char_16[2] = 'l',
52 (char) char_16[3] = 'l',
53 (char) char_16[4] = 'o',
54 (char) char_16[5] = ' ',
55 (char) char_16[6] = 'W',
56 (char) char_16[7] = 'o',
57 (char) char_16[8] = 'r',
58 (char) char_16[9] = 'l',
59 (char) char_16[10] = 'd',
60 (char) char_16[11] = '\n',
61 (char) char_16[12] = '\0',
62 (char) char_16[13] = '\0',
63 (char) char_16[14] = '\0',
64 (char) char_16[15] = '\0'
65}
66
Johnny Chen57b47382010-09-02 22:25:47 +000067runCmd: frame variable ushort_matrix
Johnny Chend0190a62010-08-23 17:10:44 +000068output: (unsigned short [2][3]) ushort_matrix = {
69 (unsigned short [3]) ushort_matrix[0] = {
70 (unsigned short) ushort_matrix[0][0] = 0x0001,
71 (unsigned short) ushort_matrix[0][1] = 0x0002,
72 (unsigned short) ushort_matrix[0][2] = 0x0003
73 },
74 (unsigned short [3]) ushort_matrix[1] = {
75 (unsigned short) ushort_matrix[1][0] = 0x000b,
76 (unsigned short) ushort_matrix[1][1] = 0x0016,
77 (unsigned short) ushort_matrix[1][2] = 0x0021
78 }
79}
80
Johnny Chen57b47382010-09-02 22:25:47 +000081runCmd: frame variable long_6
Johnny Chend0190a62010-08-23 17:10:44 +000082output: (long [6]) long_6 = {
83 (long) long_6[0] = 1,
84 (long) long_6[1] = 2,
85 (long) long_6[2] = 3,
86 (long) long_6[3] = 4,
87 (long) long_6[4] = 5,
88 (long) long_6[5] = 6
89}
90
91.
92----------------------------------------------------------------------
93Ran 1 test in 0.349s
94
95OK
Johnny Chenbf6ffa32010-07-03 03:41:59 +000096$
97"""
98
Johnny Chen90312a82010-09-21 22:34:45 +000099import os, sys, traceback
Johnny Chenea88e942010-09-21 21:08:53 +0000100import re
Johnny Chen8952a2d2010-08-30 21:35:00 +0000101from subprocess import *
Johnny Chen150c3cc2010-10-15 01:18:29 +0000102import StringIO
Johnny Chenf2b70232010-08-25 18:49:48 +0000103import time
Johnny Chena33a93c2010-08-30 23:08:52 +0000104import types
Johnny Chen73258832010-08-05 23:42:46 +0000105import unittest2
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000106import lldb
107
Johnny Chen707b3c92010-10-11 22:25:46 +0000108# See also dotest.parseOptionsAndInitTestdirs(), where the environment variables
Johnny Chend2047fa2011-01-19 18:18:47 +0000109# LLDB_COMMAND_TRACE and LLDB_DO_CLEANUP are set from '-t' and '-r dir' options.
Johnny Chen707b3c92010-10-11 22:25:46 +0000110
111# By default, traceAlways is False.
Johnny Chen8d55a342010-08-31 17:42:54 +0000112if "LLDB_COMMAND_TRACE" in os.environ and os.environ["LLDB_COMMAND_TRACE"]=="YES":
113 traceAlways = True
114else:
115 traceAlways = False
116
Johnny Chen707b3c92010-10-11 22:25:46 +0000117# By default, doCleanup is True.
118if "LLDB_DO_CLEANUP" in os.environ and os.environ["LLDB_DO_CLEANUP"]=="NO":
119 doCleanup = False
120else:
121 doCleanup = True
122
Johnny Chen8d55a342010-08-31 17:42:54 +0000123
Johnny Chen00778092010-08-09 22:01:17 +0000124#
125# Some commonly used assert messages.
126#
127
Johnny Chenaa902922010-09-17 22:45:27 +0000128COMMAND_FAILED_AS_EXPECTED = "Command has failed as expected"
129
Johnny Chen00778092010-08-09 22:01:17 +0000130CURRENT_EXECUTABLE_SET = "Current executable set successfully"
131
Johnny Chen7d1d7532010-09-02 21:23:12 +0000132PROCESS_IS_VALID = "Process is valid"
133
134PROCESS_KILLED = "Process is killed successfully"
135
Johnny Chend5f66fc2010-12-23 01:12:19 +0000136PROCESS_EXITED = "Process exited successfully"
137
138PROCESS_STOPPED = "Process status should be stopped"
139
Johnny Chen5ee88192010-08-27 23:47:36 +0000140RUN_SUCCEEDED = "Process is launched successfully"
Johnny Chen00778092010-08-09 22:01:17 +0000141
Johnny Chen17941842010-08-09 23:44:24 +0000142RUN_COMPLETED = "Process exited successfully"
Johnny Chen00778092010-08-09 22:01:17 +0000143
Johnny Chen67af43f2010-10-05 19:27:32 +0000144BACKTRACE_DISPLAYED_CORRECTLY = "Backtrace displayed correctly"
145
Johnny Chen17941842010-08-09 23:44:24 +0000146BREAKPOINT_CREATED = "Breakpoint created successfully"
147
Johnny Chenf10af382010-12-04 00:07:24 +0000148BREAKPOINT_STATE_CORRECT = "Breakpoint state is correct"
149
Johnny Chene76896c2010-08-17 21:33:31 +0000150BREAKPOINT_PENDING_CREATED = "Pending breakpoint created successfully"
151
Johnny Chen17941842010-08-09 23:44:24 +0000152BREAKPOINT_HIT_ONCE = "Breakpoint resolved with hit cout = 1"
Johnny Chen00778092010-08-09 22:01:17 +0000153
Johnny Chen703dbd02010-09-30 17:06:24 +0000154BREAKPOINT_HIT_TWICE = "Breakpoint resolved with hit cout = 2"
155
Johnny Chen164f1e12010-10-15 18:07:09 +0000156BREAKPOINT_HIT_THRICE = "Breakpoint resolved with hit cout = 3"
157
Johnny Chen89109ed12011-06-27 20:05:23 +0000158OBJECT_PRINTED_CORRECTLY = "Object printed correctly"
159
Johnny Chen5b3a3572010-12-09 18:22:12 +0000160SOURCE_DISPLAYED_CORRECTLY = "Source code displayed correctly"
161
Johnny Chenc70b02a2010-09-22 23:00:20 +0000162STEP_OUT_SUCCEEDED = "Thread step-out succeeded"
163
Johnny Chen1691a162011-04-15 16:44:48 +0000164STOPPED_DUE_TO_EXC_BAD_ACCESS = "Process should be stopped due to bad access exception"
165
Johnny Chen5d6c4642010-11-10 23:46:38 +0000166STOPPED_DUE_TO_BREAKPOINT = "Process should be stopped due to breakpoint"
Johnny Chende0338b2010-11-10 20:20:06 +0000167
Johnny Chen5d6c4642010-11-10 23:46:38 +0000168STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS = "%s, %s" % (
169 STOPPED_DUE_TO_BREAKPOINT, "instead, the actual stop reason is: '%s'")
Johnny Chen00778092010-08-09 22:01:17 +0000170
Johnny Chen2e431ce2010-10-20 18:38:48 +0000171STOPPED_DUE_TO_BREAKPOINT_CONDITION = "Stopped due to breakpoint condition"
172
Johnny Chen0a3d1ca2010-12-13 21:49:58 +0000173STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT = "Stopped due to breakpoint and ignore count"
174
Johnny Chenc066ab42010-10-14 01:22:03 +0000175STOPPED_DUE_TO_SIGNAL = "Process state is stopped due to signal"
176
Johnny Chen00778092010-08-09 22:01:17 +0000177STOPPED_DUE_TO_STEP_IN = "Process state is stopped due to step in"
178
Johnny Chenf68cc122011-09-15 21:09:59 +0000179STOPPED_DUE_TO_WATCHPOINT = "Process should be stopped due to watchpoint"
180
Johnny Chen3c884a02010-08-24 22:07:56 +0000181DATA_TYPES_DISPLAYED_CORRECTLY = "Data type(s) displayed correctly"
182
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000183VALID_BREAKPOINT = "Got a valid breakpoint"
184
Johnny Chen5bfb8ee2010-10-22 18:10:25 +0000185VALID_BREAKPOINT_LOCATION = "Got a valid breakpoint location"
186
Johnny Chen7209d84f2011-05-06 23:26:12 +0000187VALID_COMMAND_INTERPRETER = "Got a valid command interpreter"
188
Johnny Chen5ee88192010-08-27 23:47:36 +0000189VALID_FILESPEC = "Got a valid filespec"
190
Johnny Chen025d1b82010-12-08 01:25:21 +0000191VALID_MODULE = "Got a valid module"
192
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000193VALID_PROCESS = "Got a valid process"
194
Johnny Chen025d1b82010-12-08 01:25:21 +0000195VALID_SYMBOL = "Got a valid symbol"
196
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000197VALID_TARGET = "Got a valid target"
198
Johnny Chen15f247a2012-02-03 20:43:00 +0000199VALID_TYPE = "Got a valid type"
200
Johnny Chen5819ab42011-07-15 22:28:10 +0000201VALID_VARIABLE = "Got a valid variable"
202
Johnny Chen981463d2010-08-25 19:00:04 +0000203VARIABLES_DISPLAYED_CORRECTLY = "Variable(s) displayed correctly"
Johnny Chen00778092010-08-09 22:01:17 +0000204
Johnny Chenf68cc122011-09-15 21:09:59 +0000205WATCHPOINT_CREATED = "Watchpoint created successfully"
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000206
Johnny Chenc0c67f22010-11-09 18:42:22 +0000207def CMD_MSG(str):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000208 '''A generic "Command '%s' returns successfully" message generator.'''
Johnny Chenc0c67f22010-11-09 18:42:22 +0000209 return "Command '%s' returns successfully" % str
210
Johnny Chen98aceb02012-01-20 23:02:51 +0000211def COMPLETIOND_MSG(str_before, str_after):
212 '''A generic message generator for the completion mechanism.'''
213 return "'%s' successfully completes to '%s'" % (str_before, str_after)
214
Johnny Chenc0c67f22010-11-09 18:42:22 +0000215def EXP_MSG(str, exe):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000216 '''A generic "'%s' returns expected result" message generator if exe.
217 Otherwise, it generates "'%s' matches expected result" message.'''
Johnny Chenc0c67f22010-11-09 18:42:22 +0000218 return "'%s' %s expected result" % (str, 'returns' if exe else 'matches')
Johnny Chen17941842010-08-09 23:44:24 +0000219
Johnny Chen3343f042010-10-19 19:11:38 +0000220def SETTING_MSG(setting):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000221 '''A generic "Value of setting '%s' is correct" message generator.'''
Johnny Chen3343f042010-10-19 19:11:38 +0000222 return "Value of setting '%s' is correct" % setting
223
Johnny Chen27c41232010-08-26 21:49:29 +0000224def EnvArray():
Johnny Chenaacf92e2011-05-31 22:16:51 +0000225 """Returns an env variable array from the os.environ map object."""
Johnny Chen27c41232010-08-26 21:49:29 +0000226 return map(lambda k,v: k+"="+v, os.environ.keys(), os.environ.values())
227
Johnny Chen47ceb032010-10-11 23:52:19 +0000228def line_number(filename, string_to_match):
229 """Helper function to return the line number of the first matched string."""
230 with open(filename, 'r') as f:
231 for i, line in enumerate(f):
232 if line.find(string_to_match) != -1:
233 # Found our match.
Johnny Chencd9b7772010-10-12 00:09:25 +0000234 return i+1
Johnny Chen1691a162011-04-15 16:44:48 +0000235 raise Exception("Unable to find '%s' within file %s" % (string_to_match, filename))
Johnny Chen47ceb032010-10-11 23:52:19 +0000236
Johnny Chen67af43f2010-10-05 19:27:32 +0000237def pointer_size():
238 """Return the pointer size of the host system."""
239 import ctypes
240 a_pointer = ctypes.c_void_p(0xffff)
241 return 8 * ctypes.sizeof(a_pointer)
242
Johnny Chen150c3cc2010-10-15 01:18:29 +0000243class recording(StringIO.StringIO):
244 """
245 A nice little context manager for recording the debugger interactions into
246 our session object. If trace flag is ON, it also emits the interactions
247 into the stderr.
248 """
249 def __init__(self, test, trace):
Johnny Chen690fcef2010-10-15 23:55:05 +0000250 """Create a StringIO instance; record the session obj and trace flag."""
Johnny Chen150c3cc2010-10-15 01:18:29 +0000251 StringIO.StringIO.__init__(self)
Johnny Chen0241f142011-08-16 22:06:17 +0000252 # The test might not have undergone the 'setUp(self)' phase yet, so that
253 # the attribute 'session' might not even exist yet.
Johnny Chenbfcf37f2011-08-16 17:06:45 +0000254 self.session = getattr(test, "session", None) if test else None
Johnny Chen150c3cc2010-10-15 01:18:29 +0000255 self.trace = trace
256
257 def __enter__(self):
258 """
259 Context management protocol on entry to the body of the with statement.
260 Just return the StringIO object.
261 """
262 return self
263
264 def __exit__(self, type, value, tb):
265 """
266 Context management protocol on exit from the body of the with statement.
267 If trace is ON, it emits the recordings into stderr. Always add the
268 recordings to our session object. And close the StringIO object, too.
269 """
270 if self.trace:
Johnny Chen690fcef2010-10-15 23:55:05 +0000271 print >> sys.stderr, self.getvalue()
272 if self.session:
273 print >> self.session, self.getvalue()
Johnny Chen150c3cc2010-10-15 01:18:29 +0000274 self.close()
275
Johnny Chen690fcef2010-10-15 23:55:05 +0000276# From 2.7's subprocess.check_output() convenience function.
Johnny Chenac77f3b2011-03-23 20:28:59 +0000277# Return a tuple (stdoutdata, stderrdata).
Johnny Chen690fcef2010-10-15 23:55:05 +0000278def system(*popenargs, **kwargs):
Johnny Chen8eb14a92011-11-16 22:44:28 +0000279 r"""Run an os command with arguments and return its output as a byte string.
Johnny Chen690fcef2010-10-15 23:55:05 +0000280
281 If the exit code was non-zero it raises a CalledProcessError. The
282 CalledProcessError object will have the return code in the returncode
283 attribute and output in the output attribute.
284
285 The arguments are the same as for the Popen constructor. Example:
286
287 >>> check_output(["ls", "-l", "/dev/null"])
288 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
289
290 The stdout argument is not allowed as it is used internally.
291 To capture standard error in the result, use stderr=STDOUT.
292
293 >>> check_output(["/bin/sh", "-c",
294 ... "ls -l non_existent_file ; exit 0"],
295 ... stderr=STDOUT)
296 'ls: non_existent_file: No such file or directory\n'
297 """
298
299 # Assign the sender object to variable 'test' and remove it from kwargs.
300 test = kwargs.pop('sender', None)
301
302 if 'stdout' in kwargs:
303 raise ValueError('stdout argument not allowed, it will be overridden.')
Johnny Chenac77f3b2011-03-23 20:28:59 +0000304 process = Popen(stdout=PIPE, stderr=PIPE, *popenargs, **kwargs)
Johnny Chen0bd8c312011-11-16 22:41:53 +0000305 pid = process.pid
Johnny Chen690fcef2010-10-15 23:55:05 +0000306 output, error = process.communicate()
307 retcode = process.poll()
308
309 with recording(test, traceAlways) as sbuf:
310 if isinstance(popenargs, types.StringTypes):
311 args = [popenargs]
312 else:
313 args = list(popenargs)
314 print >> sbuf
315 print >> sbuf, "os command:", args
Johnny Chen0bd8c312011-11-16 22:41:53 +0000316 print >> sbuf, "with pid:", pid
Johnny Chen690fcef2010-10-15 23:55:05 +0000317 print >> sbuf, "stdout:", output
318 print >> sbuf, "stderr:", error
319 print >> sbuf, "retcode:", retcode
320 print >> sbuf
321
322 if retcode:
323 cmd = kwargs.get("args")
324 if cmd is None:
325 cmd = popenargs[0]
326 raise CalledProcessError(retcode, cmd)
Johnny Chenac77f3b2011-03-23 20:28:59 +0000327 return (output, error)
Johnny Chen690fcef2010-10-15 23:55:05 +0000328
Johnny Chenab9c1dd2010-11-01 20:35:01 +0000329def getsource_if_available(obj):
330 """
331 Return the text of the source code for an object if available. Otherwise,
332 a print representation is returned.
333 """
334 import inspect
335 try:
336 return inspect.getsource(obj)
337 except:
338 return repr(obj)
339
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000340def builder_module():
341 return __import__("builder_" + sys.platform)
342
Johnny Chena74bb0a2011-08-01 18:46:13 +0000343#
344# Decorators for categorizing test cases.
345#
346
347from functools import wraps
348def python_api_test(func):
349 """Decorate the item as a Python API only test."""
350 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
351 raise Exception("@python_api_test can only be used to decorate a test method")
352 @wraps(func)
353 def wrapper(self, *args, **kwargs):
354 try:
355 if lldb.dont_do_python_api_test:
356 self.skipTest("python api tests")
357 except AttributeError:
358 pass
359 return func(self, *args, **kwargs)
360
361 # Mark this function as such to separate them from lldb command line tests.
362 wrapper.__python_api_test__ = True
363 return wrapper
364
Johnny Chena74bb0a2011-08-01 18:46:13 +0000365def benchmarks_test(func):
366 """Decorate the item as a benchmarks test."""
367 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
368 raise Exception("@benchmarks_test can only be used to decorate a test method")
369 @wraps(func)
370 def wrapper(self, *args, **kwargs):
371 try:
372 if not lldb.just_do_benchmarks_test:
373 self.skipTest("benchmarks tests")
374 except AttributeError:
375 pass
376 return func(self, *args, **kwargs)
377
378 # Mark this function as such to separate them from the regular tests.
379 wrapper.__benchmarks_test__ = True
380 return wrapper
381
Johnny Chen31963ce2011-08-19 00:54:27 +0000382def expectedFailureClang(func):
383 """Decorate the item as a Clang only expectedFailure."""
384 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
385 raise Exception("@expectedFailureClang can only be used to decorate a test method")
386 @wraps(func)
387 def wrapper(*args, **kwargs):
388 from unittest2 import case
389 self = args[0]
390 compiler = self.getCompiler()
391 try:
392 func(*args, **kwargs)
Johnny Chenb5825b82011-08-19 01:17:09 +0000393 except Exception:
Johnny Chen31963ce2011-08-19 00:54:27 +0000394 if "clang" in compiler:
395 raise case._ExpectedFailure(sys.exc_info())
396 else:
Johnny Chenb5825b82011-08-19 01:17:09 +0000397 raise
Johnny Chen31963ce2011-08-19 00:54:27 +0000398
399 if "clang" in compiler:
400 raise case._UnexpectedSuccess
401 return wrapper
402
Johnny Chena33843f2011-12-22 21:14:31 +0000403def expectedFailurei386(func):
404 """Decorate the item as an i386 only expectedFailure."""
405 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
406 raise Exception("@expectedFailurei386 can only be used to decorate a test method")
407 @wraps(func)
408 def wrapper(*args, **kwargs):
409 from unittest2 import case
410 self = args[0]
411 arch = self.getArchitecture()
412 try:
413 func(*args, **kwargs)
414 except Exception:
415 if "i386" in arch:
416 raise case._ExpectedFailure(sys.exc_info())
417 else:
418 raise
419
420 if "i386" in arch:
421 raise case._UnexpectedSuccess
422 return wrapper
423
Johnny Chena74bb0a2011-08-01 18:46:13 +0000424class Base(unittest2.TestCase):
Johnny Chen8334dad2010-10-22 23:15:46 +0000425 """
Johnny Chena74bb0a2011-08-01 18:46:13 +0000426 Abstract base for performing lldb (see TestBase) or other generic tests (see
427 BenchBase for one example). lldbtest.Base works with the test driver to
428 accomplish things.
429
Johnny Chen8334dad2010-10-22 23:15:46 +0000430 """
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000431 # The concrete subclass should override this attribute.
Johnny Chenf02ec122010-07-03 20:41:42 +0000432 mydir = None
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000433
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000434 # Keep track of the old current working directory.
435 oldcwd = None
Johnny Chena2124952010-08-05 21:23:45 +0000436
Johnny Chenfb4264c2011-08-01 19:50:58 +0000437 def TraceOn(self):
438 """Returns True if we are in trace mode (tracing detailed test execution)."""
439 return traceAlways
440
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000441 @classmethod
442 def setUpClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +0000443 """
444 Python unittest framework class setup fixture.
445 Do current directory manipulation.
446 """
447
Johnny Chenf02ec122010-07-03 20:41:42 +0000448 # Fail fast if 'mydir' attribute is not overridden.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000449 if not cls.mydir or len(cls.mydir) == 0:
Johnny Chenf02ec122010-07-03 20:41:42 +0000450 raise Exception("Subclasses must override the 'mydir' attribute.")
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000451 # Save old working directory.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000452 cls.oldcwd = os.getcwd()
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000453
454 # Change current working directory if ${LLDB_TEST} is defined.
455 # See also dotest.py which sets up ${LLDB_TEST}.
456 if ("LLDB_TEST" in os.environ):
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000457 if traceAlways:
Johnny Chen703dbd02010-09-30 17:06:24 +0000458 print >> sys.stderr, "Change dir to:", os.path.join(os.environ["LLDB_TEST"], cls.mydir)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000459 os.chdir(os.path.join(os.environ["LLDB_TEST"], cls.mydir))
460
461 @classmethod
462 def tearDownClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +0000463 """
464 Python unittest framework class teardown fixture.
465 Do class-wide cleanup.
466 """
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000467
Johnny Chen0fddfb22011-11-17 19:57:27 +0000468 if doCleanup and not lldb.skip_build_and_cleanup:
Johnny Chen707b3c92010-10-11 22:25:46 +0000469 # First, let's do the platform-specific cleanup.
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000470 module = builder_module()
Johnny Chen707b3c92010-10-11 22:25:46 +0000471 if not module.cleanup():
472 raise Exception("Don't know how to do cleanup")
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000473
Johnny Chen707b3c92010-10-11 22:25:46 +0000474 # Subclass might have specific cleanup function defined.
475 if getattr(cls, "classCleanup", None):
476 if traceAlways:
477 print >> sys.stderr, "Call class-specific cleanup function for class:", cls
478 try:
479 cls.classCleanup()
480 except:
481 exc_type, exc_value, exc_tb = sys.exc_info()
482 traceback.print_exception(exc_type, exc_value, exc_tb)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000483
484 # Restore old working directory.
485 if traceAlways:
Johnny Chen703dbd02010-09-30 17:06:24 +0000486 print >> sys.stderr, "Restore dir to:", cls.oldcwd
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000487 os.chdir(cls.oldcwd)
488
Johnny Chena74bb0a2011-08-01 18:46:13 +0000489 @classmethod
490 def skipLongRunningTest(cls):
491 """
492 By default, we skip long running test case.
493 This can be overridden by passing '-l' to the test driver (dotest.py).
494 """
495 if "LLDB_SKIP_LONG_RUNNING_TEST" in os.environ and "NO" == os.environ["LLDB_SKIP_LONG_RUNNING_TEST"]:
496 return False
497 else:
498 return True
Johnny Chened492022011-06-21 00:53:00 +0000499
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000500 def setUp(self):
Johnny Chenfb4264c2011-08-01 19:50:58 +0000501 """Fixture for unittest test case setup.
502
503 It works with the test driver to conditionally skip tests and does other
504 initializations."""
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000505 #import traceback
506 #traceback.print_stack()
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000507
Johnny Chenaaa82ff2011-08-02 22:54:37 +0000508 if "LLDB_EXEC" in os.environ:
509 self.lldbExec = os.environ["LLDB_EXEC"]
Johnny Chend890bfc2011-08-26 00:00:01 +0000510 else:
511 self.lldbExec = None
512 if "LLDB_HERE" in os.environ:
513 self.lldbHere = os.environ["LLDB_HERE"]
514 else:
515 self.lldbHere = None
Johnny Chenebe51722011-10-07 19:21:09 +0000516 # If we spawn an lldb process for test (via pexpect), do not load the
517 # init file unless told otherwise.
518 if "NO_LLDBINIT" in os.environ and "NO" == os.environ["NO_LLDBINIT"]:
519 self.lldbOption = ""
520 else:
521 self.lldbOption = "--no-lldbinit"
Johnny Chenaaa82ff2011-08-02 22:54:37 +0000522
Johnny Chen985e7402011-08-01 21:13:26 +0000523 # Assign the test method name to self.testMethodName.
524 #
525 # For an example of the use of this attribute, look at test/types dir.
526 # There are a bunch of test cases under test/types and we don't want the
527 # module cacheing subsystem to be confused with executable name "a.out"
528 # used for all the test cases.
529 self.testMethodName = self._testMethodName
530
Johnny Chenf3e22ac2010-12-10 18:52:10 +0000531 # Python API only test is decorated with @python_api_test,
532 # which also sets the "__python_api_test__" attribute of the
533 # function object to True.
Johnny Chen4533dad2011-05-31 23:21:42 +0000534 try:
535 if lldb.just_do_python_api_test:
536 testMethod = getattr(self, self._testMethodName)
537 if getattr(testMethod, "__python_api_test__", False):
538 pass
539 else:
Johnny Chen5ccbccf2011-07-30 01:39:58 +0000540 self.skipTest("non python api test")
541 except AttributeError:
542 pass
543
544 # Benchmarks test is decorated with @benchmarks_test,
545 # which also sets the "__benchmarks_test__" attribute of the
546 # function object to True.
547 try:
548 if lldb.just_do_benchmarks_test:
549 testMethod = getattr(self, self._testMethodName)
550 if getattr(testMethod, "__benchmarks_test__", False):
551 pass
552 else:
553 self.skipTest("non benchmarks test")
Johnny Chen4533dad2011-05-31 23:21:42 +0000554 except AttributeError:
555 pass
Johnny Chenf3e22ac2010-12-10 18:52:10 +0000556
Johnny Chen985e7402011-08-01 21:13:26 +0000557 # This is for the case of directly spawning 'lldb'/'gdb' and interacting
558 # with it using pexpect.
559 self.child = None
560 self.child_prompt = "(lldb) "
561 # If the child is interacting with the embedded script interpreter,
562 # there are two exits required during tear down, first to quit the
563 # embedded script interpreter and second to quit the lldb command
564 # interpreter.
565 self.child_in_script_interpreter = False
566
Johnny Chenfb4264c2011-08-01 19:50:58 +0000567 # These are for customized teardown cleanup.
568 self.dict = None
569 self.doTearDownCleanup = False
570 # And in rare cases where there are multiple teardown cleanups.
571 self.dicts = []
572 self.doTearDownCleanups = False
573
574 # Create a string buffer to record the session info, to be dumped into a
575 # test case specific file if test failure is encountered.
576 self.session = StringIO.StringIO()
577
578 # Optimistically set __errored__, __failed__, __expected__ to False
579 # initially. If the test errored/failed, the session info
580 # (self.session) is then dumped into a session specific file for
581 # diagnosis.
582 self.__errored__ = False
583 self.__failed__ = False
584 self.__expected__ = False
585 # We are also interested in unexpected success.
586 self.__unexpected__ = False
Johnny Chenf79b0762011-08-16 00:48:58 +0000587 # And skipped tests.
588 self.__skipped__ = False
Johnny Chenfb4264c2011-08-01 19:50:58 +0000589
590 # See addTearDownHook(self, hook) which allows the client to add a hook
591 # function to be run during tearDown() time.
592 self.hooks = []
593
594 # See HideStdout(self).
595 self.sys_stdout_hidden = False
596
Johnny Chen2a808582011-10-19 16:48:07 +0000597 def runHooks(self, child=None, child_prompt=None, use_cmd_api=False):
Johnny Chena737ba52011-10-19 01:06:21 +0000598 """Perform the run hooks to bring lldb debugger to the desired state.
599
Johnny Chen2a808582011-10-19 16:48:07 +0000600 By default, expect a pexpect spawned child and child prompt to be
601 supplied (use_cmd_api=False). If use_cmd_api is true, ignore the child
602 and child prompt and use self.runCmd() to run the hooks one by one.
603
Johnny Chena737ba52011-10-19 01:06:21 +0000604 Note that child is a process spawned by pexpect.spawn(). If not, your
605 test case is mostly likely going to fail.
606
607 See also dotest.py where lldb.runHooks are processed/populated.
608 """
609 if not lldb.runHooks:
610 self.skipTest("No runhooks specified for lldb, skip the test")
Johnny Chen2a808582011-10-19 16:48:07 +0000611 if use_cmd_api:
612 for hook in lldb.runhooks:
613 self.runCmd(hook)
614 else:
615 if not child or not child_prompt:
616 self.fail("Both child and child_prompt need to be defined.")
617 for hook in lldb.runHooks:
618 child.sendline(hook)
619 child.expect_exact(child_prompt)
Johnny Chena737ba52011-10-19 01:06:21 +0000620
Johnny Chenfb4264c2011-08-01 19:50:58 +0000621 def HideStdout(self):
622 """Hide output to stdout from the user.
623
624 During test execution, there might be cases where we don't want to show the
625 standard output to the user. For example,
626
627 self.runCmd(r'''sc print "\n\n\tHello!\n"''')
628
629 tests whether command abbreviation for 'script' works or not. There is no
630 need to show the 'Hello' output to the user as long as the 'script' command
631 succeeds and we are not in TraceOn() mode (see the '-t' option).
632
633 In this case, the test method calls self.HideStdout(self) to redirect the
634 sys.stdout to a null device, and restores the sys.stdout upon teardown.
635
636 Note that you should only call this method at most once during a test case
637 execution. Any subsequent call has no effect at all."""
638 if self.sys_stdout_hidden:
639 return
640
641 self.sys_stdout_hidden = True
642 old_stdout = sys.stdout
643 sys.stdout = open(os.devnull, 'w')
644 def restore_stdout():
645 sys.stdout = old_stdout
646 self.addTearDownHook(restore_stdout)
647
648 # =======================================================================
649 # Methods for customized teardown cleanups as well as execution of hooks.
650 # =======================================================================
651
652 def setTearDownCleanup(self, dictionary=None):
653 """Register a cleanup action at tearDown() time with a dictinary"""
654 self.dict = dictionary
655 self.doTearDownCleanup = True
656
657 def addTearDownCleanup(self, dictionary):
658 """Add a cleanup action at tearDown() time with a dictinary"""
659 self.dicts.append(dictionary)
660 self.doTearDownCleanups = True
661
662 def addTearDownHook(self, hook):
663 """
664 Add a function to be run during tearDown() time.
665
666 Hooks are executed in a first come first serve manner.
667 """
668 if callable(hook):
669 with recording(self, traceAlways) as sbuf:
670 print >> sbuf, "Adding tearDown hook:", getsource_if_available(hook)
671 self.hooks.append(hook)
672
673 def tearDown(self):
674 """Fixture for unittest test case teardown."""
675 #import traceback
676 #traceback.print_stack()
677
Johnny Chen985e7402011-08-01 21:13:26 +0000678 # This is for the case of directly spawning 'lldb' and interacting with it
679 # using pexpect.
680 import pexpect
681 if self.child and self.child.isalive():
682 with recording(self, traceAlways) as sbuf:
683 print >> sbuf, "tearing down the child process...."
684 if self.child_in_script_interpreter:
685 self.child.sendline('quit()')
686 self.child.expect_exact(self.child_prompt)
687 self.child.sendline('quit')
688 try:
689 self.child.expect(pexpect.EOF)
690 except:
691 pass
692
Johnny Chenfb4264c2011-08-01 19:50:58 +0000693 # Check and run any hook functions.
694 for hook in reversed(self.hooks):
695 with recording(self, traceAlways) as sbuf:
696 print >> sbuf, "Executing tearDown hook:", getsource_if_available(hook)
697 hook()
698
699 del self.hooks
700
701 # Perform registered teardown cleanup.
702 if doCleanup and self.doTearDownCleanup:
Johnny Chen0fddfb22011-11-17 19:57:27 +0000703 self.cleanup(dictionary=self.dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +0000704
705 # In rare cases where there are multiple teardown cleanups added.
706 if doCleanup and self.doTearDownCleanups:
Johnny Chenfb4264c2011-08-01 19:50:58 +0000707 if self.dicts:
708 for dict in reversed(self.dicts):
Johnny Chen0fddfb22011-11-17 19:57:27 +0000709 self.cleanup(dictionary=dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +0000710
711 # Decide whether to dump the session info.
712 self.dumpSessionInfo()
713
714 # =========================================================
715 # Various callbacks to allow introspection of test progress
716 # =========================================================
717
718 def markError(self):
719 """Callback invoked when an error (unexpected exception) errored."""
720 self.__errored__ = True
721 with recording(self, False) as sbuf:
722 # False because there's no need to write "ERROR" to the stderr twice.
723 # Once by the Python unittest framework, and a second time by us.
724 print >> sbuf, "ERROR"
725
726 def markFailure(self):
727 """Callback invoked when a failure (test assertion failure) occurred."""
728 self.__failed__ = True
729 with recording(self, False) as sbuf:
730 # False because there's no need to write "FAIL" to the stderr twice.
731 # Once by the Python unittest framework, and a second time by us.
732 print >> sbuf, "FAIL"
733
734 def markExpectedFailure(self):
735 """Callback invoked when an expected failure/error occurred."""
736 self.__expected__ = True
737 with recording(self, False) as sbuf:
738 # False because there's no need to write "expected failure" to the
739 # stderr twice.
740 # Once by the Python unittest framework, and a second time by us.
741 print >> sbuf, "expected failure"
742
Johnny Chenc5cc6252011-08-15 23:09:08 +0000743 def markSkippedTest(self):
744 """Callback invoked when a test is skipped."""
745 self.__skipped__ = True
746 with recording(self, False) as sbuf:
747 # False because there's no need to write "skipped test" to the
748 # stderr twice.
749 # Once by the Python unittest framework, and a second time by us.
750 print >> sbuf, "skipped test"
751
Johnny Chenfb4264c2011-08-01 19:50:58 +0000752 def markUnexpectedSuccess(self):
753 """Callback invoked when an unexpected success occurred."""
754 self.__unexpected__ = True
755 with recording(self, False) as sbuf:
756 # False because there's no need to write "unexpected success" to the
757 # stderr twice.
758 # Once by the Python unittest framework, and a second time by us.
759 print >> sbuf, "unexpected success"
760
761 def dumpSessionInfo(self):
762 """
763 Dump the debugger interactions leading to a test error/failure. This
764 allows for more convenient postmortem analysis.
765
766 See also LLDBTestResult (dotest.py) which is a singlton class derived
767 from TextTestResult and overwrites addError, addFailure, and
768 addExpectedFailure methods to allow us to to mark the test instance as
769 such.
770 """
771
772 # We are here because self.tearDown() detected that this test instance
773 # either errored or failed. The lldb.test_result singleton contains
774 # two lists (erros and failures) which get populated by the unittest
775 # framework. Look over there for stack trace information.
776 #
777 # The lists contain 2-tuples of TestCase instances and strings holding
778 # formatted tracebacks.
779 #
780 # See http://docs.python.org/library/unittest.html#unittest.TestResult.
781 if self.__errored__:
782 pairs = lldb.test_result.errors
783 prefix = 'Error'
784 elif self.__failed__:
785 pairs = lldb.test_result.failures
786 prefix = 'Failure'
787 elif self.__expected__:
788 pairs = lldb.test_result.expectedFailures
789 prefix = 'ExpectedFailure'
Johnny Chenc5cc6252011-08-15 23:09:08 +0000790 elif self.__skipped__:
791 prefix = 'SkippedTest'
Johnny Chenfb4264c2011-08-01 19:50:58 +0000792 elif self.__unexpected__:
793 prefix = "UnexpectedSuccess"
794 else:
795 # Simply return, there's no session info to dump!
796 return
797
Johnny Chenc5cc6252011-08-15 23:09:08 +0000798 if not self.__unexpected__ and not self.__skipped__:
Johnny Chenfb4264c2011-08-01 19:50:58 +0000799 for test, traceback in pairs:
800 if test is self:
801 print >> self.session, traceback
802
Johnny Chen8082a002011-08-11 00:16:28 +0000803 testMethod = getattr(self, self._testMethodName)
804 if getattr(testMethod, "__benchmarks_test__", False):
805 benchmarks = True
806 else:
807 benchmarks = False
808
Johnny Chen5daa6de2011-12-03 00:16:59 +0000809 # This records the compiler version used for the test.
810 system([self.getCompiler(), "-v"], sender=self)
811
Johnny Chenfb4264c2011-08-01 19:50:58 +0000812 dname = os.path.join(os.environ["LLDB_TEST"],
813 os.environ["LLDB_SESSION_DIRNAME"])
814 if not os.path.isdir(dname):
815 os.mkdir(dname)
816 fname = os.path.join(dname, "%s-%s.log" % (prefix, self.id()))
817 with open(fname, "w") as f:
818 import datetime
819 print >> f, "Session info generated @", datetime.datetime.now().ctime()
820 print >> f, self.session.getvalue()
821 print >> f, "To rerun this test, issue the following command from the 'test' directory:\n"
Johnny Chen8082a002011-08-11 00:16:28 +0000822 print >> f, "./dotest.py %s -v %s -f %s.%s" % (self.getRunOptions(),
823 ('+b' if benchmarks else '-t'),
Johnny Chenfb4264c2011-08-01 19:50:58 +0000824 self.__class__.__name__,
825 self._testMethodName)
826
827 # ====================================================
828 # Config. methods supported through a plugin interface
829 # (enables reading of the current test configuration)
830 # ====================================================
831
832 def getArchitecture(self):
833 """Returns the architecture in effect the test suite is running with."""
834 module = builder_module()
835 return module.getArchitecture()
836
837 def getCompiler(self):
838 """Returns the compiler in effect the test suite is running with."""
839 module = builder_module()
840 return module.getCompiler()
841
842 def getRunOptions(self):
843 """Command line option for -A and -C to run this test again, called from
844 self.dumpSessionInfo()."""
845 arch = self.getArchitecture()
846 comp = self.getCompiler()
Johnny Chenb7bdd102011-08-24 19:48:51 +0000847 if arch:
848 option_str = "-A " + arch
Johnny Chenfb4264c2011-08-01 19:50:58 +0000849 else:
Johnny Chenb7bdd102011-08-24 19:48:51 +0000850 option_str = ""
851 if comp:
852 option_str += "-C " + comp
853 return option_str
Johnny Chenfb4264c2011-08-01 19:50:58 +0000854
855 # ==================================================
856 # Build methods supported through a plugin interface
857 # ==================================================
858
Johnny Chenfdc80a5c2012-02-01 01:49:50 +0000859 def buildDefault(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +0000860 """Platform specific way to build the default binaries."""
Johnny Chen0fddfb22011-11-17 19:57:27 +0000861 if lldb.skip_build_and_cleanup:
862 return
Johnny Chenfb4264c2011-08-01 19:50:58 +0000863 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +0000864 if not module.buildDefault(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +0000865 raise Exception("Don't know how to build default binary")
866
Johnny Chenfdc80a5c2012-02-01 01:49:50 +0000867 def buildDsym(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +0000868 """Platform specific way to build binaries with dsym info."""
Johnny Chen0fddfb22011-11-17 19:57:27 +0000869 if lldb.skip_build_and_cleanup:
870 return
Johnny Chenfb4264c2011-08-01 19:50:58 +0000871 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +0000872 if not module.buildDsym(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +0000873 raise Exception("Don't know how to build binary with dsym")
874
Johnny Chenfdc80a5c2012-02-01 01:49:50 +0000875 def buildDwarf(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +0000876 """Platform specific way to build binaries with dwarf maps."""
Johnny Chen0fddfb22011-11-17 19:57:27 +0000877 if lldb.skip_build_and_cleanup:
878 return
Johnny Chenfb4264c2011-08-01 19:50:58 +0000879 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +0000880 if not module.buildDwarf(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +0000881 raise Exception("Don't know how to build binary with dwarf")
Johnny Chena74bb0a2011-08-01 18:46:13 +0000882
Johnny Chen9f4f5d92011-08-12 20:19:22 +0000883 def cleanup(self, dictionary=None):
884 """Platform specific way to do cleanup after build."""
Johnny Chen0fddfb22011-11-17 19:57:27 +0000885 if lldb.skip_build_and_cleanup:
886 return
Johnny Chen9f4f5d92011-08-12 20:19:22 +0000887 module = builder_module()
888 if not module.cleanup(self, dictionary):
Johnny Chen0fddfb22011-11-17 19:57:27 +0000889 raise Exception("Don't know how to do cleanup with dictionary: "+dictionary)
Johnny Chen9f4f5d92011-08-12 20:19:22 +0000890
Johnny Chena74bb0a2011-08-01 18:46:13 +0000891
892class TestBase(Base):
893 """
894 This abstract base class is meant to be subclassed. It provides default
895 implementations for setUpClass(), tearDownClass(), setUp(), and tearDown(),
896 among other things.
897
898 Important things for test class writers:
899
900 - Overwrite the mydir class attribute, otherwise your test class won't
901 run. It specifies the relative directory to the top level 'test' so
902 the test harness can change to the correct working directory before
903 running your test.
904
905 - The setUp method sets up things to facilitate subsequent interactions
906 with the debugger as part of the test. These include:
907 - populate the test method name
908 - create/get a debugger set with synchronous mode (self.dbg)
909 - get the command interpreter from with the debugger (self.ci)
910 - create a result object for use with the command interpreter
911 (self.res)
912 - plus other stuffs
913
914 - The tearDown method tries to perform some necessary cleanup on behalf
915 of the test to return the debugger to a good state for the next test.
916 These include:
917 - execute any tearDown hooks registered by the test method with
918 TestBase.addTearDownHook(); examples can be found in
919 settings/TestSettings.py
920 - kill the inferior process associated with each target, if any,
921 and, then delete the target from the debugger's target list
922 - perform build cleanup before running the next test method in the
923 same test class; examples of registering for this service can be
924 found in types/TestIntegerTypes.py with the call:
925 - self.setTearDownCleanup(dictionary=d)
926
927 - Similarly setUpClass and tearDownClass perform classwise setup and
928 teardown fixtures. The tearDownClass method invokes a default build
929 cleanup for the entire test class; also, subclasses can implement the
930 classmethod classCleanup(cls) to perform special class cleanup action.
931
932 - The instance methods runCmd and expect are used heavily by existing
933 test cases to send a command to the command interpreter and to perform
934 string/pattern matching on the output of such command execution. The
935 expect method also provides a mode to peform string/pattern matching
936 without running a command.
937
938 - The build methods buildDefault, buildDsym, and buildDwarf are used to
939 build the binaries used during a particular test scenario. A plugin
940 should be provided for the sys.platform running the test suite. The
941 Mac OS X implementation is located in plugins/darwin.py.
942 """
943
944 # Maximum allowed attempts when launching the inferior process.
945 # Can be overridden by the LLDB_MAX_LAUNCH_COUNT environment variable.
946 maxLaunchCount = 3;
947
948 # Time to wait before the next launching attempt in second(s).
949 # Can be overridden by the LLDB_TIME_WAIT_NEXT_LAUNCH environment variable.
950 timeWaitNextLaunch = 1.0;
951
952 def doDelay(self):
953 """See option -w of dotest.py."""
954 if ("LLDB_WAIT_BETWEEN_TEST_CASES" in os.environ and
955 os.environ["LLDB_WAIT_BETWEEN_TEST_CASES"] == 'YES'):
956 waitTime = 1.0
957 if "LLDB_TIME_WAIT_BETWEEN_TEST_CASES" in os.environ:
958 waitTime = float(os.environ["LLDB_TIME_WAIT_BETWEEN_TEST_CASES"])
959 time.sleep(waitTime)
960
961 def setUp(self):
962 #import traceback
963 #traceback.print_stack()
964
965 # Works with the test driver to conditionally skip tests via decorators.
966 Base.setUp(self)
967
Johnny Chena74bb0a2011-08-01 18:46:13 +0000968 try:
969 if lldb.blacklist:
970 className = self.__class__.__name__
971 classAndMethodName = "%s.%s" % (className, self._testMethodName)
972 if className in lldb.blacklist:
973 self.skipTest(lldb.blacklist.get(className))
974 elif classAndMethodName in lldb.blacklist:
975 self.skipTest(lldb.blacklist.get(classAndMethodName))
976 except AttributeError:
977 pass
978
Johnny Chened492022011-06-21 00:53:00 +0000979 # Insert some delay between successive test cases if specified.
980 self.doDelay()
Johnny Chen0ed37c92010-10-07 02:04:14 +0000981
Johnny Chenf2b70232010-08-25 18:49:48 +0000982 if "LLDB_MAX_LAUNCH_COUNT" in os.environ:
983 self.maxLaunchCount = int(os.environ["LLDB_MAX_LAUNCH_COUNT"])
984
Johnny Chen430eb762010-10-19 16:00:42 +0000985 if "LLDB_TIME_WAIT_NEXT_LAUNCH" in os.environ:
Johnny Chen4921b112010-11-29 20:20:34 +0000986 self.timeWaitNextLaunch = float(os.environ["LLDB_TIME_WAIT_NEXT_LAUNCH"])
Johnny Chenf2b70232010-08-25 18:49:48 +0000987
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000988 # Create the debugger instance if necessary.
989 try:
990 self.dbg = lldb.DBG
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000991 except AttributeError:
992 self.dbg = lldb.SBDebugger.Create()
Johnny Chenf02ec122010-07-03 20:41:42 +0000993
Johnny Chen3cd1e552011-05-25 19:06:18 +0000994 if not self.dbg:
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000995 raise Exception('Invalid debugger instance')
996
997 # We want our debugger to be synchronous.
998 self.dbg.SetAsync(False)
999
1000 # Retrieve the associated command interpreter instance.
1001 self.ci = self.dbg.GetCommandInterpreter()
1002 if not self.ci:
1003 raise Exception('Could not get the command interpreter')
1004
1005 # And the result object.
1006 self.res = lldb.SBCommandReturnObject()
1007
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001008 def tearDown(self):
Johnny Chen7d1d7532010-09-02 21:23:12 +00001009 #import traceback
1010 #traceback.print_stack()
1011
Johnny Chenfb4264c2011-08-01 19:50:58 +00001012 Base.tearDown(self)
Johnny Chen707d8222010-10-19 23:40:13 +00001013
Johnny Chen3794ad92011-06-15 21:24:24 +00001014 # Delete the target(s) from the debugger as a general cleanup step.
1015 # This includes terminating the process for each target, if any.
1016 # We'd like to reuse the debugger for our next test without incurring
1017 # the initialization overhead.
1018 targets = []
1019 for target in self.dbg:
1020 if target:
1021 targets.append(target)
1022 process = target.GetProcess()
1023 if process:
1024 rc = self.invoke(process, "Kill")
1025 self.assertTrue(rc.Success(), PROCESS_KILLED)
1026 for target in targets:
1027 self.dbg.DeleteTarget(target)
Johnny Chen6ca006c2010-08-16 21:28:10 +00001028
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001029 del self.dbg
Johnny Chen150c3cc2010-10-15 01:18:29 +00001030
Johnny Chen86268e42011-09-30 21:48:35 +00001031 def switch_to_thread_with_stop_reason(self, stop_reason):
1032 """
1033 Run the 'thread list' command, and select the thread with stop reason as
1034 'stop_reason'. If no such thread exists, no select action is done.
1035 """
1036 from lldbutil import stop_reason_to_str
1037 self.runCmd('thread list')
1038 output = self.res.GetOutput()
1039 thread_line_pattern = re.compile("^[ *] thread #([0-9]+):.*stop reason = %s" %
1040 stop_reason_to_str(stop_reason))
1041 for line in output.splitlines():
1042 matched = thread_line_pattern.match(line)
1043 if matched:
1044 self.runCmd('thread select %s' % matched.group(1))
1045
Johnny Chen5b67ca82011-06-15 21:38:39 +00001046 def runCmd(self, cmd, msg=None, check=True, trace=False):
Johnny Chen27f212d2010-08-19 23:26:59 +00001047 """
1048 Ask the command interpreter to handle the command and then check its
1049 return status.
1050 """
1051 # Fail fast if 'cmd' is not meaningful.
1052 if not cmd or len(cmd) == 0:
1053 raise Exception("Bad 'cmd' parameter encountered")
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001054
Johnny Chen8d55a342010-08-31 17:42:54 +00001055 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00001056
Johnny Chen63dfb272010-09-01 00:15:19 +00001057 running = (cmd.startswith("run") or cmd.startswith("process launch"))
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001058
Johnny Chen63dfb272010-09-01 00:15:19 +00001059 for i in range(self.maxLaunchCount if running else 1):
Johnny Chenf2b70232010-08-25 18:49:48 +00001060 self.ci.HandleCommand(cmd, self.res)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001061
Johnny Chen150c3cc2010-10-15 01:18:29 +00001062 with recording(self, trace) as sbuf:
1063 print >> sbuf, "runCmd:", cmd
Johnny Chenab254f52010-10-15 16:13:00 +00001064 if not check:
Johnny Chen27b107b2010-10-15 18:52:22 +00001065 print >> sbuf, "check of return status not required"
Johnny Chenf2b70232010-08-25 18:49:48 +00001066 if self.res.Succeeded():
Johnny Chen150c3cc2010-10-15 01:18:29 +00001067 print >> sbuf, "output:", self.res.GetOutput()
Johnny Chenf2b70232010-08-25 18:49:48 +00001068 else:
Johnny Chen150c3cc2010-10-15 01:18:29 +00001069 print >> sbuf, "runCmd failed!"
1070 print >> sbuf, self.res.GetError()
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001071
Johnny Chenff3d01d2010-08-20 21:03:09 +00001072 if self.res.Succeeded():
Johnny Chenf2b70232010-08-25 18:49:48 +00001073 break
Johnny Chen150c3cc2010-10-15 01:18:29 +00001074 elif running:
Johnny Chencf7f74e2011-01-19 02:02:08 +00001075 # For process launch, wait some time before possible next try.
1076 time.sleep(self.timeWaitNextLaunch)
Johnny Chen150c3cc2010-10-15 01:18:29 +00001077 with recording(self, True) as sbuf:
1078 print >> sbuf, "Command '" + cmd + "' failed!"
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001079
Johnny Chen27f212d2010-08-19 23:26:59 +00001080 if check:
1081 self.assertTrue(self.res.Succeeded(),
Johnny Chenc0c67f22010-11-09 18:42:22 +00001082 msg if msg else CMD_MSG(cmd))
Johnny Chen27f212d2010-08-19 23:26:59 +00001083
Johnny Chen86268e42011-09-30 21:48:35 +00001084 def expect(self, str, msg=None, patterns=None, startstr=None, endstr=None, substrs=None, trace=False, error=False, matching=True, exe=True):
Johnny Chen27f212d2010-08-19 23:26:59 +00001085 """
1086 Similar to runCmd; with additional expect style output matching ability.
1087
1088 Ask the command interpreter to handle the command and then check its
1089 return status. The 'msg' parameter specifies an informational assert
1090 message. We expect the output from running the command to start with
Johnny Chenea88e942010-09-21 21:08:53 +00001091 'startstr', matches the substrings contained in 'substrs', and regexp
1092 matches the patterns contained in 'patterns'.
Johnny Chenb3307862010-09-17 22:28:51 +00001093
1094 If the keyword argument error is set to True, it signifies that the API
1095 client is expecting the command to fail. In this case, the error stream
Johnny Chenaa902922010-09-17 22:45:27 +00001096 from running the command is retrieved and compared against the golden
Johnny Chenb3307862010-09-17 22:28:51 +00001097 input, instead.
Johnny Chenea88e942010-09-21 21:08:53 +00001098
1099 If the keyword argument matching is set to False, it signifies that the API
1100 client is expecting the output of the command not to match the golden
1101 input.
Johnny Chen9c48b8d2010-09-21 23:33:30 +00001102
1103 Finally, the required argument 'str' represents the lldb command to be
1104 sent to the command interpreter. In case the keyword argument 'exe' is
1105 set to False, the 'str' is treated as a string to be matched/not-matched
1106 against the golden input.
Johnny Chen27f212d2010-08-19 23:26:59 +00001107 """
Johnny Chen8d55a342010-08-31 17:42:54 +00001108 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00001109
Johnny Chen9c48b8d2010-09-21 23:33:30 +00001110 if exe:
1111 # First run the command. If we are expecting error, set check=False.
Johnny Chen62d4f862010-10-28 21:10:32 +00001112 # Pass the assert message along since it provides more semantic info.
Johnny Chenebfff952010-10-28 18:24:22 +00001113 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error)
Johnny Chen27f212d2010-08-19 23:26:59 +00001114
Johnny Chen9c48b8d2010-09-21 23:33:30 +00001115 # Then compare the output against expected strings.
1116 output = self.res.GetError() if error else self.res.GetOutput()
Johnny Chenb3307862010-09-17 22:28:51 +00001117
Johnny Chen9c48b8d2010-09-21 23:33:30 +00001118 # If error is True, the API client expects the command to fail!
1119 if error:
1120 self.assertFalse(self.res.Succeeded(),
1121 "Command '" + str + "' is expected to fail!")
1122 else:
1123 # No execution required, just compare str against the golden input.
1124 output = str
Johnny Chen150c3cc2010-10-15 01:18:29 +00001125 with recording(self, trace) as sbuf:
1126 print >> sbuf, "looking at:", output
Johnny Chenb3307862010-09-17 22:28:51 +00001127
Johnny Chenea88e942010-09-21 21:08:53 +00001128 # The heading says either "Expecting" or "Not expecting".
Johnny Chen150c3cc2010-10-15 01:18:29 +00001129 heading = "Expecting" if matching else "Not expecting"
Johnny Chenea88e942010-09-21 21:08:53 +00001130
1131 # Start from the startstr, if specified.
1132 # If there's no startstr, set the initial state appropriately.
1133 matched = output.startswith(startstr) if startstr else (True if matching else False)
Johnny Chenb145bba2010-08-20 18:25:15 +00001134
Johnny Chen150c3cc2010-10-15 01:18:29 +00001135 if startstr:
1136 with recording(self, trace) as sbuf:
1137 print >> sbuf, "%s start string: %s" % (heading, startstr)
1138 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenb145bba2010-08-20 18:25:15 +00001139
Johnny Chen86268e42011-09-30 21:48:35 +00001140 # Look for endstr, if specified.
1141 keepgoing = matched if matching else not matched
1142 if endstr:
1143 matched = output.endswith(endstr)
1144 with recording(self, trace) as sbuf:
1145 print >> sbuf, "%s end string: %s" % (heading, endstr)
1146 print >> sbuf, "Matched" if matched else "Not matched"
1147
Johnny Chenea88e942010-09-21 21:08:53 +00001148 # Look for sub strings, if specified.
1149 keepgoing = matched if matching else not matched
1150 if substrs and keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00001151 for str in substrs:
Johnny Chenb052f6c2010-09-23 23:35:28 +00001152 matched = output.find(str) != -1
Johnny Chen150c3cc2010-10-15 01:18:29 +00001153 with recording(self, trace) as sbuf:
1154 print >> sbuf, "%s sub string: %s" % (heading, str)
1155 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenea88e942010-09-21 21:08:53 +00001156 keepgoing = matched if matching else not matched
1157 if not keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00001158 break
1159
Johnny Chenea88e942010-09-21 21:08:53 +00001160 # Search for regular expression patterns, if specified.
1161 keepgoing = matched if matching else not matched
1162 if patterns and keepgoing:
1163 for pattern in patterns:
1164 # Match Objects always have a boolean value of True.
1165 matched = bool(re.search(pattern, output))
Johnny Chen150c3cc2010-10-15 01:18:29 +00001166 with recording(self, trace) as sbuf:
1167 print >> sbuf, "%s pattern: %s" % (heading, pattern)
1168 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenea88e942010-09-21 21:08:53 +00001169 keepgoing = matched if matching else not matched
1170 if not keepgoing:
1171 break
Johnny Chenea88e942010-09-21 21:08:53 +00001172
1173 self.assertTrue(matched if matching else not matched,
Johnny Chenc0c67f22010-11-09 18:42:22 +00001174 msg if msg else EXP_MSG(str, exe))
Johnny Chen27f212d2010-08-19 23:26:59 +00001175
Johnny Chenf3c59232010-08-25 22:52:45 +00001176 def invoke(self, obj, name, trace=False):
Johnny Chen61703c92010-08-25 22:56:10 +00001177 """Use reflection to call a method dynamically with no argument."""
Johnny Chen8d55a342010-08-31 17:42:54 +00001178 trace = (True if traceAlways else trace)
Johnny Chenf3c59232010-08-25 22:52:45 +00001179
1180 method = getattr(obj, name)
1181 import inspect
1182 self.assertTrue(inspect.ismethod(method),
1183 name + "is a method name of object: " + str(obj))
1184 result = method()
Johnny Chen150c3cc2010-10-15 01:18:29 +00001185 with recording(self, trace) as sbuf:
1186 print >> sbuf, str(method) + ":", result
Johnny Chenf3c59232010-08-25 22:52:45 +00001187 return result
Johnny Chen827edff2010-08-27 00:15:48 +00001188
Johnny Chenf359cf22011-05-27 23:36:52 +00001189 # =================================================
1190 # Misc. helper methods for debugging test execution
1191 # =================================================
1192
Johnny Chen56b92a72011-07-11 19:15:11 +00001193 def DebugSBValue(self, val):
Johnny Chen8d55a342010-08-31 17:42:54 +00001194 """Debug print a SBValue object, if traceAlways is True."""
Johnny Chende90f1d2011-04-27 17:43:07 +00001195 from lldbutil import value_type_to_str
Johnny Chen87bb5892010-11-03 21:37:58 +00001196
Johnny Chen8d55a342010-08-31 17:42:54 +00001197 if not traceAlways:
Johnny Chen827edff2010-08-27 00:15:48 +00001198 return
1199
1200 err = sys.stderr
1201 err.write(val.GetName() + ":\n")
Johnny Chen86268e42011-09-30 21:48:35 +00001202 err.write('\t' + "TypeName -> " + val.GetTypeName() + '\n')
1203 err.write('\t' + "ByteSize -> " + str(val.GetByteSize()) + '\n')
1204 err.write('\t' + "NumChildren -> " + str(val.GetNumChildren()) + '\n')
1205 err.write('\t' + "Value -> " + str(val.GetValue()) + '\n')
1206 err.write('\t' + "ValueAsUnsigned -> " + str(val.GetValueAsUnsigned())+ '\n')
1207 err.write('\t' + "ValueType -> " + value_type_to_str(val.GetValueType()) + '\n')
1208 err.write('\t' + "Summary -> " + str(val.GetSummary()) + '\n')
1209 err.write('\t' + "IsPointerType -> " + str(val.TypeIsPointerType()) + '\n')
1210 err.write('\t' + "Location -> " + val.GetLocation() + '\n')
Johnny Chen827edff2010-08-27 00:15:48 +00001211
Johnny Chen36c5eb12011-08-05 20:17:27 +00001212 def DebugSBType(self, type):
1213 """Debug print a SBType object, if traceAlways is True."""
1214 if not traceAlways:
1215 return
1216
1217 err = sys.stderr
1218 err.write(type.GetName() + ":\n")
1219 err.write('\t' + "ByteSize -> " + str(type.GetByteSize()) + '\n')
1220 err.write('\t' + "IsPointerType -> " + str(type.IsPointerType()) + '\n')
1221 err.write('\t' + "IsReferenceType -> " + str(type.IsReferenceType()) + '\n')
1222
Johnny Chenb877f1e2011-03-12 01:18:19 +00001223 def DebugPExpect(self, child):
1224 """Debug the spwaned pexpect object."""
1225 if not traceAlways:
1226 return
1227
1228 print child