runxpcshelltests.py 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499
  1. #!/usr/bin/env python
  2. #
  3. # This Source Code Form is subject to the terms of the Mozilla Public
  4. # License, v. 2.0. If a copy of the MPL was not distributed with this
  5. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. import copy
  7. import importlib
  8. import json
  9. import math
  10. import mozdebug
  11. import mozinfo
  12. import os
  13. import os.path
  14. import random
  15. import re
  16. import shutil
  17. import signal
  18. import subprocess
  19. import sys
  20. import tempfile
  21. import time
  22. import traceback
  23. from collections import deque, namedtuple
  24. from distutils import dir_util
  25. from distutils.version import LooseVersion
  26. from multiprocessing import cpu_count
  27. from argparse import ArgumentParser
  28. from subprocess import Popen, PIPE, STDOUT
  29. from tempfile import mkdtemp, gettempdir
  30. from threading import (
  31. Timer,
  32. Thread,
  33. Event,
  34. current_thread,
  35. )
  36. try:
  37. import psutil
  38. HAVE_PSUTIL = True
  39. except Exception:
  40. HAVE_PSUTIL = False
  41. from automation import Automation
  42. from xpcshellcommandline import parser_desktop
  43. SCRIPT_DIR = os.path.abspath(os.path.realpath(os.path.dirname(__file__)))
  44. HARNESS_TIMEOUT = 5 * 60
  45. # benchmarking on tbpl revealed that this works best for now
  46. NUM_THREADS = int(cpu_count() * 4)
  47. EXPECTED_LOG_ACTIONS = set([
  48. "test_status",
  49. "log",
  50. ])
  51. # --------------------------------------------------------------
  52. # TODO: this is a hack for mozbase without virtualenv, remove with bug 849900
  53. #
  54. here = os.path.dirname(__file__)
  55. mozbase = os.path.realpath(os.path.join(os.path.dirname(here), 'mozbase'))
  56. if os.path.isdir(mozbase):
  57. for package in os.listdir(mozbase):
  58. sys.path.append(os.path.join(mozbase, package))
  59. from manifestparser import TestManifest
  60. from manifestparser.filters import chunk_by_slice, tags, pathprefix
  61. from mozlog import commandline
  62. import mozcrash
  63. import mozinfo
  64. from mozrunner.utils import get_stack_fixer_function
  65. # --------------------------------------------------------------
  66. # TODO: perhaps this should be in a more generally shared location?
  67. # This regex matches all of the C0 and C1 control characters
  68. # (U+0000 through U+001F; U+007F; U+0080 through U+009F),
  69. # except TAB (U+0009), CR (U+000D), LF (U+000A) and backslash (U+005C).
  70. # A raw string is deliberately not used.
  71. _cleanup_encoding_re = re.compile(u'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\\\\]')
  72. def _cleanup_encoding_repl(m):
  73. c = m.group(0)
  74. return '\\\\' if c == '\\' else '\\x{0:02X}'.format(ord(c))
  75. def cleanup_encoding(s):
  76. """S is either a byte or unicode string. Either way it may
  77. contain control characters, unpaired surrogates, reserved code
  78. points, etc. If it is a byte string, it is assumed to be
  79. UTF-8, but it may not be *correct* UTF-8. Return a
  80. sanitized unicode object."""
  81. if not isinstance(s, basestring):
  82. return unicode(s)
  83. if not isinstance(s, unicode):
  84. s = s.decode('utf-8', 'replace')
  85. # Replace all C0 and C1 control characters with \xNN escapes.
  86. return _cleanup_encoding_re.sub(_cleanup_encoding_repl, s)
  87. """ Control-C handling """
  88. gotSIGINT = False
  89. def markGotSIGINT(signum, stackFrame):
  90. global gotSIGINT
  91. gotSIGINT = True
  92. class XPCShellTestThread(Thread):
  93. def __init__(self, test_object, event, cleanup_dir_list, retry=True,
  94. app_dir_key=None, interactive=False,
  95. verbose=False, pStdout=None, pStderr=None, keep_going=False,
  96. log=None, usingTSan=False, **kwargs):
  97. Thread.__init__(self)
  98. self.daemon = True
  99. self.test_object = test_object
  100. self.cleanup_dir_list = cleanup_dir_list
  101. self.retry = retry
  102. self.appPath = kwargs.get('appPath')
  103. self.xrePath = kwargs.get('xrePath')
  104. self.testingModulesDir = kwargs.get('testingModulesDir')
  105. self.debuggerInfo = kwargs.get('debuggerInfo')
  106. self.jsDebuggerInfo = kwargs.get('jsDebuggerInfo')
  107. self.pluginsPath = kwargs.get('pluginsPath')
  108. self.httpdManifest = kwargs.get('httpdManifest')
  109. self.httpdJSPath = kwargs.get('httpdJSPath')
  110. self.headJSPath = kwargs.get('headJSPath')
  111. self.testharnessdir = kwargs.get('testharnessdir')
  112. self.profileName = kwargs.get('profileName')
  113. self.singleFile = kwargs.get('singleFile')
  114. self.env = copy.deepcopy(kwargs.get('env'))
  115. self.symbolsPath = kwargs.get('symbolsPath')
  116. self.logfiles = kwargs.get('logfiles')
  117. self.xpcshell = kwargs.get('xpcshell')
  118. self.xpcsRunArgs = kwargs.get('xpcsRunArgs')
  119. self.failureManifest = kwargs.get('failureManifest')
  120. self.jscovdir = kwargs.get('jscovdir')
  121. self.stack_fixer_function = kwargs.get('stack_fixer_function')
  122. self._rootTempDir = kwargs.get('tempDir')
  123. self.app_dir_key = app_dir_key
  124. self.interactive = interactive
  125. self.verbose = verbose
  126. self.pStdout = pStdout
  127. self.pStderr = pStderr
  128. self.keep_going = keep_going
  129. self.log = log
  130. self.usingTSan = usingTSan
  131. # only one of these will be set to 1. adding them to the totals in
  132. # the harness
  133. self.passCount = 0
  134. self.todoCount = 0
  135. self.failCount = 0
  136. # Context for output processing
  137. self.output_lines = []
  138. self.has_failure_output = False
  139. self.saw_proc_start = False
  140. self.saw_proc_end = False
  141. self.complete_command = None
  142. self.harness_timeout = kwargs.get('harness_timeout')
  143. self.timedout = False
  144. # event from main thread to signal work done
  145. self.event = event
  146. self.done = False # explicitly set flag so we don't rely on thread.isAlive
  147. def run(self):
  148. try:
  149. self.run_test()
  150. except Exception as e:
  151. self.exception = e
  152. self.traceback = traceback.format_exc()
  153. else:
  154. self.exception = None
  155. self.traceback = None
  156. if self.retry:
  157. self.log.info("%s failed or timed out, will retry." %
  158. self.test_object['id'])
  159. self.done = True
  160. self.event.set()
  161. def kill(self, proc):
  162. """
  163. Simple wrapper to kill a process.
  164. On a remote system, this is overloaded to handle remote process communication.
  165. """
  166. return proc.kill()
  167. def removeDir(self, dirname):
  168. """
  169. Simple wrapper to remove (recursively) a given directory.
  170. On a remote system, we need to overload this to work on the remote filesystem.
  171. """
  172. shutil.rmtree(dirname)
  173. def poll(self, proc):
  174. """
  175. Simple wrapper to check if a process has terminated.
  176. On a remote system, this is overloaded to handle remote process communication.
  177. """
  178. return proc.poll()
  179. def createLogFile(self, test_file, stdout):
  180. """
  181. For a given test file and stdout buffer, create a log file.
  182. On a remote system we have to fix the test name since it can contain directories.
  183. """
  184. with open(test_file + ".log", "w") as f:
  185. f.write(stdout)
  186. def getReturnCode(self, proc):
  187. """
  188. Simple wrapper to get the return code for a given process.
  189. On a remote system we overload this to work with the remote process management.
  190. """
  191. return proc.returncode
  192. def communicate(self, proc):
  193. """
  194. Simple wrapper to communicate with a process.
  195. On a remote system, this is overloaded to handle remote process communication.
  196. """
  197. # Processing of incremental output put here to
  198. # sidestep issues on remote platforms, where what we know
  199. # as proc is a file pulled off of a device.
  200. if proc.stdout:
  201. while True:
  202. line = proc.stdout.readline()
  203. if not line:
  204. break
  205. self.process_line(line)
  206. if self.saw_proc_start and not self.saw_proc_end:
  207. self.has_failure_output = True
  208. return proc.communicate()
  209. def launchProcess(self, cmd, stdout, stderr, env, cwd, timeout=None):
  210. """
  211. Simple wrapper to launch a process.
  212. On a remote system, this is more complex and we need to overload this function.
  213. """
  214. # timeout is needed by remote xpcshell to extend the
  215. # devicemanager.shell() timeout. It is not used in this function.
  216. if HAVE_PSUTIL:
  217. popen_func = psutil.Popen
  218. else:
  219. popen_func = Popen
  220. proc = popen_func(cmd, stdout=stdout, stderr=stderr,
  221. env=env, cwd=cwd)
  222. return proc
  223. def checkForCrashes(self,
  224. dump_directory,
  225. symbols_path,
  226. test_name=None):
  227. """
  228. Simple wrapper to check for crashes.
  229. On a remote system, this is more complex and we need to overload this function.
  230. """
  231. return mozcrash.check_for_crashes(dump_directory, symbols_path, test_name=test_name)
  232. def logCommand(self, name, completeCmd, testdir):
  233. self.log.info("%s | full command: %r" % (name, completeCmd))
  234. self.log.info("%s | current directory: %r" % (name, testdir))
  235. # Show only those environment variables that are changed from
  236. # the ambient environment.
  237. changedEnv = (set("%s=%s" % i for i in self.env.iteritems())
  238. - set("%s=%s" % i for i in os.environ.iteritems()))
  239. self.log.info("%s | environment: %s" % (name, list(changedEnv)))
  240. def killTimeout(self, proc):
  241. Automation().killAndGetStackNoScreenshot(proc.pid,
  242. self.appPath,
  243. self.debuggerInfo)
  244. def postCheck(self, proc):
  245. """Checks for a still-running test process, kills it and fails the test if found.
  246. We can sometimes get here before the process has terminated, which would
  247. cause removeDir() to fail - so check for the process and kill it if needed.
  248. """
  249. if proc and self.poll(proc) is None:
  250. self.kill(proc)
  251. message = "%s | Process still running after test!" % self.test_object['id']
  252. if self.retry:
  253. self.log.info(message)
  254. return
  255. self.log.error(message)
  256. self.log_full_output()
  257. self.failCount = 1
  258. def testTimeout(self, proc):
  259. if self.test_object['expected'] == 'pass':
  260. expected = 'PASS'
  261. else:
  262. expected = 'FAIL'
  263. if self.retry:
  264. self.log.test_end(self.test_object['id'], 'TIMEOUT',
  265. expected='TIMEOUT',
  266. message="Test timed out")
  267. else:
  268. self.failCount = 1
  269. self.log.test_end(self.test_object['id'], 'TIMEOUT',
  270. expected=expected,
  271. message="Test timed out")
  272. self.log_full_output()
  273. self.done = True
  274. self.timedout = True
  275. self.killTimeout(proc)
  276. self.log.info("xpcshell return code: %s" % self.getReturnCode(proc))
  277. self.postCheck(proc)
  278. self.clean_temp_dirs(self.test_object['path'])
  279. def buildCmdTestFile(self, name):
  280. """
  281. Build the command line arguments for the test file.
  282. On a remote system, this may be overloaded to use a remote path structure.
  283. """
  284. return ['-e', 'const _TEST_FILE = ["%s"];' %
  285. name.replace('\\', '/')]
  286. def setupTempDir(self):
  287. tempDir = mkdtemp(prefix='xpc-other-', dir=self._rootTempDir)
  288. self.env["XPCSHELL_TEST_TEMP_DIR"] = tempDir
  289. if self.interactive:
  290. self.log.info("temp dir is %s" % tempDir)
  291. return tempDir
  292. def setupPluginsDir(self):
  293. if not os.path.isdir(self.pluginsPath):
  294. return None
  295. pluginsDir = mkdtemp(prefix='xpc-plugins-', dir=self._rootTempDir)
  296. # shutil.copytree requires dst to not exist. Deleting the tempdir
  297. # would make a race condition possible in a concurrent environment,
  298. # so we are using dir_utils.copy_tree which accepts an existing dst
  299. dir_util.copy_tree(self.pluginsPath, pluginsDir)
  300. if self.interactive:
  301. self.log.info("plugins dir is %s" % pluginsDir)
  302. return pluginsDir
  303. def setupProfileDir(self):
  304. """
  305. Create a temporary folder for the profile and set appropriate environment variables.
  306. When running check-interactive and check-one, the directory is well-defined and
  307. retained for inspection once the tests complete.
  308. On a remote system, this may be overloaded to use a remote path structure.
  309. """
  310. if self.interactive or self.singleFile:
  311. profileDir = os.path.join(gettempdir(), self.profileName, "xpcshellprofile")
  312. try:
  313. # This could be left over from previous runs
  314. self.removeDir(profileDir)
  315. except:
  316. pass
  317. os.makedirs(profileDir)
  318. else:
  319. profileDir = mkdtemp(prefix='xpc-profile-', dir=self._rootTempDir)
  320. self.env["XPCSHELL_TEST_PROFILE_DIR"] = profileDir
  321. if self.interactive or self.singleFile:
  322. self.log.info("profile dir is %s" % profileDir)
  323. return profileDir
  324. def setupMozinfoJS(self):
  325. mozInfoJSPath = os.path.join(self.profileDir, 'mozinfo.json')
  326. mozInfoJSPath = mozInfoJSPath.replace('\\', '\\\\')
  327. mozinfo.output_to_file(mozInfoJSPath)
  328. return mozInfoJSPath
  329. def buildCmdHead(self, headfiles, tailfiles, xpcscmd):
  330. """
  331. Build the command line arguments for the head and tail files,
  332. along with the address of the webserver which some tests require.
  333. On a remote system, this is overloaded to resolve quoting issues over a secondary command line.
  334. """
  335. cmdH = ", ".join(['"' + f.replace('\\', '/') + '"'
  336. for f in headfiles])
  337. cmdT = ", ".join(['"' + f.replace('\\', '/') + '"'
  338. for f in tailfiles])
  339. dbgport = 0 if self.jsDebuggerInfo is None else self.jsDebuggerInfo.port
  340. return xpcscmd + \
  341. ['-e', 'const _SERVER_ADDR = "localhost"',
  342. '-e', 'const _HEAD_FILES = [%s];' % cmdH,
  343. '-e', 'const _TAIL_FILES = [%s];' % cmdT,
  344. '-e', 'const _JSDEBUGGER_PORT = %d;' % dbgport,
  345. ]
  346. def getHeadAndTailFiles(self, test):
  347. """Obtain lists of head- and tail files. Returns a tuple
  348. containing a list of head files and a list of tail files.
  349. """
  350. def sanitize_list(s, kind):
  351. for f in s.strip().split(' '):
  352. f = f.strip()
  353. if len(f) < 1:
  354. continue
  355. path = os.path.normpath(os.path.join(test['here'], f))
  356. if not os.path.exists(path):
  357. raise Exception('%s file does not exist: %s' % (kind, path))
  358. if not os.path.isfile(path):
  359. raise Exception('%s file is not a file: %s' % (kind, path))
  360. yield path
  361. headlist = test.get('head', '')
  362. taillist = test.get('tail', '')
  363. return (list(sanitize_list(headlist, 'head')),
  364. list(sanitize_list(taillist, 'tail')))
  365. def buildXpcsCmd(self):
  366. """
  367. Load the root head.js file as the first file in our test path, before other head, test, and tail files.
  368. On a remote system, we overload this to add additional command line arguments, so this gets overloaded.
  369. """
  370. # - NOTE: if you rename/add any of the constants set here, update
  371. # do_load_child_test_harness() in head.js
  372. if not self.appPath:
  373. self.appPath = self.xrePath
  374. self.xpcsCmd = [
  375. self.xpcshell,
  376. '-g', self.xrePath,
  377. '-a', self.appPath,
  378. '-r', self.httpdManifest,
  379. '-m',
  380. '-s',
  381. '-e', 'const _HEAD_JS_PATH = "%s";' % self.headJSPath,
  382. '-e', 'const _MOZINFO_JS_PATH = "%s";' % self.mozInfoJSPath,
  383. ]
  384. if self.testingModulesDir:
  385. # Escape backslashes in string literal.
  386. sanitized = self.testingModulesDir.replace('\\', '\\\\')
  387. self.xpcsCmd.extend([
  388. '-e',
  389. 'const _TESTING_MODULES_DIR = "%s";' % sanitized
  390. ])
  391. self.xpcsCmd.extend(['-f', os.path.join(self.testharnessdir, 'head.js')])
  392. if self.debuggerInfo:
  393. self.xpcsCmd = [self.debuggerInfo.path] + self.debuggerInfo.args + self.xpcsCmd
  394. # Automation doesn't specify a pluginsPath and xpcshell defaults to
  395. # $APPDIR/plugins. We do the same here so we can carry on with
  396. # setting up every test with its own plugins directory.
  397. if not self.pluginsPath:
  398. self.pluginsPath = os.path.join(self.appPath, 'plugins')
  399. self.pluginsDir = self.setupPluginsDir()
  400. if self.pluginsDir:
  401. self.xpcsCmd.extend(['-p', self.pluginsDir])
  402. def cleanupDir(self, directory, name):
  403. if not os.path.exists(directory):
  404. return
  405. TRY_LIMIT = 25 # up to TRY_LIMIT attempts (one every second), because
  406. # the Windows filesystem is slow to react to the changes
  407. try_count = 0
  408. while try_count < TRY_LIMIT:
  409. try:
  410. self.removeDir(directory)
  411. except OSError:
  412. self.log.info("Failed to remove directory: %s. Waiting." % directory)
  413. # We suspect the filesystem may still be making changes. Wait a
  414. # little bit and try again.
  415. time.sleep(1)
  416. try_count += 1
  417. else:
  418. # removed fine
  419. return
  420. # we try cleaning up again later at the end of the run
  421. self.cleanup_dir_list.append(directory)
  422. def clean_temp_dirs(self, name):
  423. # We don't want to delete the profile when running check-interactive
  424. # or check-one.
  425. if self.profileDir and not self.interactive and not self.singleFile:
  426. self.cleanupDir(self.profileDir, name)
  427. self.cleanupDir(self.tempDir, name)
  428. if self.pluginsDir:
  429. self.cleanupDir(self.pluginsDir, name)
  430. def parse_output(self, output):
  431. """Parses process output for structured messages and saves output as it is
  432. read. Sets self.has_failure_output in case of evidence of a failure"""
  433. for line_string in output.splitlines():
  434. self.process_line(line_string)
  435. if self.saw_proc_start and not self.saw_proc_end:
  436. self.has_failure_output = True
  437. def fix_text_output(self, line):
  438. line = cleanup_encoding(line)
  439. if self.stack_fixer_function is not None:
  440. return self.stack_fixer_function(line)
  441. return line
  442. def log_line(self, line):
  443. """Log a line of output (either a parser json object or text output from
  444. the test process"""
  445. if isinstance(line, basestring):
  446. line = self.fix_text_output(line).rstrip('\r\n')
  447. self.log.process_output(self.proc_ident,
  448. line,
  449. command=self.complete_command)
  450. else:
  451. if 'message' in line:
  452. line['message'] = self.fix_text_output(line['message'])
  453. if 'xpcshell_process' in line:
  454. line['thread'] = ' '.join([current_thread().name, line['xpcshell_process']])
  455. else:
  456. line['thread'] = current_thread().name
  457. self.log.log_raw(line)
  458. def log_full_output(self):
  459. """Logs any buffered output from the test process, and clears the buffer."""
  460. if not self.output_lines:
  461. return
  462. self.log.info(">>>>>>>")
  463. for line in self.output_lines:
  464. self.log_line(line)
  465. self.log.info("<<<<<<<")
  466. self.output_lines = []
  467. def report_message(self, message):
  468. """Stores or logs a json log message in mozlog format."""
  469. if self.verbose:
  470. self.log_line(message)
  471. else:
  472. self.output_lines.append(message)
  473. def process_line(self, line_string):
  474. """ Parses a single line of output, determining its significance and
  475. reporting a message.
  476. """
  477. if not line_string.strip():
  478. return
  479. try:
  480. line_object = json.loads(line_string)
  481. if not isinstance(line_object, dict):
  482. self.report_message(line_string)
  483. return
  484. except ValueError:
  485. self.report_message(line_string)
  486. return
  487. if ('action' not in line_object or
  488. line_object['action'] not in EXPECTED_LOG_ACTIONS):
  489. # The test process output JSON.
  490. self.report_message(line_string)
  491. return
  492. action = line_object['action']
  493. self.has_failure_output = (self.has_failure_output or
  494. 'expected' in line_object or
  495. action == 'log' and line_object['level'] == 'ERROR')
  496. self.report_message(line_object)
  497. if action == 'log' and line_object['message'] == 'CHILD-TEST-STARTED':
  498. self.saw_proc_start = True
  499. elif action == 'log' and line_object['message'] == 'CHILD-TEST-COMPLETED':
  500. self.saw_proc_end = True
  501. def run_test(self):
  502. """Run an individual xpcshell test."""
  503. global gotSIGINT
  504. name = self.test_object['id']
  505. path = self.test_object['path']
  506. # Check for skipped tests
  507. if 'disabled' in self.test_object:
  508. message = self.test_object['disabled']
  509. if not message:
  510. message = 'disabled from xpcshell manifest'
  511. self.log.test_start(name)
  512. self.log.test_end(name, 'SKIP', message=message)
  513. self.retry = False
  514. self.keep_going = True
  515. return
  516. # Check for known-fail tests
  517. expect_pass = self.test_object['expected'] == 'pass'
  518. # By default self.appPath will equal the gre dir. If specified in the
  519. # xpcshell.ini file, set a different app dir for this test.
  520. if self.app_dir_key and self.app_dir_key in self.test_object:
  521. rel_app_dir = self.test_object[self.app_dir_key]
  522. rel_app_dir = os.path.join(self.xrePath, rel_app_dir)
  523. self.appPath = os.path.abspath(rel_app_dir)
  524. else:
  525. self.appPath = None
  526. test_dir = os.path.dirname(path)
  527. # Create a profile and a temp dir that the JS harness can stick
  528. # a profile and temporary data in
  529. self.profileDir = self.setupProfileDir()
  530. self.tempDir = self.setupTempDir()
  531. self.mozInfoJSPath = self.setupMozinfoJS()
  532. self.buildXpcsCmd()
  533. head_files, tail_files = self.getHeadAndTailFiles(self.test_object)
  534. cmdH = self.buildCmdHead(head_files, tail_files, self.xpcsCmd)
  535. # The test file will have to be loaded after the head files.
  536. cmdT = self.buildCmdTestFile(path)
  537. args = self.xpcsRunArgs[:]
  538. if 'debug' in self.test_object:
  539. args.insert(0, '-d')
  540. # The test name to log
  541. cmdI = ['-e', 'const _TEST_NAME = "%s"' % name]
  542. # Directory for javascript code coverage output, null by default.
  543. cmdC = ['-e', 'const _JSCOV_DIR = null']
  544. if self.jscovdir:
  545. cmdC = ['-e', 'const _JSCOV_DIR = "%s"' % self.jscovdir.replace('\\', '/')]
  546. self.complete_command = cmdH + cmdT + cmdI + cmdC + args
  547. else:
  548. self.complete_command = cmdH + cmdT + cmdI + args
  549. if self.test_object.get('dmd') == 'true':
  550. if sys.platform.startswith('linux'):
  551. preloadEnvVar = 'LD_PRELOAD'
  552. libdmd = os.path.join(self.xrePath, 'libdmd.so')
  553. elif sys.platform == 'osx' or sys.platform == 'darwin':
  554. preloadEnvVar = 'DYLD_INSERT_LIBRARIES'
  555. # self.xrePath is <prefix>/Contents/Resources.
  556. # We need <prefix>/Contents/MacOS/libdmd.dylib.
  557. contents_dir = os.path.dirname(self.xrePath)
  558. libdmd = os.path.join(contents_dir, 'MacOS', 'libdmd.dylib')
  559. elif sys.platform == 'win32':
  560. preloadEnvVar = 'MOZ_REPLACE_MALLOC_LIB'
  561. libdmd = os.path.join(self.xrePath, 'dmd.dll')
  562. self.env['PYTHON'] = sys.executable
  563. self.env['BREAKPAD_SYMBOLS_PATH'] = self.symbolsPath
  564. self.env['DMD_PRELOAD_VAR'] = preloadEnvVar
  565. self.env['DMD_PRELOAD_VALUE'] = libdmd
  566. if self.test_object.get('subprocess') == 'true':
  567. self.env['PYTHON'] = sys.executable
  568. testTimeoutInterval = self.harness_timeout
  569. # Allow a test to request a multiple of the timeout if it is expected to take long
  570. if 'requesttimeoutfactor' in self.test_object:
  571. testTimeoutInterval *= int(self.test_object['requesttimeoutfactor'])
  572. testTimer = None
  573. if not self.interactive and not self.debuggerInfo and not self.jsDebuggerInfo:
  574. testTimer = Timer(testTimeoutInterval, lambda: self.testTimeout(proc))
  575. testTimer.start()
  576. proc = None
  577. process_output = None
  578. try:
  579. self.log.test_start(name)
  580. if self.verbose:
  581. self.logCommand(name, self.complete_command, test_dir)
  582. proc = self.launchProcess(self.complete_command,
  583. stdout=self.pStdout, stderr=self.pStderr, env=self.env, cwd=test_dir, timeout=testTimeoutInterval)
  584. if hasattr(proc, "pid"):
  585. self.proc_ident = proc.pid
  586. else:
  587. # On mobile, "proc" is just a file.
  588. self.proc_ident = name
  589. if self.interactive:
  590. self.log.info("%s | Process ID: %d" % (name, self.proc_ident))
  591. # Communicate returns a tuple of (stdout, stderr), however we always
  592. # redirect stderr to stdout, so the second element is ignored.
  593. process_output, _ = self.communicate(proc)
  594. if self.interactive:
  595. # Not sure what else to do here...
  596. self.keep_going = True
  597. return
  598. if testTimer:
  599. testTimer.cancel()
  600. if process_output:
  601. # For the remote case, stdout is not yet depleted, so we parse
  602. # it here all at once.
  603. self.parse_output(process_output)
  604. return_code = self.getReturnCode(proc)
  605. # TSan'd processes return 66 if races are detected. This isn't
  606. # good in the sense that there's no way to distinguish between
  607. # a process that would normally have returned zero but has races,
  608. # and a race-free process that returns 66. But I don't see how
  609. # to do better. This ambiguity is at least constrained to the
  610. # with-TSan case. It doesn't affect normal builds.
  611. #
  612. # This also assumes that the magic value 66 isn't overridden by
  613. # a TSAN_OPTIONS=exitcode=<number> environment variable setting.
  614. #
  615. TSAN_EXIT_CODE_WITH_RACES = 66
  616. return_code_ok = (return_code == 0 or
  617. (self.usingTSan and
  618. return_code == TSAN_EXIT_CODE_WITH_RACES))
  619. passed = (not self.has_failure_output) and return_code_ok
  620. status = 'PASS' if passed else 'FAIL'
  621. expected = 'PASS' if expect_pass else 'FAIL'
  622. message = 'xpcshell return code: %d' % return_code
  623. if self.timedout:
  624. return
  625. if status != expected:
  626. if self.retry:
  627. self.log.test_end(name, status, expected=status,
  628. message="Test failed or timed out, will retry")
  629. self.clean_temp_dirs(path)
  630. return
  631. self.log.test_end(name, status, expected=expected, message=message)
  632. self.log_full_output()
  633. self.failCount += 1
  634. if self.failureManifest:
  635. with open(self.failureManifest, 'a') as f:
  636. f.write('[%s]\n' % self.test_object['path'])
  637. for k, v in self.test_object.items():
  638. f.write('%s = %s\n' % (k, v))
  639. else:
  640. # If TSan reports a race, dump the output, else we can't
  641. # diagnose what the problem was. See comments above about
  642. # the significance of TSAN_EXIT_CODE_WITH_RACES.
  643. if self.usingTSan and return_code == TSAN_EXIT_CODE_WITH_RACES:
  644. self.log_full_output()
  645. self.log.test_end(name, status, expected=expected, message=message)
  646. if self.verbose:
  647. self.log_full_output()
  648. self.retry = False
  649. if expect_pass:
  650. self.passCount = 1
  651. else:
  652. self.todoCount = 1
  653. if self.checkForCrashes(self.tempDir, self.symbolsPath, test_name=name):
  654. if self.retry:
  655. self.clean_temp_dirs(path)
  656. return
  657. # If we assert during shutdown there's a chance the test has passed
  658. # but we haven't logged full output, so do so here.
  659. self.log_full_output()
  660. self.failCount = 1
  661. if self.logfiles and process_output:
  662. self.createLogFile(name, process_output)
  663. finally:
  664. self.postCheck(proc)
  665. self.clean_temp_dirs(path)
  666. if gotSIGINT:
  667. self.log.error("Received SIGINT (control-C) during test execution")
  668. if self.keep_going:
  669. gotSIGINT = False
  670. else:
  671. self.keep_going = False
  672. return
  673. self.keep_going = True
  674. class XPCShellTests(object):
  675. def __init__(self, log=None):
  676. """ Initializes node status and logger. """
  677. self.log = log
  678. self.harness_timeout = HARNESS_TIMEOUT
  679. self.nodeProc = {}
  680. def getTestManifest(self, manifest):
  681. if isinstance(manifest, TestManifest):
  682. return manifest
  683. elif manifest is not None:
  684. manifest = os.path.normpath(os.path.abspath(manifest))
  685. if os.path.isfile(manifest):
  686. return TestManifest([manifest], strict=True)
  687. else:
  688. ini_path = os.path.join(manifest, "xpcshell.ini")
  689. else:
  690. ini_path = os.path.join(SCRIPT_DIR, "tests", "xpcshell.ini")
  691. if os.path.exists(ini_path):
  692. return TestManifest([ini_path], strict=True)
  693. else:
  694. print >> sys.stderr, ("Failed to find manifest at %s; use --manifest "
  695. "to set path explicitly." % (ini_path,))
  696. sys.exit(1)
  697. def buildTestList(self, test_tags=None, test_paths=None):
  698. """
  699. read the xpcshell.ini manifest and set self.alltests to be
  700. an array of test objects.
  701. if we are chunking tests, it will be done here as well
  702. """
  703. if test_paths is None:
  704. test_paths = []
  705. if len(test_paths) == 1 and test_paths[0].endswith(".js"):
  706. self.singleFile = os.path.basename(test_paths[0])
  707. else:
  708. self.singleFile = None
  709. mp = self.getTestManifest(self.manifest)
  710. filters = []
  711. if test_tags:
  712. filters.append(tags(test_tags))
  713. if test_paths:
  714. filters.append(pathprefix(test_paths))
  715. if self.singleFile is None and self.totalChunks > 1:
  716. filters.append(chunk_by_slice(self.thisChunk, self.totalChunks))
  717. try:
  718. self.alltests = mp.active_tests(filters=filters, **mozinfo.info)
  719. except TypeError:
  720. sys.stderr.write("*** offending mozinfo.info: %s\n" % repr(mozinfo.info))
  721. raise
  722. if len(self.alltests) == 0:
  723. self.log.error("no tests to run using specified "
  724. "combination of filters: {}".format(
  725. mp.fmt_filters()))
  726. if self.dump_tests:
  727. self.dump_tests = os.path.expanduser(self.dump_tests)
  728. assert os.path.exists(os.path.dirname(self.dump_tests))
  729. with open(self.dump_tests, 'w') as dumpFile:
  730. dumpFile.write(json.dumps({'active_tests': self.alltests}))
  731. self.log.info("Dumping active_tests to %s file." % self.dump_tests)
  732. sys.exit()
  733. def setAbsPath(self):
  734. """
  735. Set the absolute path for xpcshell, httpdjspath and xrepath.
  736. These 3 variables depend on input from the command line and we need to allow for absolute paths.
  737. This function is overloaded for a remote solution as os.path* won't work remotely.
  738. """
  739. self.testharnessdir = os.path.dirname(os.path.abspath(__file__))
  740. self.headJSPath = self.testharnessdir.replace("\\", "/") + "/head.js"
  741. self.xpcshell = os.path.abspath(self.xpcshell)
  742. if self.xrePath is None:
  743. self.xrePath = os.path.dirname(self.xpcshell)
  744. if mozinfo.isMac:
  745. # Check if we're run from an OSX app bundle and override
  746. # self.xrePath if we are.
  747. appBundlePath = os.path.join(os.path.dirname(os.path.dirname(self.xpcshell)), 'Resources')
  748. if os.path.exists(os.path.join(appBundlePath, 'application.ini')):
  749. self.xrePath = appBundlePath
  750. else:
  751. self.xrePath = os.path.abspath(self.xrePath)
  752. # httpd.js belongs in xrePath/components, which is Contents/Resources on mac
  753. self.httpdJSPath = os.path.join(self.xrePath, 'components', 'httpd.js')
  754. self.httpdJSPath = self.httpdJSPath.replace('\\', '/')
  755. self.httpdManifest = os.path.join(self.xrePath, 'components', 'httpd.manifest')
  756. self.httpdManifest = self.httpdManifest.replace('\\', '/')
  757. if self.mozInfo is None:
  758. self.mozInfo = os.path.join(self.testharnessdir, "mozinfo.json")
  759. def buildCoreEnvironment(self):
  760. """
  761. Add environment variables likely to be used across all platforms, including remote systems.
  762. """
  763. # Make assertions fatal
  764. self.env["XPCOM_DEBUG_BREAK"] = "stack-and-abort"
  765. # Don't launch the crash reporter client
  766. self.env["MOZ_CRASHREPORTER_NO_REPORT"] = "1"
  767. # Don't permit remote connections by default.
  768. # MOZ_DISABLE_NONLOCAL_CONNECTIONS can be set to "0" to temporarily
  769. # enable non-local connections for the purposes of local testing.
  770. # Don't override the user's choice here. See bug 1049688.
  771. self.env.setdefault('MOZ_DISABLE_NONLOCAL_CONNECTIONS', '1')
  772. def buildEnvironment(self):
  773. """
  774. Create and returns a dictionary of self.env to include all the appropriate env variables and values.
  775. On a remote system, we overload this to set different values and are missing things like os.environ and PATH.
  776. """
  777. self.env = dict(os.environ)
  778. self.buildCoreEnvironment()
  779. if sys.platform == 'win32':
  780. self.env["PATH"] = self.env["PATH"] + ";" + self.xrePath
  781. elif sys.platform in ('os2emx', 'os2knix'):
  782. os.environ["BEGINLIBPATH"] = self.xrePath + ";" + self.env["BEGINLIBPATH"]
  783. os.environ["LIBPATHSTRICT"] = "T"
  784. elif sys.platform == 'osx' or sys.platform == "darwin":
  785. self.env["DYLD_LIBRARY_PATH"] = os.path.join(os.path.dirname(self.xrePath), 'MacOS')
  786. else: # unix or linux?
  787. if not "LD_LIBRARY_PATH" in self.env or self.env["LD_LIBRARY_PATH"] is None:
  788. self.env["LD_LIBRARY_PATH"] = self.xrePath
  789. else:
  790. self.env["LD_LIBRARY_PATH"] = ":".join([self.xrePath, self.env["LD_LIBRARY_PATH"]])
  791. usingASan = "asan" in self.mozInfo and self.mozInfo["asan"]
  792. usingTSan = "tsan" in self.mozInfo and self.mozInfo["tsan"]
  793. if usingASan or usingTSan:
  794. # symbolizer support
  795. llvmsym = os.path.join(self.xrePath, "llvm-symbolizer")
  796. if os.path.isfile(llvmsym):
  797. if usingASan:
  798. self.env["ASAN_SYMBOLIZER_PATH"] = llvmsym
  799. else:
  800. oldTSanOptions = self.env.get("TSAN_OPTIONS", "")
  801. self.env["TSAN_OPTIONS"] = "external_symbolizer_path={} {}".format(llvmsym, oldTSanOptions)
  802. self.log.info("runxpcshelltests.py | using symbolizer at %s" % llvmsym)
  803. else:
  804. self.log.error("TEST-UNEXPECTED-FAIL | runxpcshelltests.py | Failed to find symbolizer at %s" % llvmsym)
  805. return self.env
  806. def getPipes(self):
  807. """
  808. Determine the value of the stdout and stderr for the test.
  809. Return value is a list (pStdout, pStderr).
  810. """
  811. if self.interactive:
  812. pStdout = None
  813. pStderr = None
  814. else:
  815. if (self.debuggerInfo and self.debuggerInfo.interactive):
  816. pStdout = None
  817. pStderr = None
  818. else:
  819. if sys.platform == 'os2emx':
  820. pStdout = None
  821. else:
  822. pStdout = PIPE
  823. pStderr = STDOUT
  824. return pStdout, pStderr
  825. def verifyDirPath(self, dirname):
  826. """
  827. Simple wrapper to get the absolute path for a given directory name.
  828. On a remote system, we need to overload this to work on the remote filesystem.
  829. """
  830. return os.path.abspath(dirname)
  831. def trySetupNode(self):
  832. """
  833. Run node for HTTP/2 tests, if available, and updates mozinfo as appropriate.
  834. """
  835. nodeMozInfo = {'hasNode': False} # Assume the worst
  836. nodeBin = None
  837. # We try to find the node executable in the path given to us by the user in
  838. # the MOZ_NODE_PATH environment variable
  839. localPath = os.getenv('MOZ_NODE_PATH', None)
  840. if localPath and os.path.exists(localPath) and os.path.isfile(localPath):
  841. try:
  842. version_str = subprocess.check_output([localPath, "--version"],
  843. stderr=subprocess.STDOUT)
  844. # nodejs prefixes its version strings with "v"
  845. version = LooseVersion(version_str.lstrip('v'))
  846. # Use node only if node version is >=5.0.0 because
  847. # node did not support ALPN until this version.
  848. if version >= LooseVersion("5.0.0"):
  849. nodeBin = localPath
  850. except (subprocess.CalledProcessError, OSError), e:
  851. self.log.error('Could not retrieve node version: %s' % str(e))
  852. if os.getenv('MOZ_ASSUME_NODE_RUNNING', None):
  853. self.log.info('Assuming required node servers are already running')
  854. nodeMozInfo['hasNode'] = True
  855. elif nodeBin:
  856. self.log.info('Found node at %s' % (nodeBin,))
  857. def startServer(name, serverJs):
  858. if os.path.exists(serverJs):
  859. # OK, we found our server, let's try to get it running
  860. self.log.info('Found %s at %s' % (name, serverJs))
  861. try:
  862. # We pipe stdin to node because the server will exit when its
  863. # stdin reaches EOF
  864. process = Popen([nodeBin, serverJs], stdin=PIPE, stdout=PIPE,
  865. stderr=PIPE, env=self.env, cwd=os.getcwd())
  866. self.nodeProc[name] = process
  867. # Check to make sure the server starts properly by waiting for it to
  868. # tell us it's started
  869. msg = process.stdout.readline()
  870. if 'server listening' in msg:
  871. nodeMozInfo['hasNode'] = True
  872. searchObj = re.search( r'HTTP2 server listening on port (.*)', msg, 0)
  873. if searchObj:
  874. self.env["MOZHTTP2_PORT"] = searchObj.group(1)
  875. except OSError, e:
  876. # This occurs if the subprocess couldn't be started
  877. self.log.error('Could not run %s server: %s' % (name, str(e)))
  878. myDir = os.path.split(os.path.abspath(__file__))[0]
  879. startServer('moz-http2', os.path.join(myDir, 'moz-http2', 'moz-http2.js'))
  880. mozinfo.update(nodeMozInfo)
  881. def shutdownNode(self):
  882. """
  883. Shut down our node process, if it exists
  884. """
  885. for name, proc in self.nodeProc.iteritems():
  886. self.log.info('Node %s server shutting down ...' % name)
  887. if proc.poll() is not None:
  888. self.log.info('Node server %s already dead %s' % (name, proc.poll()))
  889. else:
  890. proc.terminate()
  891. def dumpOutput(fd, label):
  892. firstTime = True
  893. for msg in fd:
  894. if firstTime:
  895. firstTime = False;
  896. self.log.info('Process %s' % label)
  897. self.log.info(msg)
  898. dumpOutput(proc.stdout, "stdout")
  899. dumpOutput(proc.stderr, "stderr")
  900. def buildXpcsRunArgs(self):
  901. """
  902. Add arguments to run the test or make it interactive.
  903. """
  904. if self.interactive:
  905. self.xpcsRunArgs = [
  906. '-e', 'print("To start the test, type |_execute_test();|.");',
  907. '-i']
  908. else:
  909. self.xpcsRunArgs = ['-e', '_execute_test(); quit(0);']
  910. def addTestResults(self, test):
  911. self.passCount += test.passCount
  912. self.failCount += test.failCount
  913. self.todoCount += test.todoCount
  914. def makeTestId(self, test_object):
  915. """Calculate an identifier for a test based on its path or a combination of
  916. its path and the source manifest."""
  917. relpath_key = 'file_relpath' if 'file_relpath' in test_object else 'relpath'
  918. path = test_object[relpath_key].replace('\\', '/');
  919. if 'dupe-manifest' in test_object and 'ancestor-manifest' in test_object:
  920. return '%s:%s' % (os.path.basename(test_object['ancestor-manifest']), path)
  921. return path
  922. def runTests(self, xpcshell=None, xrePath=None, appPath=None, symbolsPath=None,
  923. manifest=None, testPaths=None, mobileArgs=None, tempDir=None,
  924. interactive=False, verbose=False, keepGoing=False, logfiles=True,
  925. thisChunk=1, totalChunks=1, debugger=None,
  926. debuggerArgs=None, debuggerInteractive=False,
  927. profileName=None, mozInfo=None, sequential=False, shuffle=False,
  928. testingModulesDir=None, pluginsPath=None,
  929. testClass=XPCShellTestThread, failureManifest=None,
  930. log=None, stream=None, jsDebugger=False, jsDebuggerPort=0,
  931. test_tags=None, dump_tests=None, utility_path=None,
  932. rerun_failures=False, failure_manifest=None, jscovdir=None, **otherOptions):
  933. """Run xpcshell tests.
  934. |xpcshell|, is the xpcshell executable to use to run the tests.
  935. |xrePath|, if provided, is the path to the XRE to use.
  936. |appPath|, if provided, is the path to an application directory.
  937. |symbolsPath|, if provided is the path to a directory containing
  938. breakpad symbols for processing crashes in tests.
  939. |manifest|, if provided, is a file containing a list of
  940. test directories to run.
  941. |testPaths|, if provided, is a list of paths to files or directories containing
  942. tests to run.
  943. |pluginsPath|, if provided, custom plugins directory to be returned from
  944. the xpcshell dir svc provider for NS_APP_PLUGINS_DIR_LIST.
  945. |interactive|, if set to True, indicates to provide an xpcshell prompt
  946. instead of automatically executing the test.
  947. |verbose|, if set to True, will cause stdout/stderr from tests to
  948. be printed always
  949. |logfiles|, if set to False, indicates not to save output to log files.
  950. Non-interactive only option.
  951. |debugger|, if set, specifies the name of the debugger that will be used
  952. to launch xpcshell.
  953. |debuggerArgs|, if set, specifies arguments to use with the debugger.
  954. |debuggerInteractive|, if set, allows the debugger to be run in interactive
  955. mode.
  956. |profileName|, if set, specifies the name of the application for the profile
  957. directory if running only a subset of tests.
  958. |mozInfo|, if set, specifies specifies build configuration information, either as a filename containing JSON, or a dict.
  959. |shuffle|, if True, execute tests in random order.
  960. |testingModulesDir|, if provided, specifies where JS modules reside.
  961. xpcshell will register a resource handler mapping this path.
  962. |tempDir|, if provided, specifies a temporary directory to use.
  963. |otherOptions| may be present for the convenience of subclasses
  964. """
  965. global gotSIGINT
  966. # Try to guess modules directory.
  967. # This somewhat grotesque hack allows the buildbot machines to find the
  968. # modules directory without having to configure the buildbot hosts. This
  969. # code path should never be executed in local runs because the build system
  970. # should always set this argument.
  971. if not testingModulesDir:
  972. possible = os.path.join(here, os.path.pardir, 'modules')
  973. if os.path.isdir(possible):
  974. testingModulesDir = possible
  975. if rerun_failures:
  976. if os.path.exists(failure_manifest):
  977. rerun_manifest = os.path.join(os.path.dirname(failure_manifest), "rerun.ini")
  978. shutil.copyfile(failure_manifest, rerun_manifest)
  979. os.remove(failure_manifest)
  980. manifest = rerun_manifest
  981. else:
  982. print >> sys.stderr, "No failures were found to re-run."
  983. sys.exit(1)
  984. if testingModulesDir:
  985. # The resource loader expects native paths. Depending on how we were
  986. # invoked, a UNIX style path may sneak in on Windows. We try to
  987. # normalize that.
  988. testingModulesDir = os.path.normpath(testingModulesDir)
  989. if not os.path.isabs(testingModulesDir):
  990. testingModulesDir = os.path.abspath(testingModulesDir)
  991. if not testingModulesDir.endswith(os.path.sep):
  992. testingModulesDir += os.path.sep
  993. self.debuggerInfo = None
  994. if debugger:
  995. self.debuggerInfo = mozdebug.get_debugger_info(debugger, debuggerArgs, debuggerInteractive)
  996. self.jsDebuggerInfo = None
  997. if jsDebugger:
  998. # A namedtuple let's us keep .port instead of ['port']
  999. JSDebuggerInfo = namedtuple('JSDebuggerInfo', ['port'])
  1000. self.jsDebuggerInfo = JSDebuggerInfo(port=jsDebuggerPort)
  1001. self.xpcshell = xpcshell
  1002. self.xrePath = xrePath
  1003. self.appPath = appPath
  1004. self.symbolsPath = symbolsPath
  1005. self.tempDir = os.path.normpath(tempDir or tempfile.gettempdir())
  1006. self.manifest = manifest
  1007. self.dump_tests = dump_tests
  1008. self.interactive = interactive
  1009. self.verbose = verbose
  1010. self.keepGoing = keepGoing
  1011. self.logfiles = logfiles
  1012. self.totalChunks = totalChunks
  1013. self.thisChunk = thisChunk
  1014. self.profileName = profileName or "xpcshell"
  1015. self.mozInfo = mozInfo
  1016. self.testingModulesDir = testingModulesDir
  1017. self.pluginsPath = pluginsPath
  1018. self.sequential = sequential
  1019. self.failure_manifest = failure_manifest
  1020. self.jscovdir = jscovdir
  1021. self.testCount = 0
  1022. self.passCount = 0
  1023. self.failCount = 0
  1024. self.todoCount = 0
  1025. self.setAbsPath()
  1026. self.buildXpcsRunArgs()
  1027. self.event = Event()
  1028. # Handle filenames in mozInfo
  1029. if not isinstance(self.mozInfo, dict):
  1030. mozInfoFile = self.mozInfo
  1031. if not os.path.isfile(mozInfoFile):
  1032. self.log.error("Error: couldn't find mozinfo.json at '%s'. Perhaps you need to use --build-info-json?" % mozInfoFile)
  1033. return False
  1034. self.mozInfo = json.load(open(mozInfoFile))
  1035. # mozinfo.info is used as kwargs. Some builds are done with
  1036. # an older Python that can't handle Unicode keys in kwargs.
  1037. # All of the keys in question should be ASCII.
  1038. fixedInfo = {}
  1039. for k, v in self.mozInfo.items():
  1040. if isinstance(k, unicode):
  1041. k = k.encode('ascii')
  1042. fixedInfo[k] = v
  1043. self.mozInfo = fixedInfo
  1044. mozinfo.update(self.mozInfo)
  1045. self.stack_fixer_function = None
  1046. if utility_path and os.path.exists(utility_path):
  1047. self.stack_fixer_function = get_stack_fixer_function(utility_path, self.symbolsPath)
  1048. # buildEnvironment() needs mozInfo, so we call it after mozInfo is initialized.
  1049. self.buildEnvironment()
  1050. # The appDirKey is a optional entry in either the default or individual test
  1051. # sections that defines a relative application directory for test runs. If
  1052. # defined we pass 'grePath/$appDirKey' for the -a parameter of the xpcshell
  1053. # test harness.
  1054. appDirKey = None
  1055. if "appname" in self.mozInfo:
  1056. appDirKey = self.mozInfo["appname"] + "-appdir"
  1057. # We have to do this before we build the test list so we know whether or
  1058. # not to run tests that depend on having the node http/2 server
  1059. self.trySetupNode()
  1060. pStdout, pStderr = self.getPipes()
  1061. self.buildTestList(test_tags, testPaths)
  1062. if self.singleFile:
  1063. self.sequential = True
  1064. if shuffle:
  1065. random.shuffle(self.alltests)
  1066. self.cleanup_dir_list = []
  1067. self.try_again_list = []
  1068. kwargs = {
  1069. 'appPath': self.appPath,
  1070. 'xrePath': self.xrePath,
  1071. 'testingModulesDir': self.testingModulesDir,
  1072. 'debuggerInfo': self.debuggerInfo,
  1073. 'jsDebuggerInfo': self.jsDebuggerInfo,
  1074. 'pluginsPath': self.pluginsPath,
  1075. 'httpdManifest': self.httpdManifest,
  1076. 'httpdJSPath': self.httpdJSPath,
  1077. 'headJSPath': self.headJSPath,
  1078. 'tempDir': self.tempDir,
  1079. 'testharnessdir': self.testharnessdir,
  1080. 'profileName': self.profileName,
  1081. 'singleFile': self.singleFile,
  1082. 'env': self.env, # making a copy of this in the testthreads
  1083. 'symbolsPath': self.symbolsPath,
  1084. 'logfiles': self.logfiles,
  1085. 'xpcshell': self.xpcshell,
  1086. 'xpcsRunArgs': self.xpcsRunArgs,
  1087. 'failureManifest': self.failure_manifest,
  1088. 'jscovdir': self.jscovdir,
  1089. 'harness_timeout': self.harness_timeout,
  1090. 'stack_fixer_function': self.stack_fixer_function,
  1091. }
  1092. if self.sequential:
  1093. # Allow user to kill hung xpcshell subprocess with SIGINT
  1094. # when we are only running tests sequentially.
  1095. signal.signal(signal.SIGINT, markGotSIGINT)
  1096. if self.debuggerInfo:
  1097. # Force a sequential run
  1098. self.sequential = True
  1099. # If we have an interactive debugger, disable SIGINT entirely.
  1100. if self.debuggerInfo.interactive:
  1101. signal.signal(signal.SIGINT, lambda signum, frame: None)
  1102. if "lldb" in self.debuggerInfo.path:
  1103. # Ask people to start debugging using 'process launch', see bug 952211.
  1104. self.log.info("It appears that you're using LLDB to debug this test. " +
  1105. "Please use the 'process launch' command instead of the 'run' command to start xpcshell.")
  1106. if self.jsDebuggerInfo:
  1107. # The js debugger magic needs more work to do the right thing
  1108. # if debugging multiple files.
  1109. if len(self.alltests) != 1:
  1110. self.log.error("Error: --jsdebugger can only be used with a single test!")
  1111. return False
  1112. # The test itself needs to know whether it is a tsan build, since
  1113. # that has an effect on interpretation of the process return value.
  1114. usingTSan = "tsan" in self.mozInfo and self.mozInfo["tsan"]
  1115. # create a queue of all tests that will run
  1116. tests_queue = deque()
  1117. # also a list for the tests that need to be run sequentially
  1118. sequential_tests = []
  1119. for test_object in self.alltests:
  1120. # Test identifiers are provided for the convenience of logging. These
  1121. # start as path names but are rewritten in case tests from the same path
  1122. # are re-run.
  1123. path = test_object['path']
  1124. test_object['id'] = self.makeTestId(test_object)
  1125. if self.singleFile and not path.endswith(self.singleFile):
  1126. continue
  1127. self.testCount += 1
  1128. test = testClass(test_object, self.event, self.cleanup_dir_list,
  1129. app_dir_key=appDirKey,
  1130. interactive=interactive,
  1131. verbose=verbose or test_object.get("verbose") == "true",
  1132. pStdout=pStdout, pStderr=pStderr,
  1133. keep_going=keepGoing, log=self.log, usingTSan=usingTSan,
  1134. mobileArgs=mobileArgs, **kwargs)
  1135. if 'run-sequentially' in test_object or self.sequential:
  1136. sequential_tests.append(test)
  1137. else:
  1138. tests_queue.append(test)
  1139. if self.sequential:
  1140. self.log.info("Running tests sequentially.")
  1141. else:
  1142. self.log.info("Using at most %d threads." % NUM_THREADS)
  1143. # keep a set of NUM_THREADS running tests and start running the
  1144. # tests in the queue at most NUM_THREADS at a time
  1145. running_tests = set()
  1146. keep_going = True
  1147. exceptions = []
  1148. tracebacks = []
  1149. self.log.suite_start([t['id'] for t in self.alltests])
  1150. while tests_queue or running_tests:
  1151. # if we're not supposed to continue and all of the running tests
  1152. # are done, stop
  1153. if not keep_going and not running_tests:
  1154. break
  1155. # if there's room to run more tests, start running them
  1156. while keep_going and tests_queue and (len(running_tests) < NUM_THREADS):
  1157. test = tests_queue.popleft()
  1158. running_tests.add(test)
  1159. test.start()
  1160. # queue is full (for now) or no more new tests,
  1161. # process the finished tests so far
  1162. # wait for at least one of the tests to finish
  1163. self.event.wait(1)
  1164. self.event.clear()
  1165. # find what tests are done (might be more than 1)
  1166. done_tests = set()
  1167. for test in running_tests:
  1168. if test.done:
  1169. done_tests.add(test)
  1170. test.join(1) # join with timeout so we don't hang on blocked threads
  1171. # if the test had trouble, we will try running it again
  1172. # at the end of the run
  1173. if test.retry or test.is_alive():
  1174. # if the join call timed out, test.is_alive => True
  1175. self.try_again_list.append(test.test_object)
  1176. continue
  1177. # did the test encounter any exception?
  1178. if test.exception:
  1179. exceptions.append(test.exception)
  1180. tracebacks.append(test.traceback)
  1181. # we won't add any more tests, will just wait for
  1182. # the currently running ones to finish
  1183. keep_going = False
  1184. keep_going = keep_going and test.keep_going
  1185. self.addTestResults(test)
  1186. # make room for new tests to run
  1187. running_tests.difference_update(done_tests)
  1188. if keep_going:
  1189. # run the other tests sequentially
  1190. for test in sequential_tests:
  1191. if not keep_going:
  1192. self.log.error("TEST-UNEXPECTED-FAIL | Received SIGINT (control-C), so stopped run. " \
  1193. "(Use --keep-going to keep running tests after killing one with SIGINT)")
  1194. break
  1195. # we don't want to retry these tests
  1196. test.retry = False
  1197. test.start()
  1198. test.join()
  1199. self.addTestResults(test)
  1200. # did the test encounter any exception?
  1201. if test.exception:
  1202. exceptions.append(test.exception)
  1203. tracebacks.append(test.traceback)
  1204. break
  1205. keep_going = test.keep_going
  1206. # retry tests that failed when run in parallel
  1207. if self.try_again_list:
  1208. self.log.info("Retrying tests that failed when run in parallel.")
  1209. for test_object in self.try_again_list:
  1210. test = testClass(test_object, self.event, self.cleanup_dir_list,
  1211. retry=False,
  1212. app_dir_key=appDirKey, interactive=interactive,
  1213. verbose=verbose, pStdout=pStdout, pStderr=pStderr,
  1214. keep_going=keepGoing, log=self.log, mobileArgs=mobileArgs,
  1215. **kwargs)
  1216. test.start()
  1217. test.join()
  1218. self.addTestResults(test)
  1219. # did the test encounter any exception?
  1220. if test.exception:
  1221. exceptions.append(test.exception)
  1222. tracebacks.append(test.traceback)
  1223. break
  1224. keep_going = test.keep_going
  1225. # restore default SIGINT behaviour
  1226. signal.signal(signal.SIGINT, signal.SIG_DFL)
  1227. self.shutdownNode()
  1228. # Clean up any slacker directories that might be lying around
  1229. # Some might fail because of windows taking too long to unlock them.
  1230. # We don't do anything if this fails because the test slaves will have
  1231. # their $TEMP dirs cleaned up on reboot anyway.
  1232. for directory in self.cleanup_dir_list:
  1233. try:
  1234. shutil.rmtree(directory)
  1235. except:
  1236. self.log.info("%s could not be cleaned up." % directory)
  1237. if exceptions:
  1238. self.log.info("Following exceptions were raised:")
  1239. for t in tracebacks:
  1240. self.log.error(t)
  1241. raise exceptions[0]
  1242. if self.testCount == 0:
  1243. self.log.error("No tests run. Did you pass an invalid --test-path?")
  1244. self.failCount = 1
  1245. self.log.info("INFO | Result summary:")
  1246. self.log.info("INFO | Passed: %d" % self.passCount)
  1247. self.log.info("INFO | Failed: %d" % self.failCount)
  1248. self.log.info("INFO | Todo: %d" % self.todoCount)
  1249. self.log.info("INFO | Retried: %d" % len(self.try_again_list))
  1250. if gotSIGINT and not keepGoing:
  1251. self.log.error("TEST-UNEXPECTED-FAIL | Received SIGINT (control-C), so stopped run. " \
  1252. "(Use --keep-going to keep running tests after killing one with SIGINT)")
  1253. return False
  1254. self.log.suite_end()
  1255. return self.failCount == 0
  1256. def main():
  1257. parser = parser_desktop()
  1258. options = parser.parse_args()
  1259. log = commandline.setup_logging("XPCShell", options, {"tbpl": sys.stdout})
  1260. if options.xpcshell is None:
  1261. print >> sys.stderr, """Must provide path to xpcshell using --xpcshell"""
  1262. xpcsh = XPCShellTests(log)
  1263. if options.interactive and not options.testPath:
  1264. print >>sys.stderr, "Error: You must specify a test filename in interactive mode!"
  1265. sys.exit(1)
  1266. if not xpcsh.runTests(**vars(options)):
  1267. sys.exit(1)
  1268. if __name__ == '__main__':
  1269. main()