blob: be34f70b5ae88b220e8c9f7b54148ab717c15a7a [file] [log] [blame]
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001"""
2LLDB module which provides the abstract base class of lldb test case.
3
4The concrete subclass can override lldbtest.TesBase in order to inherit the
5common behavior for unitest.TestCase.setUp/tearDown implemented in this file.
6
7The subclass should override the attribute mydir in order for the python runtime
8to locate the individual test cases when running as part of a large test suite
9or when running each test case as a separate python invocation.
10
11./dotest.py provides a test driver which sets up the environment to run the
Johnny Chenc98892e2012-05-16 20:41:28 +000012entire of part of the test suite . Example:
Johnny Chenbf6ffa32010-07-03 03:41:59 +000013
Johnny Chenc98892e2012-05-16 20:41:28 +000014# Exercises the test suite in the types directory....
15/Volumes/data/lldb/svn/ToT/test $ ./dotest.py -A x86_64 types
Johnny Chen57b47382010-09-02 22:25:47 +000016...
Johnny Chend0190a62010-08-23 17:10:44 +000017
Johnny Chenc98892e2012-05-16 20:41:28 +000018Session logs for test failures/errors/unexpected successes will go into directory '2012-05-16-13_35_42'
19Command invoked: python ./dotest.py -A x86_64 types
20compilers=['clang']
Johnny Chend0190a62010-08-23 17:10:44 +000021
Johnny Chenc98892e2012-05-16 20:41:28 +000022Configuration: arch=x86_64 compiler=clang
Johnny Chend0190a62010-08-23 17:10:44 +000023----------------------------------------------------------------------
Johnny Chenc98892e2012-05-16 20:41:28 +000024Collected 72 tests
25
26........................................................................
27----------------------------------------------------------------------
28Ran 72 tests in 135.468s
Johnny Chend0190a62010-08-23 17:10:44 +000029
30OK
Johnny Chenbf6ffa32010-07-03 03:41:59 +000031$
32"""
33
Johnny Chen90312a82010-09-21 22:34:45 +000034import os, sys, traceback
Enrico Granata7e137e32012-10-24 18:14:21 +000035import os.path
Johnny Chenea88e942010-09-21 21:08:53 +000036import re
Daniel Malea69207462013-06-05 21:07:02 +000037import signal
Johnny Chen8952a2d2010-08-30 21:35:00 +000038from subprocess import *
Johnny Chen150c3cc2010-10-15 01:18:29 +000039import StringIO
Johnny Chenf2b70232010-08-25 18:49:48 +000040import time
Johnny Chena33a93c2010-08-30 23:08:52 +000041import types
Johnny Chen73258832010-08-05 23:42:46 +000042import unittest2
Johnny Chenbf6ffa32010-07-03 03:41:59 +000043import lldb
44
Johnny Chen707b3c92010-10-11 22:25:46 +000045# See also dotest.parseOptionsAndInitTestdirs(), where the environment variables
Johnny Chend2047fa2011-01-19 18:18:47 +000046# LLDB_COMMAND_TRACE and LLDB_DO_CLEANUP are set from '-t' and '-r dir' options.
Johnny Chen707b3c92010-10-11 22:25:46 +000047
48# By default, traceAlways is False.
Johnny Chen8d55a342010-08-31 17:42:54 +000049if "LLDB_COMMAND_TRACE" in os.environ and os.environ["LLDB_COMMAND_TRACE"]=="YES":
50 traceAlways = True
51else:
52 traceAlways = False
53
Johnny Chen707b3c92010-10-11 22:25:46 +000054# By default, doCleanup is True.
55if "LLDB_DO_CLEANUP" in os.environ and os.environ["LLDB_DO_CLEANUP"]=="NO":
56 doCleanup = False
57else:
58 doCleanup = True
59
Johnny Chen8d55a342010-08-31 17:42:54 +000060
Johnny Chen00778092010-08-09 22:01:17 +000061#
62# Some commonly used assert messages.
63#
64
Johnny Chenaa902922010-09-17 22:45:27 +000065COMMAND_FAILED_AS_EXPECTED = "Command has failed as expected"
66
Johnny Chen00778092010-08-09 22:01:17 +000067CURRENT_EXECUTABLE_SET = "Current executable set successfully"
68
Johnny Chen7d1d7532010-09-02 21:23:12 +000069PROCESS_IS_VALID = "Process is valid"
70
71PROCESS_KILLED = "Process is killed successfully"
72
Johnny Chend5f66fc2010-12-23 01:12:19 +000073PROCESS_EXITED = "Process exited successfully"
74
75PROCESS_STOPPED = "Process status should be stopped"
76
Johnny Chen5ee88192010-08-27 23:47:36 +000077RUN_SUCCEEDED = "Process is launched successfully"
Johnny Chen00778092010-08-09 22:01:17 +000078
Johnny Chen17941842010-08-09 23:44:24 +000079RUN_COMPLETED = "Process exited successfully"
Johnny Chen00778092010-08-09 22:01:17 +000080
Johnny Chen67af43f2010-10-05 19:27:32 +000081BACKTRACE_DISPLAYED_CORRECTLY = "Backtrace displayed correctly"
82
Johnny Chen17941842010-08-09 23:44:24 +000083BREAKPOINT_CREATED = "Breakpoint created successfully"
84
Johnny Chenf10af382010-12-04 00:07:24 +000085BREAKPOINT_STATE_CORRECT = "Breakpoint state is correct"
86
Johnny Chene76896c2010-08-17 21:33:31 +000087BREAKPOINT_PENDING_CREATED = "Pending breakpoint created successfully"
88
Johnny Chen17941842010-08-09 23:44:24 +000089BREAKPOINT_HIT_ONCE = "Breakpoint resolved with hit cout = 1"
Johnny Chen00778092010-08-09 22:01:17 +000090
Johnny Chen703dbd02010-09-30 17:06:24 +000091BREAKPOINT_HIT_TWICE = "Breakpoint resolved with hit cout = 2"
92
Johnny Chen164f1e12010-10-15 18:07:09 +000093BREAKPOINT_HIT_THRICE = "Breakpoint resolved with hit cout = 3"
94
Greg Clayton5db6b792012-10-24 18:24:14 +000095MISSING_EXPECTED_REGISTERS = "At least one expected register is unavailable."
96
Johnny Chen89109ed12011-06-27 20:05:23 +000097OBJECT_PRINTED_CORRECTLY = "Object printed correctly"
98
Johnny Chen5b3a3572010-12-09 18:22:12 +000099SOURCE_DISPLAYED_CORRECTLY = "Source code displayed correctly"
100
Johnny Chenc70b02a2010-09-22 23:00:20 +0000101STEP_OUT_SUCCEEDED = "Thread step-out succeeded"
102
Johnny Chen1691a162011-04-15 16:44:48 +0000103STOPPED_DUE_TO_EXC_BAD_ACCESS = "Process should be stopped due to bad access exception"
104
Ashok Thirumurthib4e51342013-05-17 15:35:15 +0000105STOPPED_DUE_TO_ASSERT = "Process should be stopped due to an assertion"
106
Johnny Chen5d6c4642010-11-10 23:46:38 +0000107STOPPED_DUE_TO_BREAKPOINT = "Process should be stopped due to breakpoint"
Johnny Chende0338b2010-11-10 20:20:06 +0000108
Johnny Chen5d6c4642010-11-10 23:46:38 +0000109STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS = "%s, %s" % (
110 STOPPED_DUE_TO_BREAKPOINT, "instead, the actual stop reason is: '%s'")
Johnny Chen00778092010-08-09 22:01:17 +0000111
Johnny Chen2e431ce2010-10-20 18:38:48 +0000112STOPPED_DUE_TO_BREAKPOINT_CONDITION = "Stopped due to breakpoint condition"
113
Johnny Chen0a3d1ca2010-12-13 21:49:58 +0000114STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT = "Stopped due to breakpoint and ignore count"
115
Johnny Chenc066ab42010-10-14 01:22:03 +0000116STOPPED_DUE_TO_SIGNAL = "Process state is stopped due to signal"
117
Johnny Chen00778092010-08-09 22:01:17 +0000118STOPPED_DUE_TO_STEP_IN = "Process state is stopped due to step in"
119
Johnny Chenf68cc122011-09-15 21:09:59 +0000120STOPPED_DUE_TO_WATCHPOINT = "Process should be stopped due to watchpoint"
121
Johnny Chen3c884a02010-08-24 22:07:56 +0000122DATA_TYPES_DISPLAYED_CORRECTLY = "Data type(s) displayed correctly"
123
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000124VALID_BREAKPOINT = "Got a valid breakpoint"
125
Johnny Chen5bfb8ee2010-10-22 18:10:25 +0000126VALID_BREAKPOINT_LOCATION = "Got a valid breakpoint location"
127
Johnny Chen7209d84f2011-05-06 23:26:12 +0000128VALID_COMMAND_INTERPRETER = "Got a valid command interpreter"
129
Johnny Chen5ee88192010-08-27 23:47:36 +0000130VALID_FILESPEC = "Got a valid filespec"
131
Johnny Chen025d1b82010-12-08 01:25:21 +0000132VALID_MODULE = "Got a valid module"
133
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000134VALID_PROCESS = "Got a valid process"
135
Johnny Chen025d1b82010-12-08 01:25:21 +0000136VALID_SYMBOL = "Got a valid symbol"
137
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000138VALID_TARGET = "Got a valid target"
139
Johnny Chen15f247a2012-02-03 20:43:00 +0000140VALID_TYPE = "Got a valid type"
141
Johnny Chen5819ab42011-07-15 22:28:10 +0000142VALID_VARIABLE = "Got a valid variable"
143
Johnny Chen981463d2010-08-25 19:00:04 +0000144VARIABLES_DISPLAYED_CORRECTLY = "Variable(s) displayed correctly"
Johnny Chen00778092010-08-09 22:01:17 +0000145
Johnny Chenf68cc122011-09-15 21:09:59 +0000146WATCHPOINT_CREATED = "Watchpoint created successfully"
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000147
Johnny Chenc0c67f22010-11-09 18:42:22 +0000148def CMD_MSG(str):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000149 '''A generic "Command '%s' returns successfully" message generator.'''
Johnny Chenc0c67f22010-11-09 18:42:22 +0000150 return "Command '%s' returns successfully" % str
151
Johnny Chen3bc8ae42012-03-15 19:10:00 +0000152def COMPLETION_MSG(str_before, str_after):
Johnny Chen98aceb02012-01-20 23:02:51 +0000153 '''A generic message generator for the completion mechanism.'''
154 return "'%s' successfully completes to '%s'" % (str_before, str_after)
155
Johnny Chenc0c67f22010-11-09 18:42:22 +0000156def EXP_MSG(str, exe):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000157 '''A generic "'%s' returns expected result" message generator if exe.
158 Otherwise, it generates "'%s' matches expected result" message.'''
Johnny Chenc0c67f22010-11-09 18:42:22 +0000159 return "'%s' %s expected result" % (str, 'returns' if exe else 'matches')
Johnny Chen17941842010-08-09 23:44:24 +0000160
Johnny Chen3343f042010-10-19 19:11:38 +0000161def SETTING_MSG(setting):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000162 '''A generic "Value of setting '%s' is correct" message generator.'''
Johnny Chen3343f042010-10-19 19:11:38 +0000163 return "Value of setting '%s' is correct" % setting
164
Johnny Chen27c41232010-08-26 21:49:29 +0000165def EnvArray():
Johnny Chenaacf92e2011-05-31 22:16:51 +0000166 """Returns an env variable array from the os.environ map object."""
Johnny Chen27c41232010-08-26 21:49:29 +0000167 return map(lambda k,v: k+"="+v, os.environ.keys(), os.environ.values())
168
Johnny Chen47ceb032010-10-11 23:52:19 +0000169def line_number(filename, string_to_match):
170 """Helper function to return the line number of the first matched string."""
171 with open(filename, 'r') as f:
172 for i, line in enumerate(f):
173 if line.find(string_to_match) != -1:
174 # Found our match.
Johnny Chencd9b7772010-10-12 00:09:25 +0000175 return i+1
Johnny Chen1691a162011-04-15 16:44:48 +0000176 raise Exception("Unable to find '%s' within file %s" % (string_to_match, filename))
Johnny Chen47ceb032010-10-11 23:52:19 +0000177
Johnny Chen67af43f2010-10-05 19:27:32 +0000178def pointer_size():
179 """Return the pointer size of the host system."""
180 import ctypes
181 a_pointer = ctypes.c_void_p(0xffff)
182 return 8 * ctypes.sizeof(a_pointer)
183
Johnny Chen57816732012-02-09 02:01:59 +0000184def is_exe(fpath):
185 """Returns true if fpath is an executable."""
186 return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
187
188def which(program):
189 """Returns the full path to a program; None otherwise."""
190 fpath, fname = os.path.split(program)
191 if fpath:
192 if is_exe(program):
193 return program
194 else:
195 for path in os.environ["PATH"].split(os.pathsep):
196 exe_file = os.path.join(path, program)
197 if is_exe(exe_file):
198 return exe_file
199 return None
200
Johnny Chen150c3cc2010-10-15 01:18:29 +0000201class recording(StringIO.StringIO):
202 """
203 A nice little context manager for recording the debugger interactions into
204 our session object. If trace flag is ON, it also emits the interactions
205 into the stderr.
206 """
207 def __init__(self, test, trace):
Johnny Chen690fcef2010-10-15 23:55:05 +0000208 """Create a StringIO instance; record the session obj and trace flag."""
Johnny Chen150c3cc2010-10-15 01:18:29 +0000209 StringIO.StringIO.__init__(self)
Johnny Chen0241f142011-08-16 22:06:17 +0000210 # The test might not have undergone the 'setUp(self)' phase yet, so that
211 # the attribute 'session' might not even exist yet.
Johnny Chenbfcf37f2011-08-16 17:06:45 +0000212 self.session = getattr(test, "session", None) if test else None
Johnny Chen150c3cc2010-10-15 01:18:29 +0000213 self.trace = trace
214
215 def __enter__(self):
216 """
217 Context management protocol on entry to the body of the with statement.
218 Just return the StringIO object.
219 """
220 return self
221
222 def __exit__(self, type, value, tb):
223 """
224 Context management protocol on exit from the body of the with statement.
225 If trace is ON, it emits the recordings into stderr. Always add the
226 recordings to our session object. And close the StringIO object, too.
227 """
228 if self.trace:
Johnny Chen690fcef2010-10-15 23:55:05 +0000229 print >> sys.stderr, self.getvalue()
230 if self.session:
231 print >> self.session, self.getvalue()
Johnny Chen150c3cc2010-10-15 01:18:29 +0000232 self.close()
233
Johnny Chen690fcef2010-10-15 23:55:05 +0000234# From 2.7's subprocess.check_output() convenience function.
Johnny Chenac77f3b2011-03-23 20:28:59 +0000235# Return a tuple (stdoutdata, stderrdata).
Johnny Chen690fcef2010-10-15 23:55:05 +0000236def system(*popenargs, **kwargs):
Johnny Chen8eb14a92011-11-16 22:44:28 +0000237 r"""Run an os command with arguments and return its output as a byte string.
Johnny Chen690fcef2010-10-15 23:55:05 +0000238
239 If the exit code was non-zero it raises a CalledProcessError. The
240 CalledProcessError object will have the return code in the returncode
241 attribute and output in the output attribute.
242
243 The arguments are the same as for the Popen constructor. Example:
244
245 >>> check_output(["ls", "-l", "/dev/null"])
246 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
247
248 The stdout argument is not allowed as it is used internally.
249 To capture standard error in the result, use stderr=STDOUT.
250
251 >>> check_output(["/bin/sh", "-c",
252 ... "ls -l non_existent_file ; exit 0"],
253 ... stderr=STDOUT)
254 'ls: non_existent_file: No such file or directory\n'
255 """
256
257 # Assign the sender object to variable 'test' and remove it from kwargs.
258 test = kwargs.pop('sender', None)
259
260 if 'stdout' in kwargs:
261 raise ValueError('stdout argument not allowed, it will be overridden.')
Johnny Chenac77f3b2011-03-23 20:28:59 +0000262 process = Popen(stdout=PIPE, stderr=PIPE, *popenargs, **kwargs)
Johnny Chen0bd8c312011-11-16 22:41:53 +0000263 pid = process.pid
Johnny Chen690fcef2010-10-15 23:55:05 +0000264 output, error = process.communicate()
265 retcode = process.poll()
266
267 with recording(test, traceAlways) as sbuf:
268 if isinstance(popenargs, types.StringTypes):
269 args = [popenargs]
270 else:
271 args = list(popenargs)
272 print >> sbuf
273 print >> sbuf, "os command:", args
Johnny Chen0bd8c312011-11-16 22:41:53 +0000274 print >> sbuf, "with pid:", pid
Johnny Chen690fcef2010-10-15 23:55:05 +0000275 print >> sbuf, "stdout:", output
276 print >> sbuf, "stderr:", error
277 print >> sbuf, "retcode:", retcode
278 print >> sbuf
279
280 if retcode:
281 cmd = kwargs.get("args")
282 if cmd is None:
283 cmd = popenargs[0]
284 raise CalledProcessError(retcode, cmd)
Johnny Chenac77f3b2011-03-23 20:28:59 +0000285 return (output, error)
Johnny Chen690fcef2010-10-15 23:55:05 +0000286
Johnny Chenab9c1dd2010-11-01 20:35:01 +0000287def getsource_if_available(obj):
288 """
289 Return the text of the source code for an object if available. Otherwise,
290 a print representation is returned.
291 """
292 import inspect
293 try:
294 return inspect.getsource(obj)
295 except:
296 return repr(obj)
297
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000298def builder_module():
Ed Maste4d90f0f2013-07-25 13:24:34 +0000299 if sys.platform.startswith("freebsd"):
300 return __import__("builder_freebsd")
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000301 return __import__("builder_" + sys.platform)
302
Johnny Chena74bb0a2011-08-01 18:46:13 +0000303#
304# Decorators for categorizing test cases.
305#
306
307from functools import wraps
308def python_api_test(func):
309 """Decorate the item as a Python API only test."""
310 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
311 raise Exception("@python_api_test can only be used to decorate a test method")
312 @wraps(func)
313 def wrapper(self, *args, **kwargs):
314 try:
315 if lldb.dont_do_python_api_test:
316 self.skipTest("python api tests")
317 except AttributeError:
318 pass
319 return func(self, *args, **kwargs)
320
321 # Mark this function as such to separate them from lldb command line tests.
322 wrapper.__python_api_test__ = True
323 return wrapper
324
Johnny Chena74bb0a2011-08-01 18:46:13 +0000325def benchmarks_test(func):
326 """Decorate the item as a benchmarks test."""
327 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
328 raise Exception("@benchmarks_test can only be used to decorate a test method")
329 @wraps(func)
330 def wrapper(self, *args, **kwargs):
331 try:
332 if not lldb.just_do_benchmarks_test:
333 self.skipTest("benchmarks tests")
334 except AttributeError:
335 pass
336 return func(self, *args, **kwargs)
337
338 # Mark this function as such to separate them from the regular tests.
339 wrapper.__benchmarks_test__ = True
340 return wrapper
341
Johnny Chenf1548d42012-04-06 00:56:05 +0000342def dsym_test(func):
343 """Decorate the item as a dsym test."""
344 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
345 raise Exception("@dsym_test can only be used to decorate a test method")
346 @wraps(func)
347 def wrapper(self, *args, **kwargs):
348 try:
349 if lldb.dont_do_dsym_test:
350 self.skipTest("dsym tests")
351 except AttributeError:
352 pass
353 return func(self, *args, **kwargs)
354
355 # Mark this function as such to separate them from the regular tests.
356 wrapper.__dsym_test__ = True
357 return wrapper
358
359def dwarf_test(func):
360 """Decorate the item as a dwarf test."""
361 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
362 raise Exception("@dwarf_test can only be used to decorate a test method")
363 @wraps(func)
364 def wrapper(self, *args, **kwargs):
365 try:
366 if lldb.dont_do_dwarf_test:
367 self.skipTest("dwarf tests")
368 except AttributeError:
369 pass
370 return func(self, *args, **kwargs)
371
372 # Mark this function as such to separate them from the regular tests.
373 wrapper.__dwarf_test__ = True
374 return wrapper
375
Daniel Maleae0f8f572013-08-26 23:57:52 +0000376def not_remote_testsuite_ready(func):
377 """Decorate the item as a test which is not ready yet for remote testsuite."""
378 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
379 raise Exception("@not_remote_testsuite_ready can only be used to decorate a test method")
380 @wraps(func)
381 def wrapper(self, *args, **kwargs):
382 try:
383 if lldb.lldbtest_remote_sandbox:
384 self.skipTest("not ready for remote testsuite")
385 except AttributeError:
386 pass
387 return func(self, *args, **kwargs)
388
389 # Mark this function as such to separate them from the regular tests.
390 wrapper.__not_ready_for_remote_testsuite_test__ = True
391 return wrapper
392
Ashok Thirumurthic97a6082013-05-17 20:15:07 +0000393def expectedFailureGcc(bugnumber=None, compiler_version=["=", None]):
Enrico Granatae6cedc12013-02-23 01:05:23 +0000394 if callable(bugnumber):
395 @wraps(bugnumber)
Enrico Granata2b3a0c42013-02-23 01:35:21 +0000396 def expectedFailureGcc_easy_wrapper(*args, **kwargs):
Enrico Granata43f62132013-02-23 01:28:30 +0000397 from unittest2 import case
398 self = args[0]
399 test_compiler = self.getCompiler()
400 try:
401 bugnumber(*args, **kwargs)
402 except Exception:
Ashok Thirumurthi3b037282013-06-06 14:23:31 +0000403 if "gcc" in test_compiler and self.expectedCompilerVersion(compiler_version):
Enrico Granata43f62132013-02-23 01:28:30 +0000404 raise case._ExpectedFailure(sys.exc_info(),None)
405 else:
406 raise
Enrico Granata2b3a0c42013-02-23 01:35:21 +0000407 if "gcc" in test_compiler:
Enrico Granata43f62132013-02-23 01:28:30 +0000408 raise case._UnexpectedSuccess(sys.exc_info(),None)
Enrico Granata2b3a0c42013-02-23 01:35:21 +0000409 return expectedFailureGcc_easy_wrapper
Enrico Granatae6cedc12013-02-23 01:05:23 +0000410 else:
Enrico Granata2b3a0c42013-02-23 01:35:21 +0000411 def expectedFailureGcc_impl(func):
Enrico Granatae6cedc12013-02-23 01:05:23 +0000412 @wraps(func)
413 def wrapper(*args, **kwargs):
Enrico Granata43f62132013-02-23 01:28:30 +0000414 from unittest2 import case
415 self = args[0]
416 test_compiler = self.getCompiler()
417 try:
418 func(*args, **kwargs)
419 except Exception:
Ashok Thirumurthi3b037282013-06-06 14:23:31 +0000420 if "gcc" in test_compiler and self.expectedCompilerVersion(compiler_version):
Enrico Granata43f62132013-02-23 01:28:30 +0000421 raise case._ExpectedFailure(sys.exc_info(),bugnumber)
422 else:
423 raise
Enrico Granata2b3a0c42013-02-23 01:35:21 +0000424 if "gcc" in test_compiler:
Enrico Granata43f62132013-02-23 01:28:30 +0000425 raise case._UnexpectedSuccess(sys.exc_info(),bugnumber)
Enrico Granatae6cedc12013-02-23 01:05:23 +0000426 return wrapper
Enrico Granata2b3a0c42013-02-23 01:35:21 +0000427 return expectedFailureGcc_impl
Daniel Malea249287a2013-02-19 16:08:57 +0000428
Enrico Granata2b3a0c42013-02-23 01:35:21 +0000429def expectedFailureClang(bugnumber=None):
430 if callable(bugnumber):
431 @wraps(bugnumber)
432 def expectedFailureClang_easy_wrapper(*args, **kwargs):
433 from unittest2 import case
434 self = args[0]
435 test_compiler = self.getCompiler()
436 try:
437 bugnumber(*args, **kwargs)
438 except Exception:
439 if "clang" in test_compiler:
440 raise case._ExpectedFailure(sys.exc_info(),None)
441 else:
442 raise
443 if "clang" in test_compiler:
444 raise case._UnexpectedSuccess(sys.exc_info(),None)
445 return expectedFailureClang_easy_wrapper
446 else:
447 def expectedFailureClang_impl(func):
448 @wraps(func)
449 def wrapper(*args, **kwargs):
450 from unittest2 import case
451 self = args[0]
452 test_compiler = self.getCompiler()
453 try:
454 func(*args, **kwargs)
455 except Exception:
456 if "clang" in test_compiler:
457 raise case._ExpectedFailure(sys.exc_info(),bugnumber)
458 else:
459 raise
460 if "clang" in test_compiler:
461 raise case._UnexpectedSuccess(sys.exc_info(),bugnumber)
462 return wrapper
463 return expectedFailureClang_impl
Daniel Malea249287a2013-02-19 16:08:57 +0000464
Matt Kopec0de53f02013-03-15 19:10:12 +0000465def expectedFailureIcc(bugnumber=None):
466 if callable(bugnumber):
467 @wraps(bugnumber)
468 def expectedFailureIcc_easy_wrapper(*args, **kwargs):
469 from unittest2 import case
470 self = args[0]
471 test_compiler = self.getCompiler()
472 try:
473 bugnumber(*args, **kwargs)
474 except Exception:
475 if "icc" in test_compiler:
476 raise case._ExpectedFailure(sys.exc_info(),None)
477 else:
478 raise
479 if "icc" in test_compiler:
480 raise case._UnexpectedSuccess(sys.exc_info(),None)
481 return expectedFailureIcc_easy_wrapper
482 else:
483 def expectedFailureIcc_impl(func):
484 @wraps(func)
485 def wrapper(*args, **kwargs):
486 from unittest2 import case
487 self = args[0]
488 test_compiler = self.getCompiler()
489 try:
490 func(*args, **kwargs)
491 except Exception:
492 if "icc" in test_compiler:
493 raise case._ExpectedFailure(sys.exc_info(),bugnumber)
494 else:
495 raise
496 if "icc" in test_compiler:
497 raise case._UnexpectedSuccess(sys.exc_info(),bugnumber)
498 return wrapper
499 return expectedFailureIcc_impl
500
Daniel Malea249287a2013-02-19 16:08:57 +0000501
Enrico Granatae6cedc12013-02-23 01:05:23 +0000502def expectedFailurei386(bugnumber=None):
503 if callable(bugnumber):
504 @wraps(bugnumber)
505 def expectedFailurei386_easy_wrapper(*args, **kwargs):
Enrico Granata43f62132013-02-23 01:28:30 +0000506 from unittest2 import case
507 self = args[0]
508 arch = self.getArchitecture()
509 try:
510 bugnumber(*args, **kwargs)
511 except Exception:
512 if "i386" in arch:
513 raise case._ExpectedFailure(sys.exc_info(),None)
514 else:
515 raise
516 if "i386" in arch:
517 raise case._UnexpectedSuccess(sys.exc_info(),None)
Enrico Granatae6cedc12013-02-23 01:05:23 +0000518 return expectedFailurei386_easy_wrapper
519 else:
520 def expectedFailurei386_impl(func):
521 @wraps(func)
522 def wrapper(*args, **kwargs):
Enrico Granata43f62132013-02-23 01:28:30 +0000523 from unittest2 import case
524 self = args[0]
525 arch = self.getArchitecture()
526 try:
527 func(*args, **kwargs)
528 except Exception:
529 if "i386" in arch:
530 raise case._ExpectedFailure(sys.exc_info(),bugnumber)
531 else:
532 raise
533 if "i386" in arch:
534 raise case._UnexpectedSuccess(sys.exc_info(),bugnumber)
Enrico Granatae6cedc12013-02-23 01:05:23 +0000535 return wrapper
536 return expectedFailurei386_impl
Johnny Chena33843f2011-12-22 21:14:31 +0000537
Matt Kopecee969f92013-09-26 23:30:59 +0000538def expectedFailurex86_64(bugnumber=None):
539 if callable(bugnumber):
540 @wraps(bugnumber)
541 def expectedFailurex86_64_easy_wrapper(*args, **kwargs):
542 from unittest2 import case
543 self = args[0]
544 arch = self.getArchitecture()
545 try:
546 bugnumber(*args, **kwargs)
547 except Exception:
548 if "x86_64" in arch:
549 raise case._ExpectedFailure(sys.exc_info(),None)
550 else:
551 raise
552 if "x86_64" in arch:
553 raise case._UnexpectedSuccess(sys.exc_info(),None)
554 return expectedFailurex86_64_easy_wrapper
555 else:
556 def expectedFailurex86_64_impl(func):
557 @wraps(func)
558 def wrapper(*args, **kwargs):
559 from unittest2 import case
560 self = args[0]
561 arch = self.getArchitecture()
562 try:
563 func(*args, **kwargs)
564 except Exception:
565 if "x86_64" in arch:
566 raise case._ExpectedFailure(sys.exc_info(),bugnumber)
567 else:
568 raise
569 if "x86_64" in arch:
570 raise case._UnexpectedSuccess(sys.exc_info(),bugnumber)
571 return wrapper
572 return expectedFailurex86_64_impl
573
Ed Maste24a7f7d2013-07-24 19:47:08 +0000574def expectedFailureFreeBSD(bugnumber=None, compilers=None):
575 if callable(bugnumber):
576 @wraps(bugnumber)
577 def expectedFailureFreeBSD_easy_wrapper(*args, **kwargs):
578 from unittest2 import case
579 self = args[0]
580 platform = sys.platform
581 try:
582 bugnumber(*args, **kwargs)
583 except Exception:
584 if "freebsd" in platform and self.expectedCompiler(compilers):
585 raise case._ExpectedFailure(sys.exc_info(),None)
586 else:
587 raise
588 if "freebsd" in platform and self.expectedCompiler(compilers):
589 raise case._UnexpectedSuccess(sys.exc_info(),None)
590 return expectedFailureFreeBSD_easy_wrapper
591 else:
592 def expectedFailureFreeBSD_impl(func):
593 @wraps(func)
594 def wrapper(*args, **kwargs):
595 from unittest2 import case
596 self = args[0]
597 platform = sys.platform
598 try:
599 func(*args, **kwargs)
600 except Exception:
601 if "freebsd" in platform and self.expectedCompiler(compilers):
602 raise case._ExpectedFailure(sys.exc_info(),bugnumber)
603 else:
604 raise
605 if "freebsd" in platform and self.expectedCompiler(compilers):
606 raise case._UnexpectedSuccess(sys.exc_info(),bugnumber)
607 return wrapper
608 return expectedFailureFreeBSD_impl
609
Ashok Thirumurthic97a6082013-05-17 20:15:07 +0000610def expectedFailureLinux(bugnumber=None, compilers=None):
Enrico Granatae6cedc12013-02-23 01:05:23 +0000611 if callable(bugnumber):
612 @wraps(bugnumber)
613 def expectedFailureLinux_easy_wrapper(*args, **kwargs):
Enrico Granata43f62132013-02-23 01:28:30 +0000614 from unittest2 import case
615 self = args[0]
616 platform = sys.platform
617 try:
618 bugnumber(*args, **kwargs)
619 except Exception:
Ashok Thirumurthic97a6082013-05-17 20:15:07 +0000620 if "linux" in platform and self.expectedCompiler(compilers):
Enrico Granata43f62132013-02-23 01:28:30 +0000621 raise case._ExpectedFailure(sys.exc_info(),None)
622 else:
623 raise
Ashok Thirumurthic97a6082013-05-17 20:15:07 +0000624 if "linux" in platform and self.expectedCompiler(compilers):
Enrico Granata43f62132013-02-23 01:28:30 +0000625 raise case._UnexpectedSuccess(sys.exc_info(),None)
Enrico Granatae6cedc12013-02-23 01:05:23 +0000626 return expectedFailureLinux_easy_wrapper
627 else:
628 def expectedFailureLinux_impl(func):
629 @wraps(func)
630 def wrapper(*args, **kwargs):
Enrico Granata43f62132013-02-23 01:28:30 +0000631 from unittest2 import case
632 self = args[0]
633 platform = sys.platform
634 try:
635 func(*args, **kwargs)
636 except Exception:
Ashok Thirumurthic97a6082013-05-17 20:15:07 +0000637 if "linux" in platform and self.expectedCompiler(compilers):
Enrico Granata43f62132013-02-23 01:28:30 +0000638 raise case._ExpectedFailure(sys.exc_info(),bugnumber)
639 else:
640 raise
Ashok Thirumurthic97a6082013-05-17 20:15:07 +0000641 if "linux" in platform and self.expectedCompiler(compilers):
Enrico Granata43f62132013-02-23 01:28:30 +0000642 raise case._UnexpectedSuccess(sys.exc_info(),bugnumber)
Enrico Granatae6cedc12013-02-23 01:05:23 +0000643 return wrapper
644 return expectedFailureLinux_impl
Daniel Malea93aec0f2012-11-23 21:59:29 +0000645
Matt Kopece9ea0da2013-05-07 19:29:28 +0000646def expectedFailureDarwin(bugnumber=None):
647 if callable(bugnumber):
648 @wraps(bugnumber)
649 def expectedFailureDarwin_easy_wrapper(*args, **kwargs):
650 from unittest2 import case
651 self = args[0]
652 platform = sys.platform
653 try:
654 bugnumber(*args, **kwargs)
655 except Exception:
656 if "darwin" in platform:
657 raise case._ExpectedFailure(sys.exc_info(),None)
658 else:
659 raise
660 if "darwin" in platform:
661 raise case._UnexpectedSuccess(sys.exc_info(),None)
662 return expectedFailureDarwin_easy_wrapper
663 else:
664 def expectedFailureDarwin_impl(func):
665 @wraps(func)
666 def wrapper(*args, **kwargs):
667 from unittest2 import case
668 self = args[0]
669 platform = sys.platform
670 try:
671 func(*args, **kwargs)
672 except Exception:
673 if "darwin" in platform:
674 raise case._ExpectedFailure(sys.exc_info(),bugnumber)
675 else:
676 raise
677 if "darwin" in platform:
678 raise case._UnexpectedSuccess(sys.exc_info(),bugnumber)
679 return wrapper
680 return expectedFailureDarwin_impl
681
Greg Clayton12514562013-12-05 22:22:32 +0000682def skipIfRemote(func):
683 """Decorate the item to skip tests if testing remotely."""
684 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
685 raise Exception("@skipIfRemote can only be used to decorate a test method")
686 @wraps(func)
687 def wrapper(*args, **kwargs):
688 from unittest2 import case
689 if lldb.remote_platform:
690 self = args[0]
691 self.skipTest("skip on remote platform")
692 else:
693 func(*args, **kwargs)
694 return wrapper
695
696def skipIfRemoteDueToDeadlock(func):
697 """Decorate the item to skip tests if testing remotely due to the test deadlocking."""
698 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
699 raise Exception("@skipIfRemote can only be used to decorate a test method")
700 @wraps(func)
701 def wrapper(*args, **kwargs):
702 from unittest2 import case
703 if lldb.remote_platform:
704 self = args[0]
705 self.skipTest("skip on remote platform (deadlocks)")
706 else:
707 func(*args, **kwargs)
708 return wrapper
709
Ed Maste09617a52013-06-25 19:11:36 +0000710def skipIfFreeBSD(func):
711 """Decorate the item to skip tests that should be skipped on FreeBSD."""
712 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
713 raise Exception("@skipIfFreeBSD can only be used to decorate a test method")
714 @wraps(func)
715 def wrapper(*args, **kwargs):
716 from unittest2 import case
717 self = args[0]
718 platform = sys.platform
719 if "freebsd" in platform:
720 self.skipTest("skip on FreeBSD")
721 else:
722 func(*args, **kwargs)
723 return wrapper
724
Daniel Maleae8bdd1f2013-05-15 18:48:32 +0000725def skipIfLinux(func):
Daniel Malea93aec0f2012-11-23 21:59:29 +0000726 """Decorate the item to skip tests that should be skipped on Linux."""
727 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Daniel Maleae8bdd1f2013-05-15 18:48:32 +0000728 raise Exception("@skipIfLinux can only be used to decorate a test method")
Daniel Malea93aec0f2012-11-23 21:59:29 +0000729 @wraps(func)
730 def wrapper(*args, **kwargs):
731 from unittest2 import case
732 self = args[0]
733 platform = sys.platform
734 if "linux" in platform:
735 self.skipTest("skip on linux")
736 else:
Jim Ingham9732e082012-11-27 01:21:28 +0000737 func(*args, **kwargs)
Daniel Malea93aec0f2012-11-23 21:59:29 +0000738 return wrapper
739
Daniel Maleab3d41a22013-07-09 00:08:01 +0000740def skipIfDarwin(func):
741 """Decorate the item to skip tests that should be skipped on Darwin."""
742 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Ed Mastea7f13f02013-07-09 00:24:52 +0000743 raise Exception("@skipIfDarwin can only be used to decorate a test method")
Daniel Maleab3d41a22013-07-09 00:08:01 +0000744 @wraps(func)
745 def wrapper(*args, **kwargs):
746 from unittest2 import case
747 self = args[0]
748 platform = sys.platform
749 if "darwin" in platform:
750 self.skipTest("skip on darwin")
751 else:
752 func(*args, **kwargs)
753 return wrapper
754
755
Daniel Malea48359902013-05-14 20:48:54 +0000756def skipIfLinuxClang(func):
757 """Decorate the item to skip tests that should be skipped if building on
758 Linux with clang.
759 """
760 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
761 raise Exception("@skipIfLinuxClang can only be used to decorate a test method")
762 @wraps(func)
763 def wrapper(*args, **kwargs):
764 from unittest2 import case
765 self = args[0]
766 compiler = self.getCompiler()
767 platform = sys.platform
768 if "clang" in compiler and "linux" in platform:
769 self.skipTest("skipping because Clang is used on Linux")
770 else:
771 func(*args, **kwargs)
772 return wrapper
773
Daniel Maleabe230792013-01-24 23:52:09 +0000774def skipIfGcc(func):
775 """Decorate the item to skip tests that should be skipped if building with gcc ."""
776 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Daniel Malea0aea0162013-02-27 17:29:46 +0000777 raise Exception("@skipIfGcc can only be used to decorate a test method")
Daniel Maleabe230792013-01-24 23:52:09 +0000778 @wraps(func)
779 def wrapper(*args, **kwargs):
780 from unittest2 import case
781 self = args[0]
782 compiler = self.getCompiler()
783 if "gcc" in compiler:
784 self.skipTest("skipping because gcc is the test compiler")
785 else:
786 func(*args, **kwargs)
787 return wrapper
788
Matt Kopec0de53f02013-03-15 19:10:12 +0000789def skipIfIcc(func):
790 """Decorate the item to skip tests that should be skipped if building with icc ."""
791 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
792 raise Exception("@skipIfIcc can only be used to decorate a test method")
793 @wraps(func)
794 def wrapper(*args, **kwargs):
795 from unittest2 import case
796 self = args[0]
797 compiler = self.getCompiler()
798 if "icc" in compiler:
799 self.skipTest("skipping because icc is the test compiler")
800 else:
801 func(*args, **kwargs)
802 return wrapper
803
Daniel Malea55faa402013-05-02 21:44:31 +0000804def skipIfi386(func):
805 """Decorate the item to skip tests that should be skipped if building 32-bit."""
806 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
807 raise Exception("@skipIfi386 can only be used to decorate a test method")
808 @wraps(func)
809 def wrapper(*args, **kwargs):
810 from unittest2 import case
811 self = args[0]
812 if "i386" == self.getArchitecture():
813 self.skipTest("skipping because i386 is not a supported architecture")
814 else:
815 func(*args, **kwargs)
816 return wrapper
817
818
Johnny Chena74bb0a2011-08-01 18:46:13 +0000819class Base(unittest2.TestCase):
Johnny Chen8334dad2010-10-22 23:15:46 +0000820 """
Johnny Chena74bb0a2011-08-01 18:46:13 +0000821 Abstract base for performing lldb (see TestBase) or other generic tests (see
822 BenchBase for one example). lldbtest.Base works with the test driver to
823 accomplish things.
824
Johnny Chen8334dad2010-10-22 23:15:46 +0000825 """
Enrico Granata5020f952012-10-24 21:42:49 +0000826
Enrico Granata19186272012-10-24 21:44:48 +0000827 # The concrete subclass should override this attribute.
828 mydir = None
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000829
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000830 # Keep track of the old current working directory.
831 oldcwd = None
Johnny Chena2124952010-08-05 21:23:45 +0000832
Johnny Chenfb4264c2011-08-01 19:50:58 +0000833 def TraceOn(self):
834 """Returns True if we are in trace mode (tracing detailed test execution)."""
835 return traceAlways
836
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000837 @classmethod
838 def setUpClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +0000839 """
840 Python unittest framework class setup fixture.
841 Do current directory manipulation.
842 """
843
Johnny Chenf02ec122010-07-03 20:41:42 +0000844 # Fail fast if 'mydir' attribute is not overridden.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000845 if not cls.mydir or len(cls.mydir) == 0:
Johnny Chenf02ec122010-07-03 20:41:42 +0000846 raise Exception("Subclasses must override the 'mydir' attribute.")
Enrico Granata7e137e32012-10-24 18:14:21 +0000847
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000848 # Save old working directory.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000849 cls.oldcwd = os.getcwd()
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000850
851 # Change current working directory if ${LLDB_TEST} is defined.
852 # See also dotest.py which sets up ${LLDB_TEST}.
853 if ("LLDB_TEST" in os.environ):
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000854 if traceAlways:
Johnny Chen703dbd02010-09-30 17:06:24 +0000855 print >> sys.stderr, "Change dir to:", os.path.join(os.environ["LLDB_TEST"], cls.mydir)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000856 os.chdir(os.path.join(os.environ["LLDB_TEST"], cls.mydir))
857
858 @classmethod
859 def tearDownClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +0000860 """
861 Python unittest framework class teardown fixture.
862 Do class-wide cleanup.
863 """
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000864
Johnny Chen0fddfb22011-11-17 19:57:27 +0000865 if doCleanup and not lldb.skip_build_and_cleanup:
Johnny Chen707b3c92010-10-11 22:25:46 +0000866 # First, let's do the platform-specific cleanup.
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000867 module = builder_module()
Johnny Chen707b3c92010-10-11 22:25:46 +0000868 if not module.cleanup():
869 raise Exception("Don't know how to do cleanup")
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000870
Johnny Chen707b3c92010-10-11 22:25:46 +0000871 # Subclass might have specific cleanup function defined.
872 if getattr(cls, "classCleanup", None):
873 if traceAlways:
874 print >> sys.stderr, "Call class-specific cleanup function for class:", cls
875 try:
876 cls.classCleanup()
877 except:
878 exc_type, exc_value, exc_tb = sys.exc_info()
879 traceback.print_exception(exc_type, exc_value, exc_tb)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000880
881 # Restore old working directory.
882 if traceAlways:
Johnny Chen703dbd02010-09-30 17:06:24 +0000883 print >> sys.stderr, "Restore dir to:", cls.oldcwd
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000884 os.chdir(cls.oldcwd)
885
Johnny Chena74bb0a2011-08-01 18:46:13 +0000886 @classmethod
887 def skipLongRunningTest(cls):
888 """
889 By default, we skip long running test case.
890 This can be overridden by passing '-l' to the test driver (dotest.py).
891 """
892 if "LLDB_SKIP_LONG_RUNNING_TEST" in os.environ and "NO" == os.environ["LLDB_SKIP_LONG_RUNNING_TEST"]:
893 return False
894 else:
895 return True
Johnny Chened492022011-06-21 00:53:00 +0000896
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000897 def setUp(self):
Johnny Chenfb4264c2011-08-01 19:50:58 +0000898 """Fixture for unittest test case setup.
899
900 It works with the test driver to conditionally skip tests and does other
901 initializations."""
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000902 #import traceback
903 #traceback.print_stack()
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000904
Daniel Malea9115f072013-08-06 15:02:32 +0000905 if "LIBCXX_PATH" in os.environ:
906 self.libcxxPath = os.environ["LIBCXX_PATH"]
907 else:
908 self.libcxxPath = None
909
Johnny Chenaaa82ff2011-08-02 22:54:37 +0000910 if "LLDB_EXEC" in os.environ:
911 self.lldbExec = os.environ["LLDB_EXEC"]
Johnny Chend890bfc2011-08-26 00:00:01 +0000912 else:
913 self.lldbExec = None
914 if "LLDB_HERE" in os.environ:
915 self.lldbHere = os.environ["LLDB_HERE"]
916 else:
917 self.lldbHere = None
Johnny Chenebe51722011-10-07 19:21:09 +0000918 # If we spawn an lldb process for test (via pexpect), do not load the
919 # init file unless told otherwise.
920 if "NO_LLDBINIT" in os.environ and "NO" == os.environ["NO_LLDBINIT"]:
921 self.lldbOption = ""
922 else:
923 self.lldbOption = "--no-lldbinit"
Johnny Chenaaa82ff2011-08-02 22:54:37 +0000924
Johnny Chen985e7402011-08-01 21:13:26 +0000925 # Assign the test method name to self.testMethodName.
926 #
927 # For an example of the use of this attribute, look at test/types dir.
928 # There are a bunch of test cases under test/types and we don't want the
929 # module cacheing subsystem to be confused with executable name "a.out"
930 # used for all the test cases.
931 self.testMethodName = self._testMethodName
932
Johnny Chenf3e22ac2010-12-10 18:52:10 +0000933 # Python API only test is decorated with @python_api_test,
934 # which also sets the "__python_api_test__" attribute of the
935 # function object to True.
Johnny Chen4533dad2011-05-31 23:21:42 +0000936 try:
937 if lldb.just_do_python_api_test:
938 testMethod = getattr(self, self._testMethodName)
939 if getattr(testMethod, "__python_api_test__", False):
940 pass
941 else:
Johnny Chen5ccbccf2011-07-30 01:39:58 +0000942 self.skipTest("non python api test")
943 except AttributeError:
944 pass
945
946 # Benchmarks test is decorated with @benchmarks_test,
947 # which also sets the "__benchmarks_test__" attribute of the
948 # function object to True.
949 try:
950 if lldb.just_do_benchmarks_test:
951 testMethod = getattr(self, self._testMethodName)
952 if getattr(testMethod, "__benchmarks_test__", False):
953 pass
954 else:
955 self.skipTest("non benchmarks test")
Johnny Chen4533dad2011-05-31 23:21:42 +0000956 except AttributeError:
957 pass
Johnny Chenf3e22ac2010-12-10 18:52:10 +0000958
Johnny Chen985e7402011-08-01 21:13:26 +0000959 # This is for the case of directly spawning 'lldb'/'gdb' and interacting
960 # with it using pexpect.
961 self.child = None
962 self.child_prompt = "(lldb) "
963 # If the child is interacting with the embedded script interpreter,
964 # there are two exits required during tear down, first to quit the
965 # embedded script interpreter and second to quit the lldb command
966 # interpreter.
967 self.child_in_script_interpreter = False
968
Johnny Chenfb4264c2011-08-01 19:50:58 +0000969 # These are for customized teardown cleanup.
970 self.dict = None
971 self.doTearDownCleanup = False
972 # And in rare cases where there are multiple teardown cleanups.
973 self.dicts = []
974 self.doTearDownCleanups = False
975
Daniel Malea2dd69bb2013-02-15 21:21:52 +0000976 # List of spawned subproces.Popen objects
977 self.subprocesses = []
978
Daniel Malea69207462013-06-05 21:07:02 +0000979 # List of forked process PIDs
980 self.forkedProcessPids = []
981
Johnny Chenfb4264c2011-08-01 19:50:58 +0000982 # Create a string buffer to record the session info, to be dumped into a
983 # test case specific file if test failure is encountered.
984 self.session = StringIO.StringIO()
985
986 # Optimistically set __errored__, __failed__, __expected__ to False
987 # initially. If the test errored/failed, the session info
988 # (self.session) is then dumped into a session specific file for
989 # diagnosis.
990 self.__errored__ = False
991 self.__failed__ = False
992 self.__expected__ = False
993 # We are also interested in unexpected success.
994 self.__unexpected__ = False
Johnny Chenf79b0762011-08-16 00:48:58 +0000995 # And skipped tests.
996 self.__skipped__ = False
Johnny Chenfb4264c2011-08-01 19:50:58 +0000997
998 # See addTearDownHook(self, hook) which allows the client to add a hook
999 # function to be run during tearDown() time.
1000 self.hooks = []
1001
1002 # See HideStdout(self).
1003 self.sys_stdout_hidden = False
1004
Daniel Malea179ff292012-11-26 21:21:11 +00001005 # set environment variable names for finding shared libraries
1006 if sys.platform.startswith("darwin"):
1007 self.dylibPath = 'DYLD_LIBRARY_PATH'
1008 elif sys.platform.startswith("linux") or sys.platform.startswith("freebsd"):
1009 self.dylibPath = 'LD_LIBRARY_PATH'
1010
Johnny Chen2a808582011-10-19 16:48:07 +00001011 def runHooks(self, child=None, child_prompt=None, use_cmd_api=False):
Johnny Chena737ba52011-10-19 01:06:21 +00001012 """Perform the run hooks to bring lldb debugger to the desired state.
1013
Johnny Chen2a808582011-10-19 16:48:07 +00001014 By default, expect a pexpect spawned child and child prompt to be
1015 supplied (use_cmd_api=False). If use_cmd_api is true, ignore the child
1016 and child prompt and use self.runCmd() to run the hooks one by one.
1017
Johnny Chena737ba52011-10-19 01:06:21 +00001018 Note that child is a process spawned by pexpect.spawn(). If not, your
1019 test case is mostly likely going to fail.
1020
1021 See also dotest.py where lldb.runHooks are processed/populated.
1022 """
1023 if not lldb.runHooks:
1024 self.skipTest("No runhooks specified for lldb, skip the test")
Johnny Chen2a808582011-10-19 16:48:07 +00001025 if use_cmd_api:
1026 for hook in lldb.runhooks:
1027 self.runCmd(hook)
1028 else:
1029 if not child or not child_prompt:
1030 self.fail("Both child and child_prompt need to be defined.")
1031 for hook in lldb.runHooks:
1032 child.sendline(hook)
1033 child.expect_exact(child_prompt)
Johnny Chena737ba52011-10-19 01:06:21 +00001034
Daniel Malea249287a2013-02-19 16:08:57 +00001035 def setAsync(self, value):
1036 """ Sets async mode to True/False and ensures it is reset after the testcase completes."""
1037 old_async = self.dbg.GetAsync()
1038 self.dbg.SetAsync(value)
1039 self.addTearDownHook(lambda: self.dbg.SetAsync(old_async))
1040
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001041 def cleanupSubprocesses(self):
1042 # Ensure any subprocesses are cleaned up
1043 for p in self.subprocesses:
1044 if p.poll() == None:
1045 p.terminate()
1046 del p
1047 del self.subprocesses[:]
Daniel Malea69207462013-06-05 21:07:02 +00001048 # Ensure any forked processes are cleaned up
1049 for pid in self.forkedProcessPids:
1050 if os.path.exists("/proc/" + str(pid)):
1051 os.kill(pid, signal.SIGTERM)
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001052
1053 def spawnSubprocess(self, executable, args=[]):
1054 """ Creates a subprocess.Popen object with the specified executable and arguments,
1055 saves it in self.subprocesses, and returns the object.
1056 NOTE: if using this function, ensure you also call:
1057
1058 self.addTearDownHook(self.cleanupSubprocesses)
1059
1060 otherwise the test suite will leak processes.
1061 """
1062
1063 # Don't display the stdout if not in TraceOn() mode.
1064 proc = Popen([executable] + args,
1065 stdout = open(os.devnull) if not self.TraceOn() else None,
1066 stdin = PIPE)
1067 self.subprocesses.append(proc)
1068 return proc
1069
Daniel Malea69207462013-06-05 21:07:02 +00001070 def forkSubprocess(self, executable, args=[]):
1071 """ Fork a subprocess with its own group ID.
1072 NOTE: if using this function, ensure you also call:
1073
1074 self.addTearDownHook(self.cleanupSubprocesses)
1075
1076 otherwise the test suite will leak processes.
1077 """
1078 child_pid = os.fork()
1079 if child_pid == 0:
1080 # If more I/O support is required, this can be beefed up.
1081 fd = os.open(os.devnull, os.O_RDWR)
Daniel Malea69207462013-06-05 21:07:02 +00001082 os.dup2(fd, 1)
1083 os.dup2(fd, 2)
1084 # This call causes the child to have its of group ID
1085 os.setpgid(0,0)
1086 os.execvp(executable, [executable] + args)
1087 # Give the child time to get through the execvp() call
1088 time.sleep(0.1)
1089 self.forkedProcessPids.append(child_pid)
1090 return child_pid
1091
Johnny Chenfb4264c2011-08-01 19:50:58 +00001092 def HideStdout(self):
1093 """Hide output to stdout from the user.
1094
1095 During test execution, there might be cases where we don't want to show the
1096 standard output to the user. For example,
1097
1098 self.runCmd(r'''sc print "\n\n\tHello!\n"''')
1099
1100 tests whether command abbreviation for 'script' works or not. There is no
1101 need to show the 'Hello' output to the user as long as the 'script' command
1102 succeeds and we are not in TraceOn() mode (see the '-t' option).
1103
1104 In this case, the test method calls self.HideStdout(self) to redirect the
1105 sys.stdout to a null device, and restores the sys.stdout upon teardown.
1106
1107 Note that you should only call this method at most once during a test case
1108 execution. Any subsequent call has no effect at all."""
1109 if self.sys_stdout_hidden:
1110 return
1111
1112 self.sys_stdout_hidden = True
1113 old_stdout = sys.stdout
1114 sys.stdout = open(os.devnull, 'w')
1115 def restore_stdout():
1116 sys.stdout = old_stdout
1117 self.addTearDownHook(restore_stdout)
1118
1119 # =======================================================================
1120 # Methods for customized teardown cleanups as well as execution of hooks.
1121 # =======================================================================
1122
1123 def setTearDownCleanup(self, dictionary=None):
1124 """Register a cleanup action at tearDown() time with a dictinary"""
1125 self.dict = dictionary
1126 self.doTearDownCleanup = True
1127
1128 def addTearDownCleanup(self, dictionary):
1129 """Add a cleanup action at tearDown() time with a dictinary"""
1130 self.dicts.append(dictionary)
1131 self.doTearDownCleanups = True
1132
1133 def addTearDownHook(self, hook):
1134 """
1135 Add a function to be run during tearDown() time.
1136
1137 Hooks are executed in a first come first serve manner.
1138 """
1139 if callable(hook):
1140 with recording(self, traceAlways) as sbuf:
1141 print >> sbuf, "Adding tearDown hook:", getsource_if_available(hook)
1142 self.hooks.append(hook)
1143
1144 def tearDown(self):
1145 """Fixture for unittest test case teardown."""
1146 #import traceback
1147 #traceback.print_stack()
1148
Johnny Chen985e7402011-08-01 21:13:26 +00001149 # This is for the case of directly spawning 'lldb' and interacting with it
1150 # using pexpect.
1151 import pexpect
1152 if self.child and self.child.isalive():
1153 with recording(self, traceAlways) as sbuf:
1154 print >> sbuf, "tearing down the child process...."
Johnny Chen985e7402011-08-01 21:13:26 +00001155 try:
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001156 if self.child_in_script_interpreter:
1157 self.child.sendline('quit()')
1158 self.child.expect_exact(self.child_prompt)
1159 self.child.sendline('settings set interpreter.prompt-on-quit false')
1160 self.child.sendline('quit')
Johnny Chen985e7402011-08-01 21:13:26 +00001161 self.child.expect(pexpect.EOF)
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001162 except ValueError, ExceptionPexpect:
1163 # child is already terminated
Johnny Chen985e7402011-08-01 21:13:26 +00001164 pass
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001165
Johnny Chenac257132012-02-27 23:07:40 +00001166 # Give it one final blow to make sure the child is terminated.
1167 self.child.close()
Johnny Chen985e7402011-08-01 21:13:26 +00001168
Johnny Chenfb4264c2011-08-01 19:50:58 +00001169 # Check and run any hook functions.
1170 for hook in reversed(self.hooks):
1171 with recording(self, traceAlways) as sbuf:
1172 print >> sbuf, "Executing tearDown hook:", getsource_if_available(hook)
1173 hook()
1174
1175 del self.hooks
1176
1177 # Perform registered teardown cleanup.
1178 if doCleanup and self.doTearDownCleanup:
Johnny Chen0fddfb22011-11-17 19:57:27 +00001179 self.cleanup(dictionary=self.dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001180
1181 # In rare cases where there are multiple teardown cleanups added.
1182 if doCleanup and self.doTearDownCleanups:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001183 if self.dicts:
1184 for dict in reversed(self.dicts):
Johnny Chen0fddfb22011-11-17 19:57:27 +00001185 self.cleanup(dictionary=dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001186
1187 # Decide whether to dump the session info.
1188 self.dumpSessionInfo()
1189
1190 # =========================================================
1191 # Various callbacks to allow introspection of test progress
1192 # =========================================================
1193
1194 def markError(self):
1195 """Callback invoked when an error (unexpected exception) errored."""
1196 self.__errored__ = True
1197 with recording(self, False) as sbuf:
1198 # False because there's no need to write "ERROR" to the stderr twice.
1199 # Once by the Python unittest framework, and a second time by us.
1200 print >> sbuf, "ERROR"
1201
1202 def markFailure(self):
1203 """Callback invoked when a failure (test assertion failure) occurred."""
1204 self.__failed__ = True
1205 with recording(self, False) as sbuf:
1206 # False because there's no need to write "FAIL" to the stderr twice.
1207 # Once by the Python unittest framework, and a second time by us.
1208 print >> sbuf, "FAIL"
1209
Enrico Granatae6cedc12013-02-23 01:05:23 +00001210 def markExpectedFailure(self,err,bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001211 """Callback invoked when an expected failure/error occurred."""
1212 self.__expected__ = True
1213 with recording(self, False) as sbuf:
1214 # False because there's no need to write "expected failure" to the
1215 # stderr twice.
1216 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001217 if bugnumber == None:
1218 print >> sbuf, "expected failure"
1219 else:
1220 print >> sbuf, "expected failure (problem id:" + str(bugnumber) + ")"
Johnny Chenfb4264c2011-08-01 19:50:58 +00001221
Johnny Chenc5cc6252011-08-15 23:09:08 +00001222 def markSkippedTest(self):
1223 """Callback invoked when a test is skipped."""
1224 self.__skipped__ = True
1225 with recording(self, False) as sbuf:
1226 # False because there's no need to write "skipped test" to the
1227 # stderr twice.
1228 # Once by the Python unittest framework, and a second time by us.
1229 print >> sbuf, "skipped test"
1230
Enrico Granatae6cedc12013-02-23 01:05:23 +00001231 def markUnexpectedSuccess(self, bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001232 """Callback invoked when an unexpected success occurred."""
1233 self.__unexpected__ = True
1234 with recording(self, False) as sbuf:
1235 # False because there's no need to write "unexpected success" to the
1236 # stderr twice.
1237 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001238 if bugnumber == None:
1239 print >> sbuf, "unexpected success"
1240 else:
1241 print >> sbuf, "unexpected success (problem id:" + str(bugnumber) + ")"
Johnny Chenfb4264c2011-08-01 19:50:58 +00001242
1243 def dumpSessionInfo(self):
1244 """
1245 Dump the debugger interactions leading to a test error/failure. This
1246 allows for more convenient postmortem analysis.
1247
1248 See also LLDBTestResult (dotest.py) which is a singlton class derived
1249 from TextTestResult and overwrites addError, addFailure, and
1250 addExpectedFailure methods to allow us to to mark the test instance as
1251 such.
1252 """
1253
1254 # We are here because self.tearDown() detected that this test instance
1255 # either errored or failed. The lldb.test_result singleton contains
1256 # two lists (erros and failures) which get populated by the unittest
1257 # framework. Look over there for stack trace information.
1258 #
1259 # The lists contain 2-tuples of TestCase instances and strings holding
1260 # formatted tracebacks.
1261 #
1262 # See http://docs.python.org/library/unittest.html#unittest.TestResult.
1263 if self.__errored__:
1264 pairs = lldb.test_result.errors
1265 prefix = 'Error'
1266 elif self.__failed__:
1267 pairs = lldb.test_result.failures
1268 prefix = 'Failure'
1269 elif self.__expected__:
1270 pairs = lldb.test_result.expectedFailures
1271 prefix = 'ExpectedFailure'
Johnny Chenc5cc6252011-08-15 23:09:08 +00001272 elif self.__skipped__:
1273 prefix = 'SkippedTest'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001274 elif self.__unexpected__:
1275 prefix = "UnexpectedSuccess"
1276 else:
1277 # Simply return, there's no session info to dump!
1278 return
1279
Johnny Chenc5cc6252011-08-15 23:09:08 +00001280 if not self.__unexpected__ and not self.__skipped__:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001281 for test, traceback in pairs:
1282 if test is self:
1283 print >> self.session, traceback
1284
Johnny Chen8082a002011-08-11 00:16:28 +00001285 testMethod = getattr(self, self._testMethodName)
1286 if getattr(testMethod, "__benchmarks_test__", False):
1287 benchmarks = True
1288 else:
1289 benchmarks = False
1290
Johnny Chen5daa6de2011-12-03 00:16:59 +00001291 # This records the compiler version used for the test.
1292 system([self.getCompiler(), "-v"], sender=self)
1293
Johnny Chenfb4264c2011-08-01 19:50:58 +00001294 dname = os.path.join(os.environ["LLDB_TEST"],
1295 os.environ["LLDB_SESSION_DIRNAME"])
1296 if not os.path.isdir(dname):
1297 os.mkdir(dname)
Sean Callanan794baf62012-10-16 18:22:04 +00001298 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 +00001299 with open(fname, "w") as f:
1300 import datetime
1301 print >> f, "Session info generated @", datetime.datetime.now().ctime()
1302 print >> f, self.session.getvalue()
1303 print >> f, "To rerun this test, issue the following command from the 'test' directory:\n"
Johnny Chen8082a002011-08-11 00:16:28 +00001304 print >> f, "./dotest.py %s -v %s -f %s.%s" % (self.getRunOptions(),
1305 ('+b' if benchmarks else '-t'),
Johnny Chenfb4264c2011-08-01 19:50:58 +00001306 self.__class__.__name__,
1307 self._testMethodName)
1308
1309 # ====================================================
1310 # Config. methods supported through a plugin interface
1311 # (enables reading of the current test configuration)
1312 # ====================================================
1313
1314 def getArchitecture(self):
1315 """Returns the architecture in effect the test suite is running with."""
1316 module = builder_module()
1317 return module.getArchitecture()
1318
1319 def getCompiler(self):
1320 """Returns the compiler in effect the test suite is running with."""
1321 module = builder_module()
1322 return module.getCompiler()
1323
Daniel Malea0aea0162013-02-27 17:29:46 +00001324 def getCompilerVersion(self):
1325 """ Returns a string that represents the compiler version.
1326 Supports: llvm, clang.
1327 """
1328 from lldbutil import which
1329 version = 'unknown'
1330
1331 compiler = self.getCompiler()
1332 version_output = system([which(compiler), "-v"])[1]
1333 for line in version_output.split(os.linesep):
Greg Clayton2a844b72013-03-06 02:34:51 +00001334 m = re.search('version ([0-9\.]+)', line)
Daniel Malea0aea0162013-02-27 17:29:46 +00001335 if m:
1336 version = m.group(1)
1337 return version
1338
Daniel Maleaadaaec92013-08-06 20:51:41 +00001339 def isIntelCompiler(self):
1340 """ Returns true if using an Intel (ICC) compiler, false otherwise. """
1341 return any([x in self.getCompiler() for x in ["icc", "icpc", "icl"]])
1342
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001343 def expectedCompilerVersion(self, compiler_version):
1344 """Returns True iff compiler_version[1] matches the current compiler version.
1345 Use compiler_version[0] to specify the operator used to determine if a match has occurred.
1346 Any operator other than the following defaults to an equality test:
1347 '>', '>=', "=>", '<', '<=', '=<', '!=', "!" or 'not'
1348 """
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001349 if (compiler_version == None):
1350 return True
1351 operator = str(compiler_version[0])
1352 version = compiler_version[1]
1353
1354 if (version == None):
1355 return True
1356 if (operator == '>'):
1357 return self.getCompilerVersion() > version
1358 if (operator == '>=' or operator == '=>'):
1359 return self.getCompilerVersion() >= version
1360 if (operator == '<'):
1361 return self.getCompilerVersion() < version
1362 if (operator == '<=' or operator == '=<'):
1363 return self.getCompilerVersion() <= version
1364 if (operator == '!=' or operator == '!' or operator == 'not'):
1365 return str(version) not in str(self.getCompilerVersion())
1366 return str(version) in str(self.getCompilerVersion())
1367
1368 def expectedCompiler(self, compilers):
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001369 """Returns True iff any element of compilers is a sub-string of the current compiler."""
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001370 if (compilers == None):
1371 return True
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001372
1373 for compiler in compilers:
1374 if compiler in self.getCompiler():
1375 return True
1376
1377 return False
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001378
Johnny Chenfb4264c2011-08-01 19:50:58 +00001379 def getRunOptions(self):
1380 """Command line option for -A and -C to run this test again, called from
1381 self.dumpSessionInfo()."""
1382 arch = self.getArchitecture()
1383 comp = self.getCompiler()
Johnny Chenb7bdd102011-08-24 19:48:51 +00001384 if arch:
1385 option_str = "-A " + arch
Johnny Chenfb4264c2011-08-01 19:50:58 +00001386 else:
Johnny Chenb7bdd102011-08-24 19:48:51 +00001387 option_str = ""
1388 if comp:
Johnny Chen531c0852012-03-16 20:44:00 +00001389 option_str += " -C " + comp
Johnny Chenb7bdd102011-08-24 19:48:51 +00001390 return option_str
Johnny Chenfb4264c2011-08-01 19:50:58 +00001391
1392 # ==================================================
1393 # Build methods supported through a plugin interface
1394 # ==================================================
1395
Matt Kopec7663b3a2013-09-25 17:44:00 +00001396 def getstdFlag(self):
1397 """ Returns the proper stdflag. """
Daniel Malea55faa402013-05-02 21:44:31 +00001398 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
Daniel Malea0b7c6112013-05-06 19:31:31 +00001399 stdflag = "-std=c++0x"
Daniel Malea55faa402013-05-02 21:44:31 +00001400 else:
1401 stdflag = "-std=c++11"
Matt Kopec7663b3a2013-09-25 17:44:00 +00001402 return stdflag
1403
1404 def buildDriver(self, sources, exe_name):
1405 """ Platform-specific way to build a program that links with LLDB (via the liblldb.so
1406 or LLDB.framework).
1407 """
1408
1409 stdflag = self.getstdFlag()
Daniel Malea55faa402013-05-02 21:44:31 +00001410
1411 if sys.platform.startswith("darwin"):
1412 dsym = os.path.join(self.lib_dir, 'LLDB.framework', 'LLDB')
1413 d = {'CXX_SOURCES' : sources,
1414 'EXE' : exe_name,
1415 'CFLAGS_EXTRAS' : "%s -stdlib=libc++" % stdflag,
1416 'FRAMEWORK_INCLUDES' : "-F%s" % self.lib_dir,
Stefanus Du Toit04004442013-07-30 19:19:49 +00001417 'LD_EXTRAS' : "%s -Wl,-rpath,%s" % (dsym, self.lib_dir),
Daniel Malea55faa402013-05-02 21:44:31 +00001418 }
Ed Maste372c24d2013-07-25 21:02:34 +00001419 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 +00001420 d = {'CXX_SOURCES' : sources,
1421 'EXE' : exe_name,
1422 'CFLAGS_EXTRAS' : "%s -I%s" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
1423 'LD_EXTRAS' : "-L%s -llldb" % self.lib_dir}
1424 if self.TraceOn():
1425 print "Building LLDB Driver (%s) from sources %s" % (exe_name, sources)
1426
1427 self.buildDefault(dictionary=d)
1428
Matt Kopec7663b3a2013-09-25 17:44:00 +00001429 def buildLibrary(self, sources, lib_name):
1430 """Platform specific way to build a default library. """
1431
1432 stdflag = self.getstdFlag()
1433
1434 if sys.platform.startswith("darwin"):
1435 dsym = os.path.join(self.lib_dir, 'LLDB.framework', 'LLDB')
1436 d = {'DYLIB_CXX_SOURCES' : sources,
1437 'DYLIB_NAME' : lib_name,
1438 'CFLAGS_EXTRAS' : "%s -stdlib=libc++" % stdflag,
1439 'FRAMEWORK_INCLUDES' : "-F%s" % self.lib_dir,
1440 'LD_EXTRAS' : "%s -Wl,-rpath,%s -dynamiclib" % (dsym, self.lib_dir),
1441 }
1442 elif sys.platform.startswith('freebsd') or sys.platform.startswith("linux") or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
1443 d = {'DYLIB_CXX_SOURCES' : sources,
1444 'DYLIB_NAME' : lib_name,
1445 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
1446 'LD_EXTRAS' : "-shared -L%s -llldb" % self.lib_dir}
1447 if self.TraceOn():
1448 print "Building LLDB Library (%s) from sources %s" % (lib_name, sources)
1449
1450 self.buildDefault(dictionary=d)
1451
Daniel Malea55faa402013-05-02 21:44:31 +00001452 def buildProgram(self, sources, exe_name):
1453 """ Platform specific way to build an executable from C/C++ sources. """
1454 d = {'CXX_SOURCES' : sources,
1455 'EXE' : exe_name}
1456 self.buildDefault(dictionary=d)
1457
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001458 def buildDefault(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001459 """Platform specific way to build the default binaries."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001460 if lldb.skip_build_and_cleanup:
1461 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00001462 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001463 if not module.buildDefault(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001464 raise Exception("Don't know how to build default binary")
1465
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001466 def buildDsym(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001467 """Platform specific way to build binaries with dsym info."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001468 if lldb.skip_build_and_cleanup:
1469 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00001470 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001471 if not module.buildDsym(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001472 raise Exception("Don't know how to build binary with dsym")
1473
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001474 def buildDwarf(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001475 """Platform specific way to build binaries with dwarf maps."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001476 if lldb.skip_build_and_cleanup:
1477 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00001478 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001479 if not module.buildDwarf(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001480 raise Exception("Don't know how to build binary with dwarf")
Johnny Chena74bb0a2011-08-01 18:46:13 +00001481
Daniel Malea9115f072013-08-06 15:02:32 +00001482 def getBuildFlags(self, use_cpp11=True, use_libcxx=False, use_libstdcxx=False, use_pthreads=True):
Andrew Kaylor93132f52013-05-28 23:04:25 +00001483 """ Returns a dictionary (which can be provided to build* functions above) which
1484 contains OS-specific build flags.
1485 """
1486 cflags = ""
Daniel Malea9115f072013-08-06 15:02:32 +00001487
1488 # On Mac OS X, unless specifically requested to use libstdc++, use libc++
1489 if not use_libstdcxx and sys.platform.startswith('darwin'):
1490 use_libcxx = True
1491
1492 if use_libcxx and self.libcxxPath:
1493 cflags += "-stdlib=libc++ "
1494 if self.libcxxPath:
1495 libcxxInclude = os.path.join(self.libcxxPath, "include")
1496 libcxxLib = os.path.join(self.libcxxPath, "lib")
1497 if os.path.isdir(libcxxInclude) and os.path.isdir(libcxxLib):
1498 cflags += "-nostdinc++ -I%s -L%s -Wl,-rpath,%s " % (libcxxInclude, libcxxLib, libcxxLib)
1499
Andrew Kaylor93132f52013-05-28 23:04:25 +00001500 if use_cpp11:
1501 cflags += "-std="
1502 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
1503 cflags += "c++0x"
1504 else:
1505 cflags += "c++11"
1506 if sys.platform.startswith("darwin"):
1507 cflags += " -stdlib=libc++"
1508 elif "clang" in self.getCompiler():
1509 cflags += " -stdlib=libstdc++"
1510
1511 if use_pthreads:
1512 ldflags = "-lpthread"
1513
1514 return {'CFLAGS_EXTRAS' : cflags,
1515 'LD_EXTRAS' : ldflags,
1516 }
1517
Johnny Chen9f4f5d92011-08-12 20:19:22 +00001518 def cleanup(self, dictionary=None):
1519 """Platform specific way to do cleanup after build."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001520 if lldb.skip_build_and_cleanup:
1521 return
Johnny Chen9f4f5d92011-08-12 20:19:22 +00001522 module = builder_module()
1523 if not module.cleanup(self, dictionary):
Johnny Chen0fddfb22011-11-17 19:57:27 +00001524 raise Exception("Don't know how to do cleanup with dictionary: "+dictionary)
Johnny Chen9f4f5d92011-08-12 20:19:22 +00001525
Daniel Malea55faa402013-05-02 21:44:31 +00001526 def getLLDBLibraryEnvVal(self):
1527 """ Returns the path that the OS-specific library search environment variable
1528 (self.dylibPath) should be set to in order for a program to find the LLDB
1529 library. If an environment variable named self.dylibPath is already set,
1530 the new path is appended to it and returned.
1531 """
1532 existing_library_path = os.environ[self.dylibPath] if self.dylibPath in os.environ else None
1533 if existing_library_path:
1534 return "%s:%s" % (existing_library_path, self.lib_dir)
1535 elif sys.platform.startswith("darwin"):
1536 return os.path.join(self.lib_dir, 'LLDB.framework')
1537 else:
1538 return self.lib_dir
Johnny Chena74bb0a2011-08-01 18:46:13 +00001539
Ed Maste437f8f62013-09-09 14:04:04 +00001540 def getLibcPlusPlusLibs(self):
1541 if sys.platform.startswith('freebsd'):
1542 return ['libc++.so.1']
1543 else:
1544 return ['libc++.1.dylib','libc++abi.dylib']
1545
Johnny Chena74bb0a2011-08-01 18:46:13 +00001546class TestBase(Base):
1547 """
1548 This abstract base class is meant to be subclassed. It provides default
1549 implementations for setUpClass(), tearDownClass(), setUp(), and tearDown(),
1550 among other things.
1551
1552 Important things for test class writers:
1553
1554 - Overwrite the mydir class attribute, otherwise your test class won't
1555 run. It specifies the relative directory to the top level 'test' so
1556 the test harness can change to the correct working directory before
1557 running your test.
1558
1559 - The setUp method sets up things to facilitate subsequent interactions
1560 with the debugger as part of the test. These include:
1561 - populate the test method name
1562 - create/get a debugger set with synchronous mode (self.dbg)
1563 - get the command interpreter from with the debugger (self.ci)
1564 - create a result object for use with the command interpreter
1565 (self.res)
1566 - plus other stuffs
1567
1568 - The tearDown method tries to perform some necessary cleanup on behalf
1569 of the test to return the debugger to a good state for the next test.
1570 These include:
1571 - execute any tearDown hooks registered by the test method with
1572 TestBase.addTearDownHook(); examples can be found in
1573 settings/TestSettings.py
1574 - kill the inferior process associated with each target, if any,
1575 and, then delete the target from the debugger's target list
1576 - perform build cleanup before running the next test method in the
1577 same test class; examples of registering for this service can be
1578 found in types/TestIntegerTypes.py with the call:
1579 - self.setTearDownCleanup(dictionary=d)
1580
1581 - Similarly setUpClass and tearDownClass perform classwise setup and
1582 teardown fixtures. The tearDownClass method invokes a default build
1583 cleanup for the entire test class; also, subclasses can implement the
1584 classmethod classCleanup(cls) to perform special class cleanup action.
1585
1586 - The instance methods runCmd and expect are used heavily by existing
1587 test cases to send a command to the command interpreter and to perform
1588 string/pattern matching on the output of such command execution. The
1589 expect method also provides a mode to peform string/pattern matching
1590 without running a command.
1591
1592 - The build methods buildDefault, buildDsym, and buildDwarf are used to
1593 build the binaries used during a particular test scenario. A plugin
1594 should be provided for the sys.platform running the test suite. The
1595 Mac OS X implementation is located in plugins/darwin.py.
1596 """
1597
1598 # Maximum allowed attempts when launching the inferior process.
1599 # Can be overridden by the LLDB_MAX_LAUNCH_COUNT environment variable.
1600 maxLaunchCount = 3;
1601
1602 # Time to wait before the next launching attempt in second(s).
1603 # Can be overridden by the LLDB_TIME_WAIT_NEXT_LAUNCH environment variable.
1604 timeWaitNextLaunch = 1.0;
1605
1606 def doDelay(self):
1607 """See option -w of dotest.py."""
1608 if ("LLDB_WAIT_BETWEEN_TEST_CASES" in os.environ and
1609 os.environ["LLDB_WAIT_BETWEEN_TEST_CASES"] == 'YES'):
1610 waitTime = 1.0
1611 if "LLDB_TIME_WAIT_BETWEEN_TEST_CASES" in os.environ:
1612 waitTime = float(os.environ["LLDB_TIME_WAIT_BETWEEN_TEST_CASES"])
1613 time.sleep(waitTime)
1614
Enrico Granata165f8af2012-09-21 19:10:53 +00001615 # Returns the list of categories to which this test case belongs
1616 # by default, look for a ".categories" file, and read its contents
1617 # if no such file exists, traverse the hierarchy - we guarantee
1618 # a .categories to exist at the top level directory so we do not end up
1619 # looping endlessly - subclasses are free to define their own categories
1620 # in whatever way makes sense to them
1621 def getCategories(self):
1622 import inspect
1623 import os.path
1624 folder = inspect.getfile(self.__class__)
1625 folder = os.path.dirname(folder)
1626 while folder != '/':
1627 categories_file_name = os.path.join(folder,".categories")
1628 if os.path.exists(categories_file_name):
1629 categories_file = open(categories_file_name,'r')
1630 categories = categories_file.readline()
1631 categories_file.close()
1632 categories = str.replace(categories,'\n','')
1633 categories = str.replace(categories,'\r','')
1634 return categories.split(',')
1635 else:
1636 folder = os.path.dirname(folder)
1637 continue
1638
Johnny Chena74bb0a2011-08-01 18:46:13 +00001639 def setUp(self):
1640 #import traceback
1641 #traceback.print_stack()
1642
1643 # Works with the test driver to conditionally skip tests via decorators.
1644 Base.setUp(self)
1645
Johnny Chena74bb0a2011-08-01 18:46:13 +00001646 try:
1647 if lldb.blacklist:
1648 className = self.__class__.__name__
1649 classAndMethodName = "%s.%s" % (className, self._testMethodName)
1650 if className in lldb.blacklist:
1651 self.skipTest(lldb.blacklist.get(className))
1652 elif classAndMethodName in lldb.blacklist:
1653 self.skipTest(lldb.blacklist.get(classAndMethodName))
1654 except AttributeError:
1655 pass
1656
Johnny Chened492022011-06-21 00:53:00 +00001657 # Insert some delay between successive test cases if specified.
1658 self.doDelay()
Johnny Chen0ed37c92010-10-07 02:04:14 +00001659
Johnny Chenf2b70232010-08-25 18:49:48 +00001660 if "LLDB_MAX_LAUNCH_COUNT" in os.environ:
1661 self.maxLaunchCount = int(os.environ["LLDB_MAX_LAUNCH_COUNT"])
1662
Johnny Chen430eb762010-10-19 16:00:42 +00001663 if "LLDB_TIME_WAIT_NEXT_LAUNCH" in os.environ:
Johnny Chen4921b112010-11-29 20:20:34 +00001664 self.timeWaitNextLaunch = float(os.environ["LLDB_TIME_WAIT_NEXT_LAUNCH"])
Johnny Chenf2b70232010-08-25 18:49:48 +00001665
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001666 # Create the debugger instance if necessary.
1667 try:
1668 self.dbg = lldb.DBG
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001669 except AttributeError:
1670 self.dbg = lldb.SBDebugger.Create()
Johnny Chenf02ec122010-07-03 20:41:42 +00001671
Johnny Chen3cd1e552011-05-25 19:06:18 +00001672 if not self.dbg:
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001673 raise Exception('Invalid debugger instance')
1674
Daniel Maleae0f8f572013-08-26 23:57:52 +00001675 #
1676 # Warning: MAJOR HACK AHEAD!
1677 # If we are running testsuite remotely (by checking lldb.lldbtest_remote_sandbox),
1678 # redefine the self.dbg.CreateTarget(filename) method to execute a "file filename"
1679 # command, instead. See also runCmd() where it decorates the "file filename" call
1680 # with additional functionality when running testsuite remotely.
1681 #
1682 if lldb.lldbtest_remote_sandbox:
1683 def DecoratedCreateTarget(arg):
1684 self.runCmd("file %s" % arg)
1685 target = self.dbg.GetSelectedTarget()
1686 #
1687 # SBTarget.LaunchSimple() currently not working for remote platform?
1688 # johnny @ 04/23/2012
1689 #
1690 def DecoratedLaunchSimple(argv, envp, wd):
1691 self.runCmd("run")
1692 return target.GetProcess()
1693 target.LaunchSimple = DecoratedLaunchSimple
1694
1695 return target
1696 self.dbg.CreateTarget = DecoratedCreateTarget
1697 if self.TraceOn():
1698 print "self.dbg.Create is redefined to:\n%s" % getsource_if_available(DecoratedCreateTarget)
1699
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001700 # We want our debugger to be synchronous.
1701 self.dbg.SetAsync(False)
1702
1703 # Retrieve the associated command interpreter instance.
1704 self.ci = self.dbg.GetCommandInterpreter()
1705 if not self.ci:
1706 raise Exception('Could not get the command interpreter')
1707
1708 # And the result object.
1709 self.res = lldb.SBCommandReturnObject()
1710
Johnny Chen44d24972012-04-16 18:55:15 +00001711 # Run global pre-flight code, if defined via the config file.
1712 if lldb.pre_flight:
1713 lldb.pre_flight(self)
1714
Greg Claytonfb909312013-11-23 01:58:15 +00001715 if lldb.remote_platform:
1716 #remote_test_dir = os.path.join(lldb.remote_platform_working_dir, self.mydir)
Greg Clayton5fb8f792013-12-02 19:35:49 +00001717 remote_test_dir = os.path.join(lldb.remote_platform_working_dir,
1718 self.getArchitecture(),
1719 str(self.test_number),
1720 self.mydir)
Greg Claytonfb909312013-11-23 01:58:15 +00001721 error = lldb.remote_platform.MakeDirectory(remote_test_dir, 0700)
1722 if error.Success():
Greg Claytonfb909312013-11-23 01:58:15 +00001723 lldb.remote_platform.SetWorkingDirectory(remote_test_dir)
1724 else:
1725 print "error: making remote directory '%s': %s" % (remote_test_dir, error)
1726
Enrico Granata44818162012-10-24 01:23:57 +00001727 # utility methods that tests can use to access the current objects
1728 def target(self):
1729 if not self.dbg:
1730 raise Exception('Invalid debugger instance')
1731 return self.dbg.GetSelectedTarget()
1732
1733 def process(self):
1734 if not self.dbg:
1735 raise Exception('Invalid debugger instance')
1736 return self.dbg.GetSelectedTarget().GetProcess()
1737
1738 def thread(self):
1739 if not self.dbg:
1740 raise Exception('Invalid debugger instance')
1741 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread()
1742
1743 def frame(self):
1744 if not self.dbg:
1745 raise Exception('Invalid debugger instance')
1746 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame()
1747
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001748 def tearDown(self):
Johnny Chen7d1d7532010-09-02 21:23:12 +00001749 #import traceback
1750 #traceback.print_stack()
1751
Johnny Chenfb4264c2011-08-01 19:50:58 +00001752 Base.tearDown(self)
Johnny Chen707d8222010-10-19 23:40:13 +00001753
Johnny Chen3794ad92011-06-15 21:24:24 +00001754 # Delete the target(s) from the debugger as a general cleanup step.
1755 # This includes terminating the process for each target, if any.
1756 # We'd like to reuse the debugger for our next test without incurring
1757 # the initialization overhead.
1758 targets = []
1759 for target in self.dbg:
1760 if target:
1761 targets.append(target)
1762 process = target.GetProcess()
1763 if process:
1764 rc = self.invoke(process, "Kill")
1765 self.assertTrue(rc.Success(), PROCESS_KILLED)
1766 for target in targets:
1767 self.dbg.DeleteTarget(target)
Johnny Chen6ca006c2010-08-16 21:28:10 +00001768
Johnny Chen44d24972012-04-16 18:55:15 +00001769 # Run global post-flight code, if defined via the config file.
1770 if lldb.post_flight:
1771 lldb.post_flight(self)
1772
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001773 del self.dbg
Johnny Chen150c3cc2010-10-15 01:18:29 +00001774
Johnny Chen86268e42011-09-30 21:48:35 +00001775 def switch_to_thread_with_stop_reason(self, stop_reason):
1776 """
1777 Run the 'thread list' command, and select the thread with stop reason as
1778 'stop_reason'. If no such thread exists, no select action is done.
1779 """
1780 from lldbutil import stop_reason_to_str
1781 self.runCmd('thread list')
1782 output = self.res.GetOutput()
1783 thread_line_pattern = re.compile("^[ *] thread #([0-9]+):.*stop reason = %s" %
1784 stop_reason_to_str(stop_reason))
1785 for line in output.splitlines():
1786 matched = thread_line_pattern.match(line)
1787 if matched:
1788 self.runCmd('thread select %s' % matched.group(1))
1789
Enrico Granata7594f142013-06-17 22:51:50 +00001790 def runCmd(self, cmd, msg=None, check=True, trace=False, inHistory=False):
Johnny Chen27f212d2010-08-19 23:26:59 +00001791 """
1792 Ask the command interpreter to handle the command and then check its
1793 return status.
1794 """
1795 # Fail fast if 'cmd' is not meaningful.
1796 if not cmd or len(cmd) == 0:
1797 raise Exception("Bad 'cmd' parameter encountered")
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001798
Johnny Chen8d55a342010-08-31 17:42:54 +00001799 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00001800
Daniel Maleae0f8f572013-08-26 23:57:52 +00001801 # This is an opportunity to insert the 'platform target-install' command if we are told so
1802 # via the settig of lldb.lldbtest_remote_sandbox.
1803 if cmd.startswith("target create "):
1804 cmd = cmd.replace("target create ", "file ")
1805 if cmd.startswith("file ") and lldb.lldbtest_remote_sandbox:
1806 with recording(self, trace) as sbuf:
1807 the_rest = cmd.split("file ")[1]
1808 # Split the rest of the command line.
1809 atoms = the_rest.split()
1810 #
1811 # NOTE: This assumes that the options, if any, follow the file command,
1812 # instead of follow the specified target.
1813 #
1814 target = atoms[-1]
1815 # Now let's get the absolute pathname of our target.
1816 abs_target = os.path.abspath(target)
1817 print >> sbuf, "Found a file command, target (with absolute pathname)=%s" % abs_target
1818 fpath, fname = os.path.split(abs_target)
1819 parent_dir = os.path.split(fpath)[0]
1820 platform_target_install_command = 'platform target-install %s %s' % (fpath, lldb.lldbtest_remote_sandbox)
1821 print >> sbuf, "Insert this command to be run first: %s" % platform_target_install_command
1822 self.ci.HandleCommand(platform_target_install_command, self.res)
1823 # And this is the file command we want to execute, instead.
1824 #
1825 # Warning: SIDE EFFECT AHEAD!!!
1826 # Populate the remote executable pathname into the lldb namespace,
1827 # so that test cases can grab this thing out of the namespace.
1828 #
1829 lldb.lldbtest_remote_sandboxed_executable = abs_target.replace(parent_dir, lldb.lldbtest_remote_sandbox)
1830 cmd = "file -P %s %s %s" % (lldb.lldbtest_remote_sandboxed_executable, the_rest.replace(target, ''), abs_target)
1831 print >> sbuf, "And this is the replaced file command: %s" % cmd
1832
Johnny Chen63dfb272010-09-01 00:15:19 +00001833 running = (cmd.startswith("run") or cmd.startswith("process launch"))
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001834
Johnny Chen63dfb272010-09-01 00:15:19 +00001835 for i in range(self.maxLaunchCount if running else 1):
Enrico Granata7594f142013-06-17 22:51:50 +00001836 self.ci.HandleCommand(cmd, self.res, inHistory)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001837
Johnny Chen150c3cc2010-10-15 01:18:29 +00001838 with recording(self, trace) as sbuf:
1839 print >> sbuf, "runCmd:", cmd
Johnny Chenab254f52010-10-15 16:13:00 +00001840 if not check:
Johnny Chen27b107b2010-10-15 18:52:22 +00001841 print >> sbuf, "check of return status not required"
Johnny Chenf2b70232010-08-25 18:49:48 +00001842 if self.res.Succeeded():
Johnny Chen150c3cc2010-10-15 01:18:29 +00001843 print >> sbuf, "output:", self.res.GetOutput()
Johnny Chenf2b70232010-08-25 18:49:48 +00001844 else:
Johnny Chen150c3cc2010-10-15 01:18:29 +00001845 print >> sbuf, "runCmd failed!"
1846 print >> sbuf, self.res.GetError()
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001847
Johnny Chenff3d01d2010-08-20 21:03:09 +00001848 if self.res.Succeeded():
Johnny Chenf2b70232010-08-25 18:49:48 +00001849 break
Johnny Chen150c3cc2010-10-15 01:18:29 +00001850 elif running:
Johnny Chencf7f74e2011-01-19 02:02:08 +00001851 # For process launch, wait some time before possible next try.
1852 time.sleep(self.timeWaitNextLaunch)
Johnny Chen552d6712012-08-01 19:56:04 +00001853 with recording(self, trace) as sbuf:
Johnny Chen150c3cc2010-10-15 01:18:29 +00001854 print >> sbuf, "Command '" + cmd + "' failed!"
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001855
Johnny Chen27f212d2010-08-19 23:26:59 +00001856 if check:
1857 self.assertTrue(self.res.Succeeded(),
Johnny Chenc0c67f22010-11-09 18:42:22 +00001858 msg if msg else CMD_MSG(cmd))
Johnny Chen27f212d2010-08-19 23:26:59 +00001859
Jim Ingham63dfc722012-09-22 00:05:11 +00001860 def match (self, str, patterns, msg=None, trace=False, error=False, matching=True, exe=True):
1861 """run command in str, and match the result against regexp in patterns returning the match object for the first matching pattern
1862
1863 Otherwise, all the arguments have the same meanings as for the expect function"""
1864
1865 trace = (True if traceAlways else trace)
1866
1867 if exe:
1868 # First run the command. If we are expecting error, set check=False.
1869 # Pass the assert message along since it provides more semantic info.
1870 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error)
1871
1872 # Then compare the output against expected strings.
1873 output = self.res.GetError() if error else self.res.GetOutput()
1874
1875 # If error is True, the API client expects the command to fail!
1876 if error:
1877 self.assertFalse(self.res.Succeeded(),
1878 "Command '" + str + "' is expected to fail!")
1879 else:
1880 # No execution required, just compare str against the golden input.
1881 output = str
1882 with recording(self, trace) as sbuf:
1883 print >> sbuf, "looking at:", output
1884
1885 # The heading says either "Expecting" or "Not expecting".
1886 heading = "Expecting" if matching else "Not expecting"
1887
1888 for pattern in patterns:
1889 # Match Objects always have a boolean value of True.
1890 match_object = re.search(pattern, output)
1891 matched = bool(match_object)
1892 with recording(self, trace) as sbuf:
1893 print >> sbuf, "%s pattern: %s" % (heading, pattern)
1894 print >> sbuf, "Matched" if matched else "Not matched"
1895 if matched:
1896 break
1897
1898 self.assertTrue(matched if matching else not matched,
1899 msg if msg else EXP_MSG(str, exe))
1900
1901 return match_object
1902
Enrico Granata7594f142013-06-17 22:51:50 +00001903 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 +00001904 """
1905 Similar to runCmd; with additional expect style output matching ability.
1906
1907 Ask the command interpreter to handle the command and then check its
1908 return status. The 'msg' parameter specifies an informational assert
1909 message. We expect the output from running the command to start with
Johnny Chenea88e942010-09-21 21:08:53 +00001910 'startstr', matches the substrings contained in 'substrs', and regexp
1911 matches the patterns contained in 'patterns'.
Johnny Chenb3307862010-09-17 22:28:51 +00001912
1913 If the keyword argument error is set to True, it signifies that the API
1914 client is expecting the command to fail. In this case, the error stream
Johnny Chenaa902922010-09-17 22:45:27 +00001915 from running the command is retrieved and compared against the golden
Johnny Chenb3307862010-09-17 22:28:51 +00001916 input, instead.
Johnny Chenea88e942010-09-21 21:08:53 +00001917
1918 If the keyword argument matching is set to False, it signifies that the API
1919 client is expecting the output of the command not to match the golden
1920 input.
Johnny Chen9c48b8d2010-09-21 23:33:30 +00001921
1922 Finally, the required argument 'str' represents the lldb command to be
1923 sent to the command interpreter. In case the keyword argument 'exe' is
1924 set to False, the 'str' is treated as a string to be matched/not-matched
1925 against the golden input.
Johnny Chen27f212d2010-08-19 23:26:59 +00001926 """
Johnny Chen8d55a342010-08-31 17:42:54 +00001927 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00001928
Johnny Chen9c48b8d2010-09-21 23:33:30 +00001929 if exe:
1930 # First run the command. If we are expecting error, set check=False.
Johnny Chen62d4f862010-10-28 21:10:32 +00001931 # Pass the assert message along since it provides more semantic info.
Enrico Granata7594f142013-06-17 22:51:50 +00001932 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error, inHistory=inHistory)
Johnny Chen27f212d2010-08-19 23:26:59 +00001933
Johnny Chen9c48b8d2010-09-21 23:33:30 +00001934 # Then compare the output against expected strings.
1935 output = self.res.GetError() if error else self.res.GetOutput()
Johnny Chenb3307862010-09-17 22:28:51 +00001936
Johnny Chen9c48b8d2010-09-21 23:33:30 +00001937 # If error is True, the API client expects the command to fail!
1938 if error:
1939 self.assertFalse(self.res.Succeeded(),
1940 "Command '" + str + "' is expected to fail!")
1941 else:
1942 # No execution required, just compare str against the golden input.
Enrico Granatabc08ab42012-10-23 00:09:02 +00001943 if isinstance(str,lldb.SBCommandReturnObject):
1944 output = str.GetOutput()
1945 else:
1946 output = str
Johnny Chen150c3cc2010-10-15 01:18:29 +00001947 with recording(self, trace) as sbuf:
1948 print >> sbuf, "looking at:", output
Johnny Chenb3307862010-09-17 22:28:51 +00001949
Johnny Chenea88e942010-09-21 21:08:53 +00001950 # The heading says either "Expecting" or "Not expecting".
Johnny Chen150c3cc2010-10-15 01:18:29 +00001951 heading = "Expecting" if matching else "Not expecting"
Johnny Chenea88e942010-09-21 21:08:53 +00001952
1953 # Start from the startstr, if specified.
1954 # If there's no startstr, set the initial state appropriately.
1955 matched = output.startswith(startstr) if startstr else (True if matching else False)
Johnny Chenb145bba2010-08-20 18:25:15 +00001956
Johnny Chen150c3cc2010-10-15 01:18:29 +00001957 if startstr:
1958 with recording(self, trace) as sbuf:
1959 print >> sbuf, "%s start string: %s" % (heading, startstr)
1960 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenb145bba2010-08-20 18:25:15 +00001961
Johnny Chen86268e42011-09-30 21:48:35 +00001962 # Look for endstr, if specified.
1963 keepgoing = matched if matching else not matched
1964 if endstr:
1965 matched = output.endswith(endstr)
1966 with recording(self, trace) as sbuf:
1967 print >> sbuf, "%s end string: %s" % (heading, endstr)
1968 print >> sbuf, "Matched" if matched else "Not matched"
1969
Johnny Chenea88e942010-09-21 21:08:53 +00001970 # Look for sub strings, if specified.
1971 keepgoing = matched if matching else not matched
1972 if substrs and keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00001973 for str in substrs:
Johnny Chenb052f6c2010-09-23 23:35:28 +00001974 matched = output.find(str) != -1
Johnny Chen150c3cc2010-10-15 01:18:29 +00001975 with recording(self, trace) as sbuf:
1976 print >> sbuf, "%s sub string: %s" % (heading, str)
1977 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenea88e942010-09-21 21:08:53 +00001978 keepgoing = matched if matching else not matched
1979 if not keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00001980 break
1981
Johnny Chenea88e942010-09-21 21:08:53 +00001982 # Search for regular expression patterns, if specified.
1983 keepgoing = matched if matching else not matched
1984 if patterns and keepgoing:
1985 for pattern in patterns:
1986 # Match Objects always have a boolean value of True.
1987 matched = bool(re.search(pattern, output))
Johnny Chen150c3cc2010-10-15 01:18:29 +00001988 with recording(self, trace) as sbuf:
1989 print >> sbuf, "%s pattern: %s" % (heading, pattern)
1990 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenea88e942010-09-21 21:08:53 +00001991 keepgoing = matched if matching else not matched
1992 if not keepgoing:
1993 break
Johnny Chenea88e942010-09-21 21:08:53 +00001994
1995 self.assertTrue(matched if matching else not matched,
Johnny Chenc0c67f22010-11-09 18:42:22 +00001996 msg if msg else EXP_MSG(str, exe))
Johnny Chen27f212d2010-08-19 23:26:59 +00001997
Johnny Chenf3c59232010-08-25 22:52:45 +00001998 def invoke(self, obj, name, trace=False):
Johnny Chen61703c92010-08-25 22:56:10 +00001999 """Use reflection to call a method dynamically with no argument."""
Johnny Chen8d55a342010-08-31 17:42:54 +00002000 trace = (True if traceAlways else trace)
Johnny Chenf3c59232010-08-25 22:52:45 +00002001
2002 method = getattr(obj, name)
2003 import inspect
2004 self.assertTrue(inspect.ismethod(method),
2005 name + "is a method name of object: " + str(obj))
2006 result = method()
Johnny Chen150c3cc2010-10-15 01:18:29 +00002007 with recording(self, trace) as sbuf:
2008 print >> sbuf, str(method) + ":", result
Johnny Chenf3c59232010-08-25 22:52:45 +00002009 return result
Johnny Chen827edff2010-08-27 00:15:48 +00002010
Johnny Chenf359cf22011-05-27 23:36:52 +00002011 # =================================================
2012 # Misc. helper methods for debugging test execution
2013 # =================================================
2014
Johnny Chen56b92a72011-07-11 19:15:11 +00002015 def DebugSBValue(self, val):
Johnny Chen8d55a342010-08-31 17:42:54 +00002016 """Debug print a SBValue object, if traceAlways is True."""
Johnny Chende90f1d2011-04-27 17:43:07 +00002017 from lldbutil import value_type_to_str
Johnny Chen87bb5892010-11-03 21:37:58 +00002018
Johnny Chen8d55a342010-08-31 17:42:54 +00002019 if not traceAlways:
Johnny Chen827edff2010-08-27 00:15:48 +00002020 return
2021
2022 err = sys.stderr
2023 err.write(val.GetName() + ":\n")
Johnny Chen86268e42011-09-30 21:48:35 +00002024 err.write('\t' + "TypeName -> " + val.GetTypeName() + '\n')
2025 err.write('\t' + "ByteSize -> " + str(val.GetByteSize()) + '\n')
2026 err.write('\t' + "NumChildren -> " + str(val.GetNumChildren()) + '\n')
2027 err.write('\t' + "Value -> " + str(val.GetValue()) + '\n')
2028 err.write('\t' + "ValueAsUnsigned -> " + str(val.GetValueAsUnsigned())+ '\n')
2029 err.write('\t' + "ValueType -> " + value_type_to_str(val.GetValueType()) + '\n')
2030 err.write('\t' + "Summary -> " + str(val.GetSummary()) + '\n')
2031 err.write('\t' + "IsPointerType -> " + str(val.TypeIsPointerType()) + '\n')
2032 err.write('\t' + "Location -> " + val.GetLocation() + '\n')
Johnny Chen827edff2010-08-27 00:15:48 +00002033
Johnny Chen36c5eb12011-08-05 20:17:27 +00002034 def DebugSBType(self, type):
2035 """Debug print a SBType object, if traceAlways is True."""
2036 if not traceAlways:
2037 return
2038
2039 err = sys.stderr
2040 err.write(type.GetName() + ":\n")
2041 err.write('\t' + "ByteSize -> " + str(type.GetByteSize()) + '\n')
2042 err.write('\t' + "IsPointerType -> " + str(type.IsPointerType()) + '\n')
2043 err.write('\t' + "IsReferenceType -> " + str(type.IsReferenceType()) + '\n')
2044
Johnny Chenb877f1e2011-03-12 01:18:19 +00002045 def DebugPExpect(self, child):
2046 """Debug the spwaned pexpect object."""
2047 if not traceAlways:
2048 return
2049
2050 print child
Filipe Cabecinhas0eec15a2012-06-20 10:13:40 +00002051
2052 @classmethod
2053 def RemoveTempFile(cls, file):
2054 if os.path.exists(file):
2055 os.remove(file)