blob: f719f20cf5ec60f735842fcdcc6507083273f9e4 [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
Johnny Chenc98892e2012-05-16 20:41:28 +000012entire of part of the test suite . Example:
Johnny Chenbf6ffa32010-07-03 03:41:59 +000013
Johnny Chenc98892e2012-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 Chen57b47382010-09-02 22:25:47 +000016...
Johnny Chend0190a62010-08-23 17:10:44 +000017
Johnny Chenc98892e2012-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 Chend0190a62010-08-23 17:10:44 +000021
Johnny Chenc98892e2012-05-16 20:41:28 +000022Configuration: arch=x86_64 compiler=clang
Johnny Chend0190a62010-08-23 17:10:44 +000023----------------------------------------------------------------------
Johnny Chenc98892e2012-05-16 20:41:28 +000024Collected 72 tests
25
26........................................................................
27----------------------------------------------------------------------
28Ran 72 tests in 135.468s
Johnny Chend0190a62010-08-23 17:10:44 +000029
30OK
Johnny Chenbf6ffa32010-07-03 03:41:59 +000031$
32"""
33
Johnny Chen90312a82010-09-21 22:34:45 +000034import os, sys, traceback
Enrico Granata7e137e32012-10-24 18:14:21 +000035import os.path
Johnny Chenea88e942010-09-21 21:08:53 +000036import re
Daniel Malea69207462013-06-05 21:07:02 +000037import signal
Johnny Chen8952a2d2010-08-30 21:35:00 +000038from subprocess import *
Johnny Chen150c3cc2010-10-15 01:18:29 +000039import StringIO
Johnny Chenf2b70232010-08-25 18:49:48 +000040import time
Johnny Chena33a93c2010-08-30 23:08:52 +000041import types
Johnny Chen73258832010-08-05 23:42:46 +000042import unittest2
Johnny Chenbf6ffa32010-07-03 03:41:59 +000043import lldb
44
Johnny Chen707b3c92010-10-11 22:25:46 +000045# See also dotest.parseOptionsAndInitTestdirs(), where the environment variables
Johnny Chend2047fa2011-01-19 18:18:47 +000046# LLDB_COMMAND_TRACE and LLDB_DO_CLEANUP are set from '-t' and '-r dir' options.
Johnny Chen707b3c92010-10-11 22:25:46 +000047
48# By default, traceAlways is False.
Johnny Chen8d55a342010-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 Chen707b3c92010-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 Chen8d55a342010-08-31 17:42:54 +000060
Johnny Chen00778092010-08-09 22:01:17 +000061#
62# Some commonly used assert messages.
63#
64
Johnny Chenaa902922010-09-17 22:45:27 +000065COMMAND_FAILED_AS_EXPECTED = "Command has failed as expected"
66
Johnny Chen00778092010-08-09 22:01:17 +000067CURRENT_EXECUTABLE_SET = "Current executable set successfully"
68
Johnny Chen7d1d7532010-09-02 21:23:12 +000069PROCESS_IS_VALID = "Process is valid"
70
71PROCESS_KILLED = "Process is killed successfully"
72
Johnny Chend5f66fc2010-12-23 01:12:19 +000073PROCESS_EXITED = "Process exited successfully"
74
75PROCESS_STOPPED = "Process status should be stopped"
76
Johnny Chen5ee88192010-08-27 23:47:36 +000077RUN_SUCCEEDED = "Process is launched successfully"
Johnny Chen00778092010-08-09 22:01:17 +000078
Johnny Chen17941842010-08-09 23:44:24 +000079RUN_COMPLETED = "Process exited successfully"
Johnny Chen00778092010-08-09 22:01:17 +000080
Johnny Chen67af43f2010-10-05 19:27:32 +000081BACKTRACE_DISPLAYED_CORRECTLY = "Backtrace displayed correctly"
82
Johnny Chen17941842010-08-09 23:44:24 +000083BREAKPOINT_CREATED = "Breakpoint created successfully"
84
Johnny Chenf10af382010-12-04 00:07:24 +000085BREAKPOINT_STATE_CORRECT = "Breakpoint state is correct"
86
Johnny Chene76896c2010-08-17 21:33:31 +000087BREAKPOINT_PENDING_CREATED = "Pending breakpoint created successfully"
88
Johnny Chen17941842010-08-09 23:44:24 +000089BREAKPOINT_HIT_ONCE = "Breakpoint resolved with hit cout = 1"
Johnny Chen00778092010-08-09 22:01:17 +000090
Johnny Chen703dbd02010-09-30 17:06:24 +000091BREAKPOINT_HIT_TWICE = "Breakpoint resolved with hit cout = 2"
92
Johnny Chen164f1e12010-10-15 18:07:09 +000093BREAKPOINT_HIT_THRICE = "Breakpoint resolved with hit cout = 3"
94
Greg Clayton5db6b792012-10-24 18:24:14 +000095MISSING_EXPECTED_REGISTERS = "At least one expected register is unavailable."
96
Johnny Chen89109ed12011-06-27 20:05:23 +000097OBJECT_PRINTED_CORRECTLY = "Object printed correctly"
98
Johnny Chen5b3a3572010-12-09 18:22:12 +000099SOURCE_DISPLAYED_CORRECTLY = "Source code displayed correctly"
100
Johnny Chenc70b02a2010-09-22 23:00:20 +0000101STEP_OUT_SUCCEEDED = "Thread step-out succeeded"
102
Johnny Chen1691a162011-04-15 16:44:48 +0000103STOPPED_DUE_TO_EXC_BAD_ACCESS = "Process should be stopped due to bad access exception"
104
Ashok Thirumurthib4e51342013-05-17 15:35:15 +0000105STOPPED_DUE_TO_ASSERT = "Process should be stopped due to an assertion"
106
Johnny Chen5d6c4642010-11-10 23:46:38 +0000107STOPPED_DUE_TO_BREAKPOINT = "Process should be stopped due to breakpoint"
Johnny Chende0338b2010-11-10 20:20:06 +0000108
Johnny Chen5d6c4642010-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 Chen00778092010-08-09 22:01:17 +0000111
Johnny Chen2e431ce2010-10-20 18:38:48 +0000112STOPPED_DUE_TO_BREAKPOINT_CONDITION = "Stopped due to breakpoint condition"
113
Johnny Chen0a3d1ca2010-12-13 21:49:58 +0000114STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT = "Stopped due to breakpoint and ignore count"
115
Johnny Chenc066ab42010-10-14 01:22:03 +0000116STOPPED_DUE_TO_SIGNAL = "Process state is stopped due to signal"
117
Johnny Chen00778092010-08-09 22:01:17 +0000118STOPPED_DUE_TO_STEP_IN = "Process state is stopped due to step in"
119
Johnny Chenf68cc122011-09-15 21:09:59 +0000120STOPPED_DUE_TO_WATCHPOINT = "Process should be stopped due to watchpoint"
121
Johnny Chen3c884a02010-08-24 22:07:56 +0000122DATA_TYPES_DISPLAYED_CORRECTLY = "Data type(s) displayed correctly"
123
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000124VALID_BREAKPOINT = "Got a valid breakpoint"
125
Johnny Chen5bfb8ee2010-10-22 18:10:25 +0000126VALID_BREAKPOINT_LOCATION = "Got a valid breakpoint location"
127
Johnny Chen7209d84f2011-05-06 23:26:12 +0000128VALID_COMMAND_INTERPRETER = "Got a valid command interpreter"
129
Johnny Chen5ee88192010-08-27 23:47:36 +0000130VALID_FILESPEC = "Got a valid filespec"
131
Johnny Chen025d1b82010-12-08 01:25:21 +0000132VALID_MODULE = "Got a valid module"
133
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000134VALID_PROCESS = "Got a valid process"
135
Johnny Chen025d1b82010-12-08 01:25:21 +0000136VALID_SYMBOL = "Got a valid symbol"
137
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000138VALID_TARGET = "Got a valid target"
139
Johnny Chen15f247a2012-02-03 20:43:00 +0000140VALID_TYPE = "Got a valid type"
141
Johnny Chen5819ab42011-07-15 22:28:10 +0000142VALID_VARIABLE = "Got a valid variable"
143
Johnny Chen981463d2010-08-25 19:00:04 +0000144VARIABLES_DISPLAYED_CORRECTLY = "Variable(s) displayed correctly"
Johnny Chen00778092010-08-09 22:01:17 +0000145
Johnny Chenf68cc122011-09-15 21:09:59 +0000146WATCHPOINT_CREATED = "Watchpoint created successfully"
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000147
Johnny Chenc0c67f22010-11-09 18:42:22 +0000148def CMD_MSG(str):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000149 '''A generic "Command '%s' returns successfully" message generator.'''
Johnny Chenc0c67f22010-11-09 18:42:22 +0000150 return "Command '%s' returns successfully" % str
151
Johnny Chen3bc8ae42012-03-15 19:10:00 +0000152def COMPLETION_MSG(str_before, str_after):
Johnny Chen98aceb02012-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 Chenc0c67f22010-11-09 18:42:22 +0000156def EXP_MSG(str, exe):
Johnny Chenaacf92e2011-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 Chenc0c67f22010-11-09 18:42:22 +0000159 return "'%s' %s expected result" % (str, 'returns' if exe else 'matches')
Johnny Chen17941842010-08-09 23:44:24 +0000160
Johnny Chen3343f042010-10-19 19:11:38 +0000161def SETTING_MSG(setting):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000162 '''A generic "Value of setting '%s' is correct" message generator.'''
Johnny Chen3343f042010-10-19 19:11:38 +0000163 return "Value of setting '%s' is correct" % setting
164
Johnny Chen27c41232010-08-26 21:49:29 +0000165def EnvArray():
Johnny Chenaacf92e2011-05-31 22:16:51 +0000166 """Returns an env variable array from the os.environ map object."""
Johnny Chen27c41232010-08-26 21:49:29 +0000167 return map(lambda k,v: k+"="+v, os.environ.keys(), os.environ.values())
168
Johnny Chen47ceb032010-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 Chencd9b7772010-10-12 00:09:25 +0000175 return i+1
Johnny Chen1691a162011-04-15 16:44:48 +0000176 raise Exception("Unable to find '%s' within file %s" % (string_to_match, filename))
Johnny Chen47ceb032010-10-11 23:52:19 +0000177
Johnny Chen67af43f2010-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 Chen57816732012-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 Chen150c3cc2010-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 Chen690fcef2010-10-15 23:55:05 +0000208 """Create a StringIO instance; record the session obj and trace flag."""
Johnny Chen150c3cc2010-10-15 01:18:29 +0000209 StringIO.StringIO.__init__(self)
Johnny Chen0241f142011-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 Chenbfcf37f2011-08-16 17:06:45 +0000212 self.session = getattr(test, "session", None) if test else None
Johnny Chen150c3cc2010-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 Chen690fcef2010-10-15 23:55:05 +0000229 print >> sys.stderr, self.getvalue()
230 if self.session:
231 print >> self.session, self.getvalue()
Johnny Chen150c3cc2010-10-15 01:18:29 +0000232 self.close()
233
Johnny Chen690fcef2010-10-15 23:55:05 +0000234# From 2.7's subprocess.check_output() convenience function.
Johnny Chenac77f3b2011-03-23 20:28:59 +0000235# Return a tuple (stdoutdata, stderrdata).
Johnny Chen690fcef2010-10-15 23:55:05 +0000236def system(*popenargs, **kwargs):
Johnny Chen8eb14a92011-11-16 22:44:28 +0000237 r"""Run an os command with arguments and return its output as a byte string.
Johnny Chen690fcef2010-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 Chenac77f3b2011-03-23 20:28:59 +0000262 process = Popen(stdout=PIPE, stderr=PIPE, *popenargs, **kwargs)
Johnny Chen0bd8c312011-11-16 22:41:53 +0000263 pid = process.pid
Johnny Chen690fcef2010-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 Chen0bd8c312011-11-16 22:41:53 +0000274 print >> sbuf, "with pid:", pid
Johnny Chen690fcef2010-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 Chenac77f3b2011-03-23 20:28:59 +0000285 return (output, error)
Johnny Chen690fcef2010-10-15 23:55:05 +0000286
Johnny Chenab9c1dd2010-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 Collingbourne19f48d52011-06-20 19:06:20 +0000298def builder_module():
Ed Maste4d90f0f2013-07-25 13:24:34 +0000299 if sys.platform.startswith("freebsd"):
300 return __import__("builder_freebsd")
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000301 return __import__("builder_" + sys.platform)
302
Johnny Chena74bb0a2011-08-01 18:46:13 +0000303#
304# Decorators for categorizing test cases.
305#
306
307from functools import wraps
308def python_api_test(func):
309 """Decorate the item as a Python API only test."""
310 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
311 raise Exception("@python_api_test can only be used to decorate a test method")
312 @wraps(func)
313 def wrapper(self, *args, **kwargs):
314 try:
315 if lldb.dont_do_python_api_test:
316 self.skipTest("python api tests")
317 except AttributeError:
318 pass
319 return func(self, *args, **kwargs)
320
321 # Mark this function as such to separate them from lldb command line tests.
322 wrapper.__python_api_test__ = True
323 return wrapper
324
Johnny Chena74bb0a2011-08-01 18:46:13 +0000325def benchmarks_test(func):
326 """Decorate the item as a benchmarks test."""
327 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
328 raise Exception("@benchmarks_test can only be used to decorate a test method")
329 @wraps(func)
330 def wrapper(self, *args, **kwargs):
331 try:
332 if not lldb.just_do_benchmarks_test:
333 self.skipTest("benchmarks tests")
334 except AttributeError:
335 pass
336 return func(self, *args, **kwargs)
337
338 # Mark this function as such to separate them from the regular tests.
339 wrapper.__benchmarks_test__ = True
340 return wrapper
341
Johnny Chenf1548d42012-04-06 00:56:05 +0000342def dsym_test(func):
343 """Decorate the item as a dsym test."""
344 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
345 raise Exception("@dsym_test can only be used to decorate a test method")
346 @wraps(func)
347 def wrapper(self, *args, **kwargs):
348 try:
349 if lldb.dont_do_dsym_test:
350 self.skipTest("dsym tests")
351 except AttributeError:
352 pass
353 return func(self, *args, **kwargs)
354
355 # Mark this function as such to separate them from the regular tests.
356 wrapper.__dsym_test__ = True
357 return wrapper
358
359def dwarf_test(func):
360 """Decorate the item as a dwarf test."""
361 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
362 raise Exception("@dwarf_test can only be used to decorate a test method")
363 @wraps(func)
364 def wrapper(self, *args, **kwargs):
365 try:
366 if lldb.dont_do_dwarf_test:
367 self.skipTest("dwarf tests")
368 except AttributeError:
369 pass
370 return func(self, *args, **kwargs)
371
372 # Mark this function as such to separate them from the regular tests.
373 wrapper.__dwarf_test__ = True
374 return wrapper
375
Todd Fialaa41d48c2014-04-28 04:49:40 +0000376def debugserver_test(func):
377 """Decorate the item as a debugserver test."""
378 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
379 raise Exception("@debugserver_test can only be used to decorate a test method")
380 @wraps(func)
381 def wrapper(self, *args, **kwargs):
382 try:
383 if lldb.dont_do_debugserver_test:
384 self.skipTest("debugserver tests")
385 except AttributeError:
386 pass
387 return func(self, *args, **kwargs)
388
389 # Mark this function as such to separate them from the regular tests.
390 wrapper.__debugserver_test__ = True
391 return wrapper
392
393def llgs_test(func):
394 """Decorate the item as a lldb-gdbserver test."""
395 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
396 raise Exception("@llgs_test can only be used to decorate a test method")
397 @wraps(func)
398 def wrapper(self, *args, **kwargs):
399 try:
400 if lldb.dont_do_llgs_test:
401 self.skipTest("llgs tests")
402 except AttributeError:
403 pass
404 return func(self, *args, **kwargs)
405
406 # Mark this function as such to separate them from the regular tests.
407 wrapper.__llgs_test__ = True
408 return wrapper
409
Daniel Maleae0f8f572013-08-26 23:57:52 +0000410def not_remote_testsuite_ready(func):
411 """Decorate the item as a test which is not ready yet for remote testsuite."""
412 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
413 raise Exception("@not_remote_testsuite_ready can only be used to decorate a test method")
414 @wraps(func)
415 def wrapper(self, *args, **kwargs):
416 try:
417 if lldb.lldbtest_remote_sandbox:
418 self.skipTest("not ready for remote testsuite")
419 except AttributeError:
420 pass
421 return func(self, *args, **kwargs)
422
423 # Mark this function as such to separate them from the regular tests.
424 wrapper.__not_ready_for_remote_testsuite_test__ = True
425 return wrapper
426
Ed Maste433790a2014-04-23 12:55:41 +0000427def expectedFailure(expected_fn, bugnumber=None):
428 def expectedFailure_impl(func):
429 @wraps(func)
430 def wrapper(*args, **kwargs):
Enrico Granata43f62132013-02-23 01:28:30 +0000431 from unittest2 import case
432 self = args[0]
Enrico Granata43f62132013-02-23 01:28:30 +0000433 try:
Ed Maste433790a2014-04-23 12:55:41 +0000434 func(*args, **kwargs)
Enrico Granata43f62132013-02-23 01:28:30 +0000435 except Exception:
Ed Maste433790a2014-04-23 12:55:41 +0000436 if expected_fn(self):
437 raise case._ExpectedFailure(sys.exc_info(), bugnumber)
Enrico Granata43f62132013-02-23 01:28:30 +0000438 else:
439 raise
Ed Maste433790a2014-04-23 12:55:41 +0000440 if expected_fn(self):
441 raise case._UnexpectedSuccess(sys.exc_info(), bugnumber)
442 return wrapper
443 if callable(bugnumber):
444 return expectedFailure_impl(bugnumber)
445 else:
446 return expectedFailure_impl
447
448def expectedFailureCompiler(compiler, compiler_version=None, bugnumber=None):
449 if compiler_version is None:
450 compiler_version=['=', None]
451 def fn(self):
452 return compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version)
453 return expectedFailure(fn, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000454
Enrico Granata2b3a0c42013-02-23 01:35:21 +0000455def expectedFailureClang(bugnumber=None):
Ed Maste433790a2014-04-23 12:55:41 +0000456 return expectedFailureCompiler('clang', None, bugnumber)
457
458def expectedFailureGcc(bugnumber=None, compiler_version=None):
459 return expectedFailureCompiler('gcc', compiler_version, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000460
Matt Kopec0de53f02013-03-15 19:10:12 +0000461def expectedFailureIcc(bugnumber=None):
Ed Maste433790a2014-04-23 12:55:41 +0000462 return expectedFailureCompiler('icc', None, bugnumber)
Matt Kopec0de53f02013-03-15 19:10:12 +0000463
Ed Maste433790a2014-04-23 12:55:41 +0000464def expectedFailureArch(arch, bugnumber=None):
465 def fn(self):
466 return arch in self.getArchitecture()
467 return expectedFailure(fn, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000468
Enrico Granatae6cedc12013-02-23 01:05:23 +0000469def expectedFailurei386(bugnumber=None):
Ed Maste433790a2014-04-23 12:55:41 +0000470 return expectedFailureArch('i386', bugnumber)
Johnny Chena33843f2011-12-22 21:14:31 +0000471
Matt Kopecee969f92013-09-26 23:30:59 +0000472def expectedFailurex86_64(bugnumber=None):
Ed Maste433790a2014-04-23 12:55:41 +0000473 return expectedFailureArch('x86_64', bugnumber)
474
475def expectedFailureOS(os, bugnumber=None, compilers=None):
476 def fn(self):
477 return os in sys.platform and self.expectedCompiler(compilers)
478 return expectedFailure(fn, bugnumber)
479
480def expectedFailureDarwin(bugnumber=None, compilers=None):
481 return expectedFailureOS('darwin', bugnumber, compilers)
Matt Kopecee969f92013-09-26 23:30:59 +0000482
Ed Maste24a7f7d2013-07-24 19:47:08 +0000483def expectedFailureFreeBSD(bugnumber=None, compilers=None):
Ed Maste433790a2014-04-23 12:55:41 +0000484 return expectedFailureOS('freebsd', bugnumber, compilers)
Ed Maste24a7f7d2013-07-24 19:47:08 +0000485
Ashok Thirumurthic97a6082013-05-17 20:15:07 +0000486def expectedFailureLinux(bugnumber=None, compilers=None):
Ed Maste433790a2014-04-23 12:55:41 +0000487 return expectedFailureOS('linux', bugnumber, compilers)
Matt Kopece9ea0da2013-05-07 19:29:28 +0000488
Greg Clayton12514562013-12-05 22:22:32 +0000489def skipIfRemote(func):
490 """Decorate the item to skip tests if testing remotely."""
491 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
492 raise Exception("@skipIfRemote can only be used to decorate a test method")
493 @wraps(func)
494 def wrapper(*args, **kwargs):
495 from unittest2 import case
496 if lldb.remote_platform:
497 self = args[0]
498 self.skipTest("skip on remote platform")
499 else:
500 func(*args, **kwargs)
501 return wrapper
502
503def skipIfRemoteDueToDeadlock(func):
504 """Decorate the item to skip tests if testing remotely due to the test deadlocking."""
505 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
506 raise Exception("@skipIfRemote can only be used to decorate a test method")
507 @wraps(func)
508 def wrapper(*args, **kwargs):
509 from unittest2 import case
510 if lldb.remote_platform:
511 self = args[0]
512 self.skipTest("skip on remote platform (deadlocks)")
513 else:
514 func(*args, **kwargs)
515 return wrapper
516
Ed Maste09617a52013-06-25 19:11:36 +0000517def skipIfFreeBSD(func):
518 """Decorate the item to skip tests that should be skipped on FreeBSD."""
519 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
520 raise Exception("@skipIfFreeBSD can only be used to decorate a test method")
521 @wraps(func)
522 def wrapper(*args, **kwargs):
523 from unittest2 import case
524 self = args[0]
525 platform = sys.platform
526 if "freebsd" in platform:
527 self.skipTest("skip on FreeBSD")
528 else:
529 func(*args, **kwargs)
530 return wrapper
531
Daniel Maleae8bdd1f2013-05-15 18:48:32 +0000532def skipIfLinux(func):
Daniel Malea93aec0f2012-11-23 21:59:29 +0000533 """Decorate the item to skip tests that should be skipped on Linux."""
534 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Daniel Maleae8bdd1f2013-05-15 18:48:32 +0000535 raise Exception("@skipIfLinux can only be used to decorate a test method")
Daniel Malea93aec0f2012-11-23 21:59:29 +0000536 @wraps(func)
537 def wrapper(*args, **kwargs):
538 from unittest2 import case
539 self = args[0]
540 platform = sys.platform
541 if "linux" in platform:
542 self.skipTest("skip on linux")
543 else:
Jim Ingham9732e082012-11-27 01:21:28 +0000544 func(*args, **kwargs)
Daniel Malea93aec0f2012-11-23 21:59:29 +0000545 return wrapper
546
Daniel Maleab3d41a22013-07-09 00:08:01 +0000547def skipIfDarwin(func):
548 """Decorate the item to skip tests that should be skipped on Darwin."""
549 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Ed Mastea7f13f02013-07-09 00:24:52 +0000550 raise Exception("@skipIfDarwin can only be used to decorate a test method")
Daniel Maleab3d41a22013-07-09 00:08:01 +0000551 @wraps(func)
552 def wrapper(*args, **kwargs):
553 from unittest2 import case
554 self = args[0]
555 platform = sys.platform
556 if "darwin" in platform:
557 self.skipTest("skip on darwin")
558 else:
559 func(*args, **kwargs)
560 return wrapper
561
562
Daniel Malea48359902013-05-14 20:48:54 +0000563def skipIfLinuxClang(func):
564 """Decorate the item to skip tests that should be skipped if building on
565 Linux with clang.
566 """
567 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
568 raise Exception("@skipIfLinuxClang can only be used to decorate a test method")
569 @wraps(func)
570 def wrapper(*args, **kwargs):
571 from unittest2 import case
572 self = args[0]
573 compiler = self.getCompiler()
574 platform = sys.platform
575 if "clang" in compiler and "linux" in platform:
576 self.skipTest("skipping because Clang is used on Linux")
577 else:
578 func(*args, **kwargs)
579 return wrapper
580
Daniel Maleabe230792013-01-24 23:52:09 +0000581def skipIfGcc(func):
582 """Decorate the item to skip tests that should be skipped if building with gcc ."""
583 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Daniel Malea0aea0162013-02-27 17:29:46 +0000584 raise Exception("@skipIfGcc can only be used to decorate a test method")
Daniel Maleabe230792013-01-24 23:52:09 +0000585 @wraps(func)
586 def wrapper(*args, **kwargs):
587 from unittest2 import case
588 self = args[0]
589 compiler = self.getCompiler()
590 if "gcc" in compiler:
591 self.skipTest("skipping because gcc is the test compiler")
592 else:
593 func(*args, **kwargs)
594 return wrapper
595
Matt Kopec0de53f02013-03-15 19:10:12 +0000596def skipIfIcc(func):
597 """Decorate the item to skip tests that should be skipped if building with icc ."""
598 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
599 raise Exception("@skipIfIcc can only be used to decorate a test method")
600 @wraps(func)
601 def wrapper(*args, **kwargs):
602 from unittest2 import case
603 self = args[0]
604 compiler = self.getCompiler()
605 if "icc" in compiler:
606 self.skipTest("skipping because icc is the test compiler")
607 else:
608 func(*args, **kwargs)
609 return wrapper
610
Daniel Malea55faa402013-05-02 21:44:31 +0000611def skipIfi386(func):
612 """Decorate the item to skip tests that should be skipped if building 32-bit."""
613 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
614 raise Exception("@skipIfi386 can only be used to decorate a test method")
615 @wraps(func)
616 def wrapper(*args, **kwargs):
617 from unittest2 import case
618 self = args[0]
619 if "i386" == self.getArchitecture():
620 self.skipTest("skipping because i386 is not a supported architecture")
621 else:
622 func(*args, **kwargs)
623 return wrapper
624
625
Johnny Chena74bb0a2011-08-01 18:46:13 +0000626class Base(unittest2.TestCase):
Johnny Chen8334dad2010-10-22 23:15:46 +0000627 """
Johnny Chena74bb0a2011-08-01 18:46:13 +0000628 Abstract base for performing lldb (see TestBase) or other generic tests (see
629 BenchBase for one example). lldbtest.Base works with the test driver to
630 accomplish things.
631
Johnny Chen8334dad2010-10-22 23:15:46 +0000632 """
Enrico Granata5020f952012-10-24 21:42:49 +0000633
Enrico Granata19186272012-10-24 21:44:48 +0000634 # The concrete subclass should override this attribute.
635 mydir = None
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000636
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000637 # Keep track of the old current working directory.
638 oldcwd = None
Greg Clayton4570d3e2013-12-10 23:19:29 +0000639
640 @staticmethod
641 def compute_mydir(test_file):
642 '''Subclasses should call this function to correctly calculate the required "mydir" attribute as follows:
643
644 mydir = TestBase.compute_mydir(__file__)'''
645 test_dir = os.path.dirname(test_file)
646 return test_dir[len(os.environ["LLDB_TEST"])+1:]
647
Johnny Chenfb4264c2011-08-01 19:50:58 +0000648 def TraceOn(self):
649 """Returns True if we are in trace mode (tracing detailed test execution)."""
650 return traceAlways
Greg Clayton4570d3e2013-12-10 23:19:29 +0000651
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000652 @classmethod
653 def setUpClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +0000654 """
655 Python unittest framework class setup fixture.
656 Do current directory manipulation.
657 """
658
Johnny Chenf02ec122010-07-03 20:41:42 +0000659 # Fail fast if 'mydir' attribute is not overridden.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000660 if not cls.mydir or len(cls.mydir) == 0:
Johnny Chenf02ec122010-07-03 20:41:42 +0000661 raise Exception("Subclasses must override the 'mydir' attribute.")
Enrico Granata7e137e32012-10-24 18:14:21 +0000662
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000663 # Save old working directory.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000664 cls.oldcwd = os.getcwd()
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000665
666 # Change current working directory if ${LLDB_TEST} is defined.
667 # See also dotest.py which sets up ${LLDB_TEST}.
668 if ("LLDB_TEST" in os.environ):
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000669 if traceAlways:
Johnny Chen703dbd02010-09-30 17:06:24 +0000670 print >> sys.stderr, "Change dir to:", os.path.join(os.environ["LLDB_TEST"], cls.mydir)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000671 os.chdir(os.path.join(os.environ["LLDB_TEST"], cls.mydir))
672
673 @classmethod
674 def tearDownClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +0000675 """
676 Python unittest framework class teardown fixture.
677 Do class-wide cleanup.
678 """
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000679
Johnny Chen0fddfb22011-11-17 19:57:27 +0000680 if doCleanup and not lldb.skip_build_and_cleanup:
Johnny Chen707b3c92010-10-11 22:25:46 +0000681 # First, let's do the platform-specific cleanup.
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000682 module = builder_module()
Johnny Chen707b3c92010-10-11 22:25:46 +0000683 if not module.cleanup():
684 raise Exception("Don't know how to do cleanup")
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000685
Johnny Chen707b3c92010-10-11 22:25:46 +0000686 # Subclass might have specific cleanup function defined.
687 if getattr(cls, "classCleanup", None):
688 if traceAlways:
689 print >> sys.stderr, "Call class-specific cleanup function for class:", cls
690 try:
691 cls.classCleanup()
692 except:
693 exc_type, exc_value, exc_tb = sys.exc_info()
694 traceback.print_exception(exc_type, exc_value, exc_tb)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000695
696 # Restore old working directory.
697 if traceAlways:
Johnny Chen703dbd02010-09-30 17:06:24 +0000698 print >> sys.stderr, "Restore dir to:", cls.oldcwd
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000699 os.chdir(cls.oldcwd)
700
Johnny Chena74bb0a2011-08-01 18:46:13 +0000701 @classmethod
702 def skipLongRunningTest(cls):
703 """
704 By default, we skip long running test case.
705 This can be overridden by passing '-l' to the test driver (dotest.py).
706 """
707 if "LLDB_SKIP_LONG_RUNNING_TEST" in os.environ and "NO" == os.environ["LLDB_SKIP_LONG_RUNNING_TEST"]:
708 return False
709 else:
710 return True
Johnny Chened492022011-06-21 00:53:00 +0000711
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000712 def setUp(self):
Johnny Chenfb4264c2011-08-01 19:50:58 +0000713 """Fixture for unittest test case setup.
714
715 It works with the test driver to conditionally skip tests and does other
716 initializations."""
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000717 #import traceback
718 #traceback.print_stack()
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000719
Daniel Malea9115f072013-08-06 15:02:32 +0000720 if "LIBCXX_PATH" in os.environ:
721 self.libcxxPath = os.environ["LIBCXX_PATH"]
722 else:
723 self.libcxxPath = None
724
Johnny Chenaaa82ff2011-08-02 22:54:37 +0000725 if "LLDB_EXEC" in os.environ:
726 self.lldbExec = os.environ["LLDB_EXEC"]
Johnny Chend890bfc2011-08-26 00:00:01 +0000727 else:
728 self.lldbExec = None
729 if "LLDB_HERE" in os.environ:
730 self.lldbHere = os.environ["LLDB_HERE"]
731 else:
732 self.lldbHere = None
Johnny Chenebe51722011-10-07 19:21:09 +0000733 # If we spawn an lldb process for test (via pexpect), do not load the
734 # init file unless told otherwise.
735 if "NO_LLDBINIT" in os.environ and "NO" == os.environ["NO_LLDBINIT"]:
736 self.lldbOption = ""
737 else:
738 self.lldbOption = "--no-lldbinit"
Johnny Chenaaa82ff2011-08-02 22:54:37 +0000739
Johnny Chen985e7402011-08-01 21:13:26 +0000740 # Assign the test method name to self.testMethodName.
741 #
742 # For an example of the use of this attribute, look at test/types dir.
743 # There are a bunch of test cases under test/types and we don't want the
744 # module cacheing subsystem to be confused with executable name "a.out"
745 # used for all the test cases.
746 self.testMethodName = self._testMethodName
747
Johnny Chenf3e22ac2010-12-10 18:52:10 +0000748 # Python API only test is decorated with @python_api_test,
749 # which also sets the "__python_api_test__" attribute of the
750 # function object to True.
Johnny Chen4533dad2011-05-31 23:21:42 +0000751 try:
752 if lldb.just_do_python_api_test:
753 testMethod = getattr(self, self._testMethodName)
754 if getattr(testMethod, "__python_api_test__", False):
755 pass
756 else:
Johnny Chen5ccbccf2011-07-30 01:39:58 +0000757 self.skipTest("non python api test")
758 except AttributeError:
759 pass
760
761 # Benchmarks test is decorated with @benchmarks_test,
762 # which also sets the "__benchmarks_test__" attribute of the
763 # function object to True.
764 try:
765 if lldb.just_do_benchmarks_test:
766 testMethod = getattr(self, self._testMethodName)
767 if getattr(testMethod, "__benchmarks_test__", False):
768 pass
769 else:
770 self.skipTest("non benchmarks test")
Johnny Chen4533dad2011-05-31 23:21:42 +0000771 except AttributeError:
772 pass
Johnny Chenf3e22ac2010-12-10 18:52:10 +0000773
Johnny Chen985e7402011-08-01 21:13:26 +0000774 # This is for the case of directly spawning 'lldb'/'gdb' and interacting
775 # with it using pexpect.
776 self.child = None
777 self.child_prompt = "(lldb) "
778 # If the child is interacting with the embedded script interpreter,
779 # there are two exits required during tear down, first to quit the
780 # embedded script interpreter and second to quit the lldb command
781 # interpreter.
782 self.child_in_script_interpreter = False
783
Johnny Chenfb4264c2011-08-01 19:50:58 +0000784 # These are for customized teardown cleanup.
785 self.dict = None
786 self.doTearDownCleanup = False
787 # And in rare cases where there are multiple teardown cleanups.
788 self.dicts = []
789 self.doTearDownCleanups = False
790
Daniel Malea2dd69bb2013-02-15 21:21:52 +0000791 # List of spawned subproces.Popen objects
792 self.subprocesses = []
793
Daniel Malea69207462013-06-05 21:07:02 +0000794 # List of forked process PIDs
795 self.forkedProcessPids = []
796
Johnny Chenfb4264c2011-08-01 19:50:58 +0000797 # Create a string buffer to record the session info, to be dumped into a
798 # test case specific file if test failure is encountered.
799 self.session = StringIO.StringIO()
800
801 # Optimistically set __errored__, __failed__, __expected__ to False
802 # initially. If the test errored/failed, the session info
803 # (self.session) is then dumped into a session specific file for
804 # diagnosis.
805 self.__errored__ = False
806 self.__failed__ = False
807 self.__expected__ = False
808 # We are also interested in unexpected success.
809 self.__unexpected__ = False
Johnny Chenf79b0762011-08-16 00:48:58 +0000810 # And skipped tests.
811 self.__skipped__ = False
Johnny Chenfb4264c2011-08-01 19:50:58 +0000812
813 # See addTearDownHook(self, hook) which allows the client to add a hook
814 # function to be run during tearDown() time.
815 self.hooks = []
816
817 # See HideStdout(self).
818 self.sys_stdout_hidden = False
819
Daniel Malea179ff292012-11-26 21:21:11 +0000820 # set environment variable names for finding shared libraries
821 if sys.platform.startswith("darwin"):
822 self.dylibPath = 'DYLD_LIBRARY_PATH'
823 elif sys.platform.startswith("linux") or sys.platform.startswith("freebsd"):
824 self.dylibPath = 'LD_LIBRARY_PATH'
825
Johnny Chen2a808582011-10-19 16:48:07 +0000826 def runHooks(self, child=None, child_prompt=None, use_cmd_api=False):
Johnny Chena737ba52011-10-19 01:06:21 +0000827 """Perform the run hooks to bring lldb debugger to the desired state.
828
Johnny Chen2a808582011-10-19 16:48:07 +0000829 By default, expect a pexpect spawned child and child prompt to be
830 supplied (use_cmd_api=False). If use_cmd_api is true, ignore the child
831 and child prompt and use self.runCmd() to run the hooks one by one.
832
Johnny Chena737ba52011-10-19 01:06:21 +0000833 Note that child is a process spawned by pexpect.spawn(). If not, your
834 test case is mostly likely going to fail.
835
836 See also dotest.py where lldb.runHooks are processed/populated.
837 """
838 if not lldb.runHooks:
839 self.skipTest("No runhooks specified for lldb, skip the test")
Johnny Chen2a808582011-10-19 16:48:07 +0000840 if use_cmd_api:
841 for hook in lldb.runhooks:
842 self.runCmd(hook)
843 else:
844 if not child or not child_prompt:
845 self.fail("Both child and child_prompt need to be defined.")
846 for hook in lldb.runHooks:
847 child.sendline(hook)
848 child.expect_exact(child_prompt)
Johnny Chena737ba52011-10-19 01:06:21 +0000849
Daniel Malea249287a2013-02-19 16:08:57 +0000850 def setAsync(self, value):
851 """ Sets async mode to True/False and ensures it is reset after the testcase completes."""
852 old_async = self.dbg.GetAsync()
853 self.dbg.SetAsync(value)
854 self.addTearDownHook(lambda: self.dbg.SetAsync(old_async))
855
Daniel Malea2dd69bb2013-02-15 21:21:52 +0000856 def cleanupSubprocesses(self):
857 # Ensure any subprocesses are cleaned up
858 for p in self.subprocesses:
859 if p.poll() == None:
860 p.terminate()
861 del p
862 del self.subprocesses[:]
Daniel Malea69207462013-06-05 21:07:02 +0000863 # Ensure any forked processes are cleaned up
864 for pid in self.forkedProcessPids:
865 if os.path.exists("/proc/" + str(pid)):
866 os.kill(pid, signal.SIGTERM)
Daniel Malea2dd69bb2013-02-15 21:21:52 +0000867
868 def spawnSubprocess(self, executable, args=[]):
869 """ Creates a subprocess.Popen object with the specified executable and arguments,
870 saves it in self.subprocesses, and returns the object.
871 NOTE: if using this function, ensure you also call:
872
873 self.addTearDownHook(self.cleanupSubprocesses)
874
875 otherwise the test suite will leak processes.
876 """
877
878 # Don't display the stdout if not in TraceOn() mode.
879 proc = Popen([executable] + args,
880 stdout = open(os.devnull) if not self.TraceOn() else None,
881 stdin = PIPE)
882 self.subprocesses.append(proc)
883 return proc
884
Daniel Malea69207462013-06-05 21:07:02 +0000885 def forkSubprocess(self, executable, args=[]):
886 """ Fork a subprocess with its own group ID.
887 NOTE: if using this function, ensure you also call:
888
889 self.addTearDownHook(self.cleanupSubprocesses)
890
891 otherwise the test suite will leak processes.
892 """
893 child_pid = os.fork()
894 if child_pid == 0:
895 # If more I/O support is required, this can be beefed up.
896 fd = os.open(os.devnull, os.O_RDWR)
Daniel Malea69207462013-06-05 21:07:02 +0000897 os.dup2(fd, 1)
898 os.dup2(fd, 2)
899 # This call causes the child to have its of group ID
900 os.setpgid(0,0)
901 os.execvp(executable, [executable] + args)
902 # Give the child time to get through the execvp() call
903 time.sleep(0.1)
904 self.forkedProcessPids.append(child_pid)
905 return child_pid
906
Johnny Chenfb4264c2011-08-01 19:50:58 +0000907 def HideStdout(self):
908 """Hide output to stdout from the user.
909
910 During test execution, there might be cases where we don't want to show the
911 standard output to the user. For example,
912
913 self.runCmd(r'''sc print "\n\n\tHello!\n"''')
914
915 tests whether command abbreviation for 'script' works or not. There is no
916 need to show the 'Hello' output to the user as long as the 'script' command
917 succeeds and we are not in TraceOn() mode (see the '-t' option).
918
919 In this case, the test method calls self.HideStdout(self) to redirect the
920 sys.stdout to a null device, and restores the sys.stdout upon teardown.
921
922 Note that you should only call this method at most once during a test case
923 execution. Any subsequent call has no effect at all."""
924 if self.sys_stdout_hidden:
925 return
926
927 self.sys_stdout_hidden = True
928 old_stdout = sys.stdout
929 sys.stdout = open(os.devnull, 'w')
930 def restore_stdout():
931 sys.stdout = old_stdout
932 self.addTearDownHook(restore_stdout)
933
934 # =======================================================================
935 # Methods for customized teardown cleanups as well as execution of hooks.
936 # =======================================================================
937
938 def setTearDownCleanup(self, dictionary=None):
939 """Register a cleanup action at tearDown() time with a dictinary"""
940 self.dict = dictionary
941 self.doTearDownCleanup = True
942
943 def addTearDownCleanup(self, dictionary):
944 """Add a cleanup action at tearDown() time with a dictinary"""
945 self.dicts.append(dictionary)
946 self.doTearDownCleanups = True
947
948 def addTearDownHook(self, hook):
949 """
950 Add a function to be run during tearDown() time.
951
952 Hooks are executed in a first come first serve manner.
953 """
954 if callable(hook):
955 with recording(self, traceAlways) as sbuf:
956 print >> sbuf, "Adding tearDown hook:", getsource_if_available(hook)
957 self.hooks.append(hook)
958
959 def tearDown(self):
960 """Fixture for unittest test case teardown."""
961 #import traceback
962 #traceback.print_stack()
963
Johnny Chen985e7402011-08-01 21:13:26 +0000964 # This is for the case of directly spawning 'lldb' and interacting with it
965 # using pexpect.
966 import pexpect
967 if self.child and self.child.isalive():
968 with recording(self, traceAlways) as sbuf:
969 print >> sbuf, "tearing down the child process...."
Johnny Chen985e7402011-08-01 21:13:26 +0000970 try:
Daniel Maleac9a0ec32013-02-22 00:41:26 +0000971 if self.child_in_script_interpreter:
972 self.child.sendline('quit()')
973 self.child.expect_exact(self.child_prompt)
974 self.child.sendline('settings set interpreter.prompt-on-quit false')
975 self.child.sendline('quit')
Johnny Chen985e7402011-08-01 21:13:26 +0000976 self.child.expect(pexpect.EOF)
Daniel Maleac9a0ec32013-02-22 00:41:26 +0000977 except ValueError, ExceptionPexpect:
978 # child is already terminated
Johnny Chen985e7402011-08-01 21:13:26 +0000979 pass
Daniel Maleac9a0ec32013-02-22 00:41:26 +0000980
Johnny Chenac257132012-02-27 23:07:40 +0000981 # Give it one final blow to make sure the child is terminated.
982 self.child.close()
Johnny Chen985e7402011-08-01 21:13:26 +0000983
Johnny Chenfb4264c2011-08-01 19:50:58 +0000984 # Check and run any hook functions.
985 for hook in reversed(self.hooks):
986 with recording(self, traceAlways) as sbuf:
987 print >> sbuf, "Executing tearDown hook:", getsource_if_available(hook)
988 hook()
989
990 del self.hooks
991
992 # Perform registered teardown cleanup.
993 if doCleanup and self.doTearDownCleanup:
Johnny Chen0fddfb22011-11-17 19:57:27 +0000994 self.cleanup(dictionary=self.dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +0000995
996 # In rare cases where there are multiple teardown cleanups added.
997 if doCleanup and self.doTearDownCleanups:
Johnny Chenfb4264c2011-08-01 19:50:58 +0000998 if self.dicts:
999 for dict in reversed(self.dicts):
Johnny Chen0fddfb22011-11-17 19:57:27 +00001000 self.cleanup(dictionary=dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001001
1002 # Decide whether to dump the session info.
1003 self.dumpSessionInfo()
1004
1005 # =========================================================
1006 # Various callbacks to allow introspection of test progress
1007 # =========================================================
1008
1009 def markError(self):
1010 """Callback invoked when an error (unexpected exception) errored."""
1011 self.__errored__ = True
1012 with recording(self, False) as sbuf:
1013 # False because there's no need to write "ERROR" to the stderr twice.
1014 # Once by the Python unittest framework, and a second time by us.
1015 print >> sbuf, "ERROR"
1016
1017 def markFailure(self):
1018 """Callback invoked when a failure (test assertion failure) occurred."""
1019 self.__failed__ = True
1020 with recording(self, False) as sbuf:
1021 # False because there's no need to write "FAIL" to the stderr twice.
1022 # Once by the Python unittest framework, and a second time by us.
1023 print >> sbuf, "FAIL"
1024
Enrico Granatae6cedc12013-02-23 01:05:23 +00001025 def markExpectedFailure(self,err,bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001026 """Callback invoked when an expected failure/error occurred."""
1027 self.__expected__ = True
1028 with recording(self, False) as sbuf:
1029 # False because there's no need to write "expected failure" to the
1030 # stderr twice.
1031 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001032 if bugnumber == None:
1033 print >> sbuf, "expected failure"
1034 else:
1035 print >> sbuf, "expected failure (problem id:" + str(bugnumber) + ")"
Johnny Chenfb4264c2011-08-01 19:50:58 +00001036
Johnny Chenc5cc6252011-08-15 23:09:08 +00001037 def markSkippedTest(self):
1038 """Callback invoked when a test is skipped."""
1039 self.__skipped__ = True
1040 with recording(self, False) as sbuf:
1041 # False because there's no need to write "skipped test" to the
1042 # stderr twice.
1043 # Once by the Python unittest framework, and a second time by us.
1044 print >> sbuf, "skipped test"
1045
Enrico Granatae6cedc12013-02-23 01:05:23 +00001046 def markUnexpectedSuccess(self, bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001047 """Callback invoked when an unexpected success occurred."""
1048 self.__unexpected__ = True
1049 with recording(self, False) as sbuf:
1050 # False because there's no need to write "unexpected success" to the
1051 # stderr twice.
1052 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001053 if bugnumber == None:
1054 print >> sbuf, "unexpected success"
1055 else:
1056 print >> sbuf, "unexpected success (problem id:" + str(bugnumber) + ")"
Johnny Chenfb4264c2011-08-01 19:50:58 +00001057
1058 def dumpSessionInfo(self):
1059 """
1060 Dump the debugger interactions leading to a test error/failure. This
1061 allows for more convenient postmortem analysis.
1062
1063 See also LLDBTestResult (dotest.py) which is a singlton class derived
1064 from TextTestResult and overwrites addError, addFailure, and
1065 addExpectedFailure methods to allow us to to mark the test instance as
1066 such.
1067 """
1068
1069 # We are here because self.tearDown() detected that this test instance
1070 # either errored or failed. The lldb.test_result singleton contains
1071 # two lists (erros and failures) which get populated by the unittest
1072 # framework. Look over there for stack trace information.
1073 #
1074 # The lists contain 2-tuples of TestCase instances and strings holding
1075 # formatted tracebacks.
1076 #
1077 # See http://docs.python.org/library/unittest.html#unittest.TestResult.
1078 if self.__errored__:
1079 pairs = lldb.test_result.errors
1080 prefix = 'Error'
1081 elif self.__failed__:
1082 pairs = lldb.test_result.failures
1083 prefix = 'Failure'
1084 elif self.__expected__:
1085 pairs = lldb.test_result.expectedFailures
1086 prefix = 'ExpectedFailure'
Johnny Chenc5cc6252011-08-15 23:09:08 +00001087 elif self.__skipped__:
1088 prefix = 'SkippedTest'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001089 elif self.__unexpected__:
1090 prefix = "UnexpectedSuccess"
1091 else:
1092 # Simply return, there's no session info to dump!
1093 return
1094
Johnny Chenc5cc6252011-08-15 23:09:08 +00001095 if not self.__unexpected__ and not self.__skipped__:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001096 for test, traceback in pairs:
1097 if test is self:
1098 print >> self.session, traceback
1099
Johnny Chen8082a002011-08-11 00:16:28 +00001100 testMethod = getattr(self, self._testMethodName)
1101 if getattr(testMethod, "__benchmarks_test__", False):
1102 benchmarks = True
1103 else:
1104 benchmarks = False
1105
Johnny Chen5daa6de2011-12-03 00:16:59 +00001106 # This records the compiler version used for the test.
1107 system([self.getCompiler(), "-v"], sender=self)
1108
Johnny Chenfb4264c2011-08-01 19:50:58 +00001109 dname = os.path.join(os.environ["LLDB_TEST"],
1110 os.environ["LLDB_SESSION_DIRNAME"])
1111 if not os.path.isdir(dname):
1112 os.mkdir(dname)
Sean Callanan794baf62012-10-16 18:22:04 +00001113 fname = os.path.join(dname, "%s-%s-%s-%s.log" % (prefix, self.getArchitecture(), "_".join(self.getCompiler().split('/')), self.id()))
Johnny Chenfb4264c2011-08-01 19:50:58 +00001114 with open(fname, "w") as f:
1115 import datetime
1116 print >> f, "Session info generated @", datetime.datetime.now().ctime()
1117 print >> f, self.session.getvalue()
1118 print >> f, "To rerun this test, issue the following command from the 'test' directory:\n"
Johnny Chen8082a002011-08-11 00:16:28 +00001119 print >> f, "./dotest.py %s -v %s -f %s.%s" % (self.getRunOptions(),
1120 ('+b' if benchmarks else '-t'),
Johnny Chenfb4264c2011-08-01 19:50:58 +00001121 self.__class__.__name__,
1122 self._testMethodName)
1123
1124 # ====================================================
1125 # Config. methods supported through a plugin interface
1126 # (enables reading of the current test configuration)
1127 # ====================================================
1128
1129 def getArchitecture(self):
1130 """Returns the architecture in effect the test suite is running with."""
1131 module = builder_module()
1132 return module.getArchitecture()
1133
1134 def getCompiler(self):
1135 """Returns the compiler in effect the test suite is running with."""
1136 module = builder_module()
1137 return module.getCompiler()
1138
Daniel Malea0aea0162013-02-27 17:29:46 +00001139 def getCompilerVersion(self):
1140 """ Returns a string that represents the compiler version.
1141 Supports: llvm, clang.
1142 """
1143 from lldbutil import which
1144 version = 'unknown'
1145
1146 compiler = self.getCompiler()
1147 version_output = system([which(compiler), "-v"])[1]
1148 for line in version_output.split(os.linesep):
Greg Clayton2a844b72013-03-06 02:34:51 +00001149 m = re.search('version ([0-9\.]+)', line)
Daniel Malea0aea0162013-02-27 17:29:46 +00001150 if m:
1151 version = m.group(1)
1152 return version
1153
Daniel Maleaadaaec92013-08-06 20:51:41 +00001154 def isIntelCompiler(self):
1155 """ Returns true if using an Intel (ICC) compiler, false otherwise. """
1156 return any([x in self.getCompiler() for x in ["icc", "icpc", "icl"]])
1157
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001158 def expectedCompilerVersion(self, compiler_version):
1159 """Returns True iff compiler_version[1] matches the current compiler version.
1160 Use compiler_version[0] to specify the operator used to determine if a match has occurred.
1161 Any operator other than the following defaults to an equality test:
1162 '>', '>=', "=>", '<', '<=', '=<', '!=', "!" or 'not'
1163 """
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001164 if (compiler_version == None):
1165 return True
1166 operator = str(compiler_version[0])
1167 version = compiler_version[1]
1168
1169 if (version == None):
1170 return True
1171 if (operator == '>'):
1172 return self.getCompilerVersion() > version
1173 if (operator == '>=' or operator == '=>'):
1174 return self.getCompilerVersion() >= version
1175 if (operator == '<'):
1176 return self.getCompilerVersion() < version
1177 if (operator == '<=' or operator == '=<'):
1178 return self.getCompilerVersion() <= version
1179 if (operator == '!=' or operator == '!' or operator == 'not'):
1180 return str(version) not in str(self.getCompilerVersion())
1181 return str(version) in str(self.getCompilerVersion())
1182
1183 def expectedCompiler(self, compilers):
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001184 """Returns True iff any element of compilers is a sub-string of the current compiler."""
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001185 if (compilers == None):
1186 return True
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001187
1188 for compiler in compilers:
1189 if compiler in self.getCompiler():
1190 return True
1191
1192 return False
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001193
Johnny Chenfb4264c2011-08-01 19:50:58 +00001194 def getRunOptions(self):
1195 """Command line option for -A and -C to run this test again, called from
1196 self.dumpSessionInfo()."""
1197 arch = self.getArchitecture()
1198 comp = self.getCompiler()
Johnny Chenb7bdd102011-08-24 19:48:51 +00001199 if arch:
1200 option_str = "-A " + arch
Johnny Chenfb4264c2011-08-01 19:50:58 +00001201 else:
Johnny Chenb7bdd102011-08-24 19:48:51 +00001202 option_str = ""
1203 if comp:
Johnny Chen531c0852012-03-16 20:44:00 +00001204 option_str += " -C " + comp
Johnny Chenb7bdd102011-08-24 19:48:51 +00001205 return option_str
Johnny Chenfb4264c2011-08-01 19:50:58 +00001206
1207 # ==================================================
1208 # Build methods supported through a plugin interface
1209 # ==================================================
1210
Ed Mastec97323e2014-04-01 18:47:58 +00001211 def getstdlibFlag(self):
1212 """ Returns the proper -stdlib flag, or empty if not required."""
1213 if sys.platform.startswith("darwin") or sys.platform.startswith("freebsd"):
1214 stdlibflag = "-stdlib=libc++"
1215 else:
1216 stdlibflag = ""
1217 return stdlibflag
1218
Matt Kopec7663b3a2013-09-25 17:44:00 +00001219 def getstdFlag(self):
1220 """ Returns the proper stdflag. """
Daniel Malea55faa402013-05-02 21:44:31 +00001221 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
Daniel Malea0b7c6112013-05-06 19:31:31 +00001222 stdflag = "-std=c++0x"
Daniel Malea55faa402013-05-02 21:44:31 +00001223 else:
1224 stdflag = "-std=c++11"
Matt Kopec7663b3a2013-09-25 17:44:00 +00001225 return stdflag
1226
1227 def buildDriver(self, sources, exe_name):
1228 """ Platform-specific way to build a program that links with LLDB (via the liblldb.so
1229 or LLDB.framework).
1230 """
1231
1232 stdflag = self.getstdFlag()
Ed Mastec97323e2014-04-01 18:47:58 +00001233 stdlibflag = self.getstdlibFlag()
Daniel Malea55faa402013-05-02 21:44:31 +00001234
1235 if sys.platform.startswith("darwin"):
1236 dsym = os.path.join(self.lib_dir, 'LLDB.framework', 'LLDB')
1237 d = {'CXX_SOURCES' : sources,
1238 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00001239 'CFLAGS_EXTRAS' : "%s %s" % (stdflag, stdlibflag),
Daniel Malea55faa402013-05-02 21:44:31 +00001240 'FRAMEWORK_INCLUDES' : "-F%s" % self.lib_dir,
Stefanus Du Toit04004442013-07-30 19:19:49 +00001241 'LD_EXTRAS' : "%s -Wl,-rpath,%s" % (dsym, self.lib_dir),
Daniel Malea55faa402013-05-02 21:44:31 +00001242 }
Ed Maste372c24d2013-07-25 21:02:34 +00001243 elif sys.platform.startswith('freebsd') or sys.platform.startswith("linux") or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
Daniel Malea55faa402013-05-02 21:44:31 +00001244 d = {'CXX_SOURCES' : sources,
1245 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00001246 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Daniel Malea55faa402013-05-02 21:44:31 +00001247 'LD_EXTRAS' : "-L%s -llldb" % self.lib_dir}
1248 if self.TraceOn():
1249 print "Building LLDB Driver (%s) from sources %s" % (exe_name, sources)
1250
1251 self.buildDefault(dictionary=d)
1252
Matt Kopec7663b3a2013-09-25 17:44:00 +00001253 def buildLibrary(self, sources, lib_name):
1254 """Platform specific way to build a default library. """
1255
1256 stdflag = self.getstdFlag()
1257
1258 if sys.platform.startswith("darwin"):
1259 dsym = os.path.join(self.lib_dir, 'LLDB.framework', 'LLDB')
1260 d = {'DYLIB_CXX_SOURCES' : sources,
1261 'DYLIB_NAME' : lib_name,
1262 'CFLAGS_EXTRAS' : "%s -stdlib=libc++" % stdflag,
1263 'FRAMEWORK_INCLUDES' : "-F%s" % self.lib_dir,
1264 'LD_EXTRAS' : "%s -Wl,-rpath,%s -dynamiclib" % (dsym, self.lib_dir),
1265 }
1266 elif sys.platform.startswith('freebsd') or sys.platform.startswith("linux") or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
1267 d = {'DYLIB_CXX_SOURCES' : sources,
1268 'DYLIB_NAME' : lib_name,
1269 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
1270 'LD_EXTRAS' : "-shared -L%s -llldb" % self.lib_dir}
1271 if self.TraceOn():
1272 print "Building LLDB Library (%s) from sources %s" % (lib_name, sources)
1273
1274 self.buildDefault(dictionary=d)
1275
Daniel Malea55faa402013-05-02 21:44:31 +00001276 def buildProgram(self, sources, exe_name):
1277 """ Platform specific way to build an executable from C/C++ sources. """
1278 d = {'CXX_SOURCES' : sources,
1279 'EXE' : exe_name}
1280 self.buildDefault(dictionary=d)
1281
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001282 def buildDefault(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001283 """Platform specific way to build the default binaries."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001284 if lldb.skip_build_and_cleanup:
1285 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00001286 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001287 if not module.buildDefault(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001288 raise Exception("Don't know how to build default binary")
1289
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001290 def buildDsym(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001291 """Platform specific way to build binaries with dsym info."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001292 if lldb.skip_build_and_cleanup:
1293 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00001294 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001295 if not module.buildDsym(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001296 raise Exception("Don't know how to build binary with dsym")
1297
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001298 def buildDwarf(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001299 """Platform specific way to build binaries with dwarf maps."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001300 if lldb.skip_build_and_cleanup:
1301 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00001302 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001303 if not module.buildDwarf(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001304 raise Exception("Don't know how to build binary with dwarf")
Johnny Chena74bb0a2011-08-01 18:46:13 +00001305
Daniel Malea9115f072013-08-06 15:02:32 +00001306 def getBuildFlags(self, use_cpp11=True, use_libcxx=False, use_libstdcxx=False, use_pthreads=True):
Andrew Kaylor93132f52013-05-28 23:04:25 +00001307 """ Returns a dictionary (which can be provided to build* functions above) which
1308 contains OS-specific build flags.
1309 """
1310 cflags = ""
Daniel Malea9115f072013-08-06 15:02:32 +00001311
1312 # On Mac OS X, unless specifically requested to use libstdc++, use libc++
1313 if not use_libstdcxx and sys.platform.startswith('darwin'):
1314 use_libcxx = True
1315
1316 if use_libcxx and self.libcxxPath:
1317 cflags += "-stdlib=libc++ "
1318 if self.libcxxPath:
1319 libcxxInclude = os.path.join(self.libcxxPath, "include")
1320 libcxxLib = os.path.join(self.libcxxPath, "lib")
1321 if os.path.isdir(libcxxInclude) and os.path.isdir(libcxxLib):
1322 cflags += "-nostdinc++ -I%s -L%s -Wl,-rpath,%s " % (libcxxInclude, libcxxLib, libcxxLib)
1323
Andrew Kaylor93132f52013-05-28 23:04:25 +00001324 if use_cpp11:
1325 cflags += "-std="
1326 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
1327 cflags += "c++0x"
1328 else:
1329 cflags += "c++11"
Ed Mastedbd59502014-02-02 19:24:15 +00001330 if sys.platform.startswith("darwin") or sys.platform.startswith("freebsd"):
Andrew Kaylor93132f52013-05-28 23:04:25 +00001331 cflags += " -stdlib=libc++"
1332 elif "clang" in self.getCompiler():
1333 cflags += " -stdlib=libstdc++"
1334
1335 if use_pthreads:
1336 ldflags = "-lpthread"
1337
1338 return {'CFLAGS_EXTRAS' : cflags,
1339 'LD_EXTRAS' : ldflags,
1340 }
1341
Johnny Chen9f4f5d92011-08-12 20:19:22 +00001342 def cleanup(self, dictionary=None):
1343 """Platform specific way to do cleanup after build."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001344 if lldb.skip_build_and_cleanup:
1345 return
Johnny Chen9f4f5d92011-08-12 20:19:22 +00001346 module = builder_module()
1347 if not module.cleanup(self, dictionary):
Johnny Chen0fddfb22011-11-17 19:57:27 +00001348 raise Exception("Don't know how to do cleanup with dictionary: "+dictionary)
Johnny Chen9f4f5d92011-08-12 20:19:22 +00001349
Daniel Malea55faa402013-05-02 21:44:31 +00001350 def getLLDBLibraryEnvVal(self):
1351 """ Returns the path that the OS-specific library search environment variable
1352 (self.dylibPath) should be set to in order for a program to find the LLDB
1353 library. If an environment variable named self.dylibPath is already set,
1354 the new path is appended to it and returned.
1355 """
1356 existing_library_path = os.environ[self.dylibPath] if self.dylibPath in os.environ else None
1357 if existing_library_path:
1358 return "%s:%s" % (existing_library_path, self.lib_dir)
1359 elif sys.platform.startswith("darwin"):
1360 return os.path.join(self.lib_dir, 'LLDB.framework')
1361 else:
1362 return self.lib_dir
Johnny Chena74bb0a2011-08-01 18:46:13 +00001363
Ed Maste437f8f62013-09-09 14:04:04 +00001364 def getLibcPlusPlusLibs(self):
1365 if sys.platform.startswith('freebsd'):
1366 return ['libc++.so.1']
1367 else:
1368 return ['libc++.1.dylib','libc++abi.dylib']
1369
Johnny Chena74bb0a2011-08-01 18:46:13 +00001370class TestBase(Base):
1371 """
1372 This abstract base class is meant to be subclassed. It provides default
1373 implementations for setUpClass(), tearDownClass(), setUp(), and tearDown(),
1374 among other things.
1375
1376 Important things for test class writers:
1377
1378 - Overwrite the mydir class attribute, otherwise your test class won't
1379 run. It specifies the relative directory to the top level 'test' so
1380 the test harness can change to the correct working directory before
1381 running your test.
1382
1383 - The setUp method sets up things to facilitate subsequent interactions
1384 with the debugger as part of the test. These include:
1385 - populate the test method name
1386 - create/get a debugger set with synchronous mode (self.dbg)
1387 - get the command interpreter from with the debugger (self.ci)
1388 - create a result object for use with the command interpreter
1389 (self.res)
1390 - plus other stuffs
1391
1392 - The tearDown method tries to perform some necessary cleanup on behalf
1393 of the test to return the debugger to a good state for the next test.
1394 These include:
1395 - execute any tearDown hooks registered by the test method with
1396 TestBase.addTearDownHook(); examples can be found in
1397 settings/TestSettings.py
1398 - kill the inferior process associated with each target, if any,
1399 and, then delete the target from the debugger's target list
1400 - perform build cleanup before running the next test method in the
1401 same test class; examples of registering for this service can be
1402 found in types/TestIntegerTypes.py with the call:
1403 - self.setTearDownCleanup(dictionary=d)
1404
1405 - Similarly setUpClass and tearDownClass perform classwise setup and
1406 teardown fixtures. The tearDownClass method invokes a default build
1407 cleanup for the entire test class; also, subclasses can implement the
1408 classmethod classCleanup(cls) to perform special class cleanup action.
1409
1410 - The instance methods runCmd and expect are used heavily by existing
1411 test cases to send a command to the command interpreter and to perform
1412 string/pattern matching on the output of such command execution. The
1413 expect method also provides a mode to peform string/pattern matching
1414 without running a command.
1415
1416 - The build methods buildDefault, buildDsym, and buildDwarf are used to
1417 build the binaries used during a particular test scenario. A plugin
1418 should be provided for the sys.platform running the test suite. The
1419 Mac OS X implementation is located in plugins/darwin.py.
1420 """
1421
1422 # Maximum allowed attempts when launching the inferior process.
1423 # Can be overridden by the LLDB_MAX_LAUNCH_COUNT environment variable.
1424 maxLaunchCount = 3;
1425
1426 # Time to wait before the next launching attempt in second(s).
1427 # Can be overridden by the LLDB_TIME_WAIT_NEXT_LAUNCH environment variable.
1428 timeWaitNextLaunch = 1.0;
1429
1430 def doDelay(self):
1431 """See option -w of dotest.py."""
1432 if ("LLDB_WAIT_BETWEEN_TEST_CASES" in os.environ and
1433 os.environ["LLDB_WAIT_BETWEEN_TEST_CASES"] == 'YES'):
1434 waitTime = 1.0
1435 if "LLDB_TIME_WAIT_BETWEEN_TEST_CASES" in os.environ:
1436 waitTime = float(os.environ["LLDB_TIME_WAIT_BETWEEN_TEST_CASES"])
1437 time.sleep(waitTime)
1438
Enrico Granata165f8af2012-09-21 19:10:53 +00001439 # Returns the list of categories to which this test case belongs
1440 # by default, look for a ".categories" file, and read its contents
1441 # if no such file exists, traverse the hierarchy - we guarantee
1442 # a .categories to exist at the top level directory so we do not end up
1443 # looping endlessly - subclasses are free to define their own categories
1444 # in whatever way makes sense to them
1445 def getCategories(self):
1446 import inspect
1447 import os.path
1448 folder = inspect.getfile(self.__class__)
1449 folder = os.path.dirname(folder)
1450 while folder != '/':
1451 categories_file_name = os.path.join(folder,".categories")
1452 if os.path.exists(categories_file_name):
1453 categories_file = open(categories_file_name,'r')
1454 categories = categories_file.readline()
1455 categories_file.close()
1456 categories = str.replace(categories,'\n','')
1457 categories = str.replace(categories,'\r','')
1458 return categories.split(',')
1459 else:
1460 folder = os.path.dirname(folder)
1461 continue
1462
Johnny Chena74bb0a2011-08-01 18:46:13 +00001463 def setUp(self):
1464 #import traceback
1465 #traceback.print_stack()
1466
1467 # Works with the test driver to conditionally skip tests via decorators.
1468 Base.setUp(self)
1469
Johnny Chena74bb0a2011-08-01 18:46:13 +00001470 try:
1471 if lldb.blacklist:
1472 className = self.__class__.__name__
1473 classAndMethodName = "%s.%s" % (className, self._testMethodName)
1474 if className in lldb.blacklist:
1475 self.skipTest(lldb.blacklist.get(className))
1476 elif classAndMethodName in lldb.blacklist:
1477 self.skipTest(lldb.blacklist.get(classAndMethodName))
1478 except AttributeError:
1479 pass
1480
Johnny Chened492022011-06-21 00:53:00 +00001481 # Insert some delay between successive test cases if specified.
1482 self.doDelay()
Johnny Chen0ed37c92010-10-07 02:04:14 +00001483
Johnny Chenf2b70232010-08-25 18:49:48 +00001484 if "LLDB_MAX_LAUNCH_COUNT" in os.environ:
1485 self.maxLaunchCount = int(os.environ["LLDB_MAX_LAUNCH_COUNT"])
1486
Johnny Chen430eb762010-10-19 16:00:42 +00001487 if "LLDB_TIME_WAIT_NEXT_LAUNCH" in os.environ:
Johnny Chen4921b112010-11-29 20:20:34 +00001488 self.timeWaitNextLaunch = float(os.environ["LLDB_TIME_WAIT_NEXT_LAUNCH"])
Johnny Chenf2b70232010-08-25 18:49:48 +00001489
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001490 # Create the debugger instance if necessary.
1491 try:
1492 self.dbg = lldb.DBG
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001493 except AttributeError:
1494 self.dbg = lldb.SBDebugger.Create()
Johnny Chenf02ec122010-07-03 20:41:42 +00001495
Johnny Chen3cd1e552011-05-25 19:06:18 +00001496 if not self.dbg:
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001497 raise Exception('Invalid debugger instance')
1498
Daniel Maleae0f8f572013-08-26 23:57:52 +00001499 #
1500 # Warning: MAJOR HACK AHEAD!
1501 # If we are running testsuite remotely (by checking lldb.lldbtest_remote_sandbox),
1502 # redefine the self.dbg.CreateTarget(filename) method to execute a "file filename"
1503 # command, instead. See also runCmd() where it decorates the "file filename" call
1504 # with additional functionality when running testsuite remotely.
1505 #
1506 if lldb.lldbtest_remote_sandbox:
1507 def DecoratedCreateTarget(arg):
1508 self.runCmd("file %s" % arg)
1509 target = self.dbg.GetSelectedTarget()
1510 #
Greg Claytonc6947512013-12-13 19:18:59 +00001511 # SBtarget.LaunchSimple () currently not working for remote platform?
Daniel Maleae0f8f572013-08-26 23:57:52 +00001512 # johnny @ 04/23/2012
1513 #
1514 def DecoratedLaunchSimple(argv, envp, wd):
1515 self.runCmd("run")
1516 return target.GetProcess()
1517 target.LaunchSimple = DecoratedLaunchSimple
1518
1519 return target
1520 self.dbg.CreateTarget = DecoratedCreateTarget
1521 if self.TraceOn():
1522 print "self.dbg.Create is redefined to:\n%s" % getsource_if_available(DecoratedCreateTarget)
1523
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001524 # We want our debugger to be synchronous.
1525 self.dbg.SetAsync(False)
1526
1527 # Retrieve the associated command interpreter instance.
1528 self.ci = self.dbg.GetCommandInterpreter()
1529 if not self.ci:
1530 raise Exception('Could not get the command interpreter')
1531
1532 # And the result object.
1533 self.res = lldb.SBCommandReturnObject()
1534
Johnny Chen44d24972012-04-16 18:55:15 +00001535 # Run global pre-flight code, if defined via the config file.
1536 if lldb.pre_flight:
1537 lldb.pre_flight(self)
1538
Greg Claytonfb909312013-11-23 01:58:15 +00001539 if lldb.remote_platform:
1540 #remote_test_dir = os.path.join(lldb.remote_platform_working_dir, self.mydir)
Greg Clayton5fb8f792013-12-02 19:35:49 +00001541 remote_test_dir = os.path.join(lldb.remote_platform_working_dir,
1542 self.getArchitecture(),
1543 str(self.test_number),
1544 self.mydir)
Greg Claytonfb909312013-11-23 01:58:15 +00001545 error = lldb.remote_platform.MakeDirectory(remote_test_dir, 0700)
1546 if error.Success():
Greg Claytonfb909312013-11-23 01:58:15 +00001547 lldb.remote_platform.SetWorkingDirectory(remote_test_dir)
1548 else:
1549 print "error: making remote directory '%s': %s" % (remote_test_dir, error)
1550
Enrico Granata44818162012-10-24 01:23:57 +00001551 # utility methods that tests can use to access the current objects
1552 def target(self):
1553 if not self.dbg:
1554 raise Exception('Invalid debugger instance')
1555 return self.dbg.GetSelectedTarget()
1556
1557 def process(self):
1558 if not self.dbg:
1559 raise Exception('Invalid debugger instance')
1560 return self.dbg.GetSelectedTarget().GetProcess()
1561
1562 def thread(self):
1563 if not self.dbg:
1564 raise Exception('Invalid debugger instance')
1565 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread()
1566
1567 def frame(self):
1568 if not self.dbg:
1569 raise Exception('Invalid debugger instance')
1570 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame()
1571
Greg Claytonc6947512013-12-13 19:18:59 +00001572 def get_process_working_directory(self):
1573 '''Get the working directory that should be used when launching processes for local or remote processes.'''
1574 if lldb.remote_platform:
1575 # Remote tests set the platform working directory up in TestBase.setUp()
1576 return lldb.remote_platform.GetWorkingDirectory()
1577 else:
1578 # local tests change directory into each test subdirectory
1579 return os.getcwd()
1580
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001581 def tearDown(self):
Johnny Chen7d1d7532010-09-02 21:23:12 +00001582 #import traceback
1583 #traceback.print_stack()
1584
Johnny Chenfb4264c2011-08-01 19:50:58 +00001585 Base.tearDown(self)
Johnny Chen707d8222010-10-19 23:40:13 +00001586
Johnny Chen3794ad92011-06-15 21:24:24 +00001587 # Delete the target(s) from the debugger as a general cleanup step.
1588 # This includes terminating the process for each target, if any.
1589 # We'd like to reuse the debugger for our next test without incurring
1590 # the initialization overhead.
1591 targets = []
1592 for target in self.dbg:
1593 if target:
1594 targets.append(target)
1595 process = target.GetProcess()
1596 if process:
1597 rc = self.invoke(process, "Kill")
1598 self.assertTrue(rc.Success(), PROCESS_KILLED)
1599 for target in targets:
1600 self.dbg.DeleteTarget(target)
Johnny Chen6ca006c2010-08-16 21:28:10 +00001601
Johnny Chen44d24972012-04-16 18:55:15 +00001602 # Run global post-flight code, if defined via the config file.
1603 if lldb.post_flight:
1604 lldb.post_flight(self)
1605
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001606 del self.dbg
Johnny Chen150c3cc2010-10-15 01:18:29 +00001607
Johnny Chen86268e42011-09-30 21:48:35 +00001608 def switch_to_thread_with_stop_reason(self, stop_reason):
1609 """
1610 Run the 'thread list' command, and select the thread with stop reason as
1611 'stop_reason'. If no such thread exists, no select action is done.
1612 """
1613 from lldbutil import stop_reason_to_str
1614 self.runCmd('thread list')
1615 output = self.res.GetOutput()
1616 thread_line_pattern = re.compile("^[ *] thread #([0-9]+):.*stop reason = %s" %
1617 stop_reason_to_str(stop_reason))
1618 for line in output.splitlines():
1619 matched = thread_line_pattern.match(line)
1620 if matched:
1621 self.runCmd('thread select %s' % matched.group(1))
1622
Enrico Granata7594f142013-06-17 22:51:50 +00001623 def runCmd(self, cmd, msg=None, check=True, trace=False, inHistory=False):
Johnny Chen27f212d2010-08-19 23:26:59 +00001624 """
1625 Ask the command interpreter to handle the command and then check its
1626 return status.
1627 """
1628 # Fail fast if 'cmd' is not meaningful.
1629 if not cmd or len(cmd) == 0:
1630 raise Exception("Bad 'cmd' parameter encountered")
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001631
Johnny Chen8d55a342010-08-31 17:42:54 +00001632 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00001633
Daniel Maleae0f8f572013-08-26 23:57:52 +00001634 # This is an opportunity to insert the 'platform target-install' command if we are told so
1635 # via the settig of lldb.lldbtest_remote_sandbox.
1636 if cmd.startswith("target create "):
1637 cmd = cmd.replace("target create ", "file ")
1638 if cmd.startswith("file ") and lldb.lldbtest_remote_sandbox:
1639 with recording(self, trace) as sbuf:
1640 the_rest = cmd.split("file ")[1]
1641 # Split the rest of the command line.
1642 atoms = the_rest.split()
1643 #
1644 # NOTE: This assumes that the options, if any, follow the file command,
1645 # instead of follow the specified target.
1646 #
1647 target = atoms[-1]
1648 # Now let's get the absolute pathname of our target.
1649 abs_target = os.path.abspath(target)
1650 print >> sbuf, "Found a file command, target (with absolute pathname)=%s" % abs_target
1651 fpath, fname = os.path.split(abs_target)
1652 parent_dir = os.path.split(fpath)[0]
1653 platform_target_install_command = 'platform target-install %s %s' % (fpath, lldb.lldbtest_remote_sandbox)
1654 print >> sbuf, "Insert this command to be run first: %s" % platform_target_install_command
1655 self.ci.HandleCommand(platform_target_install_command, self.res)
1656 # And this is the file command we want to execute, instead.
1657 #
1658 # Warning: SIDE EFFECT AHEAD!!!
1659 # Populate the remote executable pathname into the lldb namespace,
1660 # so that test cases can grab this thing out of the namespace.
1661 #
1662 lldb.lldbtest_remote_sandboxed_executable = abs_target.replace(parent_dir, lldb.lldbtest_remote_sandbox)
1663 cmd = "file -P %s %s %s" % (lldb.lldbtest_remote_sandboxed_executable, the_rest.replace(target, ''), abs_target)
1664 print >> sbuf, "And this is the replaced file command: %s" % cmd
1665
Johnny Chen63dfb272010-09-01 00:15:19 +00001666 running = (cmd.startswith("run") or cmd.startswith("process launch"))
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001667
Johnny Chen63dfb272010-09-01 00:15:19 +00001668 for i in range(self.maxLaunchCount if running else 1):
Enrico Granata7594f142013-06-17 22:51:50 +00001669 self.ci.HandleCommand(cmd, self.res, inHistory)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001670
Johnny Chen150c3cc2010-10-15 01:18:29 +00001671 with recording(self, trace) as sbuf:
1672 print >> sbuf, "runCmd:", cmd
Johnny Chenab254f52010-10-15 16:13:00 +00001673 if not check:
Johnny Chen27b107b2010-10-15 18:52:22 +00001674 print >> sbuf, "check of return status not required"
Johnny Chenf2b70232010-08-25 18:49:48 +00001675 if self.res.Succeeded():
Johnny Chen150c3cc2010-10-15 01:18:29 +00001676 print >> sbuf, "output:", self.res.GetOutput()
Johnny Chenf2b70232010-08-25 18:49:48 +00001677 else:
Johnny Chen150c3cc2010-10-15 01:18:29 +00001678 print >> sbuf, "runCmd failed!"
1679 print >> sbuf, self.res.GetError()
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001680
Johnny Chenff3d01d2010-08-20 21:03:09 +00001681 if self.res.Succeeded():
Johnny Chenf2b70232010-08-25 18:49:48 +00001682 break
Johnny Chen150c3cc2010-10-15 01:18:29 +00001683 elif running:
Johnny Chencf7f74e2011-01-19 02:02:08 +00001684 # For process launch, wait some time before possible next try.
1685 time.sleep(self.timeWaitNextLaunch)
Johnny Chen552d6712012-08-01 19:56:04 +00001686 with recording(self, trace) as sbuf:
Johnny Chen150c3cc2010-10-15 01:18:29 +00001687 print >> sbuf, "Command '" + cmd + "' failed!"
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001688
Johnny Chen27f212d2010-08-19 23:26:59 +00001689 if check:
1690 self.assertTrue(self.res.Succeeded(),
Johnny Chenc0c67f22010-11-09 18:42:22 +00001691 msg if msg else CMD_MSG(cmd))
Johnny Chen27f212d2010-08-19 23:26:59 +00001692
Jim Ingham63dfc722012-09-22 00:05:11 +00001693 def match (self, str, patterns, msg=None, trace=False, error=False, matching=True, exe=True):
1694 """run command in str, and match the result against regexp in patterns returning the match object for the first matching pattern
1695
1696 Otherwise, all the arguments have the same meanings as for the expect function"""
1697
1698 trace = (True if traceAlways else trace)
1699
1700 if exe:
1701 # First run the command. If we are expecting error, set check=False.
1702 # Pass the assert message along since it provides more semantic info.
1703 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error)
1704
1705 # Then compare the output against expected strings.
1706 output = self.res.GetError() if error else self.res.GetOutput()
1707
1708 # If error is True, the API client expects the command to fail!
1709 if error:
1710 self.assertFalse(self.res.Succeeded(),
1711 "Command '" + str + "' is expected to fail!")
1712 else:
1713 # No execution required, just compare str against the golden input.
1714 output = str
1715 with recording(self, trace) as sbuf:
1716 print >> sbuf, "looking at:", output
1717
1718 # The heading says either "Expecting" or "Not expecting".
1719 heading = "Expecting" if matching else "Not expecting"
1720
1721 for pattern in patterns:
1722 # Match Objects always have a boolean value of True.
1723 match_object = re.search(pattern, output)
1724 matched = bool(match_object)
1725 with recording(self, trace) as sbuf:
1726 print >> sbuf, "%s pattern: %s" % (heading, pattern)
1727 print >> sbuf, "Matched" if matched else "Not matched"
1728 if matched:
1729 break
1730
1731 self.assertTrue(matched if matching else not matched,
1732 msg if msg else EXP_MSG(str, exe))
1733
1734 return match_object
1735
Enrico Granata7594f142013-06-17 22:51:50 +00001736 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 Chen27f212d2010-08-19 23:26:59 +00001737 """
1738 Similar to runCmd; with additional expect style output matching ability.
1739
1740 Ask the command interpreter to handle the command and then check its
1741 return status. The 'msg' parameter specifies an informational assert
1742 message. We expect the output from running the command to start with
Johnny Chenea88e942010-09-21 21:08:53 +00001743 'startstr', matches the substrings contained in 'substrs', and regexp
1744 matches the patterns contained in 'patterns'.
Johnny Chenb3307862010-09-17 22:28:51 +00001745
1746 If the keyword argument error is set to True, it signifies that the API
1747 client is expecting the command to fail. In this case, the error stream
Johnny Chenaa902922010-09-17 22:45:27 +00001748 from running the command is retrieved and compared against the golden
Johnny Chenb3307862010-09-17 22:28:51 +00001749 input, instead.
Johnny Chenea88e942010-09-21 21:08:53 +00001750
1751 If the keyword argument matching is set to False, it signifies that the API
1752 client is expecting the output of the command not to match the golden
1753 input.
Johnny Chen9c48b8d2010-09-21 23:33:30 +00001754
1755 Finally, the required argument 'str' represents the lldb command to be
1756 sent to the command interpreter. In case the keyword argument 'exe' is
1757 set to False, the 'str' is treated as a string to be matched/not-matched
1758 against the golden input.
Johnny Chen27f212d2010-08-19 23:26:59 +00001759 """
Johnny Chen8d55a342010-08-31 17:42:54 +00001760 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00001761
Johnny Chen9c48b8d2010-09-21 23:33:30 +00001762 if exe:
1763 # First run the command. If we are expecting error, set check=False.
Johnny Chen62d4f862010-10-28 21:10:32 +00001764 # Pass the assert message along since it provides more semantic info.
Enrico Granata7594f142013-06-17 22:51:50 +00001765 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error, inHistory=inHistory)
Johnny Chen27f212d2010-08-19 23:26:59 +00001766
Johnny Chen9c48b8d2010-09-21 23:33:30 +00001767 # Then compare the output against expected strings.
1768 output = self.res.GetError() if error else self.res.GetOutput()
Johnny Chenb3307862010-09-17 22:28:51 +00001769
Johnny Chen9c48b8d2010-09-21 23:33:30 +00001770 # If error is True, the API client expects the command to fail!
1771 if error:
1772 self.assertFalse(self.res.Succeeded(),
1773 "Command '" + str + "' is expected to fail!")
1774 else:
1775 # No execution required, just compare str against the golden input.
Enrico Granatabc08ab42012-10-23 00:09:02 +00001776 if isinstance(str,lldb.SBCommandReturnObject):
1777 output = str.GetOutput()
1778 else:
1779 output = str
Johnny Chen150c3cc2010-10-15 01:18:29 +00001780 with recording(self, trace) as sbuf:
1781 print >> sbuf, "looking at:", output
Johnny Chenb3307862010-09-17 22:28:51 +00001782
Johnny Chenea88e942010-09-21 21:08:53 +00001783 # The heading says either "Expecting" or "Not expecting".
Johnny Chen150c3cc2010-10-15 01:18:29 +00001784 heading = "Expecting" if matching else "Not expecting"
Johnny Chenea88e942010-09-21 21:08:53 +00001785
1786 # Start from the startstr, if specified.
1787 # If there's no startstr, set the initial state appropriately.
1788 matched = output.startswith(startstr) if startstr else (True if matching else False)
Johnny Chenb145bba2010-08-20 18:25:15 +00001789
Johnny Chen150c3cc2010-10-15 01:18:29 +00001790 if startstr:
1791 with recording(self, trace) as sbuf:
1792 print >> sbuf, "%s start string: %s" % (heading, startstr)
1793 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenb145bba2010-08-20 18:25:15 +00001794
Johnny Chen86268e42011-09-30 21:48:35 +00001795 # Look for endstr, if specified.
1796 keepgoing = matched if matching else not matched
1797 if endstr:
1798 matched = output.endswith(endstr)
1799 with recording(self, trace) as sbuf:
1800 print >> sbuf, "%s end string: %s" % (heading, endstr)
1801 print >> sbuf, "Matched" if matched else "Not matched"
1802
Johnny Chenea88e942010-09-21 21:08:53 +00001803 # Look for sub strings, if specified.
1804 keepgoing = matched if matching else not matched
1805 if substrs and keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00001806 for str in substrs:
Johnny Chenb052f6c2010-09-23 23:35:28 +00001807 matched = output.find(str) != -1
Johnny Chen150c3cc2010-10-15 01:18:29 +00001808 with recording(self, trace) as sbuf:
1809 print >> sbuf, "%s sub string: %s" % (heading, str)
1810 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenea88e942010-09-21 21:08:53 +00001811 keepgoing = matched if matching else not matched
1812 if not keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00001813 break
1814
Johnny Chenea88e942010-09-21 21:08:53 +00001815 # Search for regular expression patterns, if specified.
1816 keepgoing = matched if matching else not matched
1817 if patterns and keepgoing:
1818 for pattern in patterns:
1819 # Match Objects always have a boolean value of True.
1820 matched = bool(re.search(pattern, output))
Johnny Chen150c3cc2010-10-15 01:18:29 +00001821 with recording(self, trace) as sbuf:
1822 print >> sbuf, "%s pattern: %s" % (heading, pattern)
1823 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenea88e942010-09-21 21:08:53 +00001824 keepgoing = matched if matching else not matched
1825 if not keepgoing:
1826 break
Johnny Chenea88e942010-09-21 21:08:53 +00001827
1828 self.assertTrue(matched if matching else not matched,
Johnny Chenc0c67f22010-11-09 18:42:22 +00001829 msg if msg else EXP_MSG(str, exe))
Johnny Chen27f212d2010-08-19 23:26:59 +00001830
Johnny Chenf3c59232010-08-25 22:52:45 +00001831 def invoke(self, obj, name, trace=False):
Johnny Chen61703c92010-08-25 22:56:10 +00001832 """Use reflection to call a method dynamically with no argument."""
Johnny Chen8d55a342010-08-31 17:42:54 +00001833 trace = (True if traceAlways else trace)
Johnny Chenf3c59232010-08-25 22:52:45 +00001834
1835 method = getattr(obj, name)
1836 import inspect
1837 self.assertTrue(inspect.ismethod(method),
1838 name + "is a method name of object: " + str(obj))
1839 result = method()
Johnny Chen150c3cc2010-10-15 01:18:29 +00001840 with recording(self, trace) as sbuf:
1841 print >> sbuf, str(method) + ":", result
Johnny Chenf3c59232010-08-25 22:52:45 +00001842 return result
Johnny Chen827edff2010-08-27 00:15:48 +00001843
Johnny Chenf359cf22011-05-27 23:36:52 +00001844 # =================================================
1845 # Misc. helper methods for debugging test execution
1846 # =================================================
1847
Johnny Chen56b92a72011-07-11 19:15:11 +00001848 def DebugSBValue(self, val):
Johnny Chen8d55a342010-08-31 17:42:54 +00001849 """Debug print a SBValue object, if traceAlways is True."""
Johnny Chende90f1d2011-04-27 17:43:07 +00001850 from lldbutil import value_type_to_str
Johnny Chen87bb5892010-11-03 21:37:58 +00001851
Johnny Chen8d55a342010-08-31 17:42:54 +00001852 if not traceAlways:
Johnny Chen827edff2010-08-27 00:15:48 +00001853 return
1854
1855 err = sys.stderr
1856 err.write(val.GetName() + ":\n")
Johnny Chen86268e42011-09-30 21:48:35 +00001857 err.write('\t' + "TypeName -> " + val.GetTypeName() + '\n')
1858 err.write('\t' + "ByteSize -> " + str(val.GetByteSize()) + '\n')
1859 err.write('\t' + "NumChildren -> " + str(val.GetNumChildren()) + '\n')
1860 err.write('\t' + "Value -> " + str(val.GetValue()) + '\n')
1861 err.write('\t' + "ValueAsUnsigned -> " + str(val.GetValueAsUnsigned())+ '\n')
1862 err.write('\t' + "ValueType -> " + value_type_to_str(val.GetValueType()) + '\n')
1863 err.write('\t' + "Summary -> " + str(val.GetSummary()) + '\n')
1864 err.write('\t' + "IsPointerType -> " + str(val.TypeIsPointerType()) + '\n')
1865 err.write('\t' + "Location -> " + val.GetLocation() + '\n')
Johnny Chen827edff2010-08-27 00:15:48 +00001866
Johnny Chen36c5eb12011-08-05 20:17:27 +00001867 def DebugSBType(self, type):
1868 """Debug print a SBType object, if traceAlways is True."""
1869 if not traceAlways:
1870 return
1871
1872 err = sys.stderr
1873 err.write(type.GetName() + ":\n")
1874 err.write('\t' + "ByteSize -> " + str(type.GetByteSize()) + '\n')
1875 err.write('\t' + "IsPointerType -> " + str(type.IsPointerType()) + '\n')
1876 err.write('\t' + "IsReferenceType -> " + str(type.IsReferenceType()) + '\n')
1877
Johnny Chenb877f1e2011-03-12 01:18:19 +00001878 def DebugPExpect(self, child):
1879 """Debug the spwaned pexpect object."""
1880 if not traceAlways:
1881 return
1882
1883 print child
Filipe Cabecinhas0eec15a2012-06-20 10:13:40 +00001884
1885 @classmethod
1886 def RemoveTempFile(cls, file):
1887 if os.path.exists(file):
1888 os.remove(file)