blob: 5e0a258288638b55230c6220d8120e1f012cc5e0 [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
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +000034import abc
Johnny Chen90312a82010-09-21 22:34:45 +000035import os, sys, traceback
Enrico Granata7e137e32012-10-24 18:14:21 +000036import os.path
Johnny Chenea88e942010-09-21 21:08:53 +000037import re
Daniel Malea69207462013-06-05 21:07:02 +000038import signal
Johnny Chen8952a2d2010-08-30 21:35:00 +000039from subprocess import *
Johnny Chen150c3cc2010-10-15 01:18:29 +000040import StringIO
Johnny Chenf2b70232010-08-25 18:49:48 +000041import time
Johnny Chena33a93c2010-08-30 23:08:52 +000042import types
Johnny Chen73258832010-08-05 23:42:46 +000043import unittest2
Johnny Chenbf6ffa32010-07-03 03:41:59 +000044import lldb
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +000045from _pyio import __metaclass__
Johnny Chenbf6ffa32010-07-03 03:41:59 +000046
Johnny Chen707b3c92010-10-11 22:25:46 +000047# See also dotest.parseOptionsAndInitTestdirs(), where the environment variables
Johnny Chend2047fa2011-01-19 18:18:47 +000048# LLDB_COMMAND_TRACE and LLDB_DO_CLEANUP are set from '-t' and '-r dir' options.
Johnny Chen707b3c92010-10-11 22:25:46 +000049
50# By default, traceAlways is False.
Johnny Chen8d55a342010-08-31 17:42:54 +000051if "LLDB_COMMAND_TRACE" in os.environ and os.environ["LLDB_COMMAND_TRACE"]=="YES":
52 traceAlways = True
53else:
54 traceAlways = False
55
Johnny Chen707b3c92010-10-11 22:25:46 +000056# By default, doCleanup is True.
57if "LLDB_DO_CLEANUP" in os.environ and os.environ["LLDB_DO_CLEANUP"]=="NO":
58 doCleanup = False
59else:
60 doCleanup = True
61
Johnny Chen8d55a342010-08-31 17:42:54 +000062
Johnny Chen00778092010-08-09 22:01:17 +000063#
64# Some commonly used assert messages.
65#
66
Johnny Chenaa902922010-09-17 22:45:27 +000067COMMAND_FAILED_AS_EXPECTED = "Command has failed as expected"
68
Johnny Chen00778092010-08-09 22:01:17 +000069CURRENT_EXECUTABLE_SET = "Current executable set successfully"
70
Johnny Chen7d1d7532010-09-02 21:23:12 +000071PROCESS_IS_VALID = "Process is valid"
72
73PROCESS_KILLED = "Process is killed successfully"
74
Johnny Chend5f66fc2010-12-23 01:12:19 +000075PROCESS_EXITED = "Process exited successfully"
76
77PROCESS_STOPPED = "Process status should be stopped"
78
Johnny Chen5ee88192010-08-27 23:47:36 +000079RUN_SUCCEEDED = "Process is launched successfully"
Johnny Chen00778092010-08-09 22:01:17 +000080
Johnny Chen17941842010-08-09 23:44:24 +000081RUN_COMPLETED = "Process exited successfully"
Johnny Chen00778092010-08-09 22:01:17 +000082
Johnny Chen67af43f2010-10-05 19:27:32 +000083BACKTRACE_DISPLAYED_CORRECTLY = "Backtrace displayed correctly"
84
Johnny Chen17941842010-08-09 23:44:24 +000085BREAKPOINT_CREATED = "Breakpoint created successfully"
86
Johnny Chenf10af382010-12-04 00:07:24 +000087BREAKPOINT_STATE_CORRECT = "Breakpoint state is correct"
88
Johnny Chene76896c2010-08-17 21:33:31 +000089BREAKPOINT_PENDING_CREATED = "Pending breakpoint created successfully"
90
Johnny Chen17941842010-08-09 23:44:24 +000091BREAKPOINT_HIT_ONCE = "Breakpoint resolved with hit cout = 1"
Johnny Chen00778092010-08-09 22:01:17 +000092
Johnny Chen703dbd02010-09-30 17:06:24 +000093BREAKPOINT_HIT_TWICE = "Breakpoint resolved with hit cout = 2"
94
Johnny Chen164f1e12010-10-15 18:07:09 +000095BREAKPOINT_HIT_THRICE = "Breakpoint resolved with hit cout = 3"
96
Greg Clayton5db6b792012-10-24 18:24:14 +000097MISSING_EXPECTED_REGISTERS = "At least one expected register is unavailable."
98
Johnny Chen89109ed12011-06-27 20:05:23 +000099OBJECT_PRINTED_CORRECTLY = "Object printed correctly"
100
Johnny Chen5b3a3572010-12-09 18:22:12 +0000101SOURCE_DISPLAYED_CORRECTLY = "Source code displayed correctly"
102
Johnny Chenc70b02a2010-09-22 23:00:20 +0000103STEP_OUT_SUCCEEDED = "Thread step-out succeeded"
104
Johnny Chen1691a162011-04-15 16:44:48 +0000105STOPPED_DUE_TO_EXC_BAD_ACCESS = "Process should be stopped due to bad access exception"
106
Ashok Thirumurthib4e51342013-05-17 15:35:15 +0000107STOPPED_DUE_TO_ASSERT = "Process should be stopped due to an assertion"
108
Johnny Chen5d6c4642010-11-10 23:46:38 +0000109STOPPED_DUE_TO_BREAKPOINT = "Process should be stopped due to breakpoint"
Johnny Chende0338b2010-11-10 20:20:06 +0000110
Johnny Chen5d6c4642010-11-10 23:46:38 +0000111STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS = "%s, %s" % (
112 STOPPED_DUE_TO_BREAKPOINT, "instead, the actual stop reason is: '%s'")
Johnny Chen00778092010-08-09 22:01:17 +0000113
Johnny Chen2e431ce2010-10-20 18:38:48 +0000114STOPPED_DUE_TO_BREAKPOINT_CONDITION = "Stopped due to breakpoint condition"
115
Johnny Chen0a3d1ca2010-12-13 21:49:58 +0000116STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT = "Stopped due to breakpoint and ignore count"
117
Johnny Chenc066ab42010-10-14 01:22:03 +0000118STOPPED_DUE_TO_SIGNAL = "Process state is stopped due to signal"
119
Johnny Chen00778092010-08-09 22:01:17 +0000120STOPPED_DUE_TO_STEP_IN = "Process state is stopped due to step in"
121
Johnny Chenf68cc122011-09-15 21:09:59 +0000122STOPPED_DUE_TO_WATCHPOINT = "Process should be stopped due to watchpoint"
123
Johnny Chen3c884a02010-08-24 22:07:56 +0000124DATA_TYPES_DISPLAYED_CORRECTLY = "Data type(s) displayed correctly"
125
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000126VALID_BREAKPOINT = "Got a valid breakpoint"
127
Johnny Chen5bfb8ee2010-10-22 18:10:25 +0000128VALID_BREAKPOINT_LOCATION = "Got a valid breakpoint location"
129
Johnny Chen7209d84f2011-05-06 23:26:12 +0000130VALID_COMMAND_INTERPRETER = "Got a valid command interpreter"
131
Johnny Chen5ee88192010-08-27 23:47:36 +0000132VALID_FILESPEC = "Got a valid filespec"
133
Johnny Chen025d1b82010-12-08 01:25:21 +0000134VALID_MODULE = "Got a valid module"
135
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000136VALID_PROCESS = "Got a valid process"
137
Johnny Chen025d1b82010-12-08 01:25:21 +0000138VALID_SYMBOL = "Got a valid symbol"
139
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000140VALID_TARGET = "Got a valid target"
141
Matthew Gardinerc928de32014-10-22 07:22:56 +0000142VALID_PLATFORM = "Got a valid platform"
143
Johnny Chen15f247a2012-02-03 20:43:00 +0000144VALID_TYPE = "Got a valid type"
145
Johnny Chen5819ab42011-07-15 22:28:10 +0000146VALID_VARIABLE = "Got a valid variable"
147
Johnny Chen981463d2010-08-25 19:00:04 +0000148VARIABLES_DISPLAYED_CORRECTLY = "Variable(s) displayed correctly"
Johnny Chen00778092010-08-09 22:01:17 +0000149
Johnny Chenf68cc122011-09-15 21:09:59 +0000150WATCHPOINT_CREATED = "Watchpoint created successfully"
Johnny Chen5fca8ca2010-08-26 20:04:17 +0000151
Johnny Chenc0c67f22010-11-09 18:42:22 +0000152def CMD_MSG(str):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000153 '''A generic "Command '%s' returns successfully" message generator.'''
Johnny Chenc0c67f22010-11-09 18:42:22 +0000154 return "Command '%s' returns successfully" % str
155
Johnny Chen3bc8ae42012-03-15 19:10:00 +0000156def COMPLETION_MSG(str_before, str_after):
Johnny Chen98aceb02012-01-20 23:02:51 +0000157 '''A generic message generator for the completion mechanism.'''
158 return "'%s' successfully completes to '%s'" % (str_before, str_after)
159
Johnny Chenc0c67f22010-11-09 18:42:22 +0000160def EXP_MSG(str, exe):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000161 '''A generic "'%s' returns expected result" message generator if exe.
162 Otherwise, it generates "'%s' matches expected result" message.'''
Johnny Chenc0c67f22010-11-09 18:42:22 +0000163 return "'%s' %s expected result" % (str, 'returns' if exe else 'matches')
Johnny Chen17941842010-08-09 23:44:24 +0000164
Johnny Chen3343f042010-10-19 19:11:38 +0000165def SETTING_MSG(setting):
Johnny Chenaacf92e2011-05-31 22:16:51 +0000166 '''A generic "Value of setting '%s' is correct" message generator.'''
Johnny Chen3343f042010-10-19 19:11:38 +0000167 return "Value of setting '%s' is correct" % setting
168
Johnny Chen27c41232010-08-26 21:49:29 +0000169def EnvArray():
Johnny Chenaacf92e2011-05-31 22:16:51 +0000170 """Returns an env variable array from the os.environ map object."""
Johnny Chen27c41232010-08-26 21:49:29 +0000171 return map(lambda k,v: k+"="+v, os.environ.keys(), os.environ.values())
172
Johnny Chen47ceb032010-10-11 23:52:19 +0000173def line_number(filename, string_to_match):
174 """Helper function to return the line number of the first matched string."""
175 with open(filename, 'r') as f:
176 for i, line in enumerate(f):
177 if line.find(string_to_match) != -1:
178 # Found our match.
Johnny Chencd9b7772010-10-12 00:09:25 +0000179 return i+1
Johnny Chen1691a162011-04-15 16:44:48 +0000180 raise Exception("Unable to find '%s' within file %s" % (string_to_match, filename))
Johnny Chen47ceb032010-10-11 23:52:19 +0000181
Johnny Chen67af43f2010-10-05 19:27:32 +0000182def pointer_size():
183 """Return the pointer size of the host system."""
184 import ctypes
185 a_pointer = ctypes.c_void_p(0xffff)
186 return 8 * ctypes.sizeof(a_pointer)
187
Johnny Chen57816732012-02-09 02:01:59 +0000188def is_exe(fpath):
189 """Returns true if fpath is an executable."""
190 return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
191
192def which(program):
193 """Returns the full path to a program; None otherwise."""
194 fpath, fname = os.path.split(program)
195 if fpath:
196 if is_exe(program):
197 return program
198 else:
199 for path in os.environ["PATH"].split(os.pathsep):
200 exe_file = os.path.join(path, program)
201 if is_exe(exe_file):
202 return exe_file
203 return None
204
Johnny Chen150c3cc2010-10-15 01:18:29 +0000205class recording(StringIO.StringIO):
206 """
207 A nice little context manager for recording the debugger interactions into
208 our session object. If trace flag is ON, it also emits the interactions
209 into the stderr.
210 """
211 def __init__(self, test, trace):
Johnny Chen690fcef2010-10-15 23:55:05 +0000212 """Create a StringIO instance; record the session obj and trace flag."""
Johnny Chen150c3cc2010-10-15 01:18:29 +0000213 StringIO.StringIO.__init__(self)
Johnny Chen0241f142011-08-16 22:06:17 +0000214 # The test might not have undergone the 'setUp(self)' phase yet, so that
215 # the attribute 'session' might not even exist yet.
Johnny Chenbfcf37f2011-08-16 17:06:45 +0000216 self.session = getattr(test, "session", None) if test else None
Johnny Chen150c3cc2010-10-15 01:18:29 +0000217 self.trace = trace
218
219 def __enter__(self):
220 """
221 Context management protocol on entry to the body of the with statement.
222 Just return the StringIO object.
223 """
224 return self
225
226 def __exit__(self, type, value, tb):
227 """
228 Context management protocol on exit from the body of the with statement.
229 If trace is ON, it emits the recordings into stderr. Always add the
230 recordings to our session object. And close the StringIO object, too.
231 """
232 if self.trace:
Johnny Chen690fcef2010-10-15 23:55:05 +0000233 print >> sys.stderr, self.getvalue()
234 if self.session:
235 print >> self.session, self.getvalue()
Johnny Chen150c3cc2010-10-15 01:18:29 +0000236 self.close()
237
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000238class _BaseProcess(object):
239 __metaclass__ = abc.ABCMeta
240
241 @abc.abstractproperty
242 def pid(self):
243 """Returns process PID if has been launched already."""
244
245 @abc.abstractmethod
246 def launch(self, executable, args):
247 """Launches new process with given executable and args."""
248
249 @abc.abstractmethod
250 def terminate(self):
251 """Terminates previously launched process.."""
252
253class _LocalProcess(_BaseProcess):
254
255 def __init__(self, trace_on):
256 self._proc = None
257 self._trace_on = trace_on
Ilia K725abcb2015-04-15 13:35:49 +0000258 self._delayafterterminate = 0.1
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000259
260 @property
261 def pid(self):
262 return self._proc.pid
263
264 def launch(self, executable, args):
265 self._proc = Popen([executable] + args,
266 stdout = open(os.devnull) if not self._trace_on else None,
267 stdin = PIPE)
268
269 def terminate(self):
270 if self._proc.poll() == None:
Ilia K725abcb2015-04-15 13:35:49 +0000271 # Terminate _proc like it does the pexpect
272 self._proc.send_signal(signal.SIGHUP)
273 time.sleep(self._delayafterterminate)
274 if self._proc.poll() != None:
275 return
276 self._proc.send_signal(signal.SIGCONT)
277 time.sleep(self._delayafterterminate)
278 if self._proc.poll() != None:
279 return
280 self._proc.send_signal(signal.SIGINT)
281 time.sleep(self._delayafterterminate)
282 if self._proc.poll() != None:
283 return
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000284 self._proc.terminate()
Ilia K725abcb2015-04-15 13:35:49 +0000285 time.sleep(self._delayafterterminate)
286 if self._proc.poll() != None:
287 return
288 self._proc.kill()
289 time.sleep(self._delayafterterminate)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000290
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000291 def poll(self):
292 return self._proc.poll()
293
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000294class _RemoteProcess(_BaseProcess):
295
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000296 def __init__(self, install_remote):
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000297 self._pid = None
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000298 self._install_remote = install_remote
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000299
300 @property
301 def pid(self):
302 return self._pid
303
304 def launch(self, executable, args):
305 remote_work_dir = lldb.remote_platform.GetWorkingDirectory()
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000306
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000307 if self._install_remote:
308 src_path = executable
309 dst_path = os.path.join(remote_work_dir, os.path.basename(executable))
310
311 dst_file_spec = lldb.SBFileSpec(dst_path, False)
312 err = lldb.remote_platform.Install(lldb.SBFileSpec(src_path, True), dst_file_spec)
313 if err.Fail():
314 raise Exception("remote_platform.Install('%s', '%s') failed: %s" % (src_path, dst_path, err))
315 else:
316 dst_path = executable
317 dst_file_spec = lldb.SBFileSpec(executable, False)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000318
319 launch_info = lldb.SBLaunchInfo(args)
320 launch_info.SetExecutableFile(dst_file_spec, True)
321 launch_info.SetWorkingDirectory(remote_work_dir)
322
323 # Redirect stdout and stderr to /dev/null
324 launch_info.AddSuppressFileAction(1, False, True)
325 launch_info.AddSuppressFileAction(2, False, True)
326
327 err = lldb.remote_platform.Launch(launch_info)
328 if err.Fail():
329 raise Exception("remote_platform.Launch('%s', '%s') failed: %s" % (dst_path, args, err))
330 self._pid = launch_info.GetProcessID()
331
332 def terminate(self):
Tamas Berghammer04f51d12015-03-11 13:51:07 +0000333 lldb.remote_platform.Kill(self._pid)
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000334
Johnny Chen690fcef2010-10-15 23:55:05 +0000335# From 2.7's subprocess.check_output() convenience function.
Johnny Chenac77f3b2011-03-23 20:28:59 +0000336# Return a tuple (stdoutdata, stderrdata).
Zachary Turner9ef307b2014-07-22 16:19:29 +0000337def system(commands, **kwargs):
Johnny Chen8eb14a92011-11-16 22:44:28 +0000338 r"""Run an os command with arguments and return its output as a byte string.
Johnny Chen690fcef2010-10-15 23:55:05 +0000339
340 If the exit code was non-zero it raises a CalledProcessError. The
341 CalledProcessError object will have the return code in the returncode
342 attribute and output in the output attribute.
343
344 The arguments are the same as for the Popen constructor. Example:
345
346 >>> check_output(["ls", "-l", "/dev/null"])
347 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
348
349 The stdout argument is not allowed as it is used internally.
350 To capture standard error in the result, use stderr=STDOUT.
351
352 >>> check_output(["/bin/sh", "-c",
353 ... "ls -l non_existent_file ; exit 0"],
354 ... stderr=STDOUT)
355 'ls: non_existent_file: No such file or directory\n'
356 """
357
358 # Assign the sender object to variable 'test' and remove it from kwargs.
359 test = kwargs.pop('sender', None)
360
Zachary Turner9ef307b2014-07-22 16:19:29 +0000361 # [['make', 'clean', 'foo'], ['make', 'foo']] -> ['make clean foo', 'make foo']
362 commandList = [' '.join(x) for x in commands]
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000363 output = ""
364 error = ""
365 for shellCommand in commandList:
366 if 'stdout' in kwargs:
367 raise ValueError('stdout argument not allowed, it will be overridden.')
368 if 'shell' in kwargs and kwargs['shell']==False:
369 raise ValueError('shell=False not allowed')
370 process = Popen(shellCommand, stdout=PIPE, stderr=PIPE, shell=True, **kwargs)
371 pid = process.pid
372 this_output, this_error = process.communicate()
373 retcode = process.poll()
Zachary Turner9ef307b2014-07-22 16:19:29 +0000374
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000375 # Enable trace on failure return while tracking down FreeBSD buildbot issues
376 trace = traceAlways
377 if not trace and retcode and sys.platform.startswith("freebsd"):
378 trace = True
Johnny Chen690fcef2010-10-15 23:55:05 +0000379
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000380 with recording(test, trace) as sbuf:
381 print >> sbuf
382 print >> sbuf, "os command:", shellCommand
383 print >> sbuf, "with pid:", pid
Adrian McCarthy1d574332015-04-03 17:10:30 +0000384 print >> sbuf, "stdout:", this_output
385 print >> sbuf, "stderr:", this_error
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000386 print >> sbuf, "retcode:", retcode
387 print >> sbuf
Ed Maste6e496332014-08-05 20:33:17 +0000388
Zachary Turner65fe1eb2015-03-26 16:43:25 +0000389 if retcode:
390 cmd = kwargs.get("args")
391 if cmd is None:
392 cmd = shellCommand
393 raise CalledProcessError(retcode, cmd)
394 output = output + this_output
395 error = error + this_error
Johnny Chenac77f3b2011-03-23 20:28:59 +0000396 return (output, error)
Johnny Chen690fcef2010-10-15 23:55:05 +0000397
Johnny Chenab9c1dd2010-11-01 20:35:01 +0000398def getsource_if_available(obj):
399 """
400 Return the text of the source code for an object if available. Otherwise,
401 a print representation is returned.
402 """
403 import inspect
404 try:
405 return inspect.getsource(obj)
406 except:
407 return repr(obj)
408
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000409def builder_module():
Ed Maste4d90f0f2013-07-25 13:24:34 +0000410 if sys.platform.startswith("freebsd"):
411 return __import__("builder_freebsd")
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000412 return __import__("builder_" + sys.platform)
413
Johnny Chena74bb0a2011-08-01 18:46:13 +0000414#
415# Decorators for categorizing test cases.
416#
417
418from functools import wraps
419def python_api_test(func):
420 """Decorate the item as a Python API only test."""
421 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
422 raise Exception("@python_api_test can only be used to decorate a test method")
423 @wraps(func)
424 def wrapper(self, *args, **kwargs):
425 try:
426 if lldb.dont_do_python_api_test:
427 self.skipTest("python api tests")
428 except AttributeError:
429 pass
430 return func(self, *args, **kwargs)
431
432 # Mark this function as such to separate them from lldb command line tests.
433 wrapper.__python_api_test__ = True
434 return wrapper
435
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +0000436def lldbmi_test(func):
437 """Decorate the item as a lldb-mi only test."""
438 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
439 raise Exception("@lldbmi_test can only be used to decorate a test method")
440 @wraps(func)
441 def wrapper(self, *args, **kwargs):
442 try:
443 if lldb.dont_do_lldbmi_test:
444 self.skipTest("lldb-mi tests")
445 except AttributeError:
446 pass
447 return func(self, *args, **kwargs)
448
449 # Mark this function as such to separate them from lldb command line tests.
450 wrapper.__lldbmi_test__ = True
451 return wrapper
452
Johnny Chena74bb0a2011-08-01 18:46:13 +0000453def benchmarks_test(func):
454 """Decorate the item as a benchmarks test."""
455 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
456 raise Exception("@benchmarks_test can only be used to decorate a test method")
457 @wraps(func)
458 def wrapper(self, *args, **kwargs):
459 try:
460 if not lldb.just_do_benchmarks_test:
461 self.skipTest("benchmarks tests")
462 except AttributeError:
463 pass
464 return func(self, *args, **kwargs)
465
466 # Mark this function as such to separate them from the regular tests.
467 wrapper.__benchmarks_test__ = True
468 return wrapper
469
Johnny Chenf1548d42012-04-06 00:56:05 +0000470def dsym_test(func):
471 """Decorate the item as a dsym test."""
472 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
473 raise Exception("@dsym_test can only be used to decorate a test method")
474 @wraps(func)
475 def wrapper(self, *args, **kwargs):
476 try:
477 if lldb.dont_do_dsym_test:
478 self.skipTest("dsym tests")
479 except AttributeError:
480 pass
481 return func(self, *args, **kwargs)
482
483 # Mark this function as such to separate them from the regular tests.
484 wrapper.__dsym_test__ = True
485 return wrapper
486
487def dwarf_test(func):
488 """Decorate the item as a dwarf test."""
489 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
490 raise Exception("@dwarf_test can only be used to decorate a test method")
491 @wraps(func)
492 def wrapper(self, *args, **kwargs):
493 try:
494 if lldb.dont_do_dwarf_test:
495 self.skipTest("dwarf tests")
496 except AttributeError:
497 pass
498 return func(self, *args, **kwargs)
499
500 # Mark this function as such to separate them from the regular tests.
501 wrapper.__dwarf_test__ = True
502 return wrapper
503
Todd Fialaa41d48c2014-04-28 04:49:40 +0000504def debugserver_test(func):
505 """Decorate the item as a debugserver test."""
506 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
507 raise Exception("@debugserver_test can only be used to decorate a test method")
508 @wraps(func)
509 def wrapper(self, *args, **kwargs):
510 try:
511 if lldb.dont_do_debugserver_test:
512 self.skipTest("debugserver tests")
513 except AttributeError:
514 pass
515 return func(self, *args, **kwargs)
516
517 # Mark this function as such to separate them from the regular tests.
518 wrapper.__debugserver_test__ = True
519 return wrapper
520
521def llgs_test(func):
Robert Flack8cc4cf12015-03-06 14:36:33 +0000522 """Decorate the item as a lldb-server test."""
Todd Fialaa41d48c2014-04-28 04:49:40 +0000523 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
524 raise Exception("@llgs_test can only be used to decorate a test method")
525 @wraps(func)
526 def wrapper(self, *args, **kwargs):
527 try:
528 if lldb.dont_do_llgs_test:
529 self.skipTest("llgs tests")
530 except AttributeError:
531 pass
532 return func(self, *args, **kwargs)
533
534 # Mark this function as such to separate them from the regular tests.
535 wrapper.__llgs_test__ = True
536 return wrapper
537
Daniel Maleae0f8f572013-08-26 23:57:52 +0000538def not_remote_testsuite_ready(func):
539 """Decorate the item as a test which is not ready yet for remote testsuite."""
540 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
541 raise Exception("@not_remote_testsuite_ready can only be used to decorate a test method")
542 @wraps(func)
543 def wrapper(self, *args, **kwargs):
544 try:
Tamas Berghammer3e0ecb22015-03-25 15:13:28 +0000545 if lldb.lldbtest_remote_sandbox or lldb.remote_platform:
Daniel Maleae0f8f572013-08-26 23:57:52 +0000546 self.skipTest("not ready for remote testsuite")
547 except AttributeError:
548 pass
549 return func(self, *args, **kwargs)
550
551 # Mark this function as such to separate them from the regular tests.
552 wrapper.__not_ready_for_remote_testsuite_test__ = True
553 return wrapper
554
Ed Maste433790a2014-04-23 12:55:41 +0000555def expectedFailure(expected_fn, bugnumber=None):
556 def expectedFailure_impl(func):
557 @wraps(func)
558 def wrapper(*args, **kwargs):
Enrico Granata43f62132013-02-23 01:28:30 +0000559 from unittest2 import case
560 self = args[0]
Enrico Granata43f62132013-02-23 01:28:30 +0000561 try:
Ed Maste433790a2014-04-23 12:55:41 +0000562 func(*args, **kwargs)
Enrico Granata43f62132013-02-23 01:28:30 +0000563 except Exception:
Ed Maste433790a2014-04-23 12:55:41 +0000564 if expected_fn(self):
565 raise case._ExpectedFailure(sys.exc_info(), bugnumber)
Enrico Granata43f62132013-02-23 01:28:30 +0000566 else:
567 raise
Ed Maste433790a2014-04-23 12:55:41 +0000568 if expected_fn(self):
569 raise case._UnexpectedSuccess(sys.exc_info(), bugnumber)
570 return wrapper
Ying Chen464d1e12015-03-27 00:26:52 +0000571 # if bugnumber is not-callable(incluing None), that means decorator function is called with optional arguments
572 # return decorator in this case, so it will be used to decorating original method
573 if callable(bugnumber):
574 return expectedFailure_impl(bugnumber)
575 else:
576 return expectedFailure_impl
Ed Maste433790a2014-04-23 12:55:41 +0000577
578def expectedFailureCompiler(compiler, compiler_version=None, bugnumber=None):
579 if compiler_version is None:
580 compiler_version=['=', None]
581 def fn(self):
582 return compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version)
Ying Chen464d1e12015-03-27 00:26:52 +0000583 return expectedFailure(fn, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000584
Vince Harron8974ce22015-03-13 19:54:54 +0000585# to XFAIL a specific clang versions, try this
586# @expectedFailureClang('bugnumber', ['<=', '3.4'])
587def expectedFailureClang(bugnumber=None, compiler_version=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000588 return expectedFailureCompiler('clang', compiler_version, bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000589
590def expectedFailureGcc(bugnumber=None, compiler_version=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000591 return expectedFailureCompiler('gcc', compiler_version, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000592
Matt Kopec0de53f02013-03-15 19:10:12 +0000593def expectedFailureIcc(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000594 return expectedFailureCompiler('icc', None, bugnumber)
Matt Kopec0de53f02013-03-15 19:10:12 +0000595
Ed Maste433790a2014-04-23 12:55:41 +0000596def expectedFailureArch(arch, bugnumber=None):
597 def fn(self):
598 return arch in self.getArchitecture()
Ying Chen464d1e12015-03-27 00:26:52 +0000599 return expectedFailure(fn, bugnumber)
Daniel Malea249287a2013-02-19 16:08:57 +0000600
Enrico Granatae6cedc12013-02-23 01:05:23 +0000601def expectedFailurei386(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000602 return expectedFailureArch('i386', bugnumber)
Johnny Chena33843f2011-12-22 21:14:31 +0000603
Matt Kopecee969f92013-09-26 23:30:59 +0000604def expectedFailurex86_64(bugnumber=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000605 return expectedFailureArch('x86_64', bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000606
Robert Flackefa49c22015-03-26 19:34:26 +0000607def expectedFailureOS(oslist, bugnumber=None, compilers=None):
Ed Maste433790a2014-04-23 12:55:41 +0000608 def fn(self):
Robert Flack13c7ad92015-03-30 14:12:17 +0000609 return (self.getPlatform() in oslist and
Robert Flackefa49c22015-03-26 19:34:26 +0000610 self.expectedCompiler(compilers))
Ying Chen464d1e12015-03-27 00:26:52 +0000611 return expectedFailure(fn, bugnumber)
Ed Maste433790a2014-04-23 12:55:41 +0000612
613def expectedFailureDarwin(bugnumber=None, compilers=None):
Robert Flackefa49c22015-03-26 19:34:26 +0000614 # For legacy reasons, we support both "darwin" and "macosx" as OS X triples.
Greg Claytone0d0a762015-04-02 18:24:03 +0000615 return expectedFailureOS(getDarwinOSTriples(), bugnumber, compilers)
Matt Kopecee969f92013-09-26 23:30:59 +0000616
Ed Maste24a7f7d2013-07-24 19:47:08 +0000617def expectedFailureFreeBSD(bugnumber=None, compilers=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000618 return expectedFailureOS(['freebsd'], bugnumber, compilers)
Ed Maste24a7f7d2013-07-24 19:47:08 +0000619
Ashok Thirumurthic97a6082013-05-17 20:15:07 +0000620def expectedFailureLinux(bugnumber=None, compilers=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000621 return expectedFailureOS(['linux'], bugnumber, compilers)
Matt Kopece9ea0da2013-05-07 19:29:28 +0000622
Zachary Turner80c2c602014-12-09 19:28:00 +0000623def expectedFailureWindows(bugnumber=None, compilers=None):
Ying Chen464d1e12015-03-27 00:26:52 +0000624 return expectedFailureOS(['windows'], bugnumber, compilers)
Zachary Turner80c2c602014-12-09 19:28:00 +0000625
Chaoren Lin72b8f052015-02-03 01:51:18 +0000626def expectedFailureLLGS(bugnumber=None, compilers=None):
627 def fn(self):
Robert Flackf4db5462015-04-09 14:54:26 +0000628 # llgs local is only an option on Linux targets
Robert Flackfb2f6c62015-04-17 08:02:18 +0000629 if self.getPlatform() != 'linux':
Vince Harronbc477dd2015-03-01 23:21:29 +0000630 return False
631 self.runCmd('settings show platform.plugin.linux.use-llgs-for-local')
632 return 'true' in self.res.GetOutput() and self.expectedCompiler(compilers)
Ying Chen464d1e12015-03-27 00:26:52 +0000633 return expectedFailure(fn, bugnumber)
Chaoren Lin72b8f052015-02-03 01:51:18 +0000634
Greg Clayton12514562013-12-05 22:22:32 +0000635def skipIfRemote(func):
636 """Decorate the item to skip tests if testing remotely."""
637 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
638 raise Exception("@skipIfRemote can only be used to decorate a test method")
639 @wraps(func)
640 def wrapper(*args, **kwargs):
641 from unittest2 import case
642 if lldb.remote_platform:
643 self = args[0]
644 self.skipTest("skip on remote platform")
645 else:
646 func(*args, **kwargs)
647 return wrapper
648
649def skipIfRemoteDueToDeadlock(func):
650 """Decorate the item to skip tests if testing remotely due to the test deadlocking."""
651 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
652 raise Exception("@skipIfRemote can only be used to decorate a test method")
653 @wraps(func)
654 def wrapper(*args, **kwargs):
655 from unittest2 import case
656 if lldb.remote_platform:
657 self = args[0]
658 self.skipTest("skip on remote platform (deadlocks)")
659 else:
660 func(*args, **kwargs)
661 return wrapper
662
Enrico Granatab633e432014-10-06 21:37:06 +0000663def skipIfNoSBHeaders(func):
664 """Decorate the item to mark tests that should be skipped when LLDB is built with no SB API headers."""
665 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Ed Maste59cca5d2014-10-07 01:57:52 +0000666 raise Exception("@skipIfNoSBHeaders can only be used to decorate a test method")
Enrico Granatab633e432014-10-06 21:37:06 +0000667 @wraps(func)
668 def wrapper(*args, **kwargs):
669 from unittest2 import case
670 self = args[0]
Shawn Best181b09b2014-11-08 00:04:04 +0000671 if sys.platform.startswith("darwin"):
672 header = os.path.join(self.lib_dir, 'LLDB.framework', 'Versions','Current','Headers','LLDB.h')
673 else:
674 header = os.path.join(os.environ["LLDB_SRC"], "include", "lldb", "API", "LLDB.h")
Enrico Granatab633e432014-10-06 21:37:06 +0000675 platform = sys.platform
Enrico Granatab633e432014-10-06 21:37:06 +0000676 if not os.path.exists(header):
677 self.skipTest("skip because LLDB.h header not found")
678 else:
679 func(*args, **kwargs)
680 return wrapper
681
Robert Flack13c7ad92015-03-30 14:12:17 +0000682def skipIfFreeBSD(func):
683 """Decorate the item to skip tests that should be skipped on FreeBSD."""
684 return skipIfPlatform(["freebsd"])(func)
Zachary Turnerc7826522014-08-13 17:44:53 +0000685
Greg Claytone0d0a762015-04-02 18:24:03 +0000686def getDarwinOSTriples():
687 return ['darwin', 'macosx', 'ios']
688
Daniel Maleab3d41a22013-07-09 00:08:01 +0000689def skipIfDarwin(func):
690 """Decorate the item to skip tests that should be skipped on Darwin."""
Greg Claytone0d0a762015-04-02 18:24:03 +0000691 return skipIfPlatform(getDarwinOSTriples())(func)
Daniel Maleab3d41a22013-07-09 00:08:01 +0000692
Robert Flack13c7ad92015-03-30 14:12:17 +0000693def skipIfLinux(func):
694 """Decorate the item to skip tests that should be skipped on Linux."""
695 return skipIfPlatform(["linux"])(func)
696
697def skipIfWindows(func):
698 """Decorate the item to skip tests that should be skipped on Windows."""
699 return skipIfPlatform(["windows"])(func)
700
701def skipUnlessDarwin(func):
702 """Decorate the item to skip tests that should be skipped on any non Darwin platform."""
Greg Claytone0d0a762015-04-02 18:24:03 +0000703 return skipUnlessPlatform(getDarwinOSTriples())(func)
Robert Flack13c7ad92015-03-30 14:12:17 +0000704
Robert Flack068898c2015-04-09 18:07:58 +0000705def getPlatform():
Robert Flackfb2f6c62015-04-17 08:02:18 +0000706 """Returns the target platform the test suite is running on."""
Robert Flack068898c2015-04-09 18:07:58 +0000707 platform = lldb.DBG.GetSelectedPlatform().GetTriple().split('-')[2]
708 if platform.startswith('freebsd'):
709 platform = 'freebsd'
710 return platform
711
Robert Flackfb2f6c62015-04-17 08:02:18 +0000712def platformIsDarwin():
713 """Returns true if the OS triple for the selected platform is any valid apple OS"""
714 return getPlatform() in getDarwinOSTriples()
715
Robert Flack13c7ad92015-03-30 14:12:17 +0000716def skipIfPlatform(oslist):
717 """Decorate the item to skip tests if running on one of the listed platforms."""
Robert Flack068898c2015-04-09 18:07:58 +0000718 return unittest2.skipIf(getPlatform() in oslist,
719 "skip on %s" % (", ".join(oslist)))
Robert Flack13c7ad92015-03-30 14:12:17 +0000720
721def skipUnlessPlatform(oslist):
722 """Decorate the item to skip tests unless running on one of the listed platforms."""
Robert Flack068898c2015-04-09 18:07:58 +0000723 return unittest2.skipUnless(getPlatform() in oslist,
724 "requires on of %s" % (", ".join(oslist)))
Daniel Maleab3d41a22013-07-09 00:08:01 +0000725
Daniel Malea48359902013-05-14 20:48:54 +0000726def skipIfLinuxClang(func):
727 """Decorate the item to skip tests that should be skipped if building on
728 Linux with clang.
729 """
730 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
731 raise Exception("@skipIfLinuxClang can only be used to decorate a test method")
732 @wraps(func)
733 def wrapper(*args, **kwargs):
734 from unittest2 import case
735 self = args[0]
736 compiler = self.getCompiler()
737 platform = sys.platform
738 if "clang" in compiler and "linux" in platform:
739 self.skipTest("skipping because Clang is used on Linux")
740 else:
741 func(*args, **kwargs)
742 return wrapper
743
Daniel Maleabe230792013-01-24 23:52:09 +0000744def skipIfGcc(func):
745 """Decorate the item to skip tests that should be skipped if building with gcc ."""
746 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
Daniel Malea0aea0162013-02-27 17:29:46 +0000747 raise Exception("@skipIfGcc can only be used to decorate a test method")
Daniel Maleabe230792013-01-24 23:52:09 +0000748 @wraps(func)
749 def wrapper(*args, **kwargs):
750 from unittest2 import case
751 self = args[0]
752 compiler = self.getCompiler()
753 if "gcc" in compiler:
754 self.skipTest("skipping because gcc is the test compiler")
755 else:
756 func(*args, **kwargs)
757 return wrapper
758
Matt Kopec0de53f02013-03-15 19:10:12 +0000759def skipIfIcc(func):
760 """Decorate the item to skip tests that should be skipped if building with icc ."""
761 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
762 raise Exception("@skipIfIcc can only be used to decorate a test method")
763 @wraps(func)
764 def wrapper(*args, **kwargs):
765 from unittest2 import case
766 self = args[0]
767 compiler = self.getCompiler()
768 if "icc" in compiler:
769 self.skipTest("skipping because icc is the test compiler")
770 else:
771 func(*args, **kwargs)
772 return wrapper
773
Daniel Malea55faa402013-05-02 21:44:31 +0000774def skipIfi386(func):
775 """Decorate the item to skip tests that should be skipped if building 32-bit."""
776 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
777 raise Exception("@skipIfi386 can only be used to decorate a test method")
778 @wraps(func)
779 def wrapper(*args, **kwargs):
780 from unittest2 import case
781 self = args[0]
782 if "i386" == self.getArchitecture():
783 self.skipTest("skipping because i386 is not a supported architecture")
784 else:
785 func(*args, **kwargs)
786 return wrapper
787
Tamas Berghammer1253a812015-03-13 10:12:25 +0000788def skipIfTargetAndroid(func):
789 """Decorate the item to skip tests that should be skipped when the target is Android."""
790 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
791 raise Exception("@skipIfTargetAndroid can only be used to decorate a test method")
792 @wraps(func)
793 def wrapper(*args, **kwargs):
794 from unittest2 import case
795 self = args[0]
796 triple = self.dbg.GetSelectedPlatform().GetTriple()
797 if re.match(".*-.*-.*-android", triple):
798 self.skipTest("skip on Android target")
799 else:
800 func(*args, **kwargs)
801 return wrapper
802
Ilia Kd9953052015-03-12 07:19:41 +0000803def skipUnlessCompilerRt(func):
804 """Decorate the item to skip tests if testing remotely."""
805 if isinstance(func, type) and issubclass(func, unittest2.TestCase):
806 raise Exception("@skipUnless can only be used to decorate a test method")
807 @wraps(func)
808 def wrapper(*args, **kwargs):
809 from unittest2 import case
810 import os.path
811 compilerRtPath = os.path.join(os.path.dirname(__file__), "..", "..", "..", "projects", "compiler-rt")
812 if not os.path.exists(compilerRtPath):
813 self = args[0]
814 self.skipTest("skip if compiler-rt not found")
815 else:
816 func(*args, **kwargs)
817 return wrapper
Daniel Malea55faa402013-05-02 21:44:31 +0000818
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +0000819class _PlatformContext(object):
820 """Value object class which contains platform-specific options."""
821
822 def __init__(self, shlib_environment_var, shlib_prefix, shlib_extension):
823 self.shlib_environment_var = shlib_environment_var
824 self.shlib_prefix = shlib_prefix
825 self.shlib_extension = shlib_extension
826
827
Johnny Chena74bb0a2011-08-01 18:46:13 +0000828class Base(unittest2.TestCase):
Johnny Chen8334dad2010-10-22 23:15:46 +0000829 """
Johnny Chena74bb0a2011-08-01 18:46:13 +0000830 Abstract base for performing lldb (see TestBase) or other generic tests (see
831 BenchBase for one example). lldbtest.Base works with the test driver to
832 accomplish things.
833
Johnny Chen8334dad2010-10-22 23:15:46 +0000834 """
Enrico Granata5020f952012-10-24 21:42:49 +0000835
Enrico Granata19186272012-10-24 21:44:48 +0000836 # The concrete subclass should override this attribute.
837 mydir = None
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000838
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000839 # Keep track of the old current working directory.
840 oldcwd = None
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +0000841
Greg Clayton4570d3e2013-12-10 23:19:29 +0000842 @staticmethod
843 def compute_mydir(test_file):
844 '''Subclasses should call this function to correctly calculate the required "mydir" attribute as follows:
845
846 mydir = TestBase.compute_mydir(__file__)'''
847 test_dir = os.path.dirname(test_file)
848 return test_dir[len(os.environ["LLDB_TEST"])+1:]
849
Johnny Chenfb4264c2011-08-01 19:50:58 +0000850 def TraceOn(self):
851 """Returns True if we are in trace mode (tracing detailed test execution)."""
852 return traceAlways
Greg Clayton4570d3e2013-12-10 23:19:29 +0000853
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000854 @classmethod
855 def setUpClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +0000856 """
857 Python unittest framework class setup fixture.
858 Do current directory manipulation.
859 """
860
Johnny Chenf02ec122010-07-03 20:41:42 +0000861 # Fail fast if 'mydir' attribute is not overridden.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000862 if not cls.mydir or len(cls.mydir) == 0:
Johnny Chenf02ec122010-07-03 20:41:42 +0000863 raise Exception("Subclasses must override the 'mydir' attribute.")
Enrico Granata7e137e32012-10-24 18:14:21 +0000864
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000865 # Save old working directory.
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000866 cls.oldcwd = os.getcwd()
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000867
868 # Change current working directory if ${LLDB_TEST} is defined.
869 # See also dotest.py which sets up ${LLDB_TEST}.
870 if ("LLDB_TEST" in os.environ):
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000871 if traceAlways:
Johnny Chen703dbd02010-09-30 17:06:24 +0000872 print >> sys.stderr, "Change dir to:", os.path.join(os.environ["LLDB_TEST"], cls.mydir)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000873 os.chdir(os.path.join(os.environ["LLDB_TEST"], cls.mydir))
874
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +0000875 # Set platform context.
Robert Flackfb2f6c62015-04-17 08:02:18 +0000876 if platformIsDarwin():
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +0000877 cls.platformContext = _PlatformContext('DYLD_LIBRARY_PATH', 'lib', 'dylib')
Robert Flackfb2f6c62015-04-17 08:02:18 +0000878 elif getPlatform() == "linux" or getPlatform() == "freebsd":
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +0000879 cls.platformContext = _PlatformContext('LD_LIBRARY_PATH', 'lib', 'so')
Zachary Turnerbe40b2f2014-12-02 21:32:44 +0000880 else:
881 cls.platformContext = None
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +0000882
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000883 @classmethod
884 def tearDownClass(cls):
Johnny Chenda884342010-10-01 22:59:49 +0000885 """
886 Python unittest framework class teardown fixture.
887 Do class-wide cleanup.
888 """
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000889
Johnny Chen0fddfb22011-11-17 19:57:27 +0000890 if doCleanup and not lldb.skip_build_and_cleanup:
Johnny Chen707b3c92010-10-11 22:25:46 +0000891 # First, let's do the platform-specific cleanup.
Peter Collingbourne19f48d52011-06-20 19:06:20 +0000892 module = builder_module()
Johnny Chen707b3c92010-10-11 22:25:46 +0000893 if not module.cleanup():
894 raise Exception("Don't know how to do cleanup")
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000895
Johnny Chen707b3c92010-10-11 22:25:46 +0000896 # Subclass might have specific cleanup function defined.
897 if getattr(cls, "classCleanup", None):
898 if traceAlways:
899 print >> sys.stderr, "Call class-specific cleanup function for class:", cls
900 try:
901 cls.classCleanup()
902 except:
903 exc_type, exc_value, exc_tb = sys.exc_info()
904 traceback.print_exception(exc_type, exc_value, exc_tb)
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000905
906 # Restore old working directory.
907 if traceAlways:
Johnny Chen703dbd02010-09-30 17:06:24 +0000908 print >> sys.stderr, "Restore dir to:", cls.oldcwd
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000909 os.chdir(cls.oldcwd)
910
Johnny Chena74bb0a2011-08-01 18:46:13 +0000911 @classmethod
912 def skipLongRunningTest(cls):
913 """
914 By default, we skip long running test case.
915 This can be overridden by passing '-l' to the test driver (dotest.py).
916 """
917 if "LLDB_SKIP_LONG_RUNNING_TEST" in os.environ and "NO" == os.environ["LLDB_SKIP_LONG_RUNNING_TEST"]:
918 return False
919 else:
920 return True
Johnny Chened492022011-06-21 00:53:00 +0000921
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000922 def setUp(self):
Johnny Chenfb4264c2011-08-01 19:50:58 +0000923 """Fixture for unittest test case setup.
924
925 It works with the test driver to conditionally skip tests and does other
926 initializations."""
Johnny Chen1a9f4dd2010-09-16 01:53:04 +0000927 #import traceback
928 #traceback.print_stack()
Johnny Chenbf6ffa32010-07-03 03:41:59 +0000929
Daniel Malea9115f072013-08-06 15:02:32 +0000930 if "LIBCXX_PATH" in os.environ:
931 self.libcxxPath = os.environ["LIBCXX_PATH"]
932 else:
933 self.libcxxPath = None
934
Johnny Chenaaa82ff2011-08-02 22:54:37 +0000935 if "LLDB_EXEC" in os.environ:
936 self.lldbExec = os.environ["LLDB_EXEC"]
Johnny Chend890bfc2011-08-26 00:00:01 +0000937 else:
938 self.lldbExec = None
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +0000939 if "LLDBMI_EXEC" in os.environ:
940 self.lldbMiExec = os.environ["LLDBMI_EXEC"]
941 else:
942 self.lldbMiExec = None
943 self.dont_do_lldbmi_test = True
Johnny Chend890bfc2011-08-26 00:00:01 +0000944 if "LLDB_HERE" in os.environ:
945 self.lldbHere = os.environ["LLDB_HERE"]
946 else:
947 self.lldbHere = None
Johnny Chenebe51722011-10-07 19:21:09 +0000948 # If we spawn an lldb process for test (via pexpect), do not load the
949 # init file unless told otherwise.
950 if "NO_LLDBINIT" in os.environ and "NO" == os.environ["NO_LLDBINIT"]:
951 self.lldbOption = ""
952 else:
953 self.lldbOption = "--no-lldbinit"
Johnny Chenaaa82ff2011-08-02 22:54:37 +0000954
Johnny Chen985e7402011-08-01 21:13:26 +0000955 # Assign the test method name to self.testMethodName.
956 #
957 # For an example of the use of this attribute, look at test/types dir.
958 # There are a bunch of test cases under test/types and we don't want the
959 # module cacheing subsystem to be confused with executable name "a.out"
960 # used for all the test cases.
961 self.testMethodName = self._testMethodName
962
Johnny Chenf3e22ac2010-12-10 18:52:10 +0000963 # Python API only test is decorated with @python_api_test,
964 # which also sets the "__python_api_test__" attribute of the
965 # function object to True.
Johnny Chen4533dad2011-05-31 23:21:42 +0000966 try:
967 if lldb.just_do_python_api_test:
968 testMethod = getattr(self, self._testMethodName)
969 if getattr(testMethod, "__python_api_test__", False):
970 pass
971 else:
Johnny Chen5ccbccf2011-07-30 01:39:58 +0000972 self.skipTest("non python api test")
973 except AttributeError:
974 pass
975
Hafiz Abid Qadeer1cbac4e2014-11-25 10:41:57 +0000976 # lldb-mi only test is decorated with @lldbmi_test,
977 # which also sets the "__lldbmi_test__" attribute of the
978 # function object to True.
979 try:
980 if lldb.just_do_lldbmi_test:
981 testMethod = getattr(self, self._testMethodName)
982 if getattr(testMethod, "__lldbmi_test__", False):
983 pass
984 else:
985 self.skipTest("non lldb-mi test")
986 except AttributeError:
987 pass
988
Johnny Chen5ccbccf2011-07-30 01:39:58 +0000989 # Benchmarks test is decorated with @benchmarks_test,
990 # which also sets the "__benchmarks_test__" attribute of the
991 # function object to True.
992 try:
993 if lldb.just_do_benchmarks_test:
994 testMethod = getattr(self, self._testMethodName)
995 if getattr(testMethod, "__benchmarks_test__", False):
996 pass
997 else:
998 self.skipTest("non benchmarks test")
Johnny Chen4533dad2011-05-31 23:21:42 +0000999 except AttributeError:
1000 pass
Johnny Chenf3e22ac2010-12-10 18:52:10 +00001001
Johnny Chen985e7402011-08-01 21:13:26 +00001002 # This is for the case of directly spawning 'lldb'/'gdb' and interacting
1003 # with it using pexpect.
1004 self.child = None
1005 self.child_prompt = "(lldb) "
1006 # If the child is interacting with the embedded script interpreter,
1007 # there are two exits required during tear down, first to quit the
1008 # embedded script interpreter and second to quit the lldb command
1009 # interpreter.
1010 self.child_in_script_interpreter = False
1011
Johnny Chenfb4264c2011-08-01 19:50:58 +00001012 # These are for customized teardown cleanup.
1013 self.dict = None
1014 self.doTearDownCleanup = False
1015 # And in rare cases where there are multiple teardown cleanups.
1016 self.dicts = []
1017 self.doTearDownCleanups = False
1018
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001019 # List of spawned subproces.Popen objects
1020 self.subprocesses = []
1021
Daniel Malea69207462013-06-05 21:07:02 +00001022 # List of forked process PIDs
1023 self.forkedProcessPids = []
1024
Johnny Chenfb4264c2011-08-01 19:50:58 +00001025 # Create a string buffer to record the session info, to be dumped into a
1026 # test case specific file if test failure is encountered.
1027 self.session = StringIO.StringIO()
1028
1029 # Optimistically set __errored__, __failed__, __expected__ to False
1030 # initially. If the test errored/failed, the session info
1031 # (self.session) is then dumped into a session specific file for
1032 # diagnosis.
1033 self.__errored__ = False
1034 self.__failed__ = False
1035 self.__expected__ = False
1036 # We are also interested in unexpected success.
1037 self.__unexpected__ = False
Johnny Chenf79b0762011-08-16 00:48:58 +00001038 # And skipped tests.
1039 self.__skipped__ = False
Johnny Chenfb4264c2011-08-01 19:50:58 +00001040
1041 # See addTearDownHook(self, hook) which allows the client to add a hook
1042 # function to be run during tearDown() time.
1043 self.hooks = []
1044
1045 # See HideStdout(self).
1046 self.sys_stdout_hidden = False
1047
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00001048 if self.platformContext:
1049 # set environment variable names for finding shared libraries
1050 self.dylibPath = self.platformContext.shlib_environment_var
Daniel Malea179ff292012-11-26 21:21:11 +00001051
Johnny Chen2a808582011-10-19 16:48:07 +00001052 def runHooks(self, child=None, child_prompt=None, use_cmd_api=False):
Johnny Chena737ba52011-10-19 01:06:21 +00001053 """Perform the run hooks to bring lldb debugger to the desired state.
1054
Johnny Chen2a808582011-10-19 16:48:07 +00001055 By default, expect a pexpect spawned child and child prompt to be
1056 supplied (use_cmd_api=False). If use_cmd_api is true, ignore the child
1057 and child prompt and use self.runCmd() to run the hooks one by one.
1058
Johnny Chena737ba52011-10-19 01:06:21 +00001059 Note that child is a process spawned by pexpect.spawn(). If not, your
1060 test case is mostly likely going to fail.
1061
1062 See also dotest.py where lldb.runHooks are processed/populated.
1063 """
1064 if not lldb.runHooks:
1065 self.skipTest("No runhooks specified for lldb, skip the test")
Johnny Chen2a808582011-10-19 16:48:07 +00001066 if use_cmd_api:
1067 for hook in lldb.runhooks:
1068 self.runCmd(hook)
1069 else:
1070 if not child or not child_prompt:
1071 self.fail("Both child and child_prompt need to be defined.")
1072 for hook in lldb.runHooks:
1073 child.sendline(hook)
1074 child.expect_exact(child_prompt)
Johnny Chena737ba52011-10-19 01:06:21 +00001075
Daniel Malea249287a2013-02-19 16:08:57 +00001076 def setAsync(self, value):
1077 """ Sets async mode to True/False and ensures it is reset after the testcase completes."""
1078 old_async = self.dbg.GetAsync()
1079 self.dbg.SetAsync(value)
1080 self.addTearDownHook(lambda: self.dbg.SetAsync(old_async))
1081
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001082 def cleanupSubprocesses(self):
1083 # Ensure any subprocesses are cleaned up
1084 for p in self.subprocesses:
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001085 p.terminate()
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001086 del p
1087 del self.subprocesses[:]
Daniel Malea69207462013-06-05 21:07:02 +00001088 # Ensure any forked processes are cleaned up
1089 for pid in self.forkedProcessPids:
1090 if os.path.exists("/proc/" + str(pid)):
1091 os.kill(pid, signal.SIGTERM)
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001092
Tamas Berghammer04f51d12015-03-11 13:51:07 +00001093 def spawnSubprocess(self, executable, args=[], install_remote=True):
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001094 """ Creates a subprocess.Popen object with the specified executable and arguments,
1095 saves it in self.subprocesses, and returns the object.
1096 NOTE: if using this function, ensure you also call:
1097
1098 self.addTearDownHook(self.cleanupSubprocesses)
1099
1100 otherwise the test suite will leak processes.
1101 """
Tamas Berghammer04f51d12015-03-11 13:51:07 +00001102 proc = _RemoteProcess(install_remote) if lldb.remote_platform else _LocalProcess(self.TraceOn())
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001103 proc.launch(executable, args)
Daniel Malea2dd69bb2013-02-15 21:21:52 +00001104 self.subprocesses.append(proc)
1105 return proc
1106
Daniel Malea69207462013-06-05 21:07:02 +00001107 def forkSubprocess(self, executable, args=[]):
1108 """ Fork a subprocess with its own group ID.
1109 NOTE: if using this function, ensure you also call:
1110
1111 self.addTearDownHook(self.cleanupSubprocesses)
1112
1113 otherwise the test suite will leak processes.
1114 """
1115 child_pid = os.fork()
1116 if child_pid == 0:
1117 # If more I/O support is required, this can be beefed up.
1118 fd = os.open(os.devnull, os.O_RDWR)
Daniel Malea69207462013-06-05 21:07:02 +00001119 os.dup2(fd, 1)
1120 os.dup2(fd, 2)
1121 # This call causes the child to have its of group ID
1122 os.setpgid(0,0)
1123 os.execvp(executable, [executable] + args)
1124 # Give the child time to get through the execvp() call
1125 time.sleep(0.1)
1126 self.forkedProcessPids.append(child_pid)
1127 return child_pid
1128
Johnny Chenfb4264c2011-08-01 19:50:58 +00001129 def HideStdout(self):
1130 """Hide output to stdout from the user.
1131
1132 During test execution, there might be cases where we don't want to show the
1133 standard output to the user. For example,
1134
1135 self.runCmd(r'''sc print "\n\n\tHello!\n"''')
1136
1137 tests whether command abbreviation for 'script' works or not. There is no
1138 need to show the 'Hello' output to the user as long as the 'script' command
1139 succeeds and we are not in TraceOn() mode (see the '-t' option).
1140
1141 In this case, the test method calls self.HideStdout(self) to redirect the
1142 sys.stdout to a null device, and restores the sys.stdout upon teardown.
1143
1144 Note that you should only call this method at most once during a test case
1145 execution. Any subsequent call has no effect at all."""
1146 if self.sys_stdout_hidden:
1147 return
1148
1149 self.sys_stdout_hidden = True
1150 old_stdout = sys.stdout
1151 sys.stdout = open(os.devnull, 'w')
1152 def restore_stdout():
1153 sys.stdout = old_stdout
1154 self.addTearDownHook(restore_stdout)
1155
1156 # =======================================================================
1157 # Methods for customized teardown cleanups as well as execution of hooks.
1158 # =======================================================================
1159
1160 def setTearDownCleanup(self, dictionary=None):
1161 """Register a cleanup action at tearDown() time with a dictinary"""
1162 self.dict = dictionary
1163 self.doTearDownCleanup = True
1164
1165 def addTearDownCleanup(self, dictionary):
1166 """Add a cleanup action at tearDown() time with a dictinary"""
1167 self.dicts.append(dictionary)
1168 self.doTearDownCleanups = True
1169
1170 def addTearDownHook(self, hook):
1171 """
1172 Add a function to be run during tearDown() time.
1173
1174 Hooks are executed in a first come first serve manner.
1175 """
1176 if callable(hook):
1177 with recording(self, traceAlways) as sbuf:
1178 print >> sbuf, "Adding tearDown hook:", getsource_if_available(hook)
1179 self.hooks.append(hook)
Enrico Granataab0e8312014-11-05 21:31:57 +00001180
1181 return self
Johnny Chenfb4264c2011-08-01 19:50:58 +00001182
Jim Inghamda3a3862014-10-16 23:02:14 +00001183 def deletePexpectChild(self):
Johnny Chen985e7402011-08-01 21:13:26 +00001184 # This is for the case of directly spawning 'lldb' and interacting with it
1185 # using pexpect.
Johnny Chen985e7402011-08-01 21:13:26 +00001186 if self.child and self.child.isalive():
Zachary Turner9ef307b2014-07-22 16:19:29 +00001187 import pexpect
Johnny Chen985e7402011-08-01 21:13:26 +00001188 with recording(self, traceAlways) as sbuf:
1189 print >> sbuf, "tearing down the child process...."
Johnny Chen985e7402011-08-01 21:13:26 +00001190 try:
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001191 if self.child_in_script_interpreter:
1192 self.child.sendline('quit()')
1193 self.child.expect_exact(self.child_prompt)
1194 self.child.sendline('settings set interpreter.prompt-on-quit false')
1195 self.child.sendline('quit')
Johnny Chen985e7402011-08-01 21:13:26 +00001196 self.child.expect(pexpect.EOF)
Ilia K47448c22015-02-11 21:41:58 +00001197 except (ValueError, pexpect.ExceptionPexpect):
1198 # child is already terminated
1199 pass
1200 except OSError as exception:
1201 import errno
1202 if exception.errno != errno.EIO:
1203 # unexpected error
1204 raise
Daniel Maleac9a0ec32013-02-22 00:41:26 +00001205 # child is already terminated
Johnny Chen985e7402011-08-01 21:13:26 +00001206 pass
Shawn Besteb3e9052014-11-06 17:52:15 +00001207 finally:
1208 # Give it one final blow to make sure the child is terminated.
1209 self.child.close()
Jim Inghamda3a3862014-10-16 23:02:14 +00001210
1211 def tearDown(self):
1212 """Fixture for unittest test case teardown."""
1213 #import traceback
1214 #traceback.print_stack()
1215
1216 self.deletePexpectChild()
1217
Johnny Chenfb4264c2011-08-01 19:50:58 +00001218 # Check and run any hook functions.
1219 for hook in reversed(self.hooks):
1220 with recording(self, traceAlways) as sbuf:
1221 print >> sbuf, "Executing tearDown hook:", getsource_if_available(hook)
Enrico Granataab0e8312014-11-05 21:31:57 +00001222 import inspect
1223 hook_argc = len(inspect.getargspec(hook).args)
Enrico Granata6e0566c2014-11-17 19:00:20 +00001224 if hook_argc == 0 or getattr(hook,'im_self',None):
Enrico Granataab0e8312014-11-05 21:31:57 +00001225 hook()
1226 elif hook_argc == 1:
1227 hook(self)
1228 else:
1229 hook() # try the plain call and hope it works
Johnny Chenfb4264c2011-08-01 19:50:58 +00001230
1231 del self.hooks
1232
1233 # Perform registered teardown cleanup.
1234 if doCleanup and self.doTearDownCleanup:
Johnny Chen0fddfb22011-11-17 19:57:27 +00001235 self.cleanup(dictionary=self.dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001236
1237 # In rare cases where there are multiple teardown cleanups added.
1238 if doCleanup and self.doTearDownCleanups:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001239 if self.dicts:
1240 for dict in reversed(self.dicts):
Johnny Chen0fddfb22011-11-17 19:57:27 +00001241 self.cleanup(dictionary=dict)
Johnny Chenfb4264c2011-08-01 19:50:58 +00001242
1243 # Decide whether to dump the session info.
1244 self.dumpSessionInfo()
1245
1246 # =========================================================
1247 # Various callbacks to allow introspection of test progress
1248 # =========================================================
1249
1250 def markError(self):
1251 """Callback invoked when an error (unexpected exception) errored."""
1252 self.__errored__ = True
1253 with recording(self, False) as sbuf:
1254 # False because there's no need to write "ERROR" to the stderr twice.
1255 # Once by the Python unittest framework, and a second time by us.
1256 print >> sbuf, "ERROR"
1257
1258 def markFailure(self):
1259 """Callback invoked when a failure (test assertion failure) occurred."""
1260 self.__failed__ = True
1261 with recording(self, False) as sbuf:
1262 # False because there's no need to write "FAIL" to the stderr twice.
1263 # Once by the Python unittest framework, and a second time by us.
1264 print >> sbuf, "FAIL"
1265
Enrico Granatae6cedc12013-02-23 01:05:23 +00001266 def markExpectedFailure(self,err,bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001267 """Callback invoked when an expected failure/error occurred."""
1268 self.__expected__ = True
1269 with recording(self, False) as sbuf:
1270 # False because there's no need to write "expected failure" to the
1271 # stderr twice.
1272 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001273 if bugnumber == None:
1274 print >> sbuf, "expected failure"
1275 else:
1276 print >> sbuf, "expected failure (problem id:" + str(bugnumber) + ")"
Johnny Chenfb4264c2011-08-01 19:50:58 +00001277
Johnny Chenc5cc6252011-08-15 23:09:08 +00001278 def markSkippedTest(self):
1279 """Callback invoked when a test is skipped."""
1280 self.__skipped__ = True
1281 with recording(self, False) as sbuf:
1282 # False because there's no need to write "skipped test" to the
1283 # stderr twice.
1284 # Once by the Python unittest framework, and a second time by us.
1285 print >> sbuf, "skipped test"
1286
Enrico Granatae6cedc12013-02-23 01:05:23 +00001287 def markUnexpectedSuccess(self, bugnumber):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001288 """Callback invoked when an unexpected success occurred."""
1289 self.__unexpected__ = True
1290 with recording(self, False) as sbuf:
1291 # False because there's no need to write "unexpected success" to the
1292 # stderr twice.
1293 # Once by the Python unittest framework, and a second time by us.
Enrico Granatae6cedc12013-02-23 01:05:23 +00001294 if bugnumber == None:
1295 print >> sbuf, "unexpected success"
1296 else:
1297 print >> sbuf, "unexpected success (problem id:" + str(bugnumber) + ")"
Johnny Chenfb4264c2011-08-01 19:50:58 +00001298
Greg Clayton70995582015-01-07 22:25:50 +00001299 def getRerunArgs(self):
1300 return " -f %s.%s" % (self.__class__.__name__, self._testMethodName)
1301
Johnny Chenfb4264c2011-08-01 19:50:58 +00001302 def dumpSessionInfo(self):
1303 """
1304 Dump the debugger interactions leading to a test error/failure. This
1305 allows for more convenient postmortem analysis.
1306
1307 See also LLDBTestResult (dotest.py) which is a singlton class derived
1308 from TextTestResult and overwrites addError, addFailure, and
1309 addExpectedFailure methods to allow us to to mark the test instance as
1310 such.
1311 """
1312
1313 # We are here because self.tearDown() detected that this test instance
1314 # either errored or failed. The lldb.test_result singleton contains
1315 # two lists (erros and failures) which get populated by the unittest
1316 # framework. Look over there for stack trace information.
1317 #
1318 # The lists contain 2-tuples of TestCase instances and strings holding
1319 # formatted tracebacks.
1320 #
1321 # See http://docs.python.org/library/unittest.html#unittest.TestResult.
1322 if self.__errored__:
1323 pairs = lldb.test_result.errors
1324 prefix = 'Error'
1325 elif self.__failed__:
1326 pairs = lldb.test_result.failures
1327 prefix = 'Failure'
1328 elif self.__expected__:
1329 pairs = lldb.test_result.expectedFailures
1330 prefix = 'ExpectedFailure'
Johnny Chenc5cc6252011-08-15 23:09:08 +00001331 elif self.__skipped__:
1332 prefix = 'SkippedTest'
Johnny Chenfb4264c2011-08-01 19:50:58 +00001333 elif self.__unexpected__:
1334 prefix = "UnexpectedSuccess"
1335 else:
1336 # Simply return, there's no session info to dump!
1337 return
1338
Johnny Chenc5cc6252011-08-15 23:09:08 +00001339 if not self.__unexpected__ and not self.__skipped__:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001340 for test, traceback in pairs:
1341 if test is self:
1342 print >> self.session, traceback
1343
Johnny Chen8082a002011-08-11 00:16:28 +00001344 testMethod = getattr(self, self._testMethodName)
1345 if getattr(testMethod, "__benchmarks_test__", False):
1346 benchmarks = True
1347 else:
1348 benchmarks = False
1349
Johnny Chenfb4264c2011-08-01 19:50:58 +00001350 dname = os.path.join(os.environ["LLDB_TEST"],
1351 os.environ["LLDB_SESSION_DIRNAME"])
1352 if not os.path.isdir(dname):
1353 os.mkdir(dname)
Zachary Turner756acba2014-10-14 21:54:14 +00001354 compiler = self.getCompiler()
1355 if compiler[1] == ':':
1356 compiler = compiler[2:]
1357
Tamas Berghammer6698d842015-03-12 10:24:11 +00001358 fname = "%s-%s-%s-%s.log" % (prefix, self.getArchitecture(), "_".join(compiler.split(os.path.sep)), self.id())
1359 if len(fname) > 255:
1360 fname = "%s-%s-%s-%s.log" % (prefix, self.getArchitecture(), compiler.split(os.path.sep)[-1], self.id())
1361 pname = os.path.join(dname, fname)
1362 with open(pname, "w") as f:
Johnny Chenfb4264c2011-08-01 19:50:58 +00001363 import datetime
1364 print >> f, "Session info generated @", datetime.datetime.now().ctime()
1365 print >> f, self.session.getvalue()
1366 print >> f, "To rerun this test, issue the following command from the 'test' directory:\n"
Greg Clayton70995582015-01-07 22:25:50 +00001367 print >> f, "./dotest.py %s -v %s %s" % (self.getRunOptions(),
1368 ('+b' if benchmarks else '-t'),
1369 self.getRerunArgs())
Johnny Chenfb4264c2011-08-01 19:50:58 +00001370
1371 # ====================================================
1372 # Config. methods supported through a plugin interface
1373 # (enables reading of the current test configuration)
1374 # ====================================================
1375
1376 def getArchitecture(self):
1377 """Returns the architecture in effect the test suite is running with."""
1378 module = builder_module()
Ed Maste0f434e62015-04-06 15:50:48 +00001379 arch = module.getArchitecture()
1380 if arch == 'amd64':
1381 arch = 'x86_64'
1382 return arch
Johnny Chenfb4264c2011-08-01 19:50:58 +00001383
1384 def getCompiler(self):
1385 """Returns the compiler in effect the test suite is running with."""
1386 module = builder_module()
1387 return module.getCompiler()
1388
Oleksiy Vyalovdc4067c2014-11-26 18:30:04 +00001389 def getCompilerBinary(self):
1390 """Returns the compiler binary the test suite is running with."""
1391 return self.getCompiler().split()[0]
1392
Daniel Malea0aea0162013-02-27 17:29:46 +00001393 def getCompilerVersion(self):
1394 """ Returns a string that represents the compiler version.
1395 Supports: llvm, clang.
1396 """
1397 from lldbutil import which
1398 version = 'unknown'
1399
Oleksiy Vyalovdc4067c2014-11-26 18:30:04 +00001400 compiler = self.getCompilerBinary()
Zachary Turner9ef307b2014-07-22 16:19:29 +00001401 version_output = system([[which(compiler), "-v"]])[1]
Daniel Malea0aea0162013-02-27 17:29:46 +00001402 for line in version_output.split(os.linesep):
Greg Clayton2a844b72013-03-06 02:34:51 +00001403 m = re.search('version ([0-9\.]+)', line)
Daniel Malea0aea0162013-02-27 17:29:46 +00001404 if m:
1405 version = m.group(1)
1406 return version
1407
Greg Claytone0d0a762015-04-02 18:24:03 +00001408 def platformIsDarwin(self):
1409 """Returns true if the OS triple for the selected platform is any valid apple OS"""
Robert Flackfb2f6c62015-04-17 08:02:18 +00001410 return platformIsDarwin()
Vince Harron20952cc2015-04-03 01:00:06 +00001411
Robert Flack13c7ad92015-03-30 14:12:17 +00001412 def getPlatform(self):
Robert Flackfb2f6c62015-04-17 08:02:18 +00001413 """Returns the target platform the test suite is running on."""
Robert Flack068898c2015-04-09 18:07:58 +00001414 return getPlatform()
Robert Flack13c7ad92015-03-30 14:12:17 +00001415
Daniel Maleaadaaec92013-08-06 20:51:41 +00001416 def isIntelCompiler(self):
1417 """ Returns true if using an Intel (ICC) compiler, false otherwise. """
1418 return any([x in self.getCompiler() for x in ["icc", "icpc", "icl"]])
1419
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001420 def expectedCompilerVersion(self, compiler_version):
1421 """Returns True iff compiler_version[1] matches the current compiler version.
1422 Use compiler_version[0] to specify the operator used to determine if a match has occurred.
1423 Any operator other than the following defaults to an equality test:
1424 '>', '>=', "=>", '<', '<=', '=<', '!=', "!" or 'not'
1425 """
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001426 if (compiler_version == None):
1427 return True
1428 operator = str(compiler_version[0])
1429 version = compiler_version[1]
1430
1431 if (version == None):
1432 return True
1433 if (operator == '>'):
1434 return self.getCompilerVersion() > version
1435 if (operator == '>=' or operator == '=>'):
1436 return self.getCompilerVersion() >= version
1437 if (operator == '<'):
1438 return self.getCompilerVersion() < version
1439 if (operator == '<=' or operator == '=<'):
1440 return self.getCompilerVersion() <= version
1441 if (operator == '!=' or operator == '!' or operator == 'not'):
1442 return str(version) not in str(self.getCompilerVersion())
1443 return str(version) in str(self.getCompilerVersion())
1444
1445 def expectedCompiler(self, compilers):
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001446 """Returns True iff any element of compilers is a sub-string of the current compiler."""
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001447 if (compilers == None):
1448 return True
Ashok Thirumurthi3b037282013-06-06 14:23:31 +00001449
1450 for compiler in compilers:
1451 if compiler in self.getCompiler():
1452 return True
1453
1454 return False
Ashok Thirumurthic97a6082013-05-17 20:15:07 +00001455
Johnny Chenfb4264c2011-08-01 19:50:58 +00001456 def getRunOptions(self):
1457 """Command line option for -A and -C to run this test again, called from
1458 self.dumpSessionInfo()."""
1459 arch = self.getArchitecture()
1460 comp = self.getCompiler()
Johnny Chenb7bdd102011-08-24 19:48:51 +00001461 if arch:
1462 option_str = "-A " + arch
Johnny Chenfb4264c2011-08-01 19:50:58 +00001463 else:
Johnny Chenb7bdd102011-08-24 19:48:51 +00001464 option_str = ""
1465 if comp:
Johnny Chen531c0852012-03-16 20:44:00 +00001466 option_str += " -C " + comp
Johnny Chenb7bdd102011-08-24 19:48:51 +00001467 return option_str
Johnny Chenfb4264c2011-08-01 19:50:58 +00001468
1469 # ==================================================
1470 # Build methods supported through a plugin interface
1471 # ==================================================
1472
Ed Mastec97323e2014-04-01 18:47:58 +00001473 def getstdlibFlag(self):
1474 """ Returns the proper -stdlib flag, or empty if not required."""
1475 if sys.platform.startswith("darwin") or sys.platform.startswith("freebsd"):
1476 stdlibflag = "-stdlib=libc++"
1477 else:
1478 stdlibflag = ""
1479 return stdlibflag
1480
Matt Kopec7663b3a2013-09-25 17:44:00 +00001481 def getstdFlag(self):
1482 """ Returns the proper stdflag. """
Daniel Malea55faa402013-05-02 21:44:31 +00001483 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
Daniel Malea0b7c6112013-05-06 19:31:31 +00001484 stdflag = "-std=c++0x"
Daniel Malea55faa402013-05-02 21:44:31 +00001485 else:
1486 stdflag = "-std=c++11"
Matt Kopec7663b3a2013-09-25 17:44:00 +00001487 return stdflag
1488
1489 def buildDriver(self, sources, exe_name):
1490 """ Platform-specific way to build a program that links with LLDB (via the liblldb.so
1491 or LLDB.framework).
1492 """
1493
1494 stdflag = self.getstdFlag()
Ed Mastec97323e2014-04-01 18:47:58 +00001495 stdlibflag = self.getstdlibFlag()
Daniel Malea55faa402013-05-02 21:44:31 +00001496
1497 if sys.platform.startswith("darwin"):
1498 dsym = os.path.join(self.lib_dir, 'LLDB.framework', 'LLDB')
1499 d = {'CXX_SOURCES' : sources,
1500 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00001501 'CFLAGS_EXTRAS' : "%s %s" % (stdflag, stdlibflag),
Daniel Malea55faa402013-05-02 21:44:31 +00001502 'FRAMEWORK_INCLUDES' : "-F%s" % self.lib_dir,
Stefanus Du Toit04004442013-07-30 19:19:49 +00001503 'LD_EXTRAS' : "%s -Wl,-rpath,%s" % (dsym, self.lib_dir),
Daniel Malea55faa402013-05-02 21:44:31 +00001504 }
Ed Maste372c24d2013-07-25 21:02:34 +00001505 elif sys.platform.startswith('freebsd') or sys.platform.startswith("linux") or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
Adrian McCarthyb016b3c2015-03-27 20:47:35 +00001506 d = {'CXX_SOURCES' : sources,
Daniel Malea55faa402013-05-02 21:44:31 +00001507 'EXE' : exe_name,
Ed Mastec97323e2014-04-01 18:47:58 +00001508 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
Daniel Malea55faa402013-05-02 21:44:31 +00001509 'LD_EXTRAS' : "-L%s -llldb" % self.lib_dir}
Adrian McCarthyb016b3c2015-03-27 20:47:35 +00001510 elif sys.platform.startswith('win'):
1511 d = {'CXX_SOURCES' : sources,
1512 'EXE' : exe_name,
1513 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
1514 'LD_EXTRAS' : "-L%s -lliblldb" % self.implib_dir}
Daniel Malea55faa402013-05-02 21:44:31 +00001515 if self.TraceOn():
1516 print "Building LLDB Driver (%s) from sources %s" % (exe_name, sources)
1517
1518 self.buildDefault(dictionary=d)
1519
Matt Kopec7663b3a2013-09-25 17:44:00 +00001520 def buildLibrary(self, sources, lib_name):
1521 """Platform specific way to build a default library. """
1522
1523 stdflag = self.getstdFlag()
1524
1525 if sys.platform.startswith("darwin"):
1526 dsym = os.path.join(self.lib_dir, 'LLDB.framework', 'LLDB')
1527 d = {'DYLIB_CXX_SOURCES' : sources,
1528 'DYLIB_NAME' : lib_name,
1529 'CFLAGS_EXTRAS' : "%s -stdlib=libc++" % stdflag,
1530 'FRAMEWORK_INCLUDES' : "-F%s" % self.lib_dir,
1531 'LD_EXTRAS' : "%s -Wl,-rpath,%s -dynamiclib" % (dsym, self.lib_dir),
1532 }
Adrian McCarthyb016b3c2015-03-27 20:47:35 +00001533 elif sys.platform.startswith('freebsd') or sys.platform.startswith("linux") or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
Matt Kopec7663b3a2013-09-25 17:44:00 +00001534 d = {'DYLIB_CXX_SOURCES' : sources,
1535 'DYLIB_NAME' : lib_name,
1536 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
1537 'LD_EXTRAS' : "-shared -L%s -llldb" % self.lib_dir}
Adrian McCarthyb016b3c2015-03-27 20:47:35 +00001538 elif sys.platform.startswith("win"):
1539 d = {'DYLIB_CXX_SOURCES' : sources,
1540 'DYLIB_NAME' : lib_name,
1541 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
1542 'LD_EXTRAS' : "-shared -l%s\liblldb.lib" % self.implib_dir}
Matt Kopec7663b3a2013-09-25 17:44:00 +00001543 if self.TraceOn():
1544 print "Building LLDB Library (%s) from sources %s" % (lib_name, sources)
1545
1546 self.buildDefault(dictionary=d)
1547
Daniel Malea55faa402013-05-02 21:44:31 +00001548 def buildProgram(self, sources, exe_name):
1549 """ Platform specific way to build an executable from C/C++ sources. """
1550 d = {'CXX_SOURCES' : sources,
1551 'EXE' : exe_name}
1552 self.buildDefault(dictionary=d)
1553
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001554 def buildDefault(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001555 """Platform specific way to build the default binaries."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001556 if lldb.skip_build_and_cleanup:
1557 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00001558 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001559 if not module.buildDefault(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001560 raise Exception("Don't know how to build default binary")
1561
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001562 def buildDsym(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001563 """Platform specific way to build binaries with dsym info."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001564 if lldb.skip_build_and_cleanup:
1565 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00001566 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001567 if not module.buildDsym(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001568 raise Exception("Don't know how to build binary with dsym")
1569
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001570 def buildDwarf(self, architecture=None, compiler=None, dictionary=None, clean=True):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001571 """Platform specific way to build binaries with dwarf maps."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001572 if lldb.skip_build_and_cleanup:
1573 return
Johnny Chenfb4264c2011-08-01 19:50:58 +00001574 module = builder_module()
Johnny Chenfdc80a5c2012-02-01 01:49:50 +00001575 if not module.buildDwarf(self, architecture, compiler, dictionary, clean):
Johnny Chenfb4264c2011-08-01 19:50:58 +00001576 raise Exception("Don't know how to build binary with dwarf")
Johnny Chena74bb0a2011-08-01 18:46:13 +00001577
Oleksiy Vyalov49b71c62015-01-22 20:03:21 +00001578 def signBinary(self, binary_path):
1579 if sys.platform.startswith("darwin"):
1580 codesign_cmd = "codesign --force --sign lldb_codesign %s" % (binary_path)
1581 call(codesign_cmd, shell=True)
1582
Kuba Breckabeed8212014-09-04 01:03:18 +00001583 def findBuiltClang(self):
1584 """Tries to find and use Clang from the build directory as the compiler (instead of the system compiler)."""
1585 paths_to_try = [
1586 "llvm-build/Release+Asserts/x86_64/Release+Asserts/bin/clang",
1587 "llvm-build/Debug+Asserts/x86_64/Debug+Asserts/bin/clang",
1588 "llvm-build/Release/x86_64/Release/bin/clang",
1589 "llvm-build/Debug/x86_64/Debug/bin/clang",
1590 ]
1591 lldb_root_path = os.path.join(os.path.dirname(__file__), "..")
1592 for p in paths_to_try:
1593 path = os.path.join(lldb_root_path, p)
1594 if os.path.exists(path):
1595 return path
Ilia Kd9953052015-03-12 07:19:41 +00001596
1597 # Tries to find clang at the same folder as the lldb
1598 path = os.path.join(os.path.dirname(self.lldbExec), "clang")
1599 if os.path.exists(path):
1600 return path
Kuba Breckabeed8212014-09-04 01:03:18 +00001601
1602 return os.environ["CC"]
1603
Tamas Berghammer765b5e52015-02-25 13:26:28 +00001604 def getBuildFlags(self, use_cpp11=True, use_libcxx=False, use_libstdcxx=False):
Andrew Kaylor93132f52013-05-28 23:04:25 +00001605 """ Returns a dictionary (which can be provided to build* functions above) which
1606 contains OS-specific build flags.
1607 """
1608 cflags = ""
Tamas Berghammer765b5e52015-02-25 13:26:28 +00001609 ldflags = ""
Daniel Malea9115f072013-08-06 15:02:32 +00001610
1611 # On Mac OS X, unless specifically requested to use libstdc++, use libc++
1612 if not use_libstdcxx and sys.platform.startswith('darwin'):
1613 use_libcxx = True
1614
1615 if use_libcxx and self.libcxxPath:
1616 cflags += "-stdlib=libc++ "
1617 if self.libcxxPath:
1618 libcxxInclude = os.path.join(self.libcxxPath, "include")
1619 libcxxLib = os.path.join(self.libcxxPath, "lib")
1620 if os.path.isdir(libcxxInclude) and os.path.isdir(libcxxLib):
1621 cflags += "-nostdinc++ -I%s -L%s -Wl,-rpath,%s " % (libcxxInclude, libcxxLib, libcxxLib)
1622
Andrew Kaylor93132f52013-05-28 23:04:25 +00001623 if use_cpp11:
1624 cflags += "-std="
1625 if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
1626 cflags += "c++0x"
1627 else:
1628 cflags += "c++11"
Ed Mastedbd59502014-02-02 19:24:15 +00001629 if sys.platform.startswith("darwin") or sys.platform.startswith("freebsd"):
Andrew Kaylor93132f52013-05-28 23:04:25 +00001630 cflags += " -stdlib=libc++"
1631 elif "clang" in self.getCompiler():
1632 cflags += " -stdlib=libstdc++"
1633
Andrew Kaylor93132f52013-05-28 23:04:25 +00001634 return {'CFLAGS_EXTRAS' : cflags,
1635 'LD_EXTRAS' : ldflags,
1636 }
1637
Johnny Chen9f4f5d92011-08-12 20:19:22 +00001638 def cleanup(self, dictionary=None):
1639 """Platform specific way to do cleanup after build."""
Johnny Chen0fddfb22011-11-17 19:57:27 +00001640 if lldb.skip_build_and_cleanup:
1641 return
Johnny Chen9f4f5d92011-08-12 20:19:22 +00001642 module = builder_module()
1643 if not module.cleanup(self, dictionary):
Johnny Chen0fddfb22011-11-17 19:57:27 +00001644 raise Exception("Don't know how to do cleanup with dictionary: "+dictionary)
Johnny Chen9f4f5d92011-08-12 20:19:22 +00001645
Daniel Malea55faa402013-05-02 21:44:31 +00001646 def getLLDBLibraryEnvVal(self):
1647 """ Returns the path that the OS-specific library search environment variable
1648 (self.dylibPath) should be set to in order for a program to find the LLDB
1649 library. If an environment variable named self.dylibPath is already set,
1650 the new path is appended to it and returned.
1651 """
1652 existing_library_path = os.environ[self.dylibPath] if self.dylibPath in os.environ else None
1653 if existing_library_path:
1654 return "%s:%s" % (existing_library_path, self.lib_dir)
1655 elif sys.platform.startswith("darwin"):
1656 return os.path.join(self.lib_dir, 'LLDB.framework')
1657 else:
1658 return self.lib_dir
Johnny Chena74bb0a2011-08-01 18:46:13 +00001659
Ed Maste437f8f62013-09-09 14:04:04 +00001660 def getLibcPlusPlusLibs(self):
1661 if sys.platform.startswith('freebsd'):
1662 return ['libc++.so.1']
1663 else:
1664 return ['libc++.1.dylib','libc++abi.dylib']
1665
Johnny Chena74bb0a2011-08-01 18:46:13 +00001666class TestBase(Base):
1667 """
1668 This abstract base class is meant to be subclassed. It provides default
1669 implementations for setUpClass(), tearDownClass(), setUp(), and tearDown(),
1670 among other things.
1671
1672 Important things for test class writers:
1673
1674 - Overwrite the mydir class attribute, otherwise your test class won't
1675 run. It specifies the relative directory to the top level 'test' so
1676 the test harness can change to the correct working directory before
1677 running your test.
1678
1679 - The setUp method sets up things to facilitate subsequent interactions
1680 with the debugger as part of the test. These include:
1681 - populate the test method name
1682 - create/get a debugger set with synchronous mode (self.dbg)
1683 - get the command interpreter from with the debugger (self.ci)
1684 - create a result object for use with the command interpreter
1685 (self.res)
1686 - plus other stuffs
1687
1688 - The tearDown method tries to perform some necessary cleanup on behalf
1689 of the test to return the debugger to a good state for the next test.
1690 These include:
1691 - execute any tearDown hooks registered by the test method with
1692 TestBase.addTearDownHook(); examples can be found in
1693 settings/TestSettings.py
1694 - kill the inferior process associated with each target, if any,
1695 and, then delete the target from the debugger's target list
1696 - perform build cleanup before running the next test method in the
1697 same test class; examples of registering for this service can be
1698 found in types/TestIntegerTypes.py with the call:
1699 - self.setTearDownCleanup(dictionary=d)
1700
1701 - Similarly setUpClass and tearDownClass perform classwise setup and
1702 teardown fixtures. The tearDownClass method invokes a default build
1703 cleanup for the entire test class; also, subclasses can implement the
1704 classmethod classCleanup(cls) to perform special class cleanup action.
1705
1706 - The instance methods runCmd and expect are used heavily by existing
1707 test cases to send a command to the command interpreter and to perform
1708 string/pattern matching on the output of such command execution. The
1709 expect method also provides a mode to peform string/pattern matching
1710 without running a command.
1711
1712 - The build methods buildDefault, buildDsym, and buildDwarf are used to
1713 build the binaries used during a particular test scenario. A plugin
1714 should be provided for the sys.platform running the test suite. The
1715 Mac OS X implementation is located in plugins/darwin.py.
1716 """
1717
1718 # Maximum allowed attempts when launching the inferior process.
1719 # Can be overridden by the LLDB_MAX_LAUNCH_COUNT environment variable.
1720 maxLaunchCount = 3;
1721
1722 # Time to wait before the next launching attempt in second(s).
1723 # Can be overridden by the LLDB_TIME_WAIT_NEXT_LAUNCH environment variable.
1724 timeWaitNextLaunch = 1.0;
1725
1726 def doDelay(self):
1727 """See option -w of dotest.py."""
1728 if ("LLDB_WAIT_BETWEEN_TEST_CASES" in os.environ and
1729 os.environ["LLDB_WAIT_BETWEEN_TEST_CASES"] == 'YES'):
1730 waitTime = 1.0
1731 if "LLDB_TIME_WAIT_BETWEEN_TEST_CASES" in os.environ:
1732 waitTime = float(os.environ["LLDB_TIME_WAIT_BETWEEN_TEST_CASES"])
1733 time.sleep(waitTime)
1734
Enrico Granata165f8af2012-09-21 19:10:53 +00001735 # Returns the list of categories to which this test case belongs
1736 # by default, look for a ".categories" file, and read its contents
1737 # if no such file exists, traverse the hierarchy - we guarantee
1738 # a .categories to exist at the top level directory so we do not end up
1739 # looping endlessly - subclasses are free to define their own categories
1740 # in whatever way makes sense to them
1741 def getCategories(self):
1742 import inspect
1743 import os.path
1744 folder = inspect.getfile(self.__class__)
1745 folder = os.path.dirname(folder)
1746 while folder != '/':
1747 categories_file_name = os.path.join(folder,".categories")
1748 if os.path.exists(categories_file_name):
1749 categories_file = open(categories_file_name,'r')
1750 categories = categories_file.readline()
1751 categories_file.close()
1752 categories = str.replace(categories,'\n','')
1753 categories = str.replace(categories,'\r','')
1754 return categories.split(',')
1755 else:
1756 folder = os.path.dirname(folder)
1757 continue
1758
Johnny Chena74bb0a2011-08-01 18:46:13 +00001759 def setUp(self):
1760 #import traceback
1761 #traceback.print_stack()
1762
1763 # Works with the test driver to conditionally skip tests via decorators.
1764 Base.setUp(self)
1765
Johnny Chena74bb0a2011-08-01 18:46:13 +00001766 try:
1767 if lldb.blacklist:
1768 className = self.__class__.__name__
1769 classAndMethodName = "%s.%s" % (className, self._testMethodName)
1770 if className in lldb.blacklist:
1771 self.skipTest(lldb.blacklist.get(className))
1772 elif classAndMethodName in lldb.blacklist:
1773 self.skipTest(lldb.blacklist.get(classAndMethodName))
1774 except AttributeError:
1775 pass
1776
Johnny Chened492022011-06-21 00:53:00 +00001777 # Insert some delay between successive test cases if specified.
1778 self.doDelay()
Johnny Chen0ed37c92010-10-07 02:04:14 +00001779
Johnny Chenf2b70232010-08-25 18:49:48 +00001780 if "LLDB_MAX_LAUNCH_COUNT" in os.environ:
1781 self.maxLaunchCount = int(os.environ["LLDB_MAX_LAUNCH_COUNT"])
1782
Johnny Chen430eb762010-10-19 16:00:42 +00001783 if "LLDB_TIME_WAIT_NEXT_LAUNCH" in os.environ:
Johnny Chen4921b112010-11-29 20:20:34 +00001784 self.timeWaitNextLaunch = float(os.environ["LLDB_TIME_WAIT_NEXT_LAUNCH"])
Johnny Chenf2b70232010-08-25 18:49:48 +00001785
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001786 # Create the debugger instance if necessary.
1787 try:
1788 self.dbg = lldb.DBG
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001789 except AttributeError:
1790 self.dbg = lldb.SBDebugger.Create()
Johnny Chenf02ec122010-07-03 20:41:42 +00001791
Johnny Chen3cd1e552011-05-25 19:06:18 +00001792 if not self.dbg:
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001793 raise Exception('Invalid debugger instance')
1794
Daniel Maleae0f8f572013-08-26 23:57:52 +00001795 #
1796 # Warning: MAJOR HACK AHEAD!
1797 # If we are running testsuite remotely (by checking lldb.lldbtest_remote_sandbox),
1798 # redefine the self.dbg.CreateTarget(filename) method to execute a "file filename"
1799 # command, instead. See also runCmd() where it decorates the "file filename" call
1800 # with additional functionality when running testsuite remotely.
1801 #
1802 if lldb.lldbtest_remote_sandbox:
1803 def DecoratedCreateTarget(arg):
1804 self.runCmd("file %s" % arg)
1805 target = self.dbg.GetSelectedTarget()
1806 #
Greg Claytonc6947512013-12-13 19:18:59 +00001807 # SBtarget.LaunchSimple () currently not working for remote platform?
Daniel Maleae0f8f572013-08-26 23:57:52 +00001808 # johnny @ 04/23/2012
1809 #
1810 def DecoratedLaunchSimple(argv, envp, wd):
1811 self.runCmd("run")
1812 return target.GetProcess()
1813 target.LaunchSimple = DecoratedLaunchSimple
1814
1815 return target
1816 self.dbg.CreateTarget = DecoratedCreateTarget
1817 if self.TraceOn():
1818 print "self.dbg.Create is redefined to:\n%s" % getsource_if_available(DecoratedCreateTarget)
1819
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001820 # We want our debugger to be synchronous.
1821 self.dbg.SetAsync(False)
1822
1823 # Retrieve the associated command interpreter instance.
1824 self.ci = self.dbg.GetCommandInterpreter()
1825 if not self.ci:
1826 raise Exception('Could not get the command interpreter')
1827
1828 # And the result object.
1829 self.res = lldb.SBCommandReturnObject()
1830
Johnny Chen44d24972012-04-16 18:55:15 +00001831 # Run global pre-flight code, if defined via the config file.
1832 if lldb.pre_flight:
1833 lldb.pre_flight(self)
1834
Greg Claytonfb909312013-11-23 01:58:15 +00001835 if lldb.remote_platform:
1836 #remote_test_dir = os.path.join(lldb.remote_platform_working_dir, self.mydir)
Greg Clayton5fb8f792013-12-02 19:35:49 +00001837 remote_test_dir = os.path.join(lldb.remote_platform_working_dir,
1838 self.getArchitecture(),
1839 str(self.test_number),
1840 self.mydir)
Greg Claytonfb909312013-11-23 01:58:15 +00001841 error = lldb.remote_platform.MakeDirectory(remote_test_dir, 0700)
1842 if error.Success():
Greg Claytonfb909312013-11-23 01:58:15 +00001843 lldb.remote_platform.SetWorkingDirectory(remote_test_dir)
1844 else:
1845 print "error: making remote directory '%s': %s" % (remote_test_dir, error)
1846
Greg Clayton35c91342014-11-17 18:40:27 +00001847 def registerSharedLibrariesWithTarget(self, target, shlibs):
1848 '''If we are remotely running the test suite, register the shared libraries with the target so they get uploaded, otherwise do nothing
1849
1850 Any modules in the target that have their remote install file specification set will
1851 get uploaded to the remote host. This function registers the local copies of the
1852 shared libraries with the target and sets their remote install locations so they will
1853 be uploaded when the target is run.
1854 '''
Zachary Turnerbe40b2f2014-12-02 21:32:44 +00001855 if not shlibs or not self.platformContext:
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001856 return None
Greg Clayton35c91342014-11-17 18:40:27 +00001857
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001858 shlib_environment_var = self.platformContext.shlib_environment_var
1859 shlib_prefix = self.platformContext.shlib_prefix
1860 shlib_extension = '.' + self.platformContext.shlib_extension
1861
1862 working_dir = self.get_process_working_directory()
1863 environment = ['%s=%s' % (shlib_environment_var, working_dir)]
1864 # Add any shared libraries to our target if remote so they get
1865 # uploaded into the working directory on the remote side
1866 for name in shlibs:
1867 # The path can be a full path to a shared library, or a make file name like "Foo" for
1868 # "libFoo.dylib" or "libFoo.so", or "Foo.so" for "Foo.so" or "libFoo.so", or just a
1869 # basename like "libFoo.so". So figure out which one it is and resolve the local copy
1870 # of the shared library accordingly
1871 if os.path.exists(name):
1872 local_shlib_path = name # name is the full path to the local shared library
1873 else:
1874 # Check relative names
1875 local_shlib_path = os.path.join(os.getcwd(), shlib_prefix + name + shlib_extension)
1876 if not os.path.exists(local_shlib_path):
1877 local_shlib_path = os.path.join(os.getcwd(), name + shlib_extension)
Greg Clayton35c91342014-11-17 18:40:27 +00001878 if not os.path.exists(local_shlib_path):
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001879 local_shlib_path = os.path.join(os.getcwd(), name)
Greg Clayton35c91342014-11-17 18:40:27 +00001880
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001881 # Make sure we found the local shared library in the above code
1882 self.assertTrue(os.path.exists(local_shlib_path))
1883
1884 # Add the shared library to our target
1885 shlib_module = target.AddModule(local_shlib_path, None, None, None)
1886 if lldb.remote_platform:
Greg Clayton35c91342014-11-17 18:40:27 +00001887 # We must set the remote install location if we want the shared library
1888 # to get uploaded to the remote target
1889 remote_shlib_path = os.path.join(lldb.remote_platform.GetWorkingDirectory(), os.path.basename(local_shlib_path))
1890 shlib_module.SetRemoteInstallFileSpec(lldb.SBFileSpec(remote_shlib_path, False))
Oleksiy Vyalova3ff6af2014-12-01 23:21:18 +00001891
1892 return environment
1893
Enrico Granata44818162012-10-24 01:23:57 +00001894 # utility methods that tests can use to access the current objects
1895 def target(self):
1896 if not self.dbg:
1897 raise Exception('Invalid debugger instance')
1898 return self.dbg.GetSelectedTarget()
1899
1900 def process(self):
1901 if not self.dbg:
1902 raise Exception('Invalid debugger instance')
1903 return self.dbg.GetSelectedTarget().GetProcess()
1904
1905 def thread(self):
1906 if not self.dbg:
1907 raise Exception('Invalid debugger instance')
1908 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread()
1909
1910 def frame(self):
1911 if not self.dbg:
1912 raise Exception('Invalid debugger instance')
1913 return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame()
1914
Greg Claytonc6947512013-12-13 19:18:59 +00001915 def get_process_working_directory(self):
1916 '''Get the working directory that should be used when launching processes for local or remote processes.'''
1917 if lldb.remote_platform:
1918 # Remote tests set the platform working directory up in TestBase.setUp()
1919 return lldb.remote_platform.GetWorkingDirectory()
1920 else:
1921 # local tests change directory into each test subdirectory
1922 return os.getcwd()
1923
Johnny Chenbf6ffa32010-07-03 03:41:59 +00001924 def tearDown(self):
Johnny Chen7d1d7532010-09-02 21:23:12 +00001925 #import traceback
1926 #traceback.print_stack()
1927
Johnny Chen3794ad92011-06-15 21:24:24 +00001928 # Delete the target(s) from the debugger as a general cleanup step.
1929 # This includes terminating the process for each target, if any.
1930 # We'd like to reuse the debugger for our next test without incurring
1931 # the initialization overhead.
1932 targets = []
1933 for target in self.dbg:
1934 if target:
1935 targets.append(target)
1936 process = target.GetProcess()
1937 if process:
1938 rc = self.invoke(process, "Kill")
1939 self.assertTrue(rc.Success(), PROCESS_KILLED)
1940 for target in targets:
1941 self.dbg.DeleteTarget(target)
Johnny Chen6ca006c2010-08-16 21:28:10 +00001942
Johnny Chen44d24972012-04-16 18:55:15 +00001943 # Run global post-flight code, if defined via the config file.
1944 if lldb.post_flight:
1945 lldb.post_flight(self)
1946
Zachary Turner65fe1eb2015-03-26 16:43:25 +00001947 # Do this last, to make sure it's in reverse order from how we setup.
1948 Base.tearDown(self)
1949
Zachary Turner95812042015-03-26 18:54:21 +00001950 # This must be the last statement, otherwise teardown hooks or other
1951 # lines might depend on this still being active.
1952 del self.dbg
1953
Johnny Chen86268e42011-09-30 21:48:35 +00001954 def switch_to_thread_with_stop_reason(self, stop_reason):
1955 """
1956 Run the 'thread list' command, and select the thread with stop reason as
1957 'stop_reason'. If no such thread exists, no select action is done.
1958 """
1959 from lldbutil import stop_reason_to_str
1960 self.runCmd('thread list')
1961 output = self.res.GetOutput()
1962 thread_line_pattern = re.compile("^[ *] thread #([0-9]+):.*stop reason = %s" %
1963 stop_reason_to_str(stop_reason))
1964 for line in output.splitlines():
1965 matched = thread_line_pattern.match(line)
1966 if matched:
1967 self.runCmd('thread select %s' % matched.group(1))
1968
Enrico Granata7594f142013-06-17 22:51:50 +00001969 def runCmd(self, cmd, msg=None, check=True, trace=False, inHistory=False):
Johnny Chen27f212d2010-08-19 23:26:59 +00001970 """
1971 Ask the command interpreter to handle the command and then check its
1972 return status.
1973 """
1974 # Fail fast if 'cmd' is not meaningful.
1975 if not cmd or len(cmd) == 0:
1976 raise Exception("Bad 'cmd' parameter encountered")
Johnny Chen5bbb88f2010-08-20 17:57:32 +00001977
Johnny Chen8d55a342010-08-31 17:42:54 +00001978 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00001979
Daniel Maleae0f8f572013-08-26 23:57:52 +00001980 # This is an opportunity to insert the 'platform target-install' command if we are told so
1981 # via the settig of lldb.lldbtest_remote_sandbox.
1982 if cmd.startswith("target create "):
1983 cmd = cmd.replace("target create ", "file ")
1984 if cmd.startswith("file ") and lldb.lldbtest_remote_sandbox:
1985 with recording(self, trace) as sbuf:
1986 the_rest = cmd.split("file ")[1]
1987 # Split the rest of the command line.
1988 atoms = the_rest.split()
1989 #
1990 # NOTE: This assumes that the options, if any, follow the file command,
1991 # instead of follow the specified target.
1992 #
1993 target = atoms[-1]
1994 # Now let's get the absolute pathname of our target.
1995 abs_target = os.path.abspath(target)
1996 print >> sbuf, "Found a file command, target (with absolute pathname)=%s" % abs_target
1997 fpath, fname = os.path.split(abs_target)
1998 parent_dir = os.path.split(fpath)[0]
1999 platform_target_install_command = 'platform target-install %s %s' % (fpath, lldb.lldbtest_remote_sandbox)
2000 print >> sbuf, "Insert this command to be run first: %s" % platform_target_install_command
2001 self.ci.HandleCommand(platform_target_install_command, self.res)
2002 # And this is the file command we want to execute, instead.
2003 #
2004 # Warning: SIDE EFFECT AHEAD!!!
2005 # Populate the remote executable pathname into the lldb namespace,
2006 # so that test cases can grab this thing out of the namespace.
2007 #
2008 lldb.lldbtest_remote_sandboxed_executable = abs_target.replace(parent_dir, lldb.lldbtest_remote_sandbox)
2009 cmd = "file -P %s %s %s" % (lldb.lldbtest_remote_sandboxed_executable, the_rest.replace(target, ''), abs_target)
2010 print >> sbuf, "And this is the replaced file command: %s" % cmd
2011
Johnny Chen63dfb272010-09-01 00:15:19 +00002012 running = (cmd.startswith("run") or cmd.startswith("process launch"))
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002013
Johnny Chen63dfb272010-09-01 00:15:19 +00002014 for i in range(self.maxLaunchCount if running else 1):
Enrico Granata7594f142013-06-17 22:51:50 +00002015 self.ci.HandleCommand(cmd, self.res, inHistory)
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002016
Johnny Chen150c3cc2010-10-15 01:18:29 +00002017 with recording(self, trace) as sbuf:
2018 print >> sbuf, "runCmd:", cmd
Johnny Chenab254f52010-10-15 16:13:00 +00002019 if not check:
Johnny Chen27b107b2010-10-15 18:52:22 +00002020 print >> sbuf, "check of return status not required"
Johnny Chenf2b70232010-08-25 18:49:48 +00002021 if self.res.Succeeded():
Johnny Chen150c3cc2010-10-15 01:18:29 +00002022 print >> sbuf, "output:", self.res.GetOutput()
Johnny Chenf2b70232010-08-25 18:49:48 +00002023 else:
Johnny Chen150c3cc2010-10-15 01:18:29 +00002024 print >> sbuf, "runCmd failed!"
2025 print >> sbuf, self.res.GetError()
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002026
Johnny Chenff3d01d2010-08-20 21:03:09 +00002027 if self.res.Succeeded():
Johnny Chenf2b70232010-08-25 18:49:48 +00002028 break
Johnny Chen150c3cc2010-10-15 01:18:29 +00002029 elif running:
Johnny Chencf7f74e2011-01-19 02:02:08 +00002030 # For process launch, wait some time before possible next try.
2031 time.sleep(self.timeWaitNextLaunch)
Johnny Chen552d6712012-08-01 19:56:04 +00002032 with recording(self, trace) as sbuf:
Johnny Chen150c3cc2010-10-15 01:18:29 +00002033 print >> sbuf, "Command '" + cmd + "' failed!"
Johnny Chen5bbb88f2010-08-20 17:57:32 +00002034
Johnny Chen27f212d2010-08-19 23:26:59 +00002035 if check:
2036 self.assertTrue(self.res.Succeeded(),
Johnny Chenc0c67f22010-11-09 18:42:22 +00002037 msg if msg else CMD_MSG(cmd))
Johnny Chen27f212d2010-08-19 23:26:59 +00002038
Jim Ingham63dfc722012-09-22 00:05:11 +00002039 def match (self, str, patterns, msg=None, trace=False, error=False, matching=True, exe=True):
2040 """run command in str, and match the result against regexp in patterns returning the match object for the first matching pattern
2041
2042 Otherwise, all the arguments have the same meanings as for the expect function"""
2043
2044 trace = (True if traceAlways else trace)
2045
2046 if exe:
2047 # First run the command. If we are expecting error, set check=False.
2048 # Pass the assert message along since it provides more semantic info.
2049 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error)
2050
2051 # Then compare the output against expected strings.
2052 output = self.res.GetError() if error else self.res.GetOutput()
2053
2054 # If error is True, the API client expects the command to fail!
2055 if error:
2056 self.assertFalse(self.res.Succeeded(),
2057 "Command '" + str + "' is expected to fail!")
2058 else:
2059 # No execution required, just compare str against the golden input.
2060 output = str
2061 with recording(self, trace) as sbuf:
2062 print >> sbuf, "looking at:", output
2063
2064 # The heading says either "Expecting" or "Not expecting".
2065 heading = "Expecting" if matching else "Not expecting"
2066
2067 for pattern in patterns:
2068 # Match Objects always have a boolean value of True.
2069 match_object = re.search(pattern, output)
2070 matched = bool(match_object)
2071 with recording(self, trace) as sbuf:
2072 print >> sbuf, "%s pattern: %s" % (heading, pattern)
2073 print >> sbuf, "Matched" if matched else "Not matched"
2074 if matched:
2075 break
2076
2077 self.assertTrue(matched if matching else not matched,
2078 msg if msg else EXP_MSG(str, exe))
2079
2080 return match_object
2081
Enrico Granata7594f142013-06-17 22:51:50 +00002082 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 +00002083 """
2084 Similar to runCmd; with additional expect style output matching ability.
2085
2086 Ask the command interpreter to handle the command and then check its
2087 return status. The 'msg' parameter specifies an informational assert
2088 message. We expect the output from running the command to start with
Johnny Chenea88e942010-09-21 21:08:53 +00002089 'startstr', matches the substrings contained in 'substrs', and regexp
2090 matches the patterns contained in 'patterns'.
Johnny Chenb3307862010-09-17 22:28:51 +00002091
2092 If the keyword argument error is set to True, it signifies that the API
2093 client is expecting the command to fail. In this case, the error stream
Johnny Chenaa902922010-09-17 22:45:27 +00002094 from running the command is retrieved and compared against the golden
Johnny Chenb3307862010-09-17 22:28:51 +00002095 input, instead.
Johnny Chenea88e942010-09-21 21:08:53 +00002096
2097 If the keyword argument matching is set to False, it signifies that the API
2098 client is expecting the output of the command not to match the golden
2099 input.
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002100
2101 Finally, the required argument 'str' represents the lldb command to be
2102 sent to the command interpreter. In case the keyword argument 'exe' is
2103 set to False, the 'str' is treated as a string to be matched/not-matched
2104 against the golden input.
Johnny Chen27f212d2010-08-19 23:26:59 +00002105 """
Johnny Chen8d55a342010-08-31 17:42:54 +00002106 trace = (True if traceAlways else trace)
Johnny Chend0190a62010-08-23 17:10:44 +00002107
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002108 if exe:
2109 # First run the command. If we are expecting error, set check=False.
Johnny Chen62d4f862010-10-28 21:10:32 +00002110 # Pass the assert message along since it provides more semantic info.
Enrico Granata7594f142013-06-17 22:51:50 +00002111 self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error, inHistory=inHistory)
Johnny Chen27f212d2010-08-19 23:26:59 +00002112
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002113 # Then compare the output against expected strings.
2114 output = self.res.GetError() if error else self.res.GetOutput()
Johnny Chenb3307862010-09-17 22:28:51 +00002115
Johnny Chen9c48b8d2010-09-21 23:33:30 +00002116 # If error is True, the API client expects the command to fail!
2117 if error:
2118 self.assertFalse(self.res.Succeeded(),
2119 "Command '" + str + "' is expected to fail!")
2120 else:
2121 # No execution required, just compare str against the golden input.
Enrico Granatabc08ab42012-10-23 00:09:02 +00002122 if isinstance(str,lldb.SBCommandReturnObject):
2123 output = str.GetOutput()
2124 else:
2125 output = str
Johnny Chen150c3cc2010-10-15 01:18:29 +00002126 with recording(self, trace) as sbuf:
2127 print >> sbuf, "looking at:", output
Johnny Chenb3307862010-09-17 22:28:51 +00002128
Johnny Chenea88e942010-09-21 21:08:53 +00002129 # The heading says either "Expecting" or "Not expecting".
Johnny Chen150c3cc2010-10-15 01:18:29 +00002130 heading = "Expecting" if matching else "Not expecting"
Johnny Chenea88e942010-09-21 21:08:53 +00002131
2132 # Start from the startstr, if specified.
2133 # If there's no startstr, set the initial state appropriately.
2134 matched = output.startswith(startstr) if startstr else (True if matching else False)
Johnny Chenb145bba2010-08-20 18:25:15 +00002135
Johnny Chen150c3cc2010-10-15 01:18:29 +00002136 if startstr:
2137 with recording(self, trace) as sbuf:
2138 print >> sbuf, "%s start string: %s" % (heading, startstr)
2139 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenb145bba2010-08-20 18:25:15 +00002140
Johnny Chen86268e42011-09-30 21:48:35 +00002141 # Look for endstr, if specified.
2142 keepgoing = matched if matching else not matched
2143 if endstr:
2144 matched = output.endswith(endstr)
2145 with recording(self, trace) as sbuf:
2146 print >> sbuf, "%s end string: %s" % (heading, endstr)
2147 print >> sbuf, "Matched" if matched else "Not matched"
2148
Johnny Chenea88e942010-09-21 21:08:53 +00002149 # Look for sub strings, if specified.
2150 keepgoing = matched if matching else not matched
2151 if substrs and keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00002152 for str in substrs:
Johnny Chenb052f6c2010-09-23 23:35:28 +00002153 matched = output.find(str) != -1
Johnny Chen150c3cc2010-10-15 01:18:29 +00002154 with recording(self, trace) as sbuf:
2155 print >> sbuf, "%s sub string: %s" % (heading, str)
2156 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenea88e942010-09-21 21:08:53 +00002157 keepgoing = matched if matching else not matched
2158 if not keepgoing:
Johnny Chen27f212d2010-08-19 23:26:59 +00002159 break
2160
Johnny Chenea88e942010-09-21 21:08:53 +00002161 # Search for regular expression patterns, if specified.
2162 keepgoing = matched if matching else not matched
2163 if patterns and keepgoing:
2164 for pattern in patterns:
2165 # Match Objects always have a boolean value of True.
2166 matched = bool(re.search(pattern, output))
Johnny Chen150c3cc2010-10-15 01:18:29 +00002167 with recording(self, trace) as sbuf:
2168 print >> sbuf, "%s pattern: %s" % (heading, pattern)
2169 print >> sbuf, "Matched" if matched else "Not matched"
Johnny Chenea88e942010-09-21 21:08:53 +00002170 keepgoing = matched if matching else not matched
2171 if not keepgoing:
2172 break
Johnny Chenea88e942010-09-21 21:08:53 +00002173
2174 self.assertTrue(matched if matching else not matched,
Johnny Chenc0c67f22010-11-09 18:42:22 +00002175 msg if msg else EXP_MSG(str, exe))
Johnny Chen27f212d2010-08-19 23:26:59 +00002176
Johnny Chenf3c59232010-08-25 22:52:45 +00002177 def invoke(self, obj, name, trace=False):
Johnny Chen61703c92010-08-25 22:56:10 +00002178 """Use reflection to call a method dynamically with no argument."""
Johnny Chen8d55a342010-08-31 17:42:54 +00002179 trace = (True if traceAlways else trace)
Johnny Chenf3c59232010-08-25 22:52:45 +00002180
2181 method = getattr(obj, name)
2182 import inspect
2183 self.assertTrue(inspect.ismethod(method),
2184 name + "is a method name of object: " + str(obj))
2185 result = method()
Johnny Chen150c3cc2010-10-15 01:18:29 +00002186 with recording(self, trace) as sbuf:
2187 print >> sbuf, str(method) + ":", result
Johnny Chenf3c59232010-08-25 22:52:45 +00002188 return result
Johnny Chen827edff2010-08-27 00:15:48 +00002189
Johnny Chenf359cf22011-05-27 23:36:52 +00002190 # =================================================
2191 # Misc. helper methods for debugging test execution
2192 # =================================================
2193
Johnny Chen56b92a72011-07-11 19:15:11 +00002194 def DebugSBValue(self, val):
Johnny Chen8d55a342010-08-31 17:42:54 +00002195 """Debug print a SBValue object, if traceAlways is True."""
Johnny Chende90f1d2011-04-27 17:43:07 +00002196 from lldbutil import value_type_to_str
Johnny Chen87bb5892010-11-03 21:37:58 +00002197
Johnny Chen8d55a342010-08-31 17:42:54 +00002198 if not traceAlways:
Johnny Chen827edff2010-08-27 00:15:48 +00002199 return
2200
2201 err = sys.stderr
2202 err.write(val.GetName() + ":\n")
Johnny Chen86268e42011-09-30 21:48:35 +00002203 err.write('\t' + "TypeName -> " + val.GetTypeName() + '\n')
2204 err.write('\t' + "ByteSize -> " + str(val.GetByteSize()) + '\n')
2205 err.write('\t' + "NumChildren -> " + str(val.GetNumChildren()) + '\n')
2206 err.write('\t' + "Value -> " + str(val.GetValue()) + '\n')
2207 err.write('\t' + "ValueAsUnsigned -> " + str(val.GetValueAsUnsigned())+ '\n')
2208 err.write('\t' + "ValueType -> " + value_type_to_str(val.GetValueType()) + '\n')
2209 err.write('\t' + "Summary -> " + str(val.GetSummary()) + '\n')
2210 err.write('\t' + "IsPointerType -> " + str(val.TypeIsPointerType()) + '\n')
2211 err.write('\t' + "Location -> " + val.GetLocation() + '\n')
Johnny Chen827edff2010-08-27 00:15:48 +00002212
Johnny Chen36c5eb12011-08-05 20:17:27 +00002213 def DebugSBType(self, type):
2214 """Debug print a SBType object, if traceAlways is True."""
2215 if not traceAlways:
2216 return
2217
2218 err = sys.stderr
2219 err.write(type.GetName() + ":\n")
2220 err.write('\t' + "ByteSize -> " + str(type.GetByteSize()) + '\n')
2221 err.write('\t' + "IsPointerType -> " + str(type.IsPointerType()) + '\n')
2222 err.write('\t' + "IsReferenceType -> " + str(type.IsReferenceType()) + '\n')
2223
Johnny Chenb877f1e2011-03-12 01:18:19 +00002224 def DebugPExpect(self, child):
2225 """Debug the spwaned pexpect object."""
2226 if not traceAlways:
2227 return
2228
2229 print child
Filipe Cabecinhas0eec15a2012-06-20 10:13:40 +00002230
2231 @classmethod
2232 def RemoveTempFile(cls, file):
2233 if os.path.exists(file):
2234 os.remove(file)