blob: 85c742ab913322ed161db879ebad14f8e19d7c46 [file] [log] [blame]
Johnny Chena1affab2010-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
Johnny Chene39170b2012-05-16 20:41:28 +000012entire of part of the test suite . Example:
Johnny Chena1affab2010-07-03 03:41:59 +000013
Johnny Chene39170b2012-05-16 20:41:28 +000014# Exercises the test suite in the types directory....
15/Volumes/data/lldb/svn/ToT/test $ ./dotest.py -A x86_64 types
Johnny Chen59ea45f2010-09-02 22:25:47 +000016...
Johnny Chend0c24b22010-08-23 17:10:44 +000017
Johnny Chene39170b2012-05-16 20:41:28 +000018Session logs for test failures/errors/unexpected successes will go into directory '2012-05-16-13_35_42'
19Command invoked: python ./dotest.py -A x86_64 types
20compilers=['clang']
Johnny Chend0c24b22010-08-23 17:10:44 +000021
Johnny Chene39170b2012-05-16 20:41:28 +000022Configuration: arch=x86_64 compiler=clang
Johnny Chend0c24b22010-08-23 17:10:44 +000023----------------------------------------------------------------------
Johnny Chene39170b2012-05-16 20:41:28 +000024Collected 72 tests
25
26........................................................................
27----------------------------------------------------------------------
28Ran 72 tests in 135.468s
Johnny Chend0c24b22010-08-23 17:10:44 +000029
30OK
Johnny Chena1affab2010-07-03 03:41:59 +000031$
32"""
33
Johnny Chen93ae6042010-09-21 22:34:45 +000034import os, sys, traceback
Enrico Granata0fd6c8d2012-10-24 18:14:21 +000035import os.path
Johnny Chen2d899752010-09-21 21:08:53 +000036import re
Daniel Maleaadbaa442013-06-05 21:07:02 +000037import signal
Johnny Chena1cc8832010-08-30 21:35:00 +000038from subprocess import *
Johnny Chen84a6d6f2010-10-15 01:18:29 +000039import StringIO
Johnny Chen65572482010-08-25 18:49:48 +000040import time
Johnny Chen1acaf632010-08-30 23:08:52 +000041import types
Johnny Chen75e28f92010-08-05 23:42:46 +000042import unittest2
Johnny Chena1affab2010-07-03 03:41:59 +000043import lldb
44
Johnny Chen548aefd2010-10-11 22:25:46 +000045# See also dotest.parseOptionsAndInitTestdirs(), where the environment variables
Johnny Chen24af2962011-01-19 18:18:47 +000046# LLDB_COMMAND_TRACE and LLDB_DO_CLEANUP are set from '-t' and '-r dir' options.
Johnny Chen548aefd2010-10-11 22:25:46 +000047
48# By default, traceAlways is False.
Johnny Chen9de4ede2010-08-31 17:42:54 +000049if "LLDB_COMMAND_TRACE" in os.environ and os.environ["LLDB_COMMAND_TRACE"]=="YES":
50 traceAlways = True
51else:
52 traceAlways = False
53
Johnny Chen548aefd2010-10-11 22:25:46 +000054# By default, doCleanup is True.
55if "LLDB_DO_CLEANUP" in os.environ and os.environ["LLDB_DO_CLEANUP"]=="NO":
56 doCleanup = False
57else:
58 doCleanup = True
59
Johnny Chen9de4ede2010-08-31 17:42:54 +000060
Johnny Chen96f08d52010-08-09 22:01:17 +000061#
62# Some commonly used assert messages.
63#
64
Johnny Chenee975b82010-09-17 22:45:27 +000065COMMAND_FAILED_AS_EXPECTED = "Command has failed as expected"
66
Johnny Chen96f08d52010-08-09 22:01:17 +000067CURRENT_EXECUTABLE_SET = "Current executable set successfully"
68
Johnny Chen72a14342010-09-02 21:23:12 +000069PROCESS_IS_VALID = "Process is valid"
70
71PROCESS_KILLED = "Process is killed successfully"
72
Johnny Chen0ace30f2010-12-23 01:12:19 +000073PROCESS_EXITED = "Process exited successfully"
74
75PROCESS_STOPPED = "Process status should be stopped"
76
Johnny Chen1bb9f9a2010-08-27 23:47:36 +000077RUN_SUCCEEDED = "Process is launched successfully"
Johnny Chen96f08d52010-08-09 22:01:17 +000078
Johnny Chend85dae52010-08-09 23:44:24 +000079RUN_COMPLETED = "Process exited successfully"
Johnny Chen96f08d52010-08-09 22:01:17 +000080
Johnny Chen5349ee22010-10-05 19:27:32 +000081BACKTRACE_DISPLAYED_CORRECTLY = "Backtrace displayed correctly"
82
Johnny Chend85dae52010-08-09 23:44:24 +000083BREAKPOINT_CREATED = "Breakpoint created successfully"
84
Johnny Chen1ad9e992010-12-04 00:07:24 +000085BREAKPOINT_STATE_CORRECT = "Breakpoint state is correct"
86
Johnny Chen9b92c6e2010-08-17 21:33:31 +000087BREAKPOINT_PENDING_CREATED = "Pending breakpoint created successfully"
88
Johnny Chend85dae52010-08-09 23:44:24 +000089BREAKPOINT_HIT_ONCE = "Breakpoint resolved with hit cout = 1"
Johnny Chen96f08d52010-08-09 22:01:17 +000090
Johnny Chen72afa8d2010-09-30 17:06:24 +000091BREAKPOINT_HIT_TWICE = "Breakpoint resolved with hit cout = 2"
92
Johnny Chenc55dace2010-10-15 18:07:09 +000093BREAKPOINT_HIT_THRICE = "Breakpoint resolved with hit cout = 3"
94
Greg Claytonb2c1a412012-10-24 18:24:14 +000095MISSING_EXPECTED_REGISTERS = "At least one expected register is unavailable."
96
Johnny Chenc0dbdc02011-06-27 20:05:23 +000097OBJECT_PRINTED_CORRECTLY = "Object printed correctly"
98
Johnny Chen6f7abb02010-12-09 18:22:12 +000099SOURCE_DISPLAYED_CORRECTLY = "Source code displayed correctly"
100
Johnny Chen0b3ee552010-09-22 23:00:20 +0000101STEP_OUT_SUCCEEDED = "Thread step-out succeeded"
102
Johnny Chen33cd0c32011-04-15 16:44:48 +0000103STOPPED_DUE_TO_EXC_BAD_ACCESS = "Process should be stopped due to bad access exception"
104
Ashok Thirumurthi5a7a2322013-05-17 15:35:15 +0000105STOPPED_DUE_TO_ASSERT = "Process should be stopped due to an assertion"
106
Johnny Chene8587d02010-11-10 23:46:38 +0000107STOPPED_DUE_TO_BREAKPOINT = "Process should be stopped due to breakpoint"
Johnny Chenc82ac762010-11-10 20:20:06 +0000108
Johnny Chene8587d02010-11-10 23:46:38 +0000109STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS = "%s, %s" % (
110 STOPPED_DUE_TO_BREAKPOINT, "instead, the actual stop reason is: '%s'")
Johnny Chen96f08d52010-08-09 22:01:17 +0000111
Johnny Chenf6bdb192010-10-20 18:38:48 +0000112STOPPED_DUE_TO_BREAKPOINT_CONDITION = "Stopped due to breakpoint condition"
113
Johnny Chen7a4512b2010-12-13 21:49:58 +0000114STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT = "Stopped due to breakpoint and ignore count"
115
Johnny Chend7a4eb02010-10-14 01:22:03 +0000116STOPPED_DUE_TO_SIGNAL = "Process state is stopped due to signal"
117
Johnny Chen96f08d52010-08-09 22:01:17 +0000118STOPPED_DUE_TO_STEP_IN = "Process state is stopped due to step in"
119
Johnny Chen58c66e22011-09-15 21:09:59 +0000120STOPPED_DUE_TO_WATCHPOINT = "Process should be stopped due to watchpoint"
121
Johnny Chen4917e102010-08-24 22:07:56 +0000122DATA_TYPES_DISPLAYED_CORRECTLY = "Data type(s) displayed correctly"
123
Johnny Chenb4d1fff2010-08-26 20:04:17 +0000124VALID_BREAKPOINT = "Got a valid breakpoint"
125
Johnny Chen0601a292010-10-22 18:10:25 +0000126VALID_BREAKPOINT_LOCATION = "Got a valid breakpoint location"
127
Johnny Chenac910272011-05-06 23:26:12 +0000128VALID_COMMAND_INTERPRETER = "Got a valid command interpreter"
129
Johnny Chen1bb9f9a2010-08-27 23:47:36 +0000130VALID_FILESPEC = "Got a valid filespec"
131
Johnny Chen8fd886c2010-12-08 01:25:21 +0000132VALID_MODULE = "Got a valid module"
133
Johnny Chenb4d1fff2010-08-26 20:04:17 +0000134VALID_PROCESS = "Got a valid process"
135
Johnny Chen8fd886c2010-12-08 01:25:21 +0000136VALID_SYMBOL = "Got a valid symbol"
137
Johnny Chenb4d1fff2010-08-26 20:04:17 +0000138VALID_TARGET = "Got a valid target"
139
Johnny Chen2ef5eae2012-02-03 20:43:00 +0000140VALID_TYPE = "Got a valid type"
141
Johnny Chen5503d462011-07-15 22:28:10 +0000142VALID_VARIABLE = "Got a valid variable"
143
Johnny Chen22b95b22010-08-25 19:00:04 +0000144VARIABLES_DISPLAYED_CORRECTLY = "Variable(s) displayed correctly"
Johnny Chen96f08d52010-08-09 22:01:17 +0000145
Johnny Chen58c66e22011-09-15 21:09:59 +0000146WATCHPOINT_CREATED = "Watchpoint created successfully"
Johnny Chenb4d1fff2010-08-26 20:04:17 +0000147
Johnny Chen05efcf782010-11-09 18:42:22 +0000148def CMD_MSG(str):
Johnny Chen006b5952011-05-31 22:16:51 +0000149 '''A generic "Command '%s' returns successfully" message generator.'''
Johnny Chen05efcf782010-11-09 18:42:22 +0000150 return "Command '%s' returns successfully" % str
151
Johnny Chendbe2c822012-03-15 19:10:00 +0000152def COMPLETION_MSG(str_before, str_after):
Johnny Chenfbcad682012-01-20 23:02:51 +0000153 '''A generic message generator for the completion mechanism.'''
154 return "'%s' successfully completes to '%s'" % (str_before, str_after)
155
Johnny Chen05efcf782010-11-09 18:42:22 +0000156def EXP_MSG(str, exe):
Johnny Chen006b5952011-05-31 22:16:51 +0000157 '''A generic "'%s' returns expected result" message generator if exe.
158 Otherwise, it generates "'%s' matches expected result" message.'''
Johnny Chen05efcf782010-11-09 18:42:22 +0000159 return "'%s' %s expected result" % (str, 'returns' if exe else 'matches')
Johnny Chend85dae52010-08-09 23:44:24 +0000160
Johnny Chendb9cbe92010-10-19 19:11:38 +0000161def SETTING_MSG(setting):
Johnny Chen006b5952011-05-31 22:16:51 +0000162 '''A generic "Value of setting '%s' is correct" message generator.'''
Johnny Chendb9cbe92010-10-19 19:11:38 +0000163 return "Value of setting '%s' is correct" % setting
164
Johnny Chenf4ce2882010-08-26 21:49:29 +0000165def EnvArray():
Johnny Chen006b5952011-05-31 22:16:51 +0000166 """Returns an env variable array from the os.environ map object."""
Johnny Chenf4ce2882010-08-26 21:49:29 +0000167 return map(lambda k,v: k+"="+v, os.environ.keys(), os.environ.values())
168
Johnny Chen14906002010-10-11 23:52:19 +0000169def line_number(filename, string_to_match):
170 """Helper function to return the line number of the first matched string."""
171 with open(filename, 'r') as f:
172 for i, line in enumerate(f):
173 if line.find(string_to_match) != -1:
174 # Found our match.
Johnny Chen0659e342010-10-12 00:09:25 +0000175 return i+1
Johnny Chen33cd0c32011-04-15 16:44:48 +0000176 raise Exception("Unable to find '%s' within file %s" % (string_to_match, filename))
Johnny Chen14906002010-10-11 23:52:19 +0000177
Johnny Chen5349ee22010-10-05 19:27:32 +0000178def pointer_size():
179 """Return the pointer size of the host system."""
180 import ctypes
181 a_pointer = ctypes.c_void_p(0xffff)
182 return 8 * ctypes.sizeof(a_pointer)
183
Johnny Chen7be5d352012-02-09 02:01:59 +0000184def is_exe(fpath):
185 """Returns true if fpath is an executable."""
186 return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
187
188def which(program):
189 """Returns the full path to a program; None otherwise."""
190 fpath, fname = os.path.split(program)
191 if fpath:
192 if is_exe(program):
193 return program
194 else:
195 for path in os.environ["PATH"].split(os.pathsep):
196 exe_file = os.path.join(path, program)
197 if is_exe(exe_file):
198 return exe_file
199 return None
200
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000201class recording(StringIO.StringIO):
202 """
203 A nice little context manager for recording the debugger interactions into
204 our session object. If trace flag is ON, it also emits the interactions
205 into the stderr.
206 """
207 def __init__(self, test, trace):
Johnny Chen1b7d6292010-10-15 23:55:05 +0000208 """Create a StringIO instance; record the session obj and trace flag."""
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000209 StringIO.StringIO.__init__(self)
Johnny Chen770683d2011-08-16 22:06:17 +0000210 # The test might not have undergone the 'setUp(self)' phase yet, so that
211 # the attribute 'session' might not even exist yet.
Johnny Chen8339f982011-08-16 17:06:45 +0000212 self.session = getattr(test, "session", None) if test else None
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000213 self.trace = trace
214
215 def __enter__(self):
216 """
217 Context management protocol on entry to the body of the with statement.
218 Just return the StringIO object.
219 """
220 return self
221
222 def __exit__(self, type, value, tb):
223 """
224 Context management protocol on exit from the body of the with statement.
225 If trace is ON, it emits the recordings into stderr. Always add the
226 recordings to our session object. And close the StringIO object, too.
227 """
228 if self.trace:
Johnny Chen1b7d6292010-10-15 23:55:05 +0000229 print >> sys.stderr, self.getvalue()
230 if self.session:
231 print >> self.session, self.getvalue()
Johnny Chen84a6d6f2010-10-15 01:18:29 +0000232 self.close()
233
Johnny Chen1b7d6292010-10-15 23:55:05 +0000234# From 2.7's subprocess.check_output() convenience function.
Johnny Chen0bfa8592011-03-23 20:28:59 +0000235# Return a tuple (stdoutdata, stderrdata).
Johnny Chen1b7d6292010-10-15 23:55:05 +0000236def system(*popenargs, **kwargs):
Johnny Chen22ca65d2011-11-16 22:44:28 +0000237 r"""Run an os command with arguments and return its output as a byte string.
Johnny Chen1b7d6292010-10-15 23:55:05 +0000238
239 If the exit code was non-zero it raises a CalledProcessError. The
240 CalledProcessError object will have the return code in the returncode
241 attribute and output in the output attribute.
242
243 The arguments are the same as for the Popen constructor. Example:
244
245 >>> check_output(["ls", "-l", "/dev/null"])
246 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
247
248 The stdout argument is not allowed as it is used internally.
249 To capture standard error in the result, use stderr=STDOUT.
250
251 >>> check_output(["/bin/sh", "-c",
252 ... "ls -l non_existent_file ; exit 0"],
253 ... stderr=STDOUT)
254 'ls: non_existent_file: No such file or directory\n'
255 """
256
257 # Assign the sender object to variable 'test' and remove it from kwargs.
258 test = kwargs.pop('sender', None)
259
260 if 'stdout' in kwargs:
261 raise ValueError('stdout argument not allowed, it will be overridden.')
Johnny Chen0bfa8592011-03-23 20:28:59 +0000262 process = Popen(stdout=PIPE, stderr=PIPE, *popenargs, **kwargs)
Johnny Chen30b30cb2011-11-16 22:41:53 +0000263 pid = process.pid
Johnny Chen1b7d6292010-10-15 23:55:05 +0000264 output, error = process.communicate()
265 retcode = process.poll()
266
267 with recording(test, traceAlways) as sbuf:
268 if isinstance(popenargs, types.StringTypes):
269 args = [popenargs]
270 else:
271 args = list(popenargs)
272 print >> sbuf
273 print >> sbuf, "os command:", args
Johnny Chen30b30cb2011-11-16 22:41:53 +0000274 print >> sbuf, "with pid:", pid
Johnny Chen1b7d6292010-10-15 23:55:05 +0000275 print >> sbuf, "stdout:", output
276 print >> sbuf, "stderr:", error
277 print >> sbuf, "retcode:", retcode
278 print >> sbuf
279
280 if retcode:
281 cmd = kwargs.get("args")
282 if cmd is None:
283 cmd = popenargs[0]
284 raise CalledProcessError(retcode, cmd)
Johnny Chen0bfa8592011-03-23 20:28:59 +0000285 return (output, error)
Johnny Chen1b7d6292010-10-15 23:55:05 +0000286
Johnny Chen29867642010-11-01 20:35:01 +0000287def getsource_if_available(obj):
288 """
289 Return the text of the source code for an object if available. Otherwise,
290 a print representation is returned.
291 """
292 import inspect
293 try:
294 return inspect.getsource(obj)
295 except:
296 return repr(obj)
297
Peter Collingbourne39bd5362011-06-20 19:06:20 +0000298def builder_module():
299 return __import__("builder_" + sys.platform)
300
Johnny Chen366fb8c2011-08-01 18:46:13 +0000301#
302# Decorators for categorizing test cases.
303#
304
305from functools import wraps
306def python_api_test(func):
307 """Decorate the item as a Python API only test."""
308 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
309 raise Exception("@python_api_test can only be used to decorate a test method")
310 @wraps(func)
311 def wrapper(self, *args, **kwargs):
312 try:
313 if lldb.dont_do_python_api_test:
314 self.skipTest("python api tests")
315 except AttributeError:
316 pass
317 return func(self, *args, **kwargs)
318
319 # Mark this function as such to separate them from lldb command line tests.
320 wrapper.__python_api_test__ = True
321 return wrapper
322
Johnny Chen366fb8c2011-08-01 18:46:13 +0000323def benchmarks_test(func):
324 """Decorate the item as a benchmarks test."""
325 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
326 raise Exception("@benchmarks_test can only be used to decorate a test method")
327 @wraps(func)
328 def wrapper(self, *args, **kwargs):
329 try:
330 if not lldb.just_do_benchmarks_test:
331 self.skipTest("benchmarks tests")
332 except AttributeError:
333 pass
334 return func(self, *args, **kwargs)
335
336 # Mark this function as such to separate them from the regular tests.
337 wrapper.__benchmarks_test__ = True
338 return wrapper
339
Johnny Chena3ed7d82012-04-06 00:56:05 +0000340def dsym_test(func):
341 """Decorate the item as a dsym test."""
342 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
343 raise Exception("@dsym_test can only be used to decorate a test method")
344 @wraps(func)
345 def wrapper(self, *args, **kwargs):
346 try:
347 if lldb.dont_do_dsym_test:
348 self.skipTest("dsym tests")
349 except AttributeError:
350 pass
351 return func(self, *args, **kwargs)
352
353 # Mark this function as such to separate them from the regular tests.
354 wrapper.__dsym_test__ = True
355 return wrapper
356
357def dwarf_test(func):
358 """Decorate the item as a dwarf test."""
359 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
360 raise Exception("@dwarf_test can only be used to decorate a test method")
361 @wraps(func)
362 def wrapper(self, *args, **kwargs):
363 try:
364 if lldb.dont_do_dwarf_test:
365 self.skipTest("dwarf tests")
366 except AttributeError:
367 pass
368 return func(self, *args, **kwargs)
369
370 # Mark this function as such to separate them from the regular tests.
371 wrapper.__dwarf_test__ = True
372 return wrapper
373
Ashok Thirumurthib7d46e32013-05-17 20:15:07 +0000374def expectedFailureGcc(bugnumber=None, compiler_version=["=", None]):
Enrico Granata21416a12013-02-23 01:05:23 +0000375 if callable(bugnumber):
376 @wraps(bugnumber)
Enrico Granata786e8732013-02-23 01:35:21 +0000377 def expectedFailureGcc_easy_wrapper(*args, **kwargs):
Enrico Granata4d82e972013-02-23 01:28:30 +0000378 from unittest2 import case
379 self = args[0]
380 test_compiler = self.getCompiler()
381 try:
382 bugnumber(*args, **kwargs)
383 except Exception:
Ashok Thirumurthi0c521642013-06-06 14:23:31 +0000384 if "gcc" in test_compiler and self.expectedCompilerVersion(compiler_version):
Enrico Granata4d82e972013-02-23 01:28:30 +0000385 raise case._ExpectedFailure(sys.exc_info(),None)
386 else:
387 raise
Enrico Granata786e8732013-02-23 01:35:21 +0000388 if "gcc" in test_compiler:
Enrico Granata4d82e972013-02-23 01:28:30 +0000389 raise case._UnexpectedSuccess(sys.exc_info(),None)
Enrico Granata786e8732013-02-23 01:35:21 +0000390 return expectedFailureGcc_easy_wrapper
Enrico Granata21416a12013-02-23 01:05:23 +0000391 else:
Enrico Granata786e8732013-02-23 01:35:21 +0000392 def expectedFailureGcc_impl(func):
Enrico Granata21416a12013-02-23 01:05:23 +0000393 @wraps(func)
394 def wrapper(*args, **kwargs):
Enrico Granata4d82e972013-02-23 01:28:30 +0000395 from unittest2 import case
396 self = args[0]
397 test_compiler = self.getCompiler()
398 try:
399 func(*args, **kwargs)
400 except Exception:
Ashok Thirumurthi0c521642013-06-06 14:23:31 +0000401 if "gcc" in test_compiler and self.expectedCompilerVersion(compiler_version):
Enrico Granata4d82e972013-02-23 01:28:30 +0000402 raise case._ExpectedFailure(sys.exc_info(),bugnumber)
403 else:
404 raise
Enrico Granata786e8732013-02-23 01:35:21 +0000405 if "gcc" in test_compiler:
Enrico Granata4d82e972013-02-23 01:28:30 +0000406 raise case._UnexpectedSuccess(sys.exc_info(),bugnumber)
Enrico Granata21416a12013-02-23 01:05:23 +0000407 return wrapper
Enrico Granata786e8732013-02-23 01:35:21 +0000408 return expectedFailureGcc_impl
Daniel Malea8b5c29d2013-02-19 16:08:57 +0000409
Enrico Granata786e8732013-02-23 01:35:21 +0000410def expectedFailureClang(bugnumber=None):
411 if callable(bugnumber):
412 @wraps(bugnumber)
413 def expectedFailureClang_easy_wrapper(*args, **kwargs):
414 from unittest2 import case
415 self = args[0]
416 test_compiler = self.getCompiler()
417 try:
418 bugnumber(*args, **kwargs)
419 except Exception:
420 if "clang" in test_compiler:
421 raise case._ExpectedFailure(sys.exc_info(),None)
422 else:
423 raise
424 if "clang" in test_compiler:
425 raise case._UnexpectedSuccess(sys.exc_info(),None)
426 return expectedFailureClang_easy_wrapper
427 else:
428 def expectedFailureClang_impl(func):
429 @wraps(func)
430 def wrapper(*args, **kwargs):
431 from unittest2 import case
432 self = args[0]
433 test_compiler = self.getCompiler()
434 try:
435 func(*args, **kwargs)
436 except Exception:
437 if "clang" in test_compiler:
438 raise case._ExpectedFailure(sys.exc_info(),bugnumber)
439 else:
440 raise
441 if "clang" in test_compiler:
442 raise case._UnexpectedSuccess(sys.exc_info(),bugnumber)
443 return wrapper
444 return expectedFailureClang_impl
Daniel Malea8b5c29d2013-02-19 16:08:57 +0000445
Matt Kopec57d4ab22013-03-15 19:10:12 +0000446def expectedFailureIcc(bugnumber=None):
447 if callable(bugnumber):
448 @wraps(bugnumber)
449 def expectedFailureIcc_easy_wrapper(*args, **kwargs):
450 from unittest2 import case
451 self = args[0]
452 test_compiler = self.getCompiler()
453 try:
454 bugnumber(*args, **kwargs)
455 except Exception:
456 if "icc" in test_compiler:
457 raise case._ExpectedFailure(sys.exc_info(),None)
458 else:
459 raise
460 if "icc" in test_compiler:
461 raise case._UnexpectedSuccess(sys.exc_info(),None)
462 return expectedFailureIcc_easy_wrapper
463 else:
464 def expectedFailureIcc_impl(func):
465 @wraps(func)
466 def wrapper(*args, **kwargs):
467 from unittest2 import case
468 self = args[0]
469 test_compiler = self.getCompiler()
470 try:
471 func(*args, **kwargs)
472 except Exception:
473 if "icc" in test_compiler:
474 raise case._ExpectedFailure(sys.exc_info(),bugnumber)
475 else:
476 raise
477 if "icc" in test_compiler:
478 raise case._UnexpectedSuccess(sys.exc_info(),bugnumber)
479 return wrapper
480 return expectedFailureIcc_impl
481
Daniel Malea8b5c29d2013-02-19 16:08:57 +0000482
Enrico Granata21416a12013-02-23 01:05:23 +0000483def expectedFailurei386(bugnumber=None):
484 if callable(bugnumber):
485 @wraps(bugnumber)
486 def expectedFailurei386_easy_wrapper(*args, **kwargs):
Enrico Granata4d82e972013-02-23 01:28:30 +0000487 from unittest2 import case
488 self = args[0]
489 arch = self.getArchitecture()
490 try:
491 bugnumber(*args, **kwargs)
492 except Exception:
493 if "i386" in arch:
494 raise case._ExpectedFailure(sys.exc_info(),None)
495 else:
496 raise
497 if "i386" in arch:
498 raise case._UnexpectedSuccess(sys.exc_info(),None)
Enrico Granata21416a12013-02-23 01:05:23 +0000499 return expectedFailurei386_easy_wrapper
500 else:
501 def expectedFailurei386_impl(func):
502 @wraps(func)
503 def wrapper(*args, **kwargs):
Enrico Granata4d82e972013-02-23 01:28:30 +0000504 from unittest2 import case
505 self = args[0]
506 arch = self.getArchitecture()
507 try:
508 func(*args, **kwargs)
509 except Exception:
510 if "i386" in arch:
511 raise case._ExpectedFailure(sys.exc_info(),bugnumber)
512 else:
513 raise
514 if "i386" in arch:
515 raise case._UnexpectedSuccess(sys.exc_info(),bugnumber)
Enrico Granata21416a12013-02-23 01:05:23 +0000516 return wrapper
517 return expectedFailurei386_impl
Johnny Chen869e2962011-12-22 21:14:31 +0000518
Ed Maste4e6d2972013-07-24 19:47:08 +0000519def expectedFailureFreeBSD(bugnumber=None, compilers=None):
520 if callable(bugnumber):
521 @wraps(bugnumber)
522 def expectedFailureFreeBSD_easy_wrapper(*args, **kwargs):
523 from unittest2 import case
524 self = args[0]
525 platform = sys.platform
526 try:
527 bugnumber(*args, **kwargs)
528 except Exception:
529 if "freebsd" in platform and self.expectedCompiler(compilers):
530 raise case._ExpectedFailure(sys.exc_info(),None)
531 else:
532 raise
533 if "freebsd" in platform and self.expectedCompiler(compilers):
534 raise case._UnexpectedSuccess(sys.exc_info(),None)
535 return expectedFailureFreeBSD_easy_wrapper
536 else:
537 def expectedFailureFreeBSD_impl(func):
538 @wraps(func)
539 def wrapper(*args, **kwargs):
540 from unittest2 import case
541 self = args[0]
542 platform = sys.platform
543 try:
544 func(*args, **kwargs)
545 except Exception:
546 if "freebsd" in platform and self.expectedCompiler(compilers):
547 raise case._ExpectedFailure(sys.exc_info(),bugnumber)
548 else:
549 raise
550 if "freebsd" in platform and self.expectedCompiler(compilers):
551 raise case._UnexpectedSuccess(sys.exc_info(),bugnumber)
552 return wrapper
553 return expectedFailureFreeBSD_impl
554
Ashok Thirumurthib7d46e32013-05-17 20:15:07 +0000555def expectedFailureLinux(bugnumber=None, compilers=None):
Enrico Granata21416a12013-02-23 01:05:23 +0000556 if callable(bugnumber):
557 @wraps(bugnumber)
558 def expectedFailureLinux_easy_wrapper(*args, **kwargs):
Enrico Granata4d82e972013-02-23 01:28:30 +0000559 from unittest2 import case
560 self = args[0]
561 platform = sys.platform
562 try:
563 bugnumber(*args, **kwargs)
564 except Exception:
Ashok Thirumurthib7d46e32013-05-17 20:15:07 +0000565 if "linux" in platform and self.expectedCompiler(compilers):
Enrico Granata4d82e972013-02-23 01:28:30 +0000566 raise case._ExpectedFailure(sys.exc_info(),None)
567 else:
568 raise
Ashok Thirumurthib7d46e32013-05-17 20:15:07 +0000569 if "linux" in platform and self.expectedCompiler(compilers):
Enrico Granata4d82e972013-02-23 01:28:30 +0000570 raise case._UnexpectedSuccess(sys.exc_info(),None)
Enrico Granata21416a12013-02-23 01:05:23 +0000571 return expectedFailureLinux_easy_wrapper
572 else:
573 def expectedFailureLinux_impl(func):
574 @wraps(func)
575 def wrapper(*args, **kwargs):
Enrico Granata4d82e972013-02-23 01:28:30 +0000576 from unittest2 import case
577 self = args[0]
578 platform = sys.platform
579 try:
580 func(*args, **kwargs)
581 except Exception:
Ashok Thirumurthib7d46e32013-05-17 20:15:07 +0000582 if "linux" in platform and self.expectedCompiler(compilers):
Enrico Granata4d82e972013-02-23 01:28:30 +0000583 raise case._ExpectedFailure(sys.exc_info(),bugnumber)
584 else:
585 raise
Ashok Thirumurthib7d46e32013-05-17 20:15:07 +0000586 if "linux" in platform and self.expectedCompiler(compilers):
Enrico Granata4d82e972013-02-23 01:28:30 +0000587 raise case._UnexpectedSuccess(sys.exc_info(),bugnumber)
Enrico Granata21416a12013-02-23 01:05:23 +0000588 return wrapper
589 return expectedFailureLinux_impl
Daniel Malea40c9d752012-11-23 21:59:29 +0000590
Matt Kopec3d4d51c2013-05-07 19:29:28 +0000591def expectedFailureDarwin(bugnumber=None):
592 if callable(bugnumber):
593 @wraps(bugnumber)
594 def expectedFailureDarwin_easy_wrapper(*args, **kwargs):
595 from unittest2 import case
596 self = args[0]
597 platform = sys.platform
598 try:
599 bugnumber(*args, **kwargs)
600 except Exception:
601 if "darwin" in platform:
602 raise case._ExpectedFailure(sys.exc_info(),None)
603 else:
604 raise
605 if "darwin" in platform:
606 raise case._UnexpectedSuccess(sys.exc_info(),None)
607 return expectedFailureDarwin_easy_wrapper
608 else:
609 def expectedFailureDarwin_impl(func):
610 @wraps(func)
611 def wrapper(*args, **kwargs):
612 from unittest2 import case
613 self = args[0]
614 platform = sys.platform
615 try:
616 func(*args, **kwargs)
617 except Exception:
618 if "darwin" in platform:
619 raise case._ExpectedFailure(sys.exc_info(),bugnumber)
620 else:
621 raise
622 if "darwin" in platform:
623 raise case._UnexpectedSuccess(sys.exc_info(),bugnumber)
624 return wrapper
625 return expectedFailureDarwin_impl
626
Ed Masteaedf8e02013-06-25 19:11:36 +0000627def skipIfFreeBSD(func):
628 """Decorate the item to skip tests that should be skipped on FreeBSD."""
629 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
630 raise Exception("@skipIfFreeBSD can only be used to decorate a test method")
631 @wraps(func)
632 def wrapper(*args, **kwargs):
633 from unittest2 import case
634 self = args[0]
635 platform = sys.platform
636 if "freebsd" in platform:
637 self.skipTest("skip on FreeBSD")
638 else:
639 func(*args, **kwargs)
640 return wrapper
641
Daniel Malea6bc4dcd2013-05-15 18:48:32 +0000642def skipIfLinux(func):
Daniel Malea40c9d752012-11-23 21:59:29 +0000643 """Decorate the item to skip tests that should be skipped on Linux."""
644 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Daniel Malea6bc4dcd2013-05-15 18:48:32 +0000645 raise Exception("@skipIfLinux can only be used to decorate a test method")
Daniel Malea40c9d752012-11-23 21:59:29 +0000646 @wraps(func)
647 def wrapper(*args, **kwargs):
648 from unittest2 import case
649 self = args[0]
650 platform = sys.platform
651 if "linux" in platform:
652 self.skipTest("skip on linux")
653 else:
Jim Ingham7bf78a02012-11-27 01:21:28 +0000654 func(*args, **kwargs)
Daniel Malea40c9d752012-11-23 21:59:29 +0000655 return wrapper
656
Daniel Maleaff5c6d92013-07-09 00:08:01 +0000657def skipIfDarwin(func):
658 """Decorate the item to skip tests that should be skipped on Darwin."""
659 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Ed Maste7847c112013-07-09 00:24:52 +0000660 raise Exception("@skipIfDarwin can only be used to decorate a test method")
Daniel Maleaff5c6d92013-07-09 00:08:01 +0000661 @wraps(func)
662 def wrapper(*args, **kwargs):
663 from unittest2 import case
664 self = args[0]
665 platform = sys.platform
666 if "darwin" in platform:
667 self.skipTest("skip on darwin")
668 else:
669 func(*args, **kwargs)
670 return wrapper
671
672
Daniel Malea156d8e02013-05-14 20:48:54 +0000673def skipIfLinuxClang(func):
674 """Decorate the item to skip tests that should be skipped if building on
675 Linux with clang.
676 """
677 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
678 raise Exception("@skipIfLinuxClang can only be used to decorate a test method")
679 @wraps(func)
680 def wrapper(*args, **kwargs):
681 from unittest2 import case
682 self = args[0]
683 compiler = self.getCompiler()
684 platform = sys.platform
685 if "clang" in compiler and "linux" in platform:
686 self.skipTest("skipping because Clang is used on Linux")
687 else:
688 func(*args, **kwargs)
689 return wrapper
690
Daniel Maleacd630e72013-01-24 23:52:09 +0000691def skipIfGcc(func):
692 """Decorate the item to skip tests that should be skipped if building with gcc ."""
693 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Daniel Malea54fcf682013-02-27 17:29:46 +0000694 raise Exception("@skipIfGcc can only be used to decorate a test method")
Daniel Maleacd630e72013-01-24 23:52:09 +0000695 @wraps(func)
696 def wrapper(*args, **kwargs):
697 from unittest2 import case
698 self = args[0]
699 compiler = self.getCompiler()
700 if "gcc" in compiler:
701 self.skipTest("skipping because gcc is the test compiler")
702 else:
703 func(*args, **kwargs)
704 return wrapper
705
Matt Kopec57d4ab22013-03-15 19:10:12 +0000706def skipIfIcc(func):
707 """Decorate the item to skip tests that should be skipped if building with icc ."""
708 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
709 raise Exception("@skipIfIcc can only be used to decorate a test method")
710 @wraps(func)
711 def wrapper(*args, **kwargs):
712 from unittest2 import case
713 self = args[0]
714 compiler = self.getCompiler()
715 if "icc" in compiler:
716 self.skipTest("skipping because icc is the test compiler")
717 else:
718 func(*args, **kwargs)
719 return wrapper
720
Daniel Malea9c570672013-05-02 21:44:31 +0000721def skipIfi386(func):
722 """Decorate the item to skip tests that should be skipped if building 32-bit."""
723 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
724 raise Exception("@skipIfi386 can only be used to decorate a test method")
725 @wraps(func)
726 def wrapper(*args, **kwargs):
727 from unittest2 import case
728 self = args[0]
729 if "i386" == self.getArchitecture():
730 self.skipTest("skipping because i386 is not a supported architecture")
731 else:
732 func(*args, **kwargs)
733 return wrapper
734
735
Johnny Chen366fb8c2011-08-01 18:46:13 +0000736class Base(unittest2.TestCase):
Johnny Chen607b7a12010-10-22 23:15:46 +0000737 """
Johnny Chen366fb8c2011-08-01 18:46:13 +0000738 Abstract base for performing lldb (see TestBase) or other generic tests (see
739 BenchBase for one example). lldbtest.Base works with the test driver to
740 accomplish things.
741
Johnny Chen607b7a12010-10-22 23:15:46 +0000742 """
Enrico Granata671dd552012-10-24 21:42:49 +0000743
Enrico Granata03bc3fd2012-10-24 21:44:48 +0000744 # The concrete subclass should override this attribute.
745 mydir = None
Johnny Chena1affab2010-07-03 03:41:59 +0000746
Johnny Chend3521cc2010-09-16 01:53:04 +0000747 # Keep track of the old current working directory.
748 oldcwd = None
Johnny Chen88f83042010-08-05 21:23:45 +0000749
Johnny Chencbe51262011-08-01 19:50:58 +0000750 def TraceOn(self):
751 """Returns True if we are in trace mode (tracing detailed test execution)."""
752 return traceAlways
753
Johnny Chend3521cc2010-09-16 01:53:04 +0000754 @classmethod
755 def setUpClass(cls):
Johnny Chen41998192010-10-01 22:59:49 +0000756 """
757 Python unittest framework class setup fixture.
758 Do current directory manipulation.
759 """
760
Johnny Chenf8c723b2010-07-03 20:41:42 +0000761 # Fail fast if 'mydir' attribute is not overridden.
Johnny Chend3521cc2010-09-16 01:53:04 +0000762 if not cls.mydir or len(cls.mydir) == 0:
Johnny Chenf8c723b2010-07-03 20:41:42 +0000763 raise Exception("Subclasses must override the 'mydir' attribute.")
Enrico Granata0fd6c8d2012-10-24 18:14:21 +0000764
Johnny Chena1affab2010-07-03 03:41:59 +0000765 # Save old working directory.
Johnny Chend3521cc2010-09-16 01:53:04 +0000766 cls.oldcwd = os.getcwd()
Johnny Chena1affab2010-07-03 03:41:59 +0000767
768 # Change current working directory if ${LLDB_TEST} is defined.
769 # See also dotest.py which sets up ${LLDB_TEST}.
770 if ("LLDB_TEST" in os.environ):
Johnny Chend3521cc2010-09-16 01:53:04 +0000771 if traceAlways:
Johnny Chen72afa8d2010-09-30 17:06:24 +0000772 print >> sys.stderr, "Change dir to:", os.path.join(os.environ["LLDB_TEST"], cls.mydir)
Johnny Chend3521cc2010-09-16 01:53:04 +0000773 os.chdir(os.path.join(os.environ["LLDB_TEST"], cls.mydir))
774
775 @classmethod
776 def tearDownClass(cls):
Johnny Chen41998192010-10-01 22:59:49 +0000777 """
778 Python unittest framework class teardown fixture.
779 Do class-wide cleanup.
780 """
Johnny Chend3521cc2010-09-16 01:53:04 +0000781
Johnny Chen028d8eb2011-11-17 19:57:27 +0000782 if doCleanup and not lldb.skip_build_and_cleanup:
Johnny Chen548aefd2010-10-11 22:25:46 +0000783 # First, let's do the platform-specific cleanup.
Peter Collingbourne39bd5362011-06-20 19:06:20 +0000784 module = builder_module()
Johnny Chen548aefd2010-10-11 22:25:46 +0000785 if not module.cleanup():
786 raise Exception("Don't know how to do cleanup")
Johnny Chend3521cc2010-09-16 01:53:04 +0000787
Johnny Chen548aefd2010-10-11 22:25:46 +0000788 # Subclass might have specific cleanup function defined.
789 if getattr(cls, "classCleanup", None):
790 if traceAlways:
791 print >> sys.stderr, "Call class-specific cleanup function for class:", cls
792 try:
793 cls.classCleanup()
794 except:
795 exc_type, exc_value, exc_tb = sys.exc_info()
796 traceback.print_exception(exc_type, exc_value, exc_tb)
Johnny Chend3521cc2010-09-16 01:53:04 +0000797
798 # Restore old working directory.
799 if traceAlways:
Johnny Chen72afa8d2010-09-30 17:06:24 +0000800 print >> sys.stderr, "Restore dir to:", cls.oldcwd
Johnny Chend3521cc2010-09-16 01:53:04 +0000801 os.chdir(cls.oldcwd)
802
Johnny Chen366fb8c2011-08-01 18:46:13 +0000803 @classmethod
804 def skipLongRunningTest(cls):
805 """
806 By default, we skip long running test case.
807 This can be overridden by passing '-l' to the test driver (dotest.py).
808 """
809 if "LLDB_SKIP_LONG_RUNNING_TEST" in os.environ and "NO" == os.environ["LLDB_SKIP_LONG_RUNNING_TEST"]:
810 return False
811 else:
812 return True
Johnny Chen9a9fcf62011-06-21 00:53:00 +0000813
Johnny Chend3521cc2010-09-16 01:53:04 +0000814 def setUp(self):
Johnny Chencbe51262011-08-01 19:50:58 +0000815 """Fixture for unittest test case setup.
816
817 It works with the test driver to conditionally skip tests and does other
818 initializations."""
Johnny Chend3521cc2010-09-16 01:53:04 +0000819 #import traceback
820 #traceback.print_stack()
Johnny Chena1affab2010-07-03 03:41:59 +0000821
Johnny Chen113388f2011-08-02 22:54:37 +0000822 if "LLDB_EXEC" in os.environ:
823 self.lldbExec = os.environ["LLDB_EXEC"]
Johnny Chen6033bed2011-08-26 00:00:01 +0000824 else:
825 self.lldbExec = None
826 if "LLDB_HERE" in os.environ:
827 self.lldbHere = os.environ["LLDB_HERE"]
828 else:
829 self.lldbHere = None
Johnny Chen7d7f4472011-10-07 19:21:09 +0000830 # If we spawn an lldb process for test (via pexpect), do not load the
831 # init file unless told otherwise.
832 if "NO_LLDBINIT" in os.environ and "NO" == os.environ["NO_LLDBINIT"]:
833 self.lldbOption = ""
834 else:
835 self.lldbOption = "--no-lldbinit"
Johnny Chen113388f2011-08-02 22:54:37 +0000836
Johnny Chen71cb7972011-08-01 21:13:26 +0000837 # Assign the test method name to self.testMethodName.
838 #
839 # For an example of the use of this attribute, look at test/types dir.
840 # There are a bunch of test cases under test/types and we don't want the
841 # module cacheing subsystem to be confused with executable name "a.out"
842 # used for all the test cases.
843 self.testMethodName = self._testMethodName
844
Johnny Chen3ebdacc2010-12-10 18:52:10 +0000845 # Python API only test is decorated with @python_api_test,
846 # which also sets the "__python_api_test__" attribute of the
847 # function object to True.
Johnny Chend8c1dd32011-05-31 23:21:42 +0000848 try:
849 if lldb.just_do_python_api_test:
850 testMethod = getattr(self, self._testMethodName)
851 if getattr(testMethod, "__python_api_test__", False):
852 pass
853 else:
Johnny Chen82ccf402011-07-30 01:39:58 +0000854 self.skipTest("non python api test")
855 except AttributeError:
856 pass
857
858 # Benchmarks test is decorated with @benchmarks_test,
859 # which also sets the "__benchmarks_test__" attribute of the
860 # function object to True.
861 try:
862 if lldb.just_do_benchmarks_test:
863 testMethod = getattr(self, self._testMethodName)
864 if getattr(testMethod, "__benchmarks_test__", False):
865 pass
866 else:
867 self.skipTest("non benchmarks test")
Johnny Chend8c1dd32011-05-31 23:21:42 +0000868 except AttributeError:
869 pass
Johnny Chen3ebdacc2010-12-10 18:52:10 +0000870
Johnny Chen71cb7972011-08-01 21:13:26 +0000871 # This is for the case of directly spawning 'lldb'/'gdb' and interacting
872 # with it using pexpect.
873 self.child = None
874 self.child_prompt = "(lldb) "
875 # If the child is interacting with the embedded script interpreter,
876 # there are two exits required during tear down, first to quit the
877 # embedded script interpreter and second to quit the lldb command
878 # interpreter.
879 self.child_in_script_interpreter = False
880
Johnny Chencbe51262011-08-01 19:50:58 +0000881 # These are for customized teardown cleanup.
882 self.dict = None
883 self.doTearDownCleanup = False
884 # And in rare cases where there are multiple teardown cleanups.
885 self.dicts = []
886 self.doTearDownCleanups = False
887
Daniel Malea5c5f01b2013-02-15 21:21:52 +0000888 # List of spawned subproces.Popen objects
889 self.subprocesses = []
890
Daniel Maleaadbaa442013-06-05 21:07:02 +0000891 # List of forked process PIDs
892 self.forkedProcessPids = []
893
Johnny Chencbe51262011-08-01 19:50:58 +0000894 # Create a string buffer to record the session info, to be dumped into a
895 # test case specific file if test failure is encountered.
896 self.session = StringIO.StringIO()
897
898 # Optimistically set __errored__, __failed__, __expected__ to False
899 # initially. If the test errored/failed, the session info
900 # (self.session) is then dumped into a session specific file for
901 # diagnosis.
902 self.__errored__ = False
903 self.__failed__ = False
904 self.__expected__ = False
905 # We are also interested in unexpected success.
906 self.__unexpected__ = False
Johnny Chencd1df5a2011-08-16 00:48:58 +0000907 # And skipped tests.
908 self.__skipped__ = False
Johnny Chencbe51262011-08-01 19:50:58 +0000909
910 # See addTearDownHook(self, hook) which allows the client to add a hook
911 # function to be run during tearDown() time.
912 self.hooks = []
913
914 # See HideStdout(self).
915 self.sys_stdout_hidden = False
916
Daniel Maleae5aa0d42012-11-26 21:21:11 +0000917 # set environment variable names for finding shared libraries
918 if sys.platform.startswith("darwin"):
919 self.dylibPath = 'DYLD_LIBRARY_PATH'
920 elif sys.platform.startswith("linux") or sys.platform.startswith("freebsd"):
921 self.dylibPath = 'LD_LIBRARY_PATH'
922
Johnny Chen644ad082011-10-19 16:48:07 +0000923 def runHooks(self, child=None, child_prompt=None, use_cmd_api=False):
Johnny Chen5f3c5672011-10-19 01:06:21 +0000924 """Perform the run hooks to bring lldb debugger to the desired state.
925
Johnny Chen644ad082011-10-19 16:48:07 +0000926 By default, expect a pexpect spawned child and child prompt to be
927 supplied (use_cmd_api=False). If use_cmd_api is true, ignore the child
928 and child prompt and use self.runCmd() to run the hooks one by one.
929
Johnny Chen5f3c5672011-10-19 01:06:21 +0000930 Note that child is a process spawned by pexpect.spawn(). If not, your
931 test case is mostly likely going to fail.
932
933 See also dotest.py where lldb.runHooks are processed/populated.
934 """
935 if not lldb.runHooks:
936 self.skipTest("No runhooks specified for lldb, skip the test")
Johnny Chen644ad082011-10-19 16:48:07 +0000937 if use_cmd_api:
938 for hook in lldb.runhooks:
939 self.runCmd(hook)
940 else:
941 if not child or not child_prompt:
942 self.fail("Both child and child_prompt need to be defined.")
943 for hook in lldb.runHooks:
944 child.sendline(hook)
945 child.expect_exact(child_prompt)
Johnny Chen5f3c5672011-10-19 01:06:21 +0000946
Daniel Malea8b5c29d2013-02-19 16:08:57 +0000947 def setAsync(self, value):
948 """ Sets async mode to True/False and ensures it is reset after the testcase completes."""
949 old_async = self.dbg.GetAsync()
950 self.dbg.SetAsync(value)
951 self.addTearDownHook(lambda: self.dbg.SetAsync(old_async))
952
Daniel Malea5c5f01b2013-02-15 21:21:52 +0000953 def cleanupSubprocesses(self):
954 # Ensure any subprocesses are cleaned up
955 for p in self.subprocesses:
956 if p.poll() == None:
957 p.terminate()
958 del p
959 del self.subprocesses[:]
Daniel Maleaadbaa442013-06-05 21:07:02 +0000960 # Ensure any forked processes are cleaned up
961 for pid in self.forkedProcessPids:
962 if os.path.exists("/proc/" + str(pid)):
963 os.kill(pid, signal.SIGTERM)
Daniel Malea5c5f01b2013-02-15 21:21:52 +0000964
965 def spawnSubprocess(self, executable, args=[]):
966 """ Creates a subprocess.Popen object with the specified executable and arguments,
967 saves it in self.subprocesses, and returns the object.
968 NOTE: if using this function, ensure you also call:
969
970 self.addTearDownHook(self.cleanupSubprocesses)
971
972 otherwise the test suite will leak processes.
973 """
974
975 # Don't display the stdout if not in TraceOn() mode.
976 proc = Popen([executable] + args,
977 stdout = open(os.devnull) if not self.TraceOn() else None,
978 stdin = PIPE)
979 self.subprocesses.append(proc)
980 return proc
981
Daniel Maleaadbaa442013-06-05 21:07:02 +0000982 def forkSubprocess(self, executable, args=[]):
983 """ Fork a subprocess with its own group ID.
984 NOTE: if using this function, ensure you also call:
985
986 self.addTearDownHook(self.cleanupSubprocesses)
987
988 otherwise the test suite will leak processes.
989 """
990 child_pid = os.fork()
991 if child_pid == 0:
992 # If more I/O support is required, this can be beefed up.
993 fd = os.open(os.devnull, os.O_RDWR)
Daniel Maleaadbaa442013-06-05 21:07:02 +0000994 os.dup2(fd, 1)
995 os.dup2(fd, 2)
996 # This call causes the child to have its of group ID
997 os.setpgid(0,0)
998 os.execvp(executable, [executable] + args)
999 # Give the child time to get through the execvp() call
1000 time.sleep(0.1)
1001 self.forkedProcessPids.append(child_pid)
1002 return child_pid
1003
Johnny Chencbe51262011-08-01 19:50:58 +00001004 def HideStdout(self):
1005 """Hide output to stdout from the user.
1006
1007 During test execution, there might be cases where we don't want to show the
1008 standard output to the user. For example,
1009
1010 self.runCmd(r'''sc print "\n\n\tHello!\n"''')
1011
1012 tests whether command abbreviation for 'script' works or not. There is no
1013 need to show the 'Hello' output to the user as long as the 'script' command
1014 succeeds and we are not in TraceOn() mode (see the '-t' option).
1015
1016 In this case, the test method calls self.HideStdout(self) to redirect the
1017 sys.stdout to a null device, and restores the sys.stdout upon teardown.
1018
1019 Note that you should only call this method at most once during a test case
1020 execution. Any subsequent call has no effect at all."""
1021 if self.sys_stdout_hidden:
1022 return
1023
1024 self.sys_stdout_hidden = True
1025 old_stdout = sys.stdout
1026 sys.stdout = open(os.devnull, 'w')
1027 def restore_stdout():
1028 sys.stdout = old_stdout
1029 self.addTearDownHook(restore_stdout)
1030
1031 # =======================================================================
1032 # Methods for customized teardown cleanups as well as execution of hooks.
1033 # =======================================================================
1034
1035 def setTearDownCleanup(self, dictionary=None):
1036 """Register a cleanup action at tearDown() time with a dictinary"""
1037 self.dict = dictionary
1038 self.doTearDownCleanup = True
1039
1040 def addTearDownCleanup(self, dictionary):
1041 """Add a cleanup action at tearDown() time with a dictinary"""
1042 self.dicts.append(dictionary)
1043 self.doTearDownCleanups = True
1044
1045 def addTearDownHook(self, hook):
1046 """
1047 Add a function to be run during tearDown() time.
1048
1049 Hooks are executed in a first come first serve manner.
1050 """
1051 if callable(hook):
1052 with recording(self, traceAlways) as sbuf:
1053 print >> sbuf, "Adding tearDown hook:", getsource_if_available(hook)
1054 self.hooks.append(hook)
1055
1056 def tearDown(self):
1057 """Fixture for unittest test case teardown."""
1058 #import traceback
1059 #traceback.print_stack()
1060
Johnny Chen71cb7972011-08-01 21:13:26 +00001061 # This is for the case of directly spawning 'lldb' and interacting with it
1062 # using pexpect.
1063 import pexpect
1064 if self.child and self.child.isalive():
1065 with recording(self, traceAlways) as sbuf:
1066 print >> sbuf, "tearing down the child process...."
Johnny Chen71cb7972011-08-01 21:13:26 +00001067 try:
Daniel Maleac29f0f32013-02-22 00:41:26 +00001068 if self.child_in_script_interpreter:
1069 self.child.sendline('quit()')
1070 self.child.expect_exact(self.child_prompt)
1071 self.child.sendline('settings set interpreter.prompt-on-quit false')
1072 self.child.sendline('quit')
Johnny Chen71cb7972011-08-01 21:13:26 +00001073 self.child.expect(pexpect.EOF)
Daniel Maleac29f0f32013-02-22 00:41:26 +00001074 except ValueError, ExceptionPexpect:
1075 # child is already terminated
Johnny Chen71cb7972011-08-01 21:13:26 +00001076 pass
Daniel Maleac29f0f32013-02-22 00:41:26 +00001077
Johnny Chenf0ff42a2012-02-27 23:07:40 +00001078 # Give it one final blow to make sure the child is terminated.
1079 self.child.close()
Johnny Chen71cb7972011-08-01 21:13:26 +00001080
Johnny Chencbe51262011-08-01 19:50:58 +00001081 # Check and run any hook functions.
1082 for hook in reversed(self.hooks):
1083 with recording(self, traceAlways) as sbuf:
1084 print >> sbuf, "Executing tearDown hook:", getsource_if_available(hook)
1085 hook()
1086
1087 del self.hooks
1088
1089 # Perform registered teardown cleanup.
1090 if doCleanup and self.doTearDownCleanup:
Johnny Chen028d8eb2011-11-17 19:57:27 +00001091 self.cleanup(dictionary=self.dict)
Johnny Chencbe51262011-08-01 19:50:58 +00001092
1093 # In rare cases where there are multiple teardown cleanups added.
1094 if doCleanup and self.doTearDownCleanups:
Johnny Chencbe51262011-08-01 19:50:58 +00001095 if self.dicts:
1096 for dict in reversed(self.dicts):
Johnny Chen028d8eb2011-11-17 19:57:27 +00001097 self.cleanup(dictionary=dict)
Johnny Chencbe51262011-08-01 19:50:58 +00001098
1099 # Decide whether to dump the session info.
1100 self.dumpSessionInfo()
1101
1102 # =========================================================
1103 # Various callbacks to allow introspection of test progress
1104 # =========================================================
1105
1106 def markError(self):
1107 """Callback invoked when an error (unexpected exception) errored."""
1108 self.__errored__ = True
1109 with recording(self, False) as sbuf:
1110 # False because there's no need to write "ERROR" to the stderr twice.
1111 # Once by the Python unittest framework, and a second time by us.
1112 print >> sbuf, "ERROR"
1113
1114 def markFailure(self):
1115 """Callback invoked when a failure (test assertion failure) occurred."""
1116 self.__failed__ = True
1117 with recording(self, False) as sbuf:
1118 # False because there's no need to write "FAIL" to the stderr twice.
1119 # Once by the Python unittest framework, and a second time by us.
1120 print >> sbuf, "FAIL"
1121
Enrico Granata21416a12013-02-23 01:05:23 +00001122 def markExpectedFailure(self,err,bugnumber):
Johnny Chencbe51262011-08-01 19:50:58 +00001123 """Callback invoked when an expected failure/error occurred."""
1124 self.__expected__ = True
1125 with recording(self, False) as sbuf:
1126 # False because there's no need to write "expected failure" to the
1127 # stderr twice.
1128 # Once by the Python unittest framework, and a second time by us.
Enrico Granata21416a12013-02-23 01:05:23 +00001129 if bugnumber == None:
1130 print >> sbuf, "expected failure"
1131 else:
1132 print >> sbuf, "expected failure (problem id:" + str(bugnumber) + ")"
Johnny Chencbe51262011-08-01 19:50:58 +00001133
Johnny Chenf5b89092011-08-15 23:09:08 +00001134 def markSkippedTest(self):
1135 """Callback invoked when a test is skipped."""
1136 self.__skipped__ = True
1137 with recording(self, False) as sbuf:
1138 # False because there's no need to write "skipped test" to the
1139 # stderr twice.
1140 # Once by the Python unittest framework, and a second time by us.
1141 print >> sbuf, "skipped test"
1142
Enrico Granata21416a12013-02-23 01:05:23 +00001143 def markUnexpectedSuccess(self, bugnumber):
Johnny Chencbe51262011-08-01 19:50:58 +00001144 """Callback invoked when an unexpected success occurred."""
1145 self.__unexpected__ = True
1146 with recording(self, False) as sbuf:
1147 # False because there's no need to write "unexpected success" to the
1148 # stderr twice.
1149 # Once by the Python unittest framework, and a second time by us.
Enrico Granata21416a12013-02-23 01:05:23 +00001150 if bugnumber == None:
1151 print >> sbuf, "unexpected success"
1152 else:
1153 print >> sbuf, "unexpected success (problem id:" + str(bugnumber) + ")"
Johnny Chencbe51262011-08-01 19:50:58 +00001154
1155 def dumpSessionInfo(self):
1156 """
1157 Dump the debugger interactions leading to a test error/failure. This
1158 allows for more convenient postmortem analysis.
1159
1160 See also LLDBTestResult (dotest.py) which is a singlton class derived
1161 from TextTestResult and overwrites addError, addFailure, and
1162 addExpectedFailure methods to allow us to to mark the test instance as
1163 such.
1164 """
1165
1166 # We are here because self.tearDown() detected that this test instance
1167 # either errored or failed. The lldb.test_result singleton contains
1168 # two lists (erros and failures) which get populated by the unittest
1169 # framework. Look over there for stack trace information.
1170 #
1171 # The lists contain 2-tuples of TestCase instances and strings holding
1172 # formatted tracebacks.
1173 #
1174 # See http://docs.python.org/library/unittest.html#unittest.TestResult.
1175 if self.__errored__:
1176 pairs = lldb.test_result.errors
1177 prefix = 'Error'
1178 elif self.__failed__:
1179 pairs = lldb.test_result.failures
1180 prefix = 'Failure'
1181 elif self.__expected__:
1182 pairs = lldb.test_result.expectedFailures
1183 prefix = 'ExpectedFailure'
Johnny Chenf5b89092011-08-15 23:09:08 +00001184 elif self.__skipped__:
1185 prefix = 'SkippedTest'
Johnny Chencbe51262011-08-01 19:50:58 +00001186 elif self.__unexpected__:
1187 prefix = "UnexpectedSuccess"
1188 else:
1189 # Simply return, there's no session info to dump!
1190 return
1191
Johnny Chenf5b89092011-08-15 23:09:08 +00001192 if not self.__unexpected__ and not self.__skipped__:
Johnny Chencbe51262011-08-01 19:50:58 +00001193 for test, traceback in pairs:
1194 if test is self:
1195 print >> self.session, traceback
1196
Johnny Chen6fd55f12011-08-11 00:16:28 +00001197 testMethod = getattr(self, self._testMethodName)
1198 if getattr(testMethod, "__benchmarks_test__", False):
1199 benchmarks = True
1200 else:
1201 benchmarks = False
1202
Johnny Chendfa0cdb2011-12-03 00:16:59 +00001203 # This records the compiler version used for the test.
1204 system([self.getCompiler(), "-v"], sender=self)
1205
Johnny Chencbe51262011-08-01 19:50:58 +00001206 dname = os.path.join(os.environ["LLDB_TEST"],
1207 os.environ["LLDB_SESSION_DIRNAME"])
1208 if not os.path.isdir(dname):
1209 os.mkdir(dname)
Sean Callanan783ac952012-10-16 18:22:04 +00001210 fname = os.path.join(dname, "%s-%s-%s-%s.log" % (prefix, self.getArchitecture(), "_".join(self.getCompiler().split('/')), self.id()))
Johnny Chencbe51262011-08-01 19:50:58 +00001211 with open(fname, "w") as f:
1212 import datetime
1213 print >> f, "Session info generated @", datetime.datetime.now().ctime()
1214 print >> f, self.session.getvalue()
1215 print >> f, "To rerun this test, issue the following command from the 'test' directory:\n"
Johnny Chen6fd55f12011-08-11 00:16:28 +00001216 print >> f, "./dotest.py %s -v %s -f %s.%s" % (self.getRunOptions(),
1217 ('+b' if benchmarks else '-t'),
Johnny Chencbe51262011-08-01 19:50:58 +00001218 self.__class__.__name__,
1219 self._testMethodName)
1220
1221 # ====================================================
1222 # Config. methods supported through a plugin interface
1223 # (enables reading of the current test configuration)
1224 # ====================================================
1225
1226 def getArchitecture(self):
1227 """Returns the architecture in effect the test suite is running with."""
1228 module = builder_module()
1229 return module.getArchitecture()
1230
1231 def getCompiler(self):
1232 """Returns the compiler in effect the test suite is running with."""
1233 module = builder_module()
1234 return module.getCompiler()
1235
Daniel Malea54fcf682013-02-27 17:29:46 +00001236 def getCompilerVersion(self):
1237 """ Returns a string that represents the compiler version.
1238 Supports: llvm, clang.
1239 """
1240 from lldbutil import which
1241 version = 'unknown'
1242
1243 compiler = self.getCompiler()
1244 version_output = system([which(compiler), "-v"])[1]
1245 for line in version_output.split(os.linesep):
Greg Clayton48c6b332013-03-06 02:34:51 +00001246 m = re.search('version ([0-9\.]+)', line)
Daniel Malea54fcf682013-02-27 17:29:46 +00001247 if m:
1248 version = m.group(1)
1249 return version
1250
Ashok Thirumurthi0c521642013-06-06 14:23:31 +00001251 def expectedCompilerVersion(self, compiler_version):
1252 """Returns True iff compiler_version[1] matches the current compiler version.
1253 Use compiler_version[0] to specify the operator used to determine if a match has occurred.
1254 Any operator other than the following defaults to an equality test:
1255 '>', '>=', "=>", '<', '<=', '=<', '!=', "!" or 'not'
1256 """
Ashok Thirumurthib7d46e32013-05-17 20:15:07 +00001257 if (compiler_version == None):
1258 return True
1259 operator = str(compiler_version[0])
1260 version = compiler_version[1]
1261
1262 if (version == None):
1263 return True
1264 if (operator == '>'):
1265 return self.getCompilerVersion() > version
1266 if (operator == '>=' or operator == '=>'):
1267 return self.getCompilerVersion() >= version
1268 if (operator == '<'):
1269 return self.getCompilerVersion() < version
1270 if (operator == '<=' or operator == '=<'):
1271 return self.getCompilerVersion() <= version
1272 if (operator == '!=' or operator == '!' or operator == 'not'):
1273 return str(version) not in str(self.getCompilerVersion())
1274 return str(version) in str(self.getCompilerVersion())
1275
1276 def expectedCompiler(self, compilers):
Ashok Thirumurthi0c521642013-06-06 14:23:31 +00001277 """Returns True iff any element of compilers is a sub-string of the current compiler."""
Ashok Thirumurthib7d46e32013-05-17 20:15:07 +00001278 if (compilers == None):
1279 return True
Ashok Thirumurthi0c521642013-06-06 14:23:31 +00001280
1281 for compiler in compilers:
1282 if compiler in self.getCompiler():
1283 return True
1284
1285 return False
Ashok Thirumurthib7d46e32013-05-17 20:15:07 +00001286
Johnny Chencbe51262011-08-01 19:50:58 +00001287 def getRunOptions(self):
1288 """Command line option for -A and -C to run this test again, called from
1289 self.dumpSessionInfo()."""
1290 arch = self.getArchitecture()
1291 comp = self.getCompiler()
Johnny Chenb7058c52011-08-24 19:48:51 +00001292 if arch:
1293 option_str = "-A " + arch
Johnny Chencbe51262011-08-01 19:50:58 +00001294 else:
Johnny Chenb7058c52011-08-24 19:48:51 +00001295 option_str = ""
1296 if comp:
Johnny Chene1219bf2012-03-16 20:44:00 +00001297 option_str += " -C " + comp
Johnny Chenb7058c52011-08-24 19:48:51 +00001298 return option_str
Johnny Chencbe51262011-08-01 19:50:58 +00001299
1300 # ==================================================
1301 # Build methods supported through a plugin interface
1302 # ==================================================
1303
Daniel Malea9c570672013-05-02 21:44:31 +00001304 def buildDriver(self, sources, exe_name):
1305 """ Platform-specific way to build a program that links with LLDB (via the liblldb.so
1306 or LLDB.framework).
1307 """
1308 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
Daniel Malea15802aa2013-05-06 19:31:31 +00001309 stdflag = "-std=c++0x"
Daniel Malea9c570672013-05-02 21:44:31 +00001310 else:
1311 stdflag = "-std=c++11"
1312
1313 if sys.platform.startswith("darwin"):
1314 dsym = os.path.join(self.lib_dir, 'LLDB.framework', 'LLDB')
1315 d = {'CXX_SOURCES' : sources,
1316 'EXE' : exe_name,
1317 'CFLAGS_EXTRAS' : "%s -stdlib=libc++" % stdflag,
1318 'FRAMEWORK_INCLUDES' : "-F%s" % self.lib_dir,
Jim Inghamec842242013-05-15 01:11:30 +00001319 'LD_EXTRAS' : "%s -rpath %s" % (dsym, self.lib_dir),
Daniel Malea9c570672013-05-02 21:44:31 +00001320 }
1321 elif sys.platform.startswith("linux") or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
1322 d = {'CXX_SOURCES' : sources,
1323 'EXE' : exe_name,
1324 'CFLAGS_EXTRAS' : "%s -I%s" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
1325 'LD_EXTRAS' : "-L%s -llldb" % self.lib_dir}
1326 if self.TraceOn():
1327 print "Building LLDB Driver (%s) from sources %s" % (exe_name, sources)
1328
1329 self.buildDefault(dictionary=d)
1330
1331 def buildProgram(self, sources, exe_name):
1332 """ Platform specific way to build an executable from C/C++ sources. """
1333 d = {'CXX_SOURCES' : sources,
1334 'EXE' : exe_name}
1335 self.buildDefault(dictionary=d)
1336
Johnny Chencbf15912012-02-01 01:49:50 +00001337 def buildDefault(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chencbe51262011-08-01 19:50:58 +00001338 """Platform specific way to build the default binaries."""
Johnny Chen028d8eb2011-11-17 19:57:27 +00001339 if lldb.skip_build_and_cleanup:
1340 return
Johnny Chencbe51262011-08-01 19:50:58 +00001341 module = builder_module()
Johnny Chencbf15912012-02-01 01:49:50 +00001342 if not module.buildDefault(self, architecture, compiler, dictionary, clean):
Johnny Chencbe51262011-08-01 19:50:58 +00001343 raise Exception("Don't know how to build default binary")
1344
Johnny Chencbf15912012-02-01 01:49:50 +00001345 def buildDsym(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chencbe51262011-08-01 19:50:58 +00001346 """Platform specific way to build binaries with dsym info."""
Johnny Chen028d8eb2011-11-17 19:57:27 +00001347 if lldb.skip_build_and_cleanup:
1348 return
Johnny Chencbe51262011-08-01 19:50:58 +00001349 module = builder_module()
Johnny Chencbf15912012-02-01 01:49:50 +00001350 if not module.buildDsym(self, architecture, compiler, dictionary, clean):
Johnny Chencbe51262011-08-01 19:50:58 +00001351 raise Exception("Don't know how to build binary with dsym")
1352
Johnny Chencbf15912012-02-01 01:49:50 +00001353 def buildDwarf(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chencbe51262011-08-01 19:50:58 +00001354 """Platform specific way to build binaries with dwarf maps."""
Johnny Chen028d8eb2011-11-17 19:57:27 +00001355 if lldb.skip_build_and_cleanup:
1356 return
Johnny Chencbe51262011-08-01 19:50:58 +00001357 module = builder_module()
Johnny Chencbf15912012-02-01 01:49:50 +00001358 if not module.buildDwarf(self, architecture, compiler, dictionary, clean):
Johnny Chencbe51262011-08-01 19:50:58 +00001359 raise Exception("Don't know how to build binary with dwarf")
Johnny Chen366fb8c2011-08-01 18:46:13 +00001360
Andrew Kaylor3bd2ebd2013-05-28 23:04:25 +00001361 def getBuildFlags(self, use_cpp11=True, use_pthreads=True):
1362 """ Returns a dictionary (which can be provided to build* functions above) which
1363 contains OS-specific build flags.
1364 """
1365 cflags = ""
1366 if use_cpp11:
1367 cflags += "-std="
1368 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
1369 cflags += "c++0x"
1370 else:
1371 cflags += "c++11"
1372 if sys.platform.startswith("darwin"):
1373 cflags += " -stdlib=libc++"
1374 elif "clang" in self.getCompiler():
1375 cflags += " -stdlib=libstdc++"
1376
1377 if use_pthreads:
1378 ldflags = "-lpthread"
1379
1380 return {'CFLAGS_EXTRAS' : cflags,
1381 'LD_EXTRAS' : ldflags,
1382 }
1383
Johnny Chen7f9985a2011-08-12 20:19:22 +00001384 def cleanup(self, dictionary=None):
1385 """Platform specific way to do cleanup after build."""
Johnny Chen028d8eb2011-11-17 19:57:27 +00001386 if lldb.skip_build_and_cleanup:
1387 return
Johnny Chen7f9985a2011-08-12 20:19:22 +00001388 module = builder_module()
1389 if not module.cleanup(self, dictionary):
Johnny Chen028d8eb2011-11-17 19:57:27 +00001390 raise Exception("Don't know how to do cleanup with dictionary: "+dictionary)
Johnny Chen7f9985a2011-08-12 20:19:22 +00001391
Daniel Malea9c570672013-05-02 21:44:31 +00001392 def getLLDBLibraryEnvVal(self):
1393 """ Returns the path that the OS-specific library search environment variable
1394 (self.dylibPath) should be set to in order for a program to find the LLDB
1395 library. If an environment variable named self.dylibPath is already set,
1396 the new path is appended to it and returned.
1397 """
1398 existing_library_path = os.environ[self.dylibPath] if self.dylibPath in os.environ else None
1399 if existing_library_path:
1400 return "%s:%s" % (existing_library_path, self.lib_dir)
1401 elif sys.platform.startswith("darwin"):
1402 return os.path.join(self.lib_dir, 'LLDB.framework')
1403 else:
1404 return self.lib_dir
Johnny Chen366fb8c2011-08-01 18:46:13 +00001405
1406class TestBase(Base):
1407 """
1408 This abstract base class is meant to be subclassed. It provides default
1409 implementations for setUpClass(), tearDownClass(), setUp(), and tearDown(),
1410 among other things.
1411
1412 Important things for test class writers:
1413
1414 - Overwrite the mydir class attribute, otherwise your test class won't
1415 run. It specifies the relative directory to the top level 'test' so
1416 the test harness can change to the correct working directory before
1417 running your test.
1418
1419 - The setUp method sets up things to facilitate subsequent interactions
1420 with the debugger as part of the test. These include:
1421 - populate the test method name
1422 - create/get a debugger set with synchronous mode (self.dbg)
1423 - get the command interpreter from with the debugger (self.ci)
1424 - create a result object for use with the command interpreter
1425 (self.res)
1426 - plus other stuffs
1427
1428 - The tearDown method tries to perform some necessary cleanup on behalf
1429 of the test to return the debugger to a good state for the next test.
1430 These include:
1431 - execute any tearDown hooks registered by the test method with
1432 TestBase.addTearDownHook(); examples can be found in
1433 settings/TestSettings.py
1434 - kill the inferior process associated with each target, if any,
1435 and, then delete the target from the debugger's target list
1436 - perform build cleanup before running the next test method in the
1437 same test class; examples of registering for this service can be
1438 found in types/TestIntegerTypes.py with the call:
1439 - self.setTearDownCleanup(dictionary=d)
1440
1441 - Similarly setUpClass and tearDownClass perform classwise setup and
1442 teardown fixtures. The tearDownClass method invokes a default build
1443 cleanup for the entire test class; also, subclasses can implement the
1444 classmethod classCleanup(cls) to perform special class cleanup action.
1445
1446 - The instance methods runCmd and expect are used heavily by existing
1447 test cases to send a command to the command interpreter and to perform
1448 string/pattern matching on the output of such command execution. The
1449 expect method also provides a mode to peform string/pattern matching
1450 without running a command.
1451
1452 - The build methods buildDefault, buildDsym, and buildDwarf are used to
1453 build the binaries used during a particular test scenario. A plugin
1454 should be provided for the sys.platform running the test suite. The
1455 Mac OS X implementation is located in plugins/darwin.py.
1456 """
1457
1458 # Maximum allowed attempts when launching the inferior process.
1459 # Can be overridden by the LLDB_MAX_LAUNCH_COUNT environment variable.
1460 maxLaunchCount = 3;
1461
1462 # Time to wait before the next launching attempt in second(s).
1463 # Can be overridden by the LLDB_TIME_WAIT_NEXT_LAUNCH environment variable.
1464 timeWaitNextLaunch = 1.0;
1465
1466 def doDelay(self):
1467 """See option -w of dotest.py."""
1468 if ("LLDB_WAIT_BETWEEN_TEST_CASES" in os.environ and
1469 os.environ["LLDB_WAIT_BETWEEN_TEST_CASES"] == 'YES'):
1470 waitTime = 1.0
1471 if "LLDB_TIME_WAIT_BETWEEN_TEST_CASES" in os.environ:
1472 waitTime = float(os.environ["LLDB_TIME_WAIT_BETWEEN_TEST_CASES"])
1473 time.sleep(waitTime)
1474
Enrico Granataac3a8e22012-09-21 19:10:53 +00001475 # Returns the list of categories to which this test case belongs
1476 # by default, look for a ".categories" file, and read its contents
1477 # if no such file exists, traverse the hierarchy - we guarantee
1478 # a .categories to exist at the top level directory so we do not end up
1479 # looping endlessly - subclasses are free to define their own categories
1480 # in whatever way makes sense to them
1481 def getCategories(self):
1482 import inspect
1483 import os.path
1484 folder = inspect.getfile(self.__class__)
1485 folder = os.path.dirname(folder)
1486 while folder != '/':
1487 categories_file_name = os.path.join(folder,".categories")
1488 if os.path.exists(categories_file_name):
1489 categories_file = open(categories_file_name,'r')
1490 categories = categories_file.readline()
1491 categories_file.close()
1492 categories = str.replace(categories,'\n','')
1493 categories = str.replace(categories,'\r','')
1494 return categories.split(',')
1495 else:
1496 folder = os.path.dirname(folder)
1497 continue
1498
Johnny Chen366fb8c2011-08-01 18:46:13 +00001499 def setUp(self):
1500 #import traceback
1501 #traceback.print_stack()
1502
1503 # Works with the test driver to conditionally skip tests via decorators.
1504 Base.setUp(self)
1505
Johnny Chen366fb8c2011-08-01 18:46:13 +00001506 try:
1507 if lldb.blacklist:
1508 className = self.__class__.__name__
1509 classAndMethodName = "%s.%s" % (className, self._testMethodName)
1510 if className in lldb.blacklist:
1511 self.skipTest(lldb.blacklist.get(className))
1512 elif classAndMethodName in lldb.blacklist:
1513 self.skipTest(lldb.blacklist.get(classAndMethodName))
1514 except AttributeError:
1515 pass
1516
Johnny Chen9a9fcf62011-06-21 00:53:00 +00001517 # Insert some delay between successive test cases if specified.
1518 self.doDelay()
Johnny Chene47649c2010-10-07 02:04:14 +00001519
Johnny Chen65572482010-08-25 18:49:48 +00001520 if "LLDB_MAX_LAUNCH_COUNT" in os.environ:
1521 self.maxLaunchCount = int(os.environ["LLDB_MAX_LAUNCH_COUNT"])
1522
Johnny Chend2965212010-10-19 16:00:42 +00001523 if "LLDB_TIME_WAIT_NEXT_LAUNCH" in os.environ:
Johnny Chen458a67e2010-11-29 20:20:34 +00001524 self.timeWaitNextLaunch = float(os.environ["LLDB_TIME_WAIT_NEXT_LAUNCH"])
Johnny Chen65572482010-08-25 18:49:48 +00001525
Johnny Chena1affab2010-07-03 03:41:59 +00001526 # Create the debugger instance if necessary.
1527 try:
1528 self.dbg = lldb.DBG
Johnny Chena1affab2010-07-03 03:41:59 +00001529 except AttributeError:
1530 self.dbg = lldb.SBDebugger.Create()
Johnny Chenf8c723b2010-07-03 20:41:42 +00001531
Johnny Chen960ce122011-05-25 19:06:18 +00001532 if not self.dbg:
Johnny Chena1affab2010-07-03 03:41:59 +00001533 raise Exception('Invalid debugger instance')
1534
1535 # We want our debugger to be synchronous.
1536 self.dbg.SetAsync(False)
1537
1538 # Retrieve the associated command interpreter instance.
1539 self.ci = self.dbg.GetCommandInterpreter()
1540 if not self.ci:
1541 raise Exception('Could not get the command interpreter')
1542
1543 # And the result object.
1544 self.res = lldb.SBCommandReturnObject()
1545
Johnny Chenac97a6b2012-04-16 18:55:15 +00001546 # Run global pre-flight code, if defined via the config file.
1547 if lldb.pre_flight:
1548 lldb.pre_flight(self)
1549
Enrico Granata251729e2012-10-24 01:23:57 +00001550 # utility methods that tests can use to access the current objects
1551 def target(self):
1552 if not self.dbg:
1553 raise Exception('Invalid debugger instance')
1554 return self.dbg.GetSelectedTarget()
1555
1556 def process(self):
1557 if not self.dbg:
1558 raise Exception('Invalid debugger instance')
1559 return self.dbg.GetSelectedTarget().GetProcess()
1560
1561 def thread(self):
1562 if not self.dbg:
1563 raise Exception('Invalid debugger instance')
1564 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread()
1565
1566 def frame(self):
1567 if not self.dbg:
1568 raise Exception('Invalid debugger instance')
1569 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame()
1570
Johnny Chena1affab2010-07-03 03:41:59 +00001571 def tearDown(self):
Johnny Chen72a14342010-09-02 21:23:12 +00001572 #import traceback
1573 #traceback.print_stack()
1574
Johnny Chencbe51262011-08-01 19:50:58 +00001575 Base.tearDown(self)
Johnny Chen705737b2010-10-19 23:40:13 +00001576
Johnny Chen409646d2011-06-15 21:24:24 +00001577 # Delete the target(s) from the debugger as a general cleanup step.
1578 # This includes terminating the process for each target, if any.
1579 # We'd like to reuse the debugger for our next test without incurring
1580 # the initialization overhead.
1581 targets = []
1582 for target in self.dbg:
1583 if target:
1584 targets.append(target)
1585 process = target.GetProcess()
1586 if process:
1587 rc = self.invoke(process, "Kill")
1588 self.assertTrue(rc.Success(), PROCESS_KILLED)
1589 for target in targets:
1590 self.dbg.DeleteTarget(target)
Johnny Chenffde4fc2010-08-16 21:28:10 +00001591
Johnny Chenac97a6b2012-04-16 18:55:15 +00001592 # Run global post-flight code, if defined via the config file.
1593 if lldb.post_flight:
1594 lldb.post_flight(self)
1595
Johnny Chena1affab2010-07-03 03:41:59 +00001596 del self.dbg
Johnny Chen84a6d6f2010-10-15 01:18:29 +00001597
Johnny Chen90c56e62011-09-30 21:48:35 +00001598 def switch_to_thread_with_stop_reason(self, stop_reason):
1599 """
1600 Run the 'thread list' command, and select the thread with stop reason as
1601 'stop_reason'. If no such thread exists, no select action is done.
1602 """
1603 from lldbutil import stop_reason_to_str
1604 self.runCmd('thread list')
1605 output = self.res.GetOutput()
1606 thread_line_pattern = re.compile("^[ *] thread #([0-9]+):.*stop reason = %s" %
1607 stop_reason_to_str(stop_reason))
1608 for line in output.splitlines():
1609 matched = thread_line_pattern.match(line)
1610 if matched:
1611 self.runCmd('thread select %s' % matched.group(1))
1612
Enrico Granatab1fb7272013-06-17 22:51:50 +00001613 def runCmd(self, cmd, msg=None, check=True, trace=False, inHistory=False):
Johnny Chen8df95eb2010-08-19 23:26:59 +00001614 """
1615 Ask the command interpreter to handle the command and then check its
1616 return status.
1617 """
1618 # Fail fast if 'cmd' is not meaningful.
1619 if not cmd or len(cmd) == 0:
1620 raise Exception("Bad 'cmd' parameter encountered")
Johnny Chen4f995f02010-08-20 17:57:32 +00001621
Johnny Chen9de4ede2010-08-31 17:42:54 +00001622 trace = (True if traceAlways else trace)
Johnny Chend0c24b22010-08-23 17:10:44 +00001623
Johnny Chen21f33412010-09-01 00:15:19 +00001624 running = (cmd.startswith("run") or cmd.startswith("process launch"))
Johnny Chen4f995f02010-08-20 17:57:32 +00001625
Johnny Chen21f33412010-09-01 00:15:19 +00001626 for i in range(self.maxLaunchCount if running else 1):
Enrico Granatab1fb7272013-06-17 22:51:50 +00001627 self.ci.HandleCommand(cmd, self.res, inHistory)
Johnny Chen4f995f02010-08-20 17:57:32 +00001628
Johnny Chen84a6d6f2010-10-15 01:18:29 +00001629 with recording(self, trace) as sbuf:
1630 print >> sbuf, "runCmd:", cmd
Johnny Chen7c565c82010-10-15 16:13:00 +00001631 if not check:
Johnny Chen31cf8e22010-10-15 18:52:22 +00001632 print >> sbuf, "check of return status not required"
Johnny Chen65572482010-08-25 18:49:48 +00001633 if self.res.Succeeded():
Johnny Chen84a6d6f2010-10-15 01:18:29 +00001634 print >> sbuf, "output:", self.res.GetOutput()
Johnny Chen65572482010-08-25 18:49:48 +00001635 else:
Johnny Chen84a6d6f2010-10-15 01:18:29 +00001636 print >> sbuf, "runCmd failed!"
1637 print >> sbuf, self.res.GetError()
Johnny Chen4f995f02010-08-20 17:57:32 +00001638
Johnny Chen029acae2010-08-20 21:03:09 +00001639 if self.res.Succeeded():
Johnny Chen65572482010-08-25 18:49:48 +00001640 break
Johnny Chen84a6d6f2010-10-15 01:18:29 +00001641 elif running:
Johnny Chendcb37222011-01-19 02:02:08 +00001642 # For process launch, wait some time before possible next try.
1643 time.sleep(self.timeWaitNextLaunch)
Johnny Chen894eab42012-08-01 19:56:04 +00001644 with recording(self, trace) as sbuf:
Johnny Chen84a6d6f2010-10-15 01:18:29 +00001645 print >> sbuf, "Command '" + cmd + "' failed!"
Johnny Chen4f995f02010-08-20 17:57:32 +00001646
Johnny Chen8df95eb2010-08-19 23:26:59 +00001647 if check:
1648 self.assertTrue(self.res.Succeeded(),
Johnny Chen05efcf782010-11-09 18:42:22 +00001649 msg if msg else CMD_MSG(cmd))
Johnny Chen8df95eb2010-08-19 23:26:59 +00001650
Jim Ingham431d8392012-09-22 00:05:11 +00001651 def match (self, str, patterns, msg=None, trace=False, error=False, matching=True, exe=True):
1652 """run command in str, and match the result against regexp in patterns returning the match object for the first matching pattern
1653
1654 Otherwise, all the arguments have the same meanings as for the expect function"""
1655
1656 trace = (True if traceAlways else trace)
1657
1658 if exe:
1659 # First run the command. If we are expecting error, set check=False.
1660 # Pass the assert message along since it provides more semantic info.
1661 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error)
1662
1663 # Then compare the output against expected strings.
1664 output = self.res.GetError() if error else self.res.GetOutput()
1665
1666 # If error is True, the API client expects the command to fail!
1667 if error:
1668 self.assertFalse(self.res.Succeeded(),
1669 "Command '" + str + "' is expected to fail!")
1670 else:
1671 # No execution required, just compare str against the golden input.
1672 output = str
1673 with recording(self, trace) as sbuf:
1674 print >> sbuf, "looking at:", output
1675
1676 # The heading says either "Expecting" or "Not expecting".
1677 heading = "Expecting" if matching else "Not expecting"
1678
1679 for pattern in patterns:
1680 # Match Objects always have a boolean value of True.
1681 match_object = re.search(pattern, output)
1682 matched = bool(match_object)
1683 with recording(self, trace) as sbuf:
1684 print >> sbuf, "%s pattern: %s" % (heading, pattern)
1685 print >> sbuf, "Matched" if matched else "Not matched"
1686 if matched:
1687 break
1688
1689 self.assertTrue(matched if matching else not matched,
1690 msg if msg else EXP_MSG(str, exe))
1691
1692 return match_object
1693
Enrico Granatab1fb7272013-06-17 22:51:50 +00001694 def expect(self, str, msg=None, patterns=None, startstr=None, endstr=None, substrs=None, trace=False, error=False, matching=True, exe=True, inHistory=False):
Johnny Chen8df95eb2010-08-19 23:26:59 +00001695 """
1696 Similar to runCmd; with additional expect style output matching ability.
1697
1698 Ask the command interpreter to handle the command and then check its
1699 return status. The 'msg' parameter specifies an informational assert
1700 message. We expect the output from running the command to start with
Johnny Chen2d899752010-09-21 21:08:53 +00001701 'startstr', matches the substrings contained in 'substrs', and regexp
1702 matches the patterns contained in 'patterns'.
Johnny Chen9792f8e2010-09-17 22:28:51 +00001703
1704 If the keyword argument error is set to True, it signifies that the API
1705 client is expecting the command to fail. In this case, the error stream
Johnny Chenee975b82010-09-17 22:45:27 +00001706 from running the command is retrieved and compared against the golden
Johnny Chen9792f8e2010-09-17 22:28:51 +00001707 input, instead.
Johnny Chen2d899752010-09-21 21:08:53 +00001708
1709 If the keyword argument matching is set to False, it signifies that the API
1710 client is expecting the output of the command not to match the golden
1711 input.
Johnny Chen8e06de92010-09-21 23:33:30 +00001712
1713 Finally, the required argument 'str' represents the lldb command to be
1714 sent to the command interpreter. In case the keyword argument 'exe' is
1715 set to False, the 'str' is treated as a string to be matched/not-matched
1716 against the golden input.
Johnny Chen8df95eb2010-08-19 23:26:59 +00001717 """
Johnny Chen9de4ede2010-08-31 17:42:54 +00001718 trace = (True if traceAlways else trace)
Johnny Chend0c24b22010-08-23 17:10:44 +00001719
Johnny Chen8e06de92010-09-21 23:33:30 +00001720 if exe:
1721 # First run the command. If we are expecting error, set check=False.
Johnny Chen60881f62010-10-28 21:10:32 +00001722 # Pass the assert message along since it provides more semantic info.
Enrico Granatab1fb7272013-06-17 22:51:50 +00001723 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error, inHistory=inHistory)
Johnny Chen8df95eb2010-08-19 23:26:59 +00001724
Johnny Chen8e06de92010-09-21 23:33:30 +00001725 # Then compare the output against expected strings.
1726 output = self.res.GetError() if error else self.res.GetOutput()
Johnny Chen9792f8e2010-09-17 22:28:51 +00001727
Johnny Chen8e06de92010-09-21 23:33:30 +00001728 # If error is True, the API client expects the command to fail!
1729 if error:
1730 self.assertFalse(self.res.Succeeded(),
1731 "Command '" + str + "' is expected to fail!")
1732 else:
1733 # No execution required, just compare str against the golden input.
Enrico Granata01458ca2012-10-23 00:09:02 +00001734 if isinstance(str,lldb.SBCommandReturnObject):
1735 output = str.GetOutput()
1736 else:
1737 output = str
Johnny Chen84a6d6f2010-10-15 01:18:29 +00001738 with recording(self, trace) as sbuf:
1739 print >> sbuf, "looking at:", output
Johnny Chen9792f8e2010-09-17 22:28:51 +00001740
Johnny Chen2d899752010-09-21 21:08:53 +00001741 # The heading says either "Expecting" or "Not expecting".
Johnny Chen84a6d6f2010-10-15 01:18:29 +00001742 heading = "Expecting" if matching else "Not expecting"
Johnny Chen2d899752010-09-21 21:08:53 +00001743
1744 # Start from the startstr, if specified.
1745 # If there's no startstr, set the initial state appropriately.
1746 matched = output.startswith(startstr) if startstr else (True if matching else False)
Johnny Chenead35c82010-08-20 18:25:15 +00001747
Johnny Chen84a6d6f2010-10-15 01:18:29 +00001748 if startstr:
1749 with recording(self, trace) as sbuf:
1750 print >> sbuf, "%s start string: %s" % (heading, startstr)
1751 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenead35c82010-08-20 18:25:15 +00001752
Johnny Chen90c56e62011-09-30 21:48:35 +00001753 # Look for endstr, if specified.
1754 keepgoing = matched if matching else not matched
1755 if endstr:
1756 matched = output.endswith(endstr)
1757 with recording(self, trace) as sbuf:
1758 print >> sbuf, "%s end string: %s" % (heading, endstr)
1759 print >> sbuf, "Matched" if matched else "Not matched"
1760
Johnny Chen2d899752010-09-21 21:08:53 +00001761 # Look for sub strings, if specified.
1762 keepgoing = matched if matching else not matched
1763 if substrs and keepgoing:
Johnny Chen8df95eb2010-08-19 23:26:59 +00001764 for str in substrs:
Johnny Chen091bb1d2010-09-23 23:35:28 +00001765 matched = output.find(str) != -1
Johnny Chen84a6d6f2010-10-15 01:18:29 +00001766 with recording(self, trace) as sbuf:
1767 print >> sbuf, "%s sub string: %s" % (heading, str)
1768 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chen2d899752010-09-21 21:08:53 +00001769 keepgoing = matched if matching else not matched
1770 if not keepgoing:
Johnny Chen8df95eb2010-08-19 23:26:59 +00001771 break
1772
Johnny Chen2d899752010-09-21 21:08:53 +00001773 # Search for regular expression patterns, if specified.
1774 keepgoing = matched if matching else not matched
1775 if patterns and keepgoing:
1776 for pattern in patterns:
1777 # Match Objects always have a boolean value of True.
1778 matched = bool(re.search(pattern, output))
Johnny Chen84a6d6f2010-10-15 01:18:29 +00001779 with recording(self, trace) as sbuf:
1780 print >> sbuf, "%s pattern: %s" % (heading, pattern)
1781 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chen2d899752010-09-21 21:08:53 +00001782 keepgoing = matched if matching else not matched
1783 if not keepgoing:
1784 break
Johnny Chen2d899752010-09-21 21:08:53 +00001785
1786 self.assertTrue(matched if matching else not matched,
Johnny Chen05efcf782010-11-09 18:42:22 +00001787 msg if msg else EXP_MSG(str, exe))
Johnny Chen8df95eb2010-08-19 23:26:59 +00001788
Johnny Chena8b3cdd2010-08-25 22:52:45 +00001789 def invoke(self, obj, name, trace=False):
Johnny Chend8473bc2010-08-25 22:56:10 +00001790 """Use reflection to call a method dynamically with no argument."""
Johnny Chen9de4ede2010-08-31 17:42:54 +00001791 trace = (True if traceAlways else trace)
Johnny Chena8b3cdd2010-08-25 22:52:45 +00001792
1793 method = getattr(obj, name)
1794 import inspect
1795 self.assertTrue(inspect.ismethod(method),
1796 name + "is a method name of object: " + str(obj))
1797 result = method()
Johnny Chen84a6d6f2010-10-15 01:18:29 +00001798 with recording(self, trace) as sbuf:
1799 print >> sbuf, str(method) + ":", result
Johnny Chena8b3cdd2010-08-25 22:52:45 +00001800 return result
Johnny Chen9c10c182010-08-27 00:15:48 +00001801
Johnny Chenb8770312011-05-27 23:36:52 +00001802 # =================================================
1803 # Misc. helper methods for debugging test execution
1804 # =================================================
1805
Johnny Chen57cd6dd2011-07-11 19:15:11 +00001806 def DebugSBValue(self, val):
Johnny Chen9de4ede2010-08-31 17:42:54 +00001807 """Debug print a SBValue object, if traceAlways is True."""
Johnny Chen47342d52011-04-27 17:43:07 +00001808 from lldbutil import value_type_to_str
Johnny Chen2c8d1592010-11-03 21:37:58 +00001809
Johnny Chen9de4ede2010-08-31 17:42:54 +00001810 if not traceAlways:
Johnny Chen9c10c182010-08-27 00:15:48 +00001811 return
1812
1813 err = sys.stderr
1814 err.write(val.GetName() + ":\n")
Johnny Chen90c56e62011-09-30 21:48:35 +00001815 err.write('\t' + "TypeName -> " + val.GetTypeName() + '\n')
1816 err.write('\t' + "ByteSize -> " + str(val.GetByteSize()) + '\n')
1817 err.write('\t' + "NumChildren -> " + str(val.GetNumChildren()) + '\n')
1818 err.write('\t' + "Value -> " + str(val.GetValue()) + '\n')
1819 err.write('\t' + "ValueAsUnsigned -> " + str(val.GetValueAsUnsigned())+ '\n')
1820 err.write('\t' + "ValueType -> " + value_type_to_str(val.GetValueType()) + '\n')
1821 err.write('\t' + "Summary -> " + str(val.GetSummary()) + '\n')
1822 err.write('\t' + "IsPointerType -> " + str(val.TypeIsPointerType()) + '\n')
1823 err.write('\t' + "Location -> " + val.GetLocation() + '\n')
Johnny Chen9c10c182010-08-27 00:15:48 +00001824
Johnny Chend7e04d92011-08-05 20:17:27 +00001825 def DebugSBType(self, type):
1826 """Debug print a SBType object, if traceAlways is True."""
1827 if not traceAlways:
1828 return
1829
1830 err = sys.stderr
1831 err.write(type.GetName() + ":\n")
1832 err.write('\t' + "ByteSize -> " + str(type.GetByteSize()) + '\n')
1833 err.write('\t' + "IsPointerType -> " + str(type.IsPointerType()) + '\n')
1834 err.write('\t' + "IsReferenceType -> " + str(type.IsReferenceType()) + '\n')
1835
Johnny Chen73041472011-03-12 01:18:19 +00001836 def DebugPExpect(self, child):
1837 """Debug the spwaned pexpect object."""
1838 if not traceAlways:
1839 return
1840
1841 print child
Filipe Cabecinhasdee13ce2012-06-20 10:13:40 +00001842
1843 @classmethod
1844 def RemoveTempFile(cls, file):
1845 if os.path.exists(file):
1846 os.remove(file)