blob: 39e48d44cc42ba73b3ce79f4622499db8abd163e [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).
Zachary Turner9ef307b2014-07-22 16:19:29 +0000236def system(commands, **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
Zachary Turner9ef307b2014-07-22 16:19:29 +0000260 separator = None
261 separator = " && " if os.name == "nt" else "; "
262 # [['make', 'clean', 'foo'], ['make', 'foo']] -> ['make clean foo', 'make foo']
263 commandList = [' '.join(x) for x in commands]
264 # ['make clean foo', 'make foo'] -> 'make clean foo; make foo'
265 shellCommand = separator.join(commandList)
266
Johnny Chen690fcef2010-10-15 23:55:05 +0000267 if 'stdout' in kwargs:
268 raise ValueError('stdout argument not allowed, it will be overridden.')
Zachary Turner9ef307b2014-07-22 16:19:29 +0000269 if 'shell' in kwargs and kwargs['shell']==False:
270 raise ValueError('shell=False not allowed')
271 process = Popen(shellCommand, stdout=PIPE, stderr=PIPE, shell=True, **kwargs)
Johnny Chen0bd8c312011-11-16 22:41:53 +0000272 pid = process.pid
Johnny Chen690fcef2010-10-15 23:55:05 +0000273 output, error = process.communicate()
274 retcode = process.poll()
275
Ed Maste6e496332014-08-05 20:33:17 +0000276 # Enable trace on failure return while tracking down FreeBSD buildbot issues
277 trace = traceAlways
278 if not trace and retcode and sys.platform.startswith("freebsd"):
279 trace = True
280
281 with recording(test, trace) as sbuf:
Johnny Chen690fcef2010-10-15 23:55:05 +0000282 print >> sbuf
Zachary Turner9ef307b2014-07-22 16:19:29 +0000283 print >> sbuf, "os command:", shellCommand
Johnny Chen0bd8c312011-11-16 22:41:53 +0000284 print >> sbuf, "with pid:", pid
Johnny Chen690fcef2010-10-15 23:55:05 +0000285 print >> sbuf, "stdout:", output
286 print >> sbuf, "stderr:", error
287 print >> sbuf, "retcode:", retcode
288 print >> sbuf
289
290 if retcode:
291 cmd = kwargs.get("args")
292 if cmd is None:
Zachary Turner9ef307b2014-07-22 16:19:29 +0000293 cmd = shellCommand
Johnny Chen690fcef2010-10-15 23:55:05 +0000294 raise CalledProcessError(retcode, cmd)
Johnny Chenac77f3b2011-03-23 20:28:59 +0000295 return (output, error)
Johnny Chen690fcef2010-10-15 23:55:05 +0000296
Johnny Chenab9c1dd2010-11-01 20:35:01 +0000297def getsource_if_available(obj):
298 """
299 Return the text of the source code for an object if available. Otherwise,
300 a print representation is returned.
301 """
302 import inspect
303 try:
304 return inspect.getsource(obj)
305 except:
306 return repr(obj)
307
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000308def builder_module():
Ed Maste4d90f0f2013-07-25 13:24:34 +0000309 if sys.platform.startswith("freebsd"):
310 return __import__("builder_freebsd")
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000311 return __import__("builder_" + sys.platform)
312
Johnny Chena74bb0a2011-08-01 18:46:13 +0000313#
314# Decorators for categorizing test cases.
315#
316
317from functools import wraps
318def python_api_test(func):
319 """Decorate the item as a Python API only test."""
320 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
321 raise Exception("@python_api_test can only be used to decorate a test method")
322 @wraps(func)
323 def wrapper(self, *args, **kwargs):
324 try:
325 if lldb.dont_do_python_api_test:
326 self.skipTest("python api tests")
327 except AttributeError:
328 pass
329 return func(self, *args, **kwargs)
330
331 # Mark this function as such to separate them from lldb command line tests.
332 wrapper.__python_api_test__ = True
333 return wrapper
334
Johnny Chena74bb0a2011-08-01 18:46:13 +0000335def benchmarks_test(func):
336 """Decorate the item as a benchmarks test."""
337 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
338 raise Exception("@benchmarks_test can only be used to decorate a test method")
339 @wraps(func)
340 def wrapper(self, *args, **kwargs):
341 try:
342 if not lldb.just_do_benchmarks_test:
343 self.skipTest("benchmarks tests")
344 except AttributeError:
345 pass
346 return func(self, *args, **kwargs)
347
348 # Mark this function as such to separate them from the regular tests.
349 wrapper.__benchmarks_test__ = True
350 return wrapper
351
Johnny Chenf1548d42012-04-06 00:56:05 +0000352def dsym_test(func):
353 """Decorate the item as a dsym test."""
354 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
355 raise Exception("@dsym_test can only be used to decorate a test method")
356 @wraps(func)
357 def wrapper(self, *args, **kwargs):
358 try:
359 if lldb.dont_do_dsym_test:
360 self.skipTest("dsym tests")
361 except AttributeError:
362 pass
363 return func(self, *args, **kwargs)
364
365 # Mark this function as such to separate them from the regular tests.
366 wrapper.__dsym_test__ = True
367 return wrapper
368
369def dwarf_test(func):
370 """Decorate the item as a dwarf test."""
371 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
372 raise Exception("@dwarf_test can only be used to decorate a test method")
373 @wraps(func)
374 def wrapper(self, *args, **kwargs):
375 try:
376 if lldb.dont_do_dwarf_test:
377 self.skipTest("dwarf tests")
378 except AttributeError:
379 pass
380 return func(self, *args, **kwargs)
381
382 # Mark this function as such to separate them from the regular tests.
383 wrapper.__dwarf_test__ = True
384 return wrapper
385
Todd Fialaa41d48c2014-04-28 04:49:40 +0000386def debugserver_test(func):
387 """Decorate the item as a debugserver test."""
388 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
389 raise Exception("@debugserver_test can only be used to decorate a test method")
390 @wraps(func)
391 def wrapper(self, *args, **kwargs):
392 try:
393 if lldb.dont_do_debugserver_test:
394 self.skipTest("debugserver tests")
395 except AttributeError:
396 pass
397 return func(self, *args, **kwargs)
398
399 # Mark this function as such to separate them from the regular tests.
400 wrapper.__debugserver_test__ = True
401 return wrapper
402
403def llgs_test(func):
404 """Decorate the item as a lldb-gdbserver test."""
405 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
406 raise Exception("@llgs_test can only be used to decorate a test method")
407 @wraps(func)
408 def wrapper(self, *args, **kwargs):
409 try:
410 if lldb.dont_do_llgs_test:
411 self.skipTest("llgs tests")
412 except AttributeError:
413 pass
414 return func(self, *args, **kwargs)
415
416 # Mark this function as such to separate them from the regular tests.
417 wrapper.__llgs_test__ = True
418 return wrapper
419
Daniel Maleae0f8f572013-08-26 23:57:52 +0000420def not_remote_testsuite_ready(func):
421 """Decorate the item as a test which is not ready yet for remote testsuite."""
422 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
423 raise Exception("@not_remote_testsuite_ready can only be used to decorate a test method")
424 @wraps(func)
425 def wrapper(self, *args, **kwargs):
426 try:
427 if lldb.lldbtest_remote_sandbox:
428 self.skipTest("not ready for remote testsuite")
429 except AttributeError:
430 pass
431 return func(self, *args, **kwargs)
432
433 # Mark this function as such to separate them from the regular tests.
434 wrapper.__not_ready_for_remote_testsuite_test__ = True
435 return wrapper
436
Ed Maste433790a2014-04-23 12:55:41 +0000437def expectedFailure(expected_fn, bugnumber=None):
438 def expectedFailure_impl(func):
439 @wraps(func)
440 def wrapper(*args, **kwargs):
Enrico Granata43f62132013-02-23 01:28:30 +0000441 from unittest2 import case
442 self = args[0]
Enrico Granata43f62132013-02-23 01:28:30 +0000443 try:
Ed Maste433790a2014-04-23 12:55:41 +0000444 func(*args, **kwargs)
Enrico Granata43f62132013-02-23 01:28:30 +0000445 except Exception:
Ed Maste433790a2014-04-23 12:55:41 +0000446 if expected_fn(self):
447 raise case._ExpectedFailure(sys.exc_info(), bugnumber)
Enrico Granata43f62132013-02-23 01:28:30 +0000448 else:
449 raise
Ed Maste433790a2014-04-23 12:55:41 +0000450 if expected_fn(self):
451 raise case._UnexpectedSuccess(sys.exc_info(), bugnumber)
452 return wrapper
453 if callable(bugnumber):
454 return expectedFailure_impl(bugnumber)
455 else:
456 return expectedFailure_impl
457
458def expectedFailureCompiler(compiler, compiler_version=None, bugnumber=None):
459 if compiler_version is None:
460 compiler_version=['=', None]
461 def fn(self):
462 return compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version)
463 return expectedFailure(fn, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000464
Enrico Granata2b3a0c42013-02-23 01:35:21 +0000465def expectedFailureClang(bugnumber=None):
Ed Maste433790a2014-04-23 12:55:41 +0000466 return expectedFailureCompiler('clang', None, bugnumber)
467
468def expectedFailureGcc(bugnumber=None, compiler_version=None):
469 return expectedFailureCompiler('gcc', compiler_version, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000470
Matt Kopec0de53f02013-03-15 19:10:12 +0000471def expectedFailureIcc(bugnumber=None):
Ed Maste433790a2014-04-23 12:55:41 +0000472 return expectedFailureCompiler('icc', None, bugnumber)
Matt Kopec0de53f02013-03-15 19:10:12 +0000473
Ed Maste433790a2014-04-23 12:55:41 +0000474def expectedFailureArch(arch, bugnumber=None):
475 def fn(self):
476 return arch in self.getArchitecture()
477 return expectedFailure(fn, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000478
Enrico Granatae6cedc12013-02-23 01:05:23 +0000479def expectedFailurei386(bugnumber=None):
Ed Maste433790a2014-04-23 12:55:41 +0000480 return expectedFailureArch('i386', bugnumber)
Johnny Chena33843f2011-12-22 21:14:31 +0000481
Matt Kopecee969f92013-09-26 23:30:59 +0000482def expectedFailurex86_64(bugnumber=None):
Ed Maste433790a2014-04-23 12:55:41 +0000483 return expectedFailureArch('x86_64', bugnumber)
484
485def expectedFailureOS(os, bugnumber=None, compilers=None):
486 def fn(self):
487 return os in sys.platform and self.expectedCompiler(compilers)
488 return expectedFailure(fn, bugnumber)
489
490def expectedFailureDarwin(bugnumber=None, compilers=None):
491 return expectedFailureOS('darwin', bugnumber, compilers)
Matt Kopecee969f92013-09-26 23:30:59 +0000492
Ed Maste24a7f7d2013-07-24 19:47:08 +0000493def expectedFailureFreeBSD(bugnumber=None, compilers=None):
Ed Maste433790a2014-04-23 12:55:41 +0000494 return expectedFailureOS('freebsd', bugnumber, compilers)
Ed Maste24a7f7d2013-07-24 19:47:08 +0000495
Ashok Thirumurthic97a6082013-05-17 20:15:07 +0000496def expectedFailureLinux(bugnumber=None, compilers=None):
Ed Maste433790a2014-04-23 12:55:41 +0000497 return expectedFailureOS('linux', bugnumber, compilers)
Matt Kopece9ea0da2013-05-07 19:29:28 +0000498
Greg Clayton12514562013-12-05 22:22:32 +0000499def skipIfRemote(func):
500 """Decorate the item to skip tests if testing remotely."""
501 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
502 raise Exception("@skipIfRemote can only be used to decorate a test method")
503 @wraps(func)
504 def wrapper(*args, **kwargs):
505 from unittest2 import case
506 if lldb.remote_platform:
507 self = args[0]
508 self.skipTest("skip on remote platform")
509 else:
510 func(*args, **kwargs)
511 return wrapper
512
513def skipIfRemoteDueToDeadlock(func):
514 """Decorate the item to skip tests if testing remotely due to the test deadlocking."""
515 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
516 raise Exception("@skipIfRemote can only be used to decorate a test method")
517 @wraps(func)
518 def wrapper(*args, **kwargs):
519 from unittest2 import case
520 if lldb.remote_platform:
521 self = args[0]
522 self.skipTest("skip on remote platform (deadlocks)")
523 else:
524 func(*args, **kwargs)
525 return wrapper
526
Ed Maste09617a52013-06-25 19:11:36 +0000527def skipIfFreeBSD(func):
528 """Decorate the item to skip tests that should be skipped on FreeBSD."""
529 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
530 raise Exception("@skipIfFreeBSD can only be used to decorate a test method")
531 @wraps(func)
532 def wrapper(*args, **kwargs):
533 from unittest2 import case
534 self = args[0]
535 platform = sys.platform
536 if "freebsd" in platform:
537 self.skipTest("skip on FreeBSD")
538 else:
539 func(*args, **kwargs)
540 return wrapper
541
Daniel Maleae8bdd1f2013-05-15 18:48:32 +0000542def skipIfLinux(func):
Daniel Malea93aec0f2012-11-23 21:59:29 +0000543 """Decorate the item to skip tests that should be skipped on Linux."""
544 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Daniel Maleae8bdd1f2013-05-15 18:48:32 +0000545 raise Exception("@skipIfLinux can only be used to decorate a test method")
Daniel Malea93aec0f2012-11-23 21:59:29 +0000546 @wraps(func)
547 def wrapper(*args, **kwargs):
548 from unittest2 import case
549 self = args[0]
550 platform = sys.platform
551 if "linux" in platform:
552 self.skipTest("skip on linux")
553 else:
Jim Ingham9732e082012-11-27 01:21:28 +0000554 func(*args, **kwargs)
Daniel Malea93aec0f2012-11-23 21:59:29 +0000555 return wrapper
556
Enrico Granatab633e432014-10-06 21:37:06 +0000557def skipIfNoSBHeaders(func):
558 """Decorate the item to mark tests that should be skipped when LLDB is built with no SB API headers."""
559 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
560 raise Exception("@skipIfLinux can only be used to decorate a test method")
561 @wraps(func)
562 def wrapper(*args, **kwargs):
563 from unittest2 import case
564 self = args[0]
565 platform = sys.platform
566 header = os.path.join(os.environ["LLDB_SRC"], "include", "lldb", "API", "LLDB.h")
567 if not os.path.exists(header):
568 self.skipTest("skip because LLDB.h header not found")
569 else:
570 func(*args, **kwargs)
571 return wrapper
572
Zachary Turnerc7826522014-08-13 17:44:53 +0000573def skipIfWindows(func):
574 """Decorate the item to skip tests that should be skipped on Windows."""
575 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
576 raise Exception("@skipIfWindows can only be used to decorate a test method")
577 @wraps(func)
578 def wrapper(*args, **kwargs):
579 from unittest2 import case
580 self = args[0]
581 platform = sys.platform
582 if "win32" in platform:
583 self.skipTest("skip on Windows")
584 else:
585 func(*args, **kwargs)
586 return wrapper
587
Daniel Maleab3d41a22013-07-09 00:08:01 +0000588def skipIfDarwin(func):
589 """Decorate the item to skip tests that should be skipped on Darwin."""
590 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Ed Mastea7f13f02013-07-09 00:24:52 +0000591 raise Exception("@skipIfDarwin can only be used to decorate a test method")
Daniel Maleab3d41a22013-07-09 00:08:01 +0000592 @wraps(func)
593 def wrapper(*args, **kwargs):
594 from unittest2 import case
595 self = args[0]
596 platform = sys.platform
597 if "darwin" in platform:
598 self.skipTest("skip on darwin")
599 else:
600 func(*args, **kwargs)
601 return wrapper
602
603
Daniel Malea48359902013-05-14 20:48:54 +0000604def skipIfLinuxClang(func):
605 """Decorate the item to skip tests that should be skipped if building on
606 Linux with clang.
607 """
608 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
609 raise Exception("@skipIfLinuxClang can only be used to decorate a test method")
610 @wraps(func)
611 def wrapper(*args, **kwargs):
612 from unittest2 import case
613 self = args[0]
614 compiler = self.getCompiler()
615 platform = sys.platform
616 if "clang" in compiler and "linux" in platform:
617 self.skipTest("skipping because Clang is used on Linux")
618 else:
619 func(*args, **kwargs)
620 return wrapper
621
Daniel Maleabe230792013-01-24 23:52:09 +0000622def skipIfGcc(func):
623 """Decorate the item to skip tests that should be skipped if building with gcc ."""
624 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Daniel Malea0aea0162013-02-27 17:29:46 +0000625 raise Exception("@skipIfGcc can only be used to decorate a test method")
Daniel Maleabe230792013-01-24 23:52:09 +0000626 @wraps(func)
627 def wrapper(*args, **kwargs):
628 from unittest2 import case
629 self = args[0]
630 compiler = self.getCompiler()
631 if "gcc" in compiler:
632 self.skipTest("skipping because gcc is the test compiler")
633 else:
634 func(*args, **kwargs)
635 return wrapper
636
Matt Kopec0de53f02013-03-15 19:10:12 +0000637def skipIfIcc(func):
638 """Decorate the item to skip tests that should be skipped if building with icc ."""
639 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
640 raise Exception("@skipIfIcc can only be used to decorate a test method")
641 @wraps(func)
642 def wrapper(*args, **kwargs):
643 from unittest2 import case
644 self = args[0]
645 compiler = self.getCompiler()
646 if "icc" in compiler:
647 self.skipTest("skipping because icc is the test compiler")
648 else:
649 func(*args, **kwargs)
650 return wrapper
651
Daniel Malea55faa402013-05-02 21:44:31 +0000652def skipIfi386(func):
653 """Decorate the item to skip tests that should be skipped if building 32-bit."""
654 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
655 raise Exception("@skipIfi386 can only be used to decorate a test method")
656 @wraps(func)
657 def wrapper(*args, **kwargs):
658 from unittest2 import case
659 self = args[0]
660 if "i386" == self.getArchitecture():
661 self.skipTest("skipping because i386 is not a supported architecture")
662 else:
663 func(*args, **kwargs)
664 return wrapper
665
666
Johnny Chena74bb0a2011-08-01 18:46:13 +0000667class Base(unittest2.TestCase):
Johnny Chen8334dad2010-10-22 23:15:46 +0000668 """
Johnny Chena74bb0a2011-08-01 18:46:13 +0000669 Abstract base for performing lldb (see TestBase) or other generic tests (see
670 BenchBase for one example). lldbtest.Base works with the test driver to
671 accomplish things.
672
Johnny Chen8334dad2010-10-22 23:15:46 +0000673 """
Enrico Granata5020f952012-10-24 21:42:49 +0000674
Enrico Granata19186272012-10-24 21:44:48 +0000675 # The concrete subclass should override this attribute.
676 mydir = None
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000677
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000678 # Keep track of the old current working directory.
679 oldcwd = None
Greg Clayton4570d3e2013-12-10 23:19:29 +0000680
681 @staticmethod
682 def compute_mydir(test_file):
683 '''Subclasses should call this function to correctly calculate the required "mydir" attribute as follows:
684
685 mydir = TestBase.compute_mydir(__file__)'''
686 test_dir = os.path.dirname(test_file)
687 return test_dir[len(os.environ["LLDB_TEST"])+1:]
688
Johnny Chenfb4264c2011-08-01 19:50:58 +0000689 def TraceOn(self):
690 """Returns True if we are in trace mode (tracing detailed test execution)."""
691 return traceAlways
Greg Clayton4570d3e2013-12-10 23:19:29 +0000692
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000693 @classmethod
694 def setUpClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +0000695 """
696 Python unittest framework class setup fixture.
697 Do current directory manipulation.
698 """
699
Johnny Chenf02ec122010-07-03 20:41:42 +0000700 # Fail fast if 'mydir' attribute is not overridden.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000701 if not cls.mydir or len(cls.mydir) == 0:
Johnny Chenf02ec122010-07-03 20:41:42 +0000702 raise Exception("Subclasses must override the 'mydir' attribute.")
Enrico Granata7e137e32012-10-24 18:14:21 +0000703
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000704 # Save old working directory.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000705 cls.oldcwd = os.getcwd()
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000706
707 # Change current working directory if ${LLDB_TEST} is defined.
708 # See also dotest.py which sets up ${LLDB_TEST}.
709 if ("LLDB_TEST" in os.environ):
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000710 if traceAlways:
Johnny Chen703dbd02010-09-30 17:06:24 +0000711 print >> sys.stderr, "Change dir to:", os.path.join(os.environ["LLDB_TEST"], cls.mydir)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000712 os.chdir(os.path.join(os.environ["LLDB_TEST"], cls.mydir))
713
714 @classmethod
715 def tearDownClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +0000716 """
717 Python unittest framework class teardown fixture.
718 Do class-wide cleanup.
719 """
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000720
Johnny Chen0fddfb22011-11-17 19:57:27 +0000721 if doCleanup and not lldb.skip_build_and_cleanup:
Johnny Chen707b3c92010-10-11 22:25:46 +0000722 # First, let's do the platform-specific cleanup.
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000723 module = builder_module()
Johnny Chen707b3c92010-10-11 22:25:46 +0000724 if not module.cleanup():
725 raise Exception("Don't know how to do cleanup")
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000726
Johnny Chen707b3c92010-10-11 22:25:46 +0000727 # Subclass might have specific cleanup function defined.
728 if getattr(cls, "classCleanup", None):
729 if traceAlways:
730 print >> sys.stderr, "Call class-specific cleanup function for class:", cls
731 try:
732 cls.classCleanup()
733 except:
734 exc_type, exc_value, exc_tb = sys.exc_info()
735 traceback.print_exception(exc_type, exc_value, exc_tb)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000736
737 # Restore old working directory.
738 if traceAlways:
Johnny Chen703dbd02010-09-30 17:06:24 +0000739 print >> sys.stderr, "Restore dir to:", cls.oldcwd
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000740 os.chdir(cls.oldcwd)
741
Johnny Chena74bb0a2011-08-01 18:46:13 +0000742 @classmethod
743 def skipLongRunningTest(cls):
744 """
745 By default, we skip long running test case.
746 This can be overridden by passing '-l' to the test driver (dotest.py).
747 """
748 if "LLDB_SKIP_LONG_RUNNING_TEST" in os.environ and "NO" == os.environ["LLDB_SKIP_LONG_RUNNING_TEST"]:
749 return False
750 else:
751 return True
Johnny Chened492022011-06-21 00:53:00 +0000752
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000753 def setUp(self):
Johnny Chenfb4264c2011-08-01 19:50:58 +0000754 """Fixture for unittest test case setup.
755
756 It works with the test driver to conditionally skip tests and does other
757 initializations."""
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000758 #import traceback
759 #traceback.print_stack()
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000760
Daniel Malea9115f072013-08-06 15:02:32 +0000761 if "LIBCXX_PATH" in os.environ:
762 self.libcxxPath = os.environ["LIBCXX_PATH"]
763 else:
764 self.libcxxPath = None
765
Johnny Chenaaa82ff2011-08-02 22:54:37 +0000766 if "LLDB_EXEC" in os.environ:
767 self.lldbExec = os.environ["LLDB_EXEC"]
Johnny Chend890bfc2011-08-26 00:00:01 +0000768 else:
769 self.lldbExec = None
770 if "LLDB_HERE" in os.environ:
771 self.lldbHere = os.environ["LLDB_HERE"]
772 else:
773 self.lldbHere = None
Johnny Chenebe51722011-10-07 19:21:09 +0000774 # If we spawn an lldb process for test (via pexpect), do not load the
775 # init file unless told otherwise.
776 if "NO_LLDBINIT" in os.environ and "NO" == os.environ["NO_LLDBINIT"]:
777 self.lldbOption = ""
778 else:
779 self.lldbOption = "--no-lldbinit"
Johnny Chenaaa82ff2011-08-02 22:54:37 +0000780
Johnny Chen985e7402011-08-01 21:13:26 +0000781 # Assign the test method name to self.testMethodName.
782 #
783 # For an example of the use of this attribute, look at test/types dir.
784 # There are a bunch of test cases under test/types and we don't want the
785 # module cacheing subsystem to be confused with executable name "a.out"
786 # used for all the test cases.
787 self.testMethodName = self._testMethodName
788
Johnny Chenf3e22ac2010-12-10 18:52:10 +0000789 # Python API only test is decorated with @python_api_test,
790 # which also sets the "__python_api_test__" attribute of the
791 # function object to True.
Johnny Chen4533dad2011-05-31 23:21:42 +0000792 try:
793 if lldb.just_do_python_api_test:
794 testMethod = getattr(self, self._testMethodName)
795 if getattr(testMethod, "__python_api_test__", False):
796 pass
797 else:
Johnny Chen5ccbccf2011-07-30 01:39:58 +0000798 self.skipTest("non python api test")
799 except AttributeError:
800 pass
801
802 # Benchmarks test is decorated with @benchmarks_test,
803 # which also sets the "__benchmarks_test__" attribute of the
804 # function object to True.
805 try:
806 if lldb.just_do_benchmarks_test:
807 testMethod = getattr(self, self._testMethodName)
808 if getattr(testMethod, "__benchmarks_test__", False):
809 pass
810 else:
811 self.skipTest("non benchmarks test")
Johnny Chen4533dad2011-05-31 23:21:42 +0000812 except AttributeError:
813 pass
Johnny Chenf3e22ac2010-12-10 18:52:10 +0000814
Johnny Chen985e7402011-08-01 21:13:26 +0000815 # This is for the case of directly spawning 'lldb'/'gdb' and interacting
816 # with it using pexpect.
817 self.child = None
818 self.child_prompt = "(lldb) "
819 # If the child is interacting with the embedded script interpreter,
820 # there are two exits required during tear down, first to quit the
821 # embedded script interpreter and second to quit the lldb command
822 # interpreter.
823 self.child_in_script_interpreter = False
824
Johnny Chenfb4264c2011-08-01 19:50:58 +0000825 # These are for customized teardown cleanup.
826 self.dict = None
827 self.doTearDownCleanup = False
828 # And in rare cases where there are multiple teardown cleanups.
829 self.dicts = []
830 self.doTearDownCleanups = False
831
Daniel Malea2dd69bb2013-02-15 21:21:52 +0000832 # List of spawned subproces.Popen objects
833 self.subprocesses = []
834
Daniel Malea69207462013-06-05 21:07:02 +0000835 # List of forked process PIDs
836 self.forkedProcessPids = []
837
Johnny Chenfb4264c2011-08-01 19:50:58 +0000838 # Create a string buffer to record the session info, to be dumped into a
839 # test case specific file if test failure is encountered.
840 self.session = StringIO.StringIO()
841
842 # Optimistically set __errored__, __failed__, __expected__ to False
843 # initially. If the test errored/failed, the session info
844 # (self.session) is then dumped into a session specific file for
845 # diagnosis.
846 self.__errored__ = False
847 self.__failed__ = False
848 self.__expected__ = False
849 # We are also interested in unexpected success.
850 self.__unexpected__ = False
Johnny Chenf79b0762011-08-16 00:48:58 +0000851 # And skipped tests.
852 self.__skipped__ = False
Johnny Chenfb4264c2011-08-01 19:50:58 +0000853
854 # See addTearDownHook(self, hook) which allows the client to add a hook
855 # function to be run during tearDown() time.
856 self.hooks = []
857
858 # See HideStdout(self).
859 self.sys_stdout_hidden = False
860
Daniel Malea179ff292012-11-26 21:21:11 +0000861 # set environment variable names for finding shared libraries
862 if sys.platform.startswith("darwin"):
863 self.dylibPath = 'DYLD_LIBRARY_PATH'
864 elif sys.platform.startswith("linux") or sys.platform.startswith("freebsd"):
865 self.dylibPath = 'LD_LIBRARY_PATH'
866
Johnny Chen2a808582011-10-19 16:48:07 +0000867 def runHooks(self, child=None, child_prompt=None, use_cmd_api=False):
Johnny Chena737ba52011-10-19 01:06:21 +0000868 """Perform the run hooks to bring lldb debugger to the desired state.
869
Johnny Chen2a808582011-10-19 16:48:07 +0000870 By default, expect a pexpect spawned child and child prompt to be
871 supplied (use_cmd_api=False). If use_cmd_api is true, ignore the child
872 and child prompt and use self.runCmd() to run the hooks one by one.
873
Johnny Chena737ba52011-10-19 01:06:21 +0000874 Note that child is a process spawned by pexpect.spawn(). If not, your
875 test case is mostly likely going to fail.
876
877 See also dotest.py where lldb.runHooks are processed/populated.
878 """
879 if not lldb.runHooks:
880 self.skipTest("No runhooks specified for lldb, skip the test")
Johnny Chen2a808582011-10-19 16:48:07 +0000881 if use_cmd_api:
882 for hook in lldb.runhooks:
883 self.runCmd(hook)
884 else:
885 if not child or not child_prompt:
886 self.fail("Both child and child_prompt need to be defined.")
887 for hook in lldb.runHooks:
888 child.sendline(hook)
889 child.expect_exact(child_prompt)
Johnny Chena737ba52011-10-19 01:06:21 +0000890
Daniel Malea249287a2013-02-19 16:08:57 +0000891 def setAsync(self, value):
892 """ Sets async mode to True/False and ensures it is reset after the testcase completes."""
893 old_async = self.dbg.GetAsync()
894 self.dbg.SetAsync(value)
895 self.addTearDownHook(lambda: self.dbg.SetAsync(old_async))
896
Daniel Malea2dd69bb2013-02-15 21:21:52 +0000897 def cleanupSubprocesses(self):
898 # Ensure any subprocesses are cleaned up
899 for p in self.subprocesses:
900 if p.poll() == None:
901 p.terminate()
902 del p
903 del self.subprocesses[:]
Daniel Malea69207462013-06-05 21:07:02 +0000904 # Ensure any forked processes are cleaned up
905 for pid in self.forkedProcessPids:
906 if os.path.exists("/proc/" + str(pid)):
907 os.kill(pid, signal.SIGTERM)
Daniel Malea2dd69bb2013-02-15 21:21:52 +0000908
909 def spawnSubprocess(self, executable, args=[]):
910 """ Creates a subprocess.Popen object with the specified executable and arguments,
911 saves it in self.subprocesses, and returns the object.
912 NOTE: if using this function, ensure you also call:
913
914 self.addTearDownHook(self.cleanupSubprocesses)
915
916 otherwise the test suite will leak processes.
917 """
918
919 # Don't display the stdout if not in TraceOn() mode.
920 proc = Popen([executable] + args,
921 stdout = open(os.devnull) if not self.TraceOn() else None,
922 stdin = PIPE)
923 self.subprocesses.append(proc)
924 return proc
925
Daniel Malea69207462013-06-05 21:07:02 +0000926 def forkSubprocess(self, executable, args=[]):
927 """ Fork a subprocess with its own group ID.
928 NOTE: if using this function, ensure you also call:
929
930 self.addTearDownHook(self.cleanupSubprocesses)
931
932 otherwise the test suite will leak processes.
933 """
934 child_pid = os.fork()
935 if child_pid == 0:
936 # If more I/O support is required, this can be beefed up.
937 fd = os.open(os.devnull, os.O_RDWR)
Daniel Malea69207462013-06-05 21:07:02 +0000938 os.dup2(fd, 1)
939 os.dup2(fd, 2)
940 # This call causes the child to have its of group ID
941 os.setpgid(0,0)
942 os.execvp(executable, [executable] + args)
943 # Give the child time to get through the execvp() call
944 time.sleep(0.1)
945 self.forkedProcessPids.append(child_pid)
946 return child_pid
947
Johnny Chenfb4264c2011-08-01 19:50:58 +0000948 def HideStdout(self):
949 """Hide output to stdout from the user.
950
951 During test execution, there might be cases where we don't want to show the
952 standard output to the user. For example,
953
954 self.runCmd(r'''sc print "\n\n\tHello!\n"''')
955
956 tests whether command abbreviation for 'script' works or not. There is no
957 need to show the 'Hello' output to the user as long as the 'script' command
958 succeeds and we are not in TraceOn() mode (see the '-t' option).
959
960 In this case, the test method calls self.HideStdout(self) to redirect the
961 sys.stdout to a null device, and restores the sys.stdout upon teardown.
962
963 Note that you should only call this method at most once during a test case
964 execution. Any subsequent call has no effect at all."""
965 if self.sys_stdout_hidden:
966 return
967
968 self.sys_stdout_hidden = True
969 old_stdout = sys.stdout
970 sys.stdout = open(os.devnull, 'w')
971 def restore_stdout():
972 sys.stdout = old_stdout
973 self.addTearDownHook(restore_stdout)
974
975 # =======================================================================
976 # Methods for customized teardown cleanups as well as execution of hooks.
977 # =======================================================================
978
979 def setTearDownCleanup(self, dictionary=None):
980 """Register a cleanup action at tearDown() time with a dictinary"""
981 self.dict = dictionary
982 self.doTearDownCleanup = True
983
984 def addTearDownCleanup(self, dictionary):
985 """Add a cleanup action at tearDown() time with a dictinary"""
986 self.dicts.append(dictionary)
987 self.doTearDownCleanups = True
988
989 def addTearDownHook(self, hook):
990 """
991 Add a function to be run during tearDown() time.
992
993 Hooks are executed in a first come first serve manner.
994 """
995 if callable(hook):
996 with recording(self, traceAlways) as sbuf:
997 print >> sbuf, "Adding tearDown hook:", getsource_if_available(hook)
998 self.hooks.append(hook)
999
1000 def tearDown(self):
1001 """Fixture for unittest test case teardown."""
1002 #import traceback
1003 #traceback.print_stack()
1004
Johnny Chen985e7402011-08-01 21:13:26 +00001005 # This is for the case of directly spawning 'lldb' and interacting with it
1006 # using pexpect.
Johnny Chen985e7402011-08-01 21:13:26 +00001007 if self.child and self.child.isalive():
Zachary Turner9ef307b2014-07-22 16:19:29 +00001008 import pexpect
Johnny Chen985e7402011-08-01 21:13:26 +00001009 with recording(self, traceAlways) as sbuf:
1010 print >> sbuf, "tearing down the child process...."
Johnny Chen985e7402011-08-01 21:13:26 +00001011 try:
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001012 if self.child_in_script_interpreter:
1013 self.child.sendline('quit()')
1014 self.child.expect_exact(self.child_prompt)
1015 self.child.sendline('settings set interpreter.prompt-on-quit false')
1016 self.child.sendline('quit')
Johnny Chen985e7402011-08-01 21:13:26 +00001017 self.child.expect(pexpect.EOF)
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001018 except ValueError, ExceptionPexpect:
1019 # child is already terminated
Johnny Chen985e7402011-08-01 21:13:26 +00001020 pass
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001021
Johnny Chenac257132012-02-27 23:07:40 +00001022 # Give it one final blow to make sure the child is terminated.
1023 self.child.close()
Johnny Chen985e7402011-08-01 21:13:26 +00001024
Johnny Chenfb4264c2011-08-01 19:50:58 +00001025 # Check and run any hook functions.
1026 for hook in reversed(self.hooks):
1027 with recording(self, traceAlways) as sbuf:
1028 print >> sbuf, "Executing tearDown hook:", getsource_if_available(hook)
1029 hook()
1030
1031 del self.hooks
1032
1033 # Perform registered teardown cleanup.
1034 if doCleanup and self.doTearDownCleanup:
Johnny Chen0fddfb22011-11-17 19:57:27 +00001035 self.cleanup(dictionary=self.dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001036
1037 # In rare cases where there are multiple teardown cleanups added.
1038 if doCleanup and self.doTearDownCleanups:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001039 if self.dicts:
1040 for dict in reversed(self.dicts):
Johnny Chen0fddfb22011-11-17 19:57:27 +00001041 self.cleanup(dictionary=dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001042
1043 # Decide whether to dump the session info.
1044 self.dumpSessionInfo()
1045
1046 # =========================================================
1047 # Various callbacks to allow introspection of test progress
1048 # =========================================================
1049
1050 def markError(self):
1051 """Callback invoked when an error (unexpected exception) errored."""
1052 self.__errored__ = True
1053 with recording(self, False) as sbuf:
1054 # False because there's no need to write "ERROR" to the stderr twice.
1055 # Once by the Python unittest framework, and a second time by us.
1056 print >> sbuf, "ERROR"
1057
1058 def markFailure(self):
1059 """Callback invoked when a failure (test assertion failure) occurred."""
1060 self.__failed__ = True
1061 with recording(self, False) as sbuf:
1062 # False because there's no need to write "FAIL" to the stderr twice.
1063 # Once by the Python unittest framework, and a second time by us.
1064 print >> sbuf, "FAIL"
1065
Enrico Granatae6cedc12013-02-23 01:05:23 +00001066 def markExpectedFailure(self,err,bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001067 """Callback invoked when an expected failure/error occurred."""
1068 self.__expected__ = True
1069 with recording(self, False) as sbuf:
1070 # False because there's no need to write "expected failure" to the
1071 # stderr twice.
1072 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001073 if bugnumber == None:
1074 print >> sbuf, "expected failure"
1075 else:
1076 print >> sbuf, "expected failure (problem id:" + str(bugnumber) + ")"
Johnny Chenfb4264c2011-08-01 19:50:58 +00001077
Johnny Chenc5cc6252011-08-15 23:09:08 +00001078 def markSkippedTest(self):
1079 """Callback invoked when a test is skipped."""
1080 self.__skipped__ = True
1081 with recording(self, False) as sbuf:
1082 # False because there's no need to write "skipped test" to the
1083 # stderr twice.
1084 # Once by the Python unittest framework, and a second time by us.
1085 print >> sbuf, "skipped test"
1086
Enrico Granatae6cedc12013-02-23 01:05:23 +00001087 def markUnexpectedSuccess(self, bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001088 """Callback invoked when an unexpected success occurred."""
1089 self.__unexpected__ = True
1090 with recording(self, False) as sbuf:
1091 # False because there's no need to write "unexpected success" to the
1092 # stderr twice.
1093 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001094 if bugnumber == None:
1095 print >> sbuf, "unexpected success"
1096 else:
1097 print >> sbuf, "unexpected success (problem id:" + str(bugnumber) + ")"
Johnny Chenfb4264c2011-08-01 19:50:58 +00001098
1099 def dumpSessionInfo(self):
1100 """
1101 Dump the debugger interactions leading to a test error/failure. This
1102 allows for more convenient postmortem analysis.
1103
1104 See also LLDBTestResult (dotest.py) which is a singlton class derived
1105 from TextTestResult and overwrites addError, addFailure, and
1106 addExpectedFailure methods to allow us to to mark the test instance as
1107 such.
1108 """
1109
1110 # We are here because self.tearDown() detected that this test instance
1111 # either errored or failed. The lldb.test_result singleton contains
1112 # two lists (erros and failures) which get populated by the unittest
1113 # framework. Look over there for stack trace information.
1114 #
1115 # The lists contain 2-tuples of TestCase instances and strings holding
1116 # formatted tracebacks.
1117 #
1118 # See http://docs.python.org/library/unittest.html#unittest.TestResult.
1119 if self.__errored__:
1120 pairs = lldb.test_result.errors
1121 prefix = 'Error'
1122 elif self.__failed__:
1123 pairs = lldb.test_result.failures
1124 prefix = 'Failure'
1125 elif self.__expected__:
1126 pairs = lldb.test_result.expectedFailures
1127 prefix = 'ExpectedFailure'
Johnny Chenc5cc6252011-08-15 23:09:08 +00001128 elif self.__skipped__:
1129 prefix = 'SkippedTest'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001130 elif self.__unexpected__:
1131 prefix = "UnexpectedSuccess"
1132 else:
1133 # Simply return, there's no session info to dump!
1134 return
1135
Johnny Chenc5cc6252011-08-15 23:09:08 +00001136 if not self.__unexpected__ and not self.__skipped__:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001137 for test, traceback in pairs:
1138 if test is self:
1139 print >> self.session, traceback
1140
Johnny Chen8082a002011-08-11 00:16:28 +00001141 testMethod = getattr(self, self._testMethodName)
1142 if getattr(testMethod, "__benchmarks_test__", False):
1143 benchmarks = True
1144 else:
1145 benchmarks = False
1146
Johnny Chenfb4264c2011-08-01 19:50:58 +00001147 dname = os.path.join(os.environ["LLDB_TEST"],
1148 os.environ["LLDB_SESSION_DIRNAME"])
1149 if not os.path.isdir(dname):
1150 os.mkdir(dname)
Sean Callanan794baf62012-10-16 18:22:04 +00001151 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 +00001152 with open(fname, "w") as f:
1153 import datetime
1154 print >> f, "Session info generated @", datetime.datetime.now().ctime()
1155 print >> f, self.session.getvalue()
1156 print >> f, "To rerun this test, issue the following command from the 'test' directory:\n"
Johnny Chen8082a002011-08-11 00:16:28 +00001157 print >> f, "./dotest.py %s -v %s -f %s.%s" % (self.getRunOptions(),
1158 ('+b' if benchmarks else '-t'),
Johnny Chenfb4264c2011-08-01 19:50:58 +00001159 self.__class__.__name__,
1160 self._testMethodName)
1161
1162 # ====================================================
1163 # Config. methods supported through a plugin interface
1164 # (enables reading of the current test configuration)
1165 # ====================================================
1166
1167 def getArchitecture(self):
1168 """Returns the architecture in effect the test suite is running with."""
1169 module = builder_module()
1170 return module.getArchitecture()
1171
1172 def getCompiler(self):
1173 """Returns the compiler in effect the test suite is running with."""
1174 module = builder_module()
1175 return module.getCompiler()
1176
Daniel Malea0aea0162013-02-27 17:29:46 +00001177 def getCompilerVersion(self):
1178 """ Returns a string that represents the compiler version.
1179 Supports: llvm, clang.
1180 """
1181 from lldbutil import which
1182 version = 'unknown'
1183
1184 compiler = self.getCompiler()
Zachary Turner9ef307b2014-07-22 16:19:29 +00001185 version_output = system([[which(compiler), "-v"]])[1]
Daniel Malea0aea0162013-02-27 17:29:46 +00001186 for line in version_output.split(os.linesep):
Greg Clayton2a844b72013-03-06 02:34:51 +00001187 m = re.search('version ([0-9\.]+)', line)
Daniel Malea0aea0162013-02-27 17:29:46 +00001188 if m:
1189 version = m.group(1)
1190 return version
1191
Daniel Maleaadaaec92013-08-06 20:51:41 +00001192 def isIntelCompiler(self):
1193 """ Returns true if using an Intel (ICC) compiler, false otherwise. """
1194 return any([x in self.getCompiler() for x in ["icc", "icpc", "icl"]])
1195
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001196 def expectedCompilerVersion(self, compiler_version):
1197 """Returns True iff compiler_version[1] matches the current compiler version.
1198 Use compiler_version[0] to specify the operator used to determine if a match has occurred.
1199 Any operator other than the following defaults to an equality test:
1200 '>', '>=', "=>", '<', '<=', '=<', '!=', "!" or 'not'
1201 """
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001202 if (compiler_version == None):
1203 return True
1204 operator = str(compiler_version[0])
1205 version = compiler_version[1]
1206
1207 if (version == None):
1208 return True
1209 if (operator == '>'):
1210 return self.getCompilerVersion() > version
1211 if (operator == '>=' or operator == '=>'):
1212 return self.getCompilerVersion() >= version
1213 if (operator == '<'):
1214 return self.getCompilerVersion() < version
1215 if (operator == '<=' or operator == '=<'):
1216 return self.getCompilerVersion() <= version
1217 if (operator == '!=' or operator == '!' or operator == 'not'):
1218 return str(version) not in str(self.getCompilerVersion())
1219 return str(version) in str(self.getCompilerVersion())
1220
1221 def expectedCompiler(self, compilers):
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001222 """Returns True iff any element of compilers is a sub-string of the current compiler."""
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001223 if (compilers == None):
1224 return True
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001225
1226 for compiler in compilers:
1227 if compiler in self.getCompiler():
1228 return True
1229
1230 return False
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001231
Johnny Chenfb4264c2011-08-01 19:50:58 +00001232 def getRunOptions(self):
1233 """Command line option for -A and -C to run this test again, called from
1234 self.dumpSessionInfo()."""
1235 arch = self.getArchitecture()
1236 comp = self.getCompiler()
Johnny Chenb7bdd102011-08-24 19:48:51 +00001237 if arch:
1238 option_str = "-A " + arch
Johnny Chenfb4264c2011-08-01 19:50:58 +00001239 else:
Johnny Chenb7bdd102011-08-24 19:48:51 +00001240 option_str = ""
1241 if comp:
Johnny Chen531c0852012-03-16 20:44:00 +00001242 option_str += " -C " + comp
Johnny Chenb7bdd102011-08-24 19:48:51 +00001243 return option_str
Johnny Chenfb4264c2011-08-01 19:50:58 +00001244
1245 # ==================================================
1246 # Build methods supported through a plugin interface
1247 # ==================================================
1248
Ed Mastec97323e2014-04-01 18:47:58 +00001249 def getstdlibFlag(self):
1250 """ Returns the proper -stdlib flag, or empty if not required."""
1251 if sys.platform.startswith("darwin") or sys.platform.startswith("freebsd"):
1252 stdlibflag = "-stdlib=libc++"
1253 else:
1254 stdlibflag = ""
1255 return stdlibflag
1256
Matt Kopec7663b3a2013-09-25 17:44:00 +00001257 def getstdFlag(self):
1258 """ Returns the proper stdflag. """
Daniel Malea55faa402013-05-02 21:44:31 +00001259 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
Daniel Malea0b7c6112013-05-06 19:31:31 +00001260 stdflag = "-std=c++0x"
Daniel Malea55faa402013-05-02 21:44:31 +00001261 else:
1262 stdflag = "-std=c++11"
Matt Kopec7663b3a2013-09-25 17:44:00 +00001263 return stdflag
1264
1265 def buildDriver(self, sources, exe_name):
1266 """ Platform-specific way to build a program that links with LLDB (via the liblldb.so
1267 or LLDB.framework).
1268 """
1269
1270 stdflag = self.getstdFlag()
Ed Mastec97323e2014-04-01 18:47:58 +00001271 stdlibflag = self.getstdlibFlag()
Daniel Malea55faa402013-05-02 21:44:31 +00001272
1273 if sys.platform.startswith("darwin"):
1274 dsym = os.path.join(self.lib_dir, 'LLDB.framework', 'LLDB')
1275 d = {'CXX_SOURCES' : sources,
1276 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00001277 'CFLAGS_EXTRAS' : "%s %s" % (stdflag, stdlibflag),
Daniel Malea55faa402013-05-02 21:44:31 +00001278 'FRAMEWORK_INCLUDES' : "-F%s" % self.lib_dir,
Stefanus Du Toit04004442013-07-30 19:19:49 +00001279 'LD_EXTRAS' : "%s -Wl,-rpath,%s" % (dsym, self.lib_dir),
Daniel Malea55faa402013-05-02 21:44:31 +00001280 }
Ed Maste372c24d2013-07-25 21:02:34 +00001281 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 +00001282 d = {'CXX_SOURCES' : sources,
1283 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00001284 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Daniel Malea55faa402013-05-02 21:44:31 +00001285 'LD_EXTRAS' : "-L%s -llldb" % self.lib_dir}
1286 if self.TraceOn():
1287 print "Building LLDB Driver (%s) from sources %s" % (exe_name, sources)
1288
1289 self.buildDefault(dictionary=d)
1290
Matt Kopec7663b3a2013-09-25 17:44:00 +00001291 def buildLibrary(self, sources, lib_name):
1292 """Platform specific way to build a default library. """
1293
1294 stdflag = self.getstdFlag()
1295
1296 if sys.platform.startswith("darwin"):
1297 dsym = os.path.join(self.lib_dir, 'LLDB.framework', 'LLDB')
1298 d = {'DYLIB_CXX_SOURCES' : sources,
1299 'DYLIB_NAME' : lib_name,
1300 'CFLAGS_EXTRAS' : "%s -stdlib=libc++" % stdflag,
1301 'FRAMEWORK_INCLUDES' : "-F%s" % self.lib_dir,
1302 'LD_EXTRAS' : "%s -Wl,-rpath,%s -dynamiclib" % (dsym, self.lib_dir),
1303 }
1304 elif sys.platform.startswith('freebsd') or sys.platform.startswith("linux") or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
1305 d = {'DYLIB_CXX_SOURCES' : sources,
1306 'DYLIB_NAME' : lib_name,
1307 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
1308 'LD_EXTRAS' : "-shared -L%s -llldb" % self.lib_dir}
1309 if self.TraceOn():
1310 print "Building LLDB Library (%s) from sources %s" % (lib_name, sources)
1311
1312 self.buildDefault(dictionary=d)
1313
Daniel Malea55faa402013-05-02 21:44:31 +00001314 def buildProgram(self, sources, exe_name):
1315 """ Platform specific way to build an executable from C/C++ sources. """
1316 d = {'CXX_SOURCES' : sources,
1317 'EXE' : exe_name}
1318 self.buildDefault(dictionary=d)
1319
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001320 def buildDefault(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001321 """Platform specific way to build the default binaries."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001322 if lldb.skip_build_and_cleanup:
1323 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00001324 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001325 if not module.buildDefault(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001326 raise Exception("Don't know how to build default binary")
1327
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001328 def buildDsym(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001329 """Platform specific way to build binaries with dsym info."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001330 if lldb.skip_build_and_cleanup:
1331 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00001332 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001333 if not module.buildDsym(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001334 raise Exception("Don't know how to build binary with dsym")
1335
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001336 def buildDwarf(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001337 """Platform specific way to build binaries with dwarf maps."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001338 if lldb.skip_build_and_cleanup:
1339 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00001340 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001341 if not module.buildDwarf(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001342 raise Exception("Don't know how to build binary with dwarf")
Johnny Chena74bb0a2011-08-01 18:46:13 +00001343
Kuba Breckabeed8212014-09-04 01:03:18 +00001344 def findBuiltClang(self):
1345 """Tries to find and use Clang from the build directory as the compiler (instead of the system compiler)."""
1346 paths_to_try = [
1347 "llvm-build/Release+Asserts/x86_64/Release+Asserts/bin/clang",
1348 "llvm-build/Debug+Asserts/x86_64/Debug+Asserts/bin/clang",
1349 "llvm-build/Release/x86_64/Release/bin/clang",
1350 "llvm-build/Debug/x86_64/Debug/bin/clang",
1351 ]
1352 lldb_root_path = os.path.join(os.path.dirname(__file__), "..")
1353 for p in paths_to_try:
1354 path = os.path.join(lldb_root_path, p)
1355 if os.path.exists(path):
1356 return path
1357
1358 return os.environ["CC"]
1359
Daniel Malea9115f072013-08-06 15:02:32 +00001360 def getBuildFlags(self, use_cpp11=True, use_libcxx=False, use_libstdcxx=False, use_pthreads=True):
Andrew Kaylor93132f52013-05-28 23:04:25 +00001361 """ Returns a dictionary (which can be provided to build* functions above) which
1362 contains OS-specific build flags.
1363 """
1364 cflags = ""
Daniel Malea9115f072013-08-06 15:02:32 +00001365
1366 # On Mac OS X, unless specifically requested to use libstdc++, use libc++
1367 if not use_libstdcxx and sys.platform.startswith('darwin'):
1368 use_libcxx = True
1369
1370 if use_libcxx and self.libcxxPath:
1371 cflags += "-stdlib=libc++ "
1372 if self.libcxxPath:
1373 libcxxInclude = os.path.join(self.libcxxPath, "include")
1374 libcxxLib = os.path.join(self.libcxxPath, "lib")
1375 if os.path.isdir(libcxxInclude) and os.path.isdir(libcxxLib):
1376 cflags += "-nostdinc++ -I%s -L%s -Wl,-rpath,%s " % (libcxxInclude, libcxxLib, libcxxLib)
1377
Andrew Kaylor93132f52013-05-28 23:04:25 +00001378 if use_cpp11:
1379 cflags += "-std="
1380 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
1381 cflags += "c++0x"
1382 else:
1383 cflags += "c++11"
Ed Mastedbd59502014-02-02 19:24:15 +00001384 if sys.platform.startswith("darwin") or sys.platform.startswith("freebsd"):
Andrew Kaylor93132f52013-05-28 23:04:25 +00001385 cflags += " -stdlib=libc++"
1386 elif "clang" in self.getCompiler():
1387 cflags += " -stdlib=libstdc++"
1388
1389 if use_pthreads:
1390 ldflags = "-lpthread"
1391
1392 return {'CFLAGS_EXTRAS' : cflags,
1393 'LD_EXTRAS' : ldflags,
1394 }
1395
Johnny Chen9f4f5d92011-08-12 20:19:22 +00001396 def cleanup(self, dictionary=None):
1397 """Platform specific way to do cleanup after build."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001398 if lldb.skip_build_and_cleanup:
1399 return
Johnny Chen9f4f5d92011-08-12 20:19:22 +00001400 module = builder_module()
1401 if not module.cleanup(self, dictionary):
Johnny Chen0fddfb22011-11-17 19:57:27 +00001402 raise Exception("Don't know how to do cleanup with dictionary: "+dictionary)
Johnny Chen9f4f5d92011-08-12 20:19:22 +00001403
Daniel Malea55faa402013-05-02 21:44:31 +00001404 def getLLDBLibraryEnvVal(self):
1405 """ Returns the path that the OS-specific library search environment variable
1406 (self.dylibPath) should be set to in order for a program to find the LLDB
1407 library. If an environment variable named self.dylibPath is already set,
1408 the new path is appended to it and returned.
1409 """
1410 existing_library_path = os.environ[self.dylibPath] if self.dylibPath in os.environ else None
1411 if existing_library_path:
1412 return "%s:%s" % (existing_library_path, self.lib_dir)
1413 elif sys.platform.startswith("darwin"):
1414 return os.path.join(self.lib_dir, 'LLDB.framework')
1415 else:
1416 return self.lib_dir
Johnny Chena74bb0a2011-08-01 18:46:13 +00001417
Ed Maste437f8f62013-09-09 14:04:04 +00001418 def getLibcPlusPlusLibs(self):
1419 if sys.platform.startswith('freebsd'):
1420 return ['libc++.so.1']
1421 else:
1422 return ['libc++.1.dylib','libc++abi.dylib']
1423
Johnny Chena74bb0a2011-08-01 18:46:13 +00001424class TestBase(Base):
1425 """
1426 This abstract base class is meant to be subclassed. It provides default
1427 implementations for setUpClass(), tearDownClass(), setUp(), and tearDown(),
1428 among other things.
1429
1430 Important things for test class writers:
1431
1432 - Overwrite the mydir class attribute, otherwise your test class won't
1433 run. It specifies the relative directory to the top level 'test' so
1434 the test harness can change to the correct working directory before
1435 running your test.
1436
1437 - The setUp method sets up things to facilitate subsequent interactions
1438 with the debugger as part of the test. These include:
1439 - populate the test method name
1440 - create/get a debugger set with synchronous mode (self.dbg)
1441 - get the command interpreter from with the debugger (self.ci)
1442 - create a result object for use with the command interpreter
1443 (self.res)
1444 - plus other stuffs
1445
1446 - The tearDown method tries to perform some necessary cleanup on behalf
1447 of the test to return the debugger to a good state for the next test.
1448 These include:
1449 - execute any tearDown hooks registered by the test method with
1450 TestBase.addTearDownHook(); examples can be found in
1451 settings/TestSettings.py
1452 - kill the inferior process associated with each target, if any,
1453 and, then delete the target from the debugger's target list
1454 - perform build cleanup before running the next test method in the
1455 same test class; examples of registering for this service can be
1456 found in types/TestIntegerTypes.py with the call:
1457 - self.setTearDownCleanup(dictionary=d)
1458
1459 - Similarly setUpClass and tearDownClass perform classwise setup and
1460 teardown fixtures. The tearDownClass method invokes a default build
1461 cleanup for the entire test class; also, subclasses can implement the
1462 classmethod classCleanup(cls) to perform special class cleanup action.
1463
1464 - The instance methods runCmd and expect are used heavily by existing
1465 test cases to send a command to the command interpreter and to perform
1466 string/pattern matching on the output of such command execution. The
1467 expect method also provides a mode to peform string/pattern matching
1468 without running a command.
1469
1470 - The build methods buildDefault, buildDsym, and buildDwarf are used to
1471 build the binaries used during a particular test scenario. A plugin
1472 should be provided for the sys.platform running the test suite. The
1473 Mac OS X implementation is located in plugins/darwin.py.
1474 """
1475
1476 # Maximum allowed attempts when launching the inferior process.
1477 # Can be overridden by the LLDB_MAX_LAUNCH_COUNT environment variable.
1478 maxLaunchCount = 3;
1479
1480 # Time to wait before the next launching attempt in second(s).
1481 # Can be overridden by the LLDB_TIME_WAIT_NEXT_LAUNCH environment variable.
1482 timeWaitNextLaunch = 1.0;
1483
1484 def doDelay(self):
1485 """See option -w of dotest.py."""
1486 if ("LLDB_WAIT_BETWEEN_TEST_CASES" in os.environ and
1487 os.environ["LLDB_WAIT_BETWEEN_TEST_CASES"] == 'YES'):
1488 waitTime = 1.0
1489 if "LLDB_TIME_WAIT_BETWEEN_TEST_CASES" in os.environ:
1490 waitTime = float(os.environ["LLDB_TIME_WAIT_BETWEEN_TEST_CASES"])
1491 time.sleep(waitTime)
1492
Enrico Granata165f8af2012-09-21 19:10:53 +00001493 # Returns the list of categories to which this test case belongs
1494 # by default, look for a ".categories" file, and read its contents
1495 # if no such file exists, traverse the hierarchy - we guarantee
1496 # a .categories to exist at the top level directory so we do not end up
1497 # looping endlessly - subclasses are free to define their own categories
1498 # in whatever way makes sense to them
1499 def getCategories(self):
1500 import inspect
1501 import os.path
1502 folder = inspect.getfile(self.__class__)
1503 folder = os.path.dirname(folder)
1504 while folder != '/':
1505 categories_file_name = os.path.join(folder,".categories")
1506 if os.path.exists(categories_file_name):
1507 categories_file = open(categories_file_name,'r')
1508 categories = categories_file.readline()
1509 categories_file.close()
1510 categories = str.replace(categories,'\n','')
1511 categories = str.replace(categories,'\r','')
1512 return categories.split(',')
1513 else:
1514 folder = os.path.dirname(folder)
1515 continue
1516
Johnny Chena74bb0a2011-08-01 18:46:13 +00001517 def setUp(self):
1518 #import traceback
1519 #traceback.print_stack()
1520
1521 # Works with the test driver to conditionally skip tests via decorators.
1522 Base.setUp(self)
1523
Johnny Chena74bb0a2011-08-01 18:46:13 +00001524 try:
1525 if lldb.blacklist:
1526 className = self.__class__.__name__
1527 classAndMethodName = "%s.%s" % (className, self._testMethodName)
1528 if className in lldb.blacklist:
1529 self.skipTest(lldb.blacklist.get(className))
1530 elif classAndMethodName in lldb.blacklist:
1531 self.skipTest(lldb.blacklist.get(classAndMethodName))
1532 except AttributeError:
1533 pass
1534
Johnny Chened492022011-06-21 00:53:00 +00001535 # Insert some delay between successive test cases if specified.
1536 self.doDelay()
Johnny Chen0ed37c92010-10-07 02:04:14 +00001537
Johnny Chenf2b70232010-08-25 18:49:48 +00001538 if "LLDB_MAX_LAUNCH_COUNT" in os.environ:
1539 self.maxLaunchCount = int(os.environ["LLDB_MAX_LAUNCH_COUNT"])
1540
Johnny Chen430eb762010-10-19 16:00:42 +00001541 if "LLDB_TIME_WAIT_NEXT_LAUNCH" in os.environ:
Johnny Chen4921b112010-11-29 20:20:34 +00001542 self.timeWaitNextLaunch = float(os.environ["LLDB_TIME_WAIT_NEXT_LAUNCH"])
Johnny Chenf2b70232010-08-25 18:49:48 +00001543
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001544 # Create the debugger instance if necessary.
1545 try:
1546 self.dbg = lldb.DBG
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001547 except AttributeError:
1548 self.dbg = lldb.SBDebugger.Create()
Johnny Chenf02ec122010-07-03 20:41:42 +00001549
Johnny Chen3cd1e552011-05-25 19:06:18 +00001550 if not self.dbg:
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001551 raise Exception('Invalid debugger instance')
1552
Daniel Maleae0f8f572013-08-26 23:57:52 +00001553 #
1554 # Warning: MAJOR HACK AHEAD!
1555 # If we are running testsuite remotely (by checking lldb.lldbtest_remote_sandbox),
1556 # redefine the self.dbg.CreateTarget(filename) method to execute a "file filename"
1557 # command, instead. See also runCmd() where it decorates the "file filename" call
1558 # with additional functionality when running testsuite remotely.
1559 #
1560 if lldb.lldbtest_remote_sandbox:
1561 def DecoratedCreateTarget(arg):
1562 self.runCmd("file %s" % arg)
1563 target = self.dbg.GetSelectedTarget()
1564 #
Greg Claytonc6947512013-12-13 19:18:59 +00001565 # SBtarget.LaunchSimple () currently not working for remote platform?
Daniel Maleae0f8f572013-08-26 23:57:52 +00001566 # johnny @ 04/23/2012
1567 #
1568 def DecoratedLaunchSimple(argv, envp, wd):
1569 self.runCmd("run")
1570 return target.GetProcess()
1571 target.LaunchSimple = DecoratedLaunchSimple
1572
1573 return target
1574 self.dbg.CreateTarget = DecoratedCreateTarget
1575 if self.TraceOn():
1576 print "self.dbg.Create is redefined to:\n%s" % getsource_if_available(DecoratedCreateTarget)
1577
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001578 # We want our debugger to be synchronous.
1579 self.dbg.SetAsync(False)
1580
1581 # Retrieve the associated command interpreter instance.
1582 self.ci = self.dbg.GetCommandInterpreter()
1583 if not self.ci:
1584 raise Exception('Could not get the command interpreter')
1585
1586 # And the result object.
1587 self.res = lldb.SBCommandReturnObject()
1588
Johnny Chen44d24972012-04-16 18:55:15 +00001589 # Run global pre-flight code, if defined via the config file.
1590 if lldb.pre_flight:
1591 lldb.pre_flight(self)
1592
Greg Claytonfb909312013-11-23 01:58:15 +00001593 if lldb.remote_platform:
1594 #remote_test_dir = os.path.join(lldb.remote_platform_working_dir, self.mydir)
Greg Clayton5fb8f792013-12-02 19:35:49 +00001595 remote_test_dir = os.path.join(lldb.remote_platform_working_dir,
1596 self.getArchitecture(),
1597 str(self.test_number),
1598 self.mydir)
Greg Claytonfb909312013-11-23 01:58:15 +00001599 error = lldb.remote_platform.MakeDirectory(remote_test_dir, 0700)
1600 if error.Success():
Greg Claytonfb909312013-11-23 01:58:15 +00001601 lldb.remote_platform.SetWorkingDirectory(remote_test_dir)
1602 else:
1603 print "error: making remote directory '%s': %s" % (remote_test_dir, error)
1604
Enrico Granata44818162012-10-24 01:23:57 +00001605 # utility methods that tests can use to access the current objects
1606 def target(self):
1607 if not self.dbg:
1608 raise Exception('Invalid debugger instance')
1609 return self.dbg.GetSelectedTarget()
1610
1611 def process(self):
1612 if not self.dbg:
1613 raise Exception('Invalid debugger instance')
1614 return self.dbg.GetSelectedTarget().GetProcess()
1615
1616 def thread(self):
1617 if not self.dbg:
1618 raise Exception('Invalid debugger instance')
1619 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread()
1620
1621 def frame(self):
1622 if not self.dbg:
1623 raise Exception('Invalid debugger instance')
1624 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame()
1625
Greg Claytonc6947512013-12-13 19:18:59 +00001626 def get_process_working_directory(self):
1627 '''Get the working directory that should be used when launching processes for local or remote processes.'''
1628 if lldb.remote_platform:
1629 # Remote tests set the platform working directory up in TestBase.setUp()
1630 return lldb.remote_platform.GetWorkingDirectory()
1631 else:
1632 # local tests change directory into each test subdirectory
1633 return os.getcwd()
1634
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001635 def tearDown(self):
Johnny Chen7d1d7532010-09-02 21:23:12 +00001636 #import traceback
1637 #traceback.print_stack()
1638
Johnny Chenfb4264c2011-08-01 19:50:58 +00001639 Base.tearDown(self)
Johnny Chen707d8222010-10-19 23:40:13 +00001640
Johnny Chen3794ad92011-06-15 21:24:24 +00001641 # Delete the target(s) from the debugger as a general cleanup step.
1642 # This includes terminating the process for each target, if any.
1643 # We'd like to reuse the debugger for our next test without incurring
1644 # the initialization overhead.
1645 targets = []
1646 for target in self.dbg:
1647 if target:
1648 targets.append(target)
1649 process = target.GetProcess()
1650 if process:
1651 rc = self.invoke(process, "Kill")
1652 self.assertTrue(rc.Success(), PROCESS_KILLED)
1653 for target in targets:
1654 self.dbg.DeleteTarget(target)
Johnny Chen6ca006c2010-08-16 21:28:10 +00001655
Johnny Chen44d24972012-04-16 18:55:15 +00001656 # Run global post-flight code, if defined via the config file.
1657 if lldb.post_flight:
1658 lldb.post_flight(self)
1659
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001660 del self.dbg
Johnny Chen150c3cc2010-10-15 01:18:29 +00001661
Johnny Chen86268e42011-09-30 21:48:35 +00001662 def switch_to_thread_with_stop_reason(self, stop_reason):
1663 """
1664 Run the 'thread list' command, and select the thread with stop reason as
1665 'stop_reason'. If no such thread exists, no select action is done.
1666 """
1667 from lldbutil import stop_reason_to_str
1668 self.runCmd('thread list')
1669 output = self.res.GetOutput()
1670 thread_line_pattern = re.compile("^[ *] thread #([0-9]+):.*stop reason = %s" %
1671 stop_reason_to_str(stop_reason))
1672 for line in output.splitlines():
1673 matched = thread_line_pattern.match(line)
1674 if matched:
1675 self.runCmd('thread select %s' % matched.group(1))
1676
Enrico Granata7594f142013-06-17 22:51:50 +00001677 def runCmd(self, cmd, msg=None, check=True, trace=False, inHistory=False):
Johnny Chen27f212d2010-08-19 23:26:59 +00001678 """
1679 Ask the command interpreter to handle the command and then check its
1680 return status.
1681 """
1682 # Fail fast if 'cmd' is not meaningful.
1683 if not cmd or len(cmd) == 0:
1684 raise Exception("Bad 'cmd' parameter encountered")
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001685
Johnny Chen8d55a342010-08-31 17:42:54 +00001686 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00001687
Daniel Maleae0f8f572013-08-26 23:57:52 +00001688 # This is an opportunity to insert the 'platform target-install' command if we are told so
1689 # via the settig of lldb.lldbtest_remote_sandbox.
1690 if cmd.startswith("target create "):
1691 cmd = cmd.replace("target create ", "file ")
1692 if cmd.startswith("file ") and lldb.lldbtest_remote_sandbox:
1693 with recording(self, trace) as sbuf:
1694 the_rest = cmd.split("file ")[1]
1695 # Split the rest of the command line.
1696 atoms = the_rest.split()
1697 #
1698 # NOTE: This assumes that the options, if any, follow the file command,
1699 # instead of follow the specified target.
1700 #
1701 target = atoms[-1]
1702 # Now let's get the absolute pathname of our target.
1703 abs_target = os.path.abspath(target)
1704 print >> sbuf, "Found a file command, target (with absolute pathname)=%s" % abs_target
1705 fpath, fname = os.path.split(abs_target)
1706 parent_dir = os.path.split(fpath)[0]
1707 platform_target_install_command = 'platform target-install %s %s' % (fpath, lldb.lldbtest_remote_sandbox)
1708 print >> sbuf, "Insert this command to be run first: %s" % platform_target_install_command
1709 self.ci.HandleCommand(platform_target_install_command, self.res)
1710 # And this is the file command we want to execute, instead.
1711 #
1712 # Warning: SIDE EFFECT AHEAD!!!
1713 # Populate the remote executable pathname into the lldb namespace,
1714 # so that test cases can grab this thing out of the namespace.
1715 #
1716 lldb.lldbtest_remote_sandboxed_executable = abs_target.replace(parent_dir, lldb.lldbtest_remote_sandbox)
1717 cmd = "file -P %s %s %s" % (lldb.lldbtest_remote_sandboxed_executable, the_rest.replace(target, ''), abs_target)
1718 print >> sbuf, "And this is the replaced file command: %s" % cmd
1719
Johnny Chen63dfb272010-09-01 00:15:19 +00001720 running = (cmd.startswith("run") or cmd.startswith("process launch"))
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001721
Johnny Chen63dfb272010-09-01 00:15:19 +00001722 for i in range(self.maxLaunchCount if running else 1):
Enrico Granata7594f142013-06-17 22:51:50 +00001723 self.ci.HandleCommand(cmd, self.res, inHistory)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001724
Johnny Chen150c3cc2010-10-15 01:18:29 +00001725 with recording(self, trace) as sbuf:
1726 print >> sbuf, "runCmd:", cmd
Johnny Chenab254f52010-10-15 16:13:00 +00001727 if not check:
Johnny Chen27b107b2010-10-15 18:52:22 +00001728 print >> sbuf, "check of return status not required"
Johnny Chenf2b70232010-08-25 18:49:48 +00001729 if self.res.Succeeded():
Johnny Chen150c3cc2010-10-15 01:18:29 +00001730 print >> sbuf, "output:", self.res.GetOutput()
Johnny Chenf2b70232010-08-25 18:49:48 +00001731 else:
Johnny Chen150c3cc2010-10-15 01:18:29 +00001732 print >> sbuf, "runCmd failed!"
1733 print >> sbuf, self.res.GetError()
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001734
Johnny Chenff3d01d2010-08-20 21:03:09 +00001735 if self.res.Succeeded():
Johnny Chenf2b70232010-08-25 18:49:48 +00001736 break
Johnny Chen150c3cc2010-10-15 01:18:29 +00001737 elif running:
Johnny Chencf7f74e2011-01-19 02:02:08 +00001738 # For process launch, wait some time before possible next try.
1739 time.sleep(self.timeWaitNextLaunch)
Johnny Chen552d6712012-08-01 19:56:04 +00001740 with recording(self, trace) as sbuf:
Johnny Chen150c3cc2010-10-15 01:18:29 +00001741 print >> sbuf, "Command '" + cmd + "' failed!"
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001742
Johnny Chen27f212d2010-08-19 23:26:59 +00001743 if check:
1744 self.assertTrue(self.res.Succeeded(),
Johnny Chenc0c67f22010-11-09 18:42:22 +00001745 msg if msg else CMD_MSG(cmd))
Johnny Chen27f212d2010-08-19 23:26:59 +00001746
Jim Ingham63dfc722012-09-22 00:05:11 +00001747 def match (self, str, patterns, msg=None, trace=False, error=False, matching=True, exe=True):
1748 """run command in str, and match the result against regexp in patterns returning the match object for the first matching pattern
1749
1750 Otherwise, all the arguments have the same meanings as for the expect function"""
1751
1752 trace = (True if traceAlways else trace)
1753
1754 if exe:
1755 # First run the command. If we are expecting error, set check=False.
1756 # Pass the assert message along since it provides more semantic info.
1757 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error)
1758
1759 # Then compare the output against expected strings.
1760 output = self.res.GetError() if error else self.res.GetOutput()
1761
1762 # If error is True, the API client expects the command to fail!
1763 if error:
1764 self.assertFalse(self.res.Succeeded(),
1765 "Command '" + str + "' is expected to fail!")
1766 else:
1767 # No execution required, just compare str against the golden input.
1768 output = str
1769 with recording(self, trace) as sbuf:
1770 print >> sbuf, "looking at:", output
1771
1772 # The heading says either "Expecting" or "Not expecting".
1773 heading = "Expecting" if matching else "Not expecting"
1774
1775 for pattern in patterns:
1776 # Match Objects always have a boolean value of True.
1777 match_object = re.search(pattern, output)
1778 matched = bool(match_object)
1779 with recording(self, trace) as sbuf:
1780 print >> sbuf, "%s pattern: %s" % (heading, pattern)
1781 print >> sbuf, "Matched" if matched else "Not matched"
1782 if matched:
1783 break
1784
1785 self.assertTrue(matched if matching else not matched,
1786 msg if msg else EXP_MSG(str, exe))
1787
1788 return match_object
1789
Enrico Granata7594f142013-06-17 22:51:50 +00001790 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 +00001791 """
1792 Similar to runCmd; with additional expect style output matching ability.
1793
1794 Ask the command interpreter to handle the command and then check its
1795 return status. The 'msg' parameter specifies an informational assert
1796 message. We expect the output from running the command to start with
Johnny Chenea88e942010-09-21 21:08:53 +00001797 'startstr', matches the substrings contained in 'substrs', and regexp
1798 matches the patterns contained in 'patterns'.
Johnny Chenb3307862010-09-17 22:28:51 +00001799
1800 If the keyword argument error is set to True, it signifies that the API
1801 client is expecting the command to fail. In this case, the error stream
Johnny Chenaa902922010-09-17 22:45:27 +00001802 from running the command is retrieved and compared against the golden
Johnny Chenb3307862010-09-17 22:28:51 +00001803 input, instead.
Johnny Chenea88e942010-09-21 21:08:53 +00001804
1805 If the keyword argument matching is set to False, it signifies that the API
1806 client is expecting the output of the command not to match the golden
1807 input.
Johnny Chen9c48b8d2010-09-21 23:33:30 +00001808
1809 Finally, the required argument 'str' represents the lldb command to be
1810 sent to the command interpreter. In case the keyword argument 'exe' is
1811 set to False, the 'str' is treated as a string to be matched/not-matched
1812 against the golden input.
Johnny Chen27f212d2010-08-19 23:26:59 +00001813 """
Johnny Chen8d55a342010-08-31 17:42:54 +00001814 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00001815
Johnny Chen9c48b8d2010-09-21 23:33:30 +00001816 if exe:
1817 # First run the command. If we are expecting error, set check=False.
Johnny Chen62d4f862010-10-28 21:10:32 +00001818 # Pass the assert message along since it provides more semantic info.
Enrico Granata7594f142013-06-17 22:51:50 +00001819 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error, inHistory=inHistory)
Johnny Chen27f212d2010-08-19 23:26:59 +00001820
Johnny Chen9c48b8d2010-09-21 23:33:30 +00001821 # Then compare the output against expected strings.
1822 output = self.res.GetError() if error else self.res.GetOutput()
Johnny Chenb3307862010-09-17 22:28:51 +00001823
Johnny Chen9c48b8d2010-09-21 23:33:30 +00001824 # If error is True, the API client expects the command to fail!
1825 if error:
1826 self.assertFalse(self.res.Succeeded(),
1827 "Command '" + str + "' is expected to fail!")
1828 else:
1829 # No execution required, just compare str against the golden input.
Enrico Granatabc08ab42012-10-23 00:09:02 +00001830 if isinstance(str,lldb.SBCommandReturnObject):
1831 output = str.GetOutput()
1832 else:
1833 output = str
Johnny Chen150c3cc2010-10-15 01:18:29 +00001834 with recording(self, trace) as sbuf:
1835 print >> sbuf, "looking at:", output
Johnny Chenb3307862010-09-17 22:28:51 +00001836
Johnny Chenea88e942010-09-21 21:08:53 +00001837 # The heading says either "Expecting" or "Not expecting".
Johnny Chen150c3cc2010-10-15 01:18:29 +00001838 heading = "Expecting" if matching else "Not expecting"
Johnny Chenea88e942010-09-21 21:08:53 +00001839
1840 # Start from the startstr, if specified.
1841 # If there's no startstr, set the initial state appropriately.
1842 matched = output.startswith(startstr) if startstr else (True if matching else False)
Johnny Chenb145bba2010-08-20 18:25:15 +00001843
Johnny Chen150c3cc2010-10-15 01:18:29 +00001844 if startstr:
1845 with recording(self, trace) as sbuf:
1846 print >> sbuf, "%s start string: %s" % (heading, startstr)
1847 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenb145bba2010-08-20 18:25:15 +00001848
Johnny Chen86268e42011-09-30 21:48:35 +00001849 # Look for endstr, if specified.
1850 keepgoing = matched if matching else not matched
1851 if endstr:
1852 matched = output.endswith(endstr)
1853 with recording(self, trace) as sbuf:
1854 print >> sbuf, "%s end string: %s" % (heading, endstr)
1855 print >> sbuf, "Matched" if matched else "Not matched"
1856
Johnny Chenea88e942010-09-21 21:08:53 +00001857 # Look for sub strings, if specified.
1858 keepgoing = matched if matching else not matched
1859 if substrs and keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00001860 for str in substrs:
Johnny Chenb052f6c2010-09-23 23:35:28 +00001861 matched = output.find(str) != -1
Johnny Chen150c3cc2010-10-15 01:18:29 +00001862 with recording(self, trace) as sbuf:
1863 print >> sbuf, "%s sub string: %s" % (heading, str)
1864 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenea88e942010-09-21 21:08:53 +00001865 keepgoing = matched if matching else not matched
1866 if not keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00001867 break
1868
Johnny Chenea88e942010-09-21 21:08:53 +00001869 # Search for regular expression patterns, if specified.
1870 keepgoing = matched if matching else not matched
1871 if patterns and keepgoing:
1872 for pattern in patterns:
1873 # Match Objects always have a boolean value of True.
1874 matched = bool(re.search(pattern, output))
Johnny Chen150c3cc2010-10-15 01:18:29 +00001875 with recording(self, trace) as sbuf:
1876 print >> sbuf, "%s pattern: %s" % (heading, pattern)
1877 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenea88e942010-09-21 21:08:53 +00001878 keepgoing = matched if matching else not matched
1879 if not keepgoing:
1880 break
Johnny Chenea88e942010-09-21 21:08:53 +00001881
1882 self.assertTrue(matched if matching else not matched,
Johnny Chenc0c67f22010-11-09 18:42:22 +00001883 msg if msg else EXP_MSG(str, exe))
Johnny Chen27f212d2010-08-19 23:26:59 +00001884
Johnny Chenf3c59232010-08-25 22:52:45 +00001885 def invoke(self, obj, name, trace=False):
Johnny Chen61703c92010-08-25 22:56:10 +00001886 """Use reflection to call a method dynamically with no argument."""
Johnny Chen8d55a342010-08-31 17:42:54 +00001887 trace = (True if traceAlways else trace)
Johnny Chenf3c59232010-08-25 22:52:45 +00001888
1889 method = getattr(obj, name)
1890 import inspect
1891 self.assertTrue(inspect.ismethod(method),
1892 name + "is a method name of object: " + str(obj))
1893 result = method()
Johnny Chen150c3cc2010-10-15 01:18:29 +00001894 with recording(self, trace) as sbuf:
1895 print >> sbuf, str(method) + ":", result
Johnny Chenf3c59232010-08-25 22:52:45 +00001896 return result
Johnny Chen827edff2010-08-27 00:15:48 +00001897
Johnny Chenf359cf22011-05-27 23:36:52 +00001898 # =================================================
1899 # Misc. helper methods for debugging test execution
1900 # =================================================
1901
Johnny Chen56b92a72011-07-11 19:15:11 +00001902 def DebugSBValue(self, val):
Johnny Chen8d55a342010-08-31 17:42:54 +00001903 """Debug print a SBValue object, if traceAlways is True."""
Johnny Chende90f1d2011-04-27 17:43:07 +00001904 from lldbutil import value_type_to_str
Johnny Chen87bb5892010-11-03 21:37:58 +00001905
Johnny Chen8d55a342010-08-31 17:42:54 +00001906 if not traceAlways:
Johnny Chen827edff2010-08-27 00:15:48 +00001907 return
1908
1909 err = sys.stderr
1910 err.write(val.GetName() + ":\n")
Johnny Chen86268e42011-09-30 21:48:35 +00001911 err.write('\t' + "TypeName -> " + val.GetTypeName() + '\n')
1912 err.write('\t' + "ByteSize -> " + str(val.GetByteSize()) + '\n')
1913 err.write('\t' + "NumChildren -> " + str(val.GetNumChildren()) + '\n')
1914 err.write('\t' + "Value -> " + str(val.GetValue()) + '\n')
1915 err.write('\t' + "ValueAsUnsigned -> " + str(val.GetValueAsUnsigned())+ '\n')
1916 err.write('\t' + "ValueType -> " + value_type_to_str(val.GetValueType()) + '\n')
1917 err.write('\t' + "Summary -> " + str(val.GetSummary()) + '\n')
1918 err.write('\t' + "IsPointerType -> " + str(val.TypeIsPointerType()) + '\n')
1919 err.write('\t' + "Location -> " + val.GetLocation() + '\n')
Johnny Chen827edff2010-08-27 00:15:48 +00001920
Johnny Chen36c5eb12011-08-05 20:17:27 +00001921 def DebugSBType(self, type):
1922 """Debug print a SBType object, if traceAlways is True."""
1923 if not traceAlways:
1924 return
1925
1926 err = sys.stderr
1927 err.write(type.GetName() + ":\n")
1928 err.write('\t' + "ByteSize -> " + str(type.GetByteSize()) + '\n')
1929 err.write('\t' + "IsPointerType -> " + str(type.IsPointerType()) + '\n')
1930 err.write('\t' + "IsReferenceType -> " + str(type.IsReferenceType()) + '\n')
1931
Johnny Chenb877f1e2011-03-12 01:18:19 +00001932 def DebugPExpect(self, child):
1933 """Debug the spwaned pexpect object."""
1934 if not traceAlways:
1935 return
1936
1937 print child
Filipe Cabecinhas0eec15a2012-06-20 10:13:40 +00001938
1939 @classmethod
1940 def RemoveTempFile(cls, file):
1941 if os.path.exists(file):
1942 os.remove(file)