TestGyp.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420
  1. # Copyright (c) 2012 Google Inc. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """
  5. TestGyp.py: a testing framework for GYP integration tests.
  6. """
  7. import collections
  8. from contextlib import contextmanager
  9. import itertools
  10. import os
  11. import random
  12. import re
  13. import shutil
  14. import stat
  15. import subprocess
  16. import sys
  17. import tempfile
  18. import time
  19. import TestCmd
  20. import TestCommon
  21. from TestCommon import __all__
  22. __all__.extend([
  23. 'TestGyp',
  24. ])
  25. def remove_debug_line_numbers(contents):
  26. """Function to remove the line numbers from the debug output
  27. of gyp and thus reduce the extreme fragility of the stdout
  28. comparison tests.
  29. """
  30. lines = contents.splitlines()
  31. # split each line on ":"
  32. lines = [l.split(":", 3) for l in lines]
  33. # join each line back together while ignoring the
  34. # 3rd column which is the line number
  35. lines = [len(l) > 3 and ":".join(l[3:]) or l for l in lines]
  36. return "\n".join(lines)
  37. def match_modulo_line_numbers(contents_a, contents_b):
  38. """File contents matcher that ignores line numbers."""
  39. contents_a = remove_debug_line_numbers(contents_a)
  40. contents_b = remove_debug_line_numbers(contents_b)
  41. return TestCommon.match_exact(contents_a, contents_b)
  42. @contextmanager
  43. def LocalEnv(local_env):
  44. """Context manager to provide a local OS environment."""
  45. old_env = os.environ.copy()
  46. os.environ.update(local_env)
  47. try:
  48. yield
  49. finally:
  50. os.environ.clear()
  51. os.environ.update(old_env)
  52. class TestGypBase(TestCommon.TestCommon):
  53. """
  54. Class for controlling end-to-end tests of gyp generators.
  55. Instantiating this class will create a temporary directory and
  56. arrange for its destruction (via the TestCmd superclass) and
  57. copy all of the non-gyptest files in the directory hierarchy of the
  58. executing script.
  59. The default behavior is to test the 'gyp' or 'gyp.bat' file in the
  60. current directory. An alternative may be specified explicitly on
  61. instantiation, or by setting the TESTGYP_GYP environment variable.
  62. This class should be subclassed for each supported gyp generator
  63. (format). Various abstract methods below define calling signatures
  64. used by the test scripts to invoke builds on the generated build
  65. configuration and to run executables generated by those builds.
  66. """
  67. formats = []
  68. build_tool = None
  69. build_tool_list = []
  70. _exe = TestCommon.exe_suffix
  71. _obj = TestCommon.obj_suffix
  72. shobj_ = TestCommon.shobj_prefix
  73. _shobj = TestCommon.shobj_suffix
  74. lib_ = TestCommon.lib_prefix
  75. _lib = TestCommon.lib_suffix
  76. dll_ = TestCommon.dll_prefix
  77. _dll = TestCommon.dll_suffix
  78. # Constants to represent different targets.
  79. ALL = '__all__'
  80. DEFAULT = '__default__'
  81. # Constants for different target types.
  82. EXECUTABLE = '__executable__'
  83. STATIC_LIB = '__static_lib__'
  84. SHARED_LIB = '__shared_lib__'
  85. def __init__(self, gyp=None, *args, **kw):
  86. self.origin_cwd = os.path.abspath(os.path.dirname(sys.argv[0]))
  87. self.extra_args = sys.argv[1:]
  88. if not gyp:
  89. gyp = os.environ.get('TESTGYP_GYP')
  90. if not gyp:
  91. if sys.platform == 'win32':
  92. gyp = 'gyp.bat'
  93. else:
  94. gyp = 'gyp'
  95. self.gyp = os.path.abspath(gyp)
  96. self.no_parallel = False
  97. self.formats = [self.format]
  98. self.initialize_build_tool()
  99. kw.setdefault('match', TestCommon.match_exact)
  100. # Put test output in out/testworkarea by default.
  101. # Use temporary names so there are no collisions.
  102. workdir = os.path.join('out', kw.get('workdir', 'testworkarea'))
  103. # Create work area if it doesn't already exist.
  104. if not os.path.isdir(workdir):
  105. os.makedirs(workdir)
  106. kw['workdir'] = tempfile.mktemp(prefix='testgyp.', dir=workdir)
  107. formats = kw.pop('formats', [])
  108. super(TestGypBase, self).__init__(*args, **kw)
  109. real_format = self.format.split('-')[-1]
  110. excluded_formats = set([f for f in formats if f[0] == '!'])
  111. included_formats = set(formats) - excluded_formats
  112. if ('!'+real_format in excluded_formats or
  113. included_formats and real_format not in included_formats):
  114. msg = 'Invalid test for %r format; skipping test.\n'
  115. self.skip_test(msg % self.format)
  116. self.copy_test_configuration(self.origin_cwd, self.workdir)
  117. self.set_configuration(None)
  118. # Set $HOME so that gyp doesn't read the user's actual
  119. # ~/.gyp/include.gypi file, which may contain variables
  120. # and other settings that would change the output.
  121. os.environ['HOME'] = self.workpath()
  122. # Clear $GYP_DEFINES for the same reason.
  123. if 'GYP_DEFINES' in os.environ:
  124. del os.environ['GYP_DEFINES']
  125. # Override the user's language settings, which could
  126. # otherwise make the output vary from what is expected.
  127. os.environ['LC_ALL'] = 'C'
  128. def built_file_must_exist(self, name, type=None, **kw):
  129. """
  130. Fails the test if the specified built file name does not exist.
  131. """
  132. return self.must_exist(self.built_file_path(name, type, **kw))
  133. def built_file_must_not_exist(self, name, type=None, **kw):
  134. """
  135. Fails the test if the specified built file name exists.
  136. """
  137. return self.must_not_exist(self.built_file_path(name, type, **kw))
  138. def built_file_must_match(self, name, contents, **kw):
  139. """
  140. Fails the test if the contents of the specified built file name
  141. do not match the specified contents.
  142. """
  143. return self.must_match(self.built_file_path(name, **kw), contents)
  144. def built_file_must_not_match(self, name, contents, **kw):
  145. """
  146. Fails the test if the contents of the specified built file name
  147. match the specified contents.
  148. """
  149. return self.must_not_match(self.built_file_path(name, **kw), contents)
  150. def built_file_must_not_contain(self, name, contents, **kw):
  151. """
  152. Fails the test if the specified built file name contains the specified
  153. contents.
  154. """
  155. return self.must_not_contain(self.built_file_path(name, **kw), contents)
  156. def copy_test_configuration(self, source_dir, dest_dir):
  157. """
  158. Copies the test configuration from the specified source_dir
  159. (the directory in which the test script lives) to the
  160. specified dest_dir (a temporary working directory).
  161. This ignores all files and directories that begin with
  162. the string 'gyptest', and all '.svn' subdirectories.
  163. """
  164. for root, dirs, files in os.walk(source_dir):
  165. if '.svn' in dirs:
  166. dirs.remove('.svn')
  167. dirs = [ d for d in dirs if not d.startswith('gyptest') ]
  168. files = [ f for f in files if not f.startswith('gyptest') ]
  169. for dirname in dirs:
  170. source = os.path.join(root, dirname)
  171. destination = source.replace(source_dir, dest_dir)
  172. os.mkdir(destination)
  173. if sys.platform != 'win32':
  174. shutil.copystat(source, destination)
  175. for filename in files:
  176. source = os.path.join(root, filename)
  177. destination = source.replace(source_dir, dest_dir)
  178. shutil.copy2(source, destination)
  179. def initialize_build_tool(self):
  180. """
  181. Initializes the .build_tool attribute.
  182. Searches the .build_tool_list for an executable name on the user's
  183. $PATH. The first tool on the list is used as-is if nothing is found
  184. on the current $PATH.
  185. """
  186. for build_tool in self.build_tool_list:
  187. if not build_tool:
  188. continue
  189. if os.path.isabs(build_tool):
  190. self.build_tool = build_tool
  191. return
  192. build_tool = self.where_is(build_tool)
  193. if build_tool:
  194. self.build_tool = build_tool
  195. return
  196. if self.build_tool_list:
  197. self.build_tool = self.build_tool_list[0]
  198. def relocate(self, source, destination):
  199. """
  200. Renames (relocates) the specified source (usually a directory)
  201. to the specified destination, creating the destination directory
  202. first if necessary.
  203. Note: Don't use this as a generic "rename" operation. In the
  204. future, "relocating" parts of a GYP tree may affect the state of
  205. the test to modify the behavior of later method calls.
  206. """
  207. destination_dir = os.path.dirname(destination)
  208. if not os.path.exists(destination_dir):
  209. self.subdir(destination_dir)
  210. os.rename(source, destination)
  211. def report_not_up_to_date(self):
  212. """
  213. Reports that a build is not up-to-date.
  214. This provides common reporting for formats that have complicated
  215. conditions for checking whether a build is up-to-date. Formats
  216. that expect exact output from the command (make) can
  217. just set stdout= when they call the run_build() method.
  218. """
  219. print "Build is not up-to-date:"
  220. print self.banner('STDOUT ')
  221. print self.stdout()
  222. stderr = self.stderr()
  223. if stderr:
  224. print self.banner('STDERR ')
  225. print stderr
  226. def run_gyp(self, gyp_file, *args, **kw):
  227. """
  228. Runs gyp against the specified gyp_file with the specified args.
  229. """
  230. # When running gyp, and comparing its output we use a comparitor
  231. # that ignores the line numbers that gyp logs in its debug output.
  232. if kw.pop('ignore_line_numbers', False):
  233. kw.setdefault('match', match_modulo_line_numbers)
  234. # TODO: --depth=. works around Chromium-specific tree climbing.
  235. depth = kw.pop('depth', '.')
  236. run_args = ['--depth='+depth]
  237. run_args.extend(['--format='+f for f in self.formats]);
  238. run_args.append(gyp_file)
  239. if self.no_parallel:
  240. run_args += ['--no-parallel']
  241. # TODO: if extra_args contains a '--build' flag
  242. # we really want that to only apply to the last format (self.format).
  243. run_args.extend(self.extra_args)
  244. # Default xcode_ninja_target_pattern to ^.*$ to fix xcode-ninja tests
  245. xcode_ninja_target_pattern = kw.pop('xcode_ninja_target_pattern', '.*')
  246. run_args.extend(
  247. ['-G', 'xcode_ninja_target_pattern=%s' % xcode_ninja_target_pattern])
  248. run_args.extend(args)
  249. return self.run(program=self.gyp, arguments=run_args, **kw)
  250. def run(self, *args, **kw):
  251. """
  252. Executes a program by calling the superclass .run() method.
  253. This exists to provide a common place to filter out keyword
  254. arguments implemented in this layer, without having to update
  255. the tool-specific subclasses or clutter the tests themselves
  256. with platform-specific code.
  257. """
  258. if kw.has_key('SYMROOT'):
  259. del kw['SYMROOT']
  260. super(TestGypBase, self).run(*args, **kw)
  261. def set_configuration(self, configuration):
  262. """
  263. Sets the configuration, to be used for invoking the build
  264. tool and testing potential built output.
  265. """
  266. self.configuration = configuration
  267. def configuration_dirname(self):
  268. if self.configuration:
  269. return self.configuration.split('|')[0]
  270. else:
  271. return 'Default'
  272. def configuration_buildname(self):
  273. if self.configuration:
  274. return self.configuration
  275. else:
  276. return 'Default'
  277. #
  278. # Abstract methods to be defined by format-specific subclasses.
  279. #
  280. def build(self, gyp_file, target=None, **kw):
  281. """
  282. Runs a build of the specified target against the configuration
  283. generated from the specified gyp_file.
  284. A 'target' argument of None or the special value TestGyp.DEFAULT
  285. specifies the default argument for the underlying build tool.
  286. A 'target' argument of TestGyp.ALL specifies the 'all' target
  287. (if any) of the underlying build tool.
  288. """
  289. raise NotImplementedError
  290. def built_file_path(self, name, type=None, **kw):
  291. """
  292. Returns a path to the specified file name, of the specified type.
  293. """
  294. raise NotImplementedError
  295. def built_file_basename(self, name, type=None, **kw):
  296. """
  297. Returns the base name of the specified file name, of the specified type.
  298. A bare=True keyword argument specifies that prefixes and suffixes shouldn't
  299. be applied.
  300. """
  301. if not kw.get('bare'):
  302. if type == self.EXECUTABLE:
  303. name = name + self._exe
  304. elif type == self.STATIC_LIB:
  305. name = self.lib_ + name + self._lib
  306. elif type == self.SHARED_LIB:
  307. name = self.dll_ + name + self._dll
  308. return name
  309. def run_built_executable(self, name, *args, **kw):
  310. """
  311. Runs an executable program built from a gyp-generated configuration.
  312. The specified name should be independent of any particular generator.
  313. Subclasses should find the output executable in the appropriate
  314. output build directory, tack on any necessary executable suffix, etc.
  315. """
  316. raise NotImplementedError
  317. def up_to_date(self, gyp_file, target=None, **kw):
  318. """
  319. Verifies that a build of the specified target is up to date.
  320. The subclass should implement this by calling build()
  321. (or a reasonable equivalent), checking whatever conditions
  322. will tell it the build was an "up to date" null build, and
  323. failing if it isn't.
  324. """
  325. raise NotImplementedError
  326. class TestGypGypd(TestGypBase):
  327. """
  328. Subclass for testing the GYP 'gypd' generator (spit out the
  329. internal data structure as pretty-printed Python).
  330. """
  331. format = 'gypd'
  332. def __init__(self, gyp=None, *args, **kw):
  333. super(TestGypGypd, self).__init__(*args, **kw)
  334. # gypd implies the use of 'golden' files, so parallelizing conflicts as it
  335. # causes ordering changes.
  336. self.no_parallel = True
  337. class TestGypCustom(TestGypBase):
  338. """
  339. Subclass for testing the GYP with custom generator
  340. """
  341. def __init__(self, gyp=None, *args, **kw):
  342. self.format = kw.pop("format")
  343. super(TestGypCustom, self).__init__(*args, **kw)
  344. class TestGypAndroid(TestGypBase):
  345. """
  346. Subclass for testing the GYP Android makefile generator. Note that
  347. build/envsetup.sh and lunch must have been run before running tests.
  348. """
  349. format = 'android'
  350. # Note that we can't use mmm as the build tool because ...
  351. # - it builds all targets, whereas we need to pass a target
  352. # - it is a function, whereas the test runner assumes the build tool is a file
  353. # Instead we use make and duplicate the logic from mmm.
  354. build_tool_list = ['make']
  355. # We use our custom target 'gyp_all_modules', as opposed to the 'all_modules'
  356. # target used by mmm, to build only those targets which are part of the gyp
  357. # target 'all'.
  358. ALL = 'gyp_all_modules'
  359. def __init__(self, gyp=None, *args, **kw):
  360. # Android requires build and test output to be inside its source tree.
  361. # We use the following working directory for the test's source, but the
  362. # test's build output still goes to $ANDROID_PRODUCT_OUT.
  363. # Note that some tests explicitly set format='gypd' to invoke the gypd
  364. # backend. This writes to the source tree, but there's no way around this.
  365. kw['workdir'] = os.path.join('/tmp', 'gyptest',
  366. kw.get('workdir', 'testworkarea'))
  367. # We need to remove all gyp outputs from out/. Ths is because some tests
  368. # don't have rules to regenerate output, so they will simply re-use stale
  369. # output if present. Since the test working directory gets regenerated for
  370. # each test run, this can confuse things.
  371. # We don't have a list of build outputs because we don't know which
  372. # dependent targets were built. Instead we delete all gyp-generated output.
  373. # This may be excessive, but should be safe.
  374. out_dir = os.environ['ANDROID_PRODUCT_OUT']
  375. obj_dir = os.path.join(out_dir, 'obj')
  376. shutil.rmtree(os.path.join(obj_dir, 'GYP'), ignore_errors = True)
  377. for x in ['EXECUTABLES', 'STATIC_LIBRARIES', 'SHARED_LIBRARIES']:
  378. for d in os.listdir(os.path.join(obj_dir, x)):
  379. if d.endswith('_gyp_intermediates'):
  380. shutil.rmtree(os.path.join(obj_dir, x, d), ignore_errors = True)
  381. for x in [os.path.join('obj', 'lib'), os.path.join('system', 'lib')]:
  382. for d in os.listdir(os.path.join(out_dir, x)):
  383. if d.endswith('_gyp.so'):
  384. os.remove(os.path.join(out_dir, x, d))
  385. super(TestGypAndroid, self).__init__(*args, **kw)
  386. self._adb_path = os.path.join(os.environ['ANDROID_HOST_OUT'], 'bin', 'adb')
  387. self._device_serial = None
  388. adb_devices_out = self._call_adb(['devices'])
  389. devices = [l.split()[0] for l in adb_devices_out.splitlines()[1:-1]
  390. if l.split()[1] == 'device']
  391. if len(devices) == 0:
  392. self._device_serial = None
  393. else:
  394. if len(devices) > 1:
  395. self._device_serial = random.choice(devices)
  396. else:
  397. self._device_serial = devices[0]
  398. self._call_adb(['root'])
  399. self._to_install = set()
  400. def target_name(self, target):
  401. if target == self.ALL:
  402. return self.ALL
  403. # The default target is 'droid'. However, we want to use our special target
  404. # to build only the gyp target 'all'.
  405. if target in (None, self.DEFAULT):
  406. return self.ALL
  407. return target
  408. _INSTALLABLE_PREFIX = 'Install: '
  409. def build(self, gyp_file, target=None, **kw):
  410. """
  411. Runs a build using the Android makefiles generated from the specified
  412. gyp_file. This logic is taken from Android's mmm.
  413. """
  414. arguments = kw.get('arguments', [])[:]
  415. arguments.append(self.target_name(target))
  416. arguments.append('-C')
  417. arguments.append(os.environ['ANDROID_BUILD_TOP'])
  418. kw['arguments'] = arguments
  419. chdir = kw.get('chdir', '')
  420. makefile = os.path.join(self.workdir, chdir, 'GypAndroid.mk')
  421. os.environ['ONE_SHOT_MAKEFILE'] = makefile
  422. result = self.run(program=self.build_tool, **kw)
  423. for l in self.stdout().splitlines():
  424. if l.startswith(TestGypAndroid._INSTALLABLE_PREFIX):
  425. self._to_install.add(os.path.abspath(os.path.join(
  426. os.environ['ANDROID_BUILD_TOP'],
  427. l[len(TestGypAndroid._INSTALLABLE_PREFIX):])))
  428. del os.environ['ONE_SHOT_MAKEFILE']
  429. return result
  430. def android_module(self, group, name, subdir):
  431. if subdir:
  432. name = '%s_%s' % (subdir, name)
  433. if group == 'SHARED_LIBRARIES':
  434. name = 'lib_%s' % name
  435. return '%s_gyp' % name
  436. def intermediates_dir(self, group, module_name):
  437. return os.path.join(os.environ['ANDROID_PRODUCT_OUT'], 'obj', group,
  438. '%s_intermediates' % module_name)
  439. def built_file_path(self, name, type=None, **kw):
  440. """
  441. Returns a path to the specified file name, of the specified type,
  442. as built by Android. Note that we don't support the configuration
  443. parameter.
  444. """
  445. # Built files are in $ANDROID_PRODUCT_OUT. This requires copying logic from
  446. # the Android build system.
  447. if type == None or type == self.EXECUTABLE:
  448. return os.path.join(os.environ['ANDROID_PRODUCT_OUT'], 'obj', 'GYP',
  449. 'shared_intermediates', name)
  450. subdir = kw.get('subdir')
  451. if type == self.STATIC_LIB:
  452. group = 'STATIC_LIBRARIES'
  453. module_name = self.android_module(group, name, subdir)
  454. return os.path.join(self.intermediates_dir(group, module_name),
  455. '%s.a' % module_name)
  456. if type == self.SHARED_LIB:
  457. group = 'SHARED_LIBRARIES'
  458. module_name = self.android_module(group, name, subdir)
  459. return os.path.join(self.intermediates_dir(group, module_name), 'LINKED',
  460. '%s.so' % module_name)
  461. assert False, 'Unhandled type'
  462. def _adb_failure(self, command, msg, stdout, stderr):
  463. """ Reports a failed adb command and fails the containing test.
  464. Args:
  465. command: The adb command that failed.
  466. msg: The error description.
  467. stdout: The standard output.
  468. stderr: The standard error.
  469. """
  470. print '%s failed%s' % (' '.join(command), ': %s' % msg if msg else '')
  471. print self.banner('STDOUT ')
  472. stdout.seek(0)
  473. print stdout.read()
  474. print self.banner('STDERR ')
  475. stderr.seek(0)
  476. print stderr.read()
  477. self.fail_test()
  478. def _call_adb(self, command, timeout=15, retry=3):
  479. """ Calls the provided adb command.
  480. If the command fails, the test fails.
  481. Args:
  482. command: The adb command to call.
  483. Returns:
  484. The command's output.
  485. """
  486. with tempfile.TemporaryFile(bufsize=0) as adb_out:
  487. with tempfile.TemporaryFile(bufsize=0) as adb_err:
  488. adb_command = [self._adb_path]
  489. if self._device_serial:
  490. adb_command += ['-s', self._device_serial]
  491. is_shell = (command[0] == 'shell')
  492. if is_shell:
  493. command = [command[0], '%s; echo "\n$?";' % ' '.join(command[1:])]
  494. adb_command += command
  495. for attempt in xrange(1, retry + 1):
  496. adb_out.seek(0)
  497. adb_out.truncate(0)
  498. adb_err.seek(0)
  499. adb_err.truncate(0)
  500. proc = subprocess.Popen(adb_command, stdout=adb_out, stderr=adb_err)
  501. deadline = time.time() + timeout
  502. timed_out = False
  503. while proc.poll() is None and not timed_out:
  504. time.sleep(1)
  505. timed_out = time.time() > deadline
  506. if timed_out:
  507. print 'Timeout for command %s (attempt %d of %s)' % (
  508. adb_command, attempt, retry)
  509. try:
  510. proc.kill()
  511. except:
  512. pass
  513. else:
  514. break
  515. if proc.returncode != 0: # returncode is None in the case of a timeout.
  516. self._adb_failure(
  517. adb_command, 'retcode=%s' % proc.returncode, adb_out, adb_err)
  518. return
  519. adb_out.seek(0)
  520. output = adb_out.read()
  521. if is_shell:
  522. output = output.splitlines(True)
  523. try:
  524. output[-2] = output[-2].rstrip('\r\n')
  525. output, rc = (''.join(output[:-1]), int(output[-1]))
  526. except ValueError:
  527. self._adb_failure(adb_command, 'unexpected output format',
  528. adb_out, adb_err)
  529. if rc != 0:
  530. self._adb_failure(adb_command, 'exited with %d' % rc, adb_out,
  531. adb_err)
  532. return output
  533. def run_built_executable(self, name, *args, **kw):
  534. """
  535. Runs an executable program built from a gyp-generated configuration.
  536. """
  537. match = kw.pop('match', self.match)
  538. executable_file = self.built_file_path(name, type=self.EXECUTABLE, **kw)
  539. if executable_file not in self._to_install:
  540. self.fail_test()
  541. if not self._device_serial:
  542. self.skip_test(message='No devices attached.\n')
  543. storage = self._call_adb(['shell', 'echo', '$ANDROID_DATA']).strip()
  544. if not len(storage):
  545. self.fail_test()
  546. installed = set()
  547. try:
  548. for i in self._to_install:
  549. a = os.path.abspath(
  550. os.path.join(os.environ['ANDROID_BUILD_TOP'], i))
  551. dest = '%s/%s' % (storage, os.path.basename(a))
  552. self._call_adb(['push', os.path.abspath(a), dest])
  553. installed.add(dest)
  554. if i == executable_file:
  555. device_executable = dest
  556. self._call_adb(['shell', 'chmod', '755', device_executable])
  557. out = self._call_adb(
  558. ['shell', 'LD_LIBRARY_PATH=$LD_LIBRARY_PATH:%s' % storage,
  559. device_executable],
  560. timeout=60,
  561. retry=1)
  562. out = out.replace('\r\n', '\n')
  563. self._complete(out, kw.pop('stdout', None), None, None, None, match)
  564. finally:
  565. if len(installed):
  566. self._call_adb(['shell', 'rm'] + list(installed))
  567. def match_single_line(self, lines = None, expected_line = None):
  568. """
  569. Checks that specified line appears in the text.
  570. """
  571. for line in lines.split('\n'):
  572. if line == expected_line:
  573. return 1
  574. return
  575. def up_to_date(self, gyp_file, target=None, **kw):
  576. """
  577. Verifies that a build of the specified target is up to date.
  578. """
  579. kw['stdout'] = ("make: Nothing to be done for `%s'." %
  580. self.target_name(target))
  581. # We need to supply a custom matcher, since we don't want to depend on the
  582. # exact stdout string.
  583. kw['match'] = self.match_single_line
  584. return self.build(gyp_file, target, **kw)
  585. class TestGypCMake(TestGypBase):
  586. """
  587. Subclass for testing the GYP CMake generator, using cmake's ninja backend.
  588. """
  589. format = 'cmake'
  590. build_tool_list = ['cmake']
  591. ALL = 'all'
  592. def cmake_build(self, gyp_file, target=None, **kw):
  593. arguments = kw.get('arguments', [])[:]
  594. self.build_tool_list = ['cmake']
  595. self.initialize_build_tool()
  596. chdir = os.path.join(kw.get('chdir', '.'),
  597. 'out',
  598. self.configuration_dirname())
  599. kw['chdir'] = chdir
  600. arguments.append('-G')
  601. arguments.append('Ninja')
  602. kw['arguments'] = arguments
  603. stderr = kw.get('stderr', None)
  604. if stderr:
  605. kw['stderr'] = stderr.split('$$$')[0]
  606. self.run(program=self.build_tool, **kw)
  607. def ninja_build(self, gyp_file, target=None, **kw):
  608. arguments = kw.get('arguments', [])[:]
  609. self.build_tool_list = ['ninja']
  610. self.initialize_build_tool()
  611. # Add a -C output/path to the command line.
  612. arguments.append('-C')
  613. arguments.append(os.path.join('out', self.configuration_dirname()))
  614. if target not in (None, self.DEFAULT):
  615. arguments.append(target)
  616. kw['arguments'] = arguments
  617. stderr = kw.get('stderr', None)
  618. if stderr:
  619. stderrs = stderr.split('$$$')
  620. kw['stderr'] = stderrs[1] if len(stderrs) > 1 else ''
  621. return self.run(program=self.build_tool, **kw)
  622. def build(self, gyp_file, target=None, status=0, **kw):
  623. # Two tools must be run to build, cmake and the ninja.
  624. # Allow cmake to succeed when the overall expectation is to fail.
  625. if status is None:
  626. kw['status'] = None
  627. else:
  628. if not isinstance(status, collections.Iterable): status = (status,)
  629. kw['status'] = list(itertools.chain((0,), status))
  630. self.cmake_build(gyp_file, target, **kw)
  631. kw['status'] = status
  632. self.ninja_build(gyp_file, target, **kw)
  633. def run_built_executable(self, name, *args, **kw):
  634. # Enclosing the name in a list avoids prepending the original dir.
  635. program = [self.built_file_path(name, type=self.EXECUTABLE, **kw)]
  636. if sys.platform == 'darwin':
  637. configuration = self.configuration_dirname()
  638. os.environ['DYLD_LIBRARY_PATH'] = os.path.join('out', configuration)
  639. return self.run(program=program, *args, **kw)
  640. def built_file_path(self, name, type=None, **kw):
  641. result = []
  642. chdir = kw.get('chdir')
  643. if chdir:
  644. result.append(chdir)
  645. result.append('out')
  646. result.append(self.configuration_dirname())
  647. if type == self.STATIC_LIB:
  648. if sys.platform != 'darwin':
  649. result.append('obj.target')
  650. elif type == self.SHARED_LIB:
  651. if sys.platform != 'darwin' and sys.platform != 'win32':
  652. result.append('lib.target')
  653. subdir = kw.get('subdir')
  654. if subdir and type != self.SHARED_LIB:
  655. result.append(subdir)
  656. result.append(self.built_file_basename(name, type, **kw))
  657. return self.workpath(*result)
  658. def up_to_date(self, gyp_file, target=None, **kw):
  659. result = self.ninja_build(gyp_file, target, **kw)
  660. if not result:
  661. stdout = self.stdout()
  662. if 'ninja: no work to do' not in stdout:
  663. self.report_not_up_to_date()
  664. self.fail_test()
  665. return result
  666. class TestGypMake(TestGypBase):
  667. """
  668. Subclass for testing the GYP Make generator.
  669. """
  670. format = 'make'
  671. build_tool_list = ['make']
  672. ALL = 'all'
  673. def build(self, gyp_file, target=None, **kw):
  674. """
  675. Runs a Make build using the Makefiles generated from the specified
  676. gyp_file.
  677. """
  678. arguments = kw.get('arguments', [])[:]
  679. if self.configuration:
  680. arguments.append('BUILDTYPE=' + self.configuration)
  681. if target not in (None, self.DEFAULT):
  682. arguments.append(target)
  683. # Sub-directory builds provide per-gyp Makefiles (i.e.
  684. # Makefile.gyp_filename), so use that if there is no Makefile.
  685. chdir = kw.get('chdir', '')
  686. if not os.path.exists(os.path.join(chdir, 'Makefile')):
  687. print "NO Makefile in " + os.path.join(chdir, 'Makefile')
  688. arguments.insert(0, '-f')
  689. arguments.insert(1, os.path.splitext(gyp_file)[0] + '.Makefile')
  690. kw['arguments'] = arguments
  691. return self.run(program=self.build_tool, **kw)
  692. def up_to_date(self, gyp_file, target=None, **kw):
  693. """
  694. Verifies that a build of the specified Make target is up to date.
  695. """
  696. if target in (None, self.DEFAULT):
  697. message_target = 'all'
  698. else:
  699. message_target = target
  700. kw['stdout'] = "make: Nothing to be done for `%s'.\n" % message_target
  701. return self.build(gyp_file, target, **kw)
  702. def run_built_executable(self, name, *args, **kw):
  703. """
  704. Runs an executable built by Make.
  705. """
  706. configuration = self.configuration_dirname()
  707. libdir = os.path.join('out', configuration, 'lib')
  708. # TODO(piman): when everything is cross-compile safe, remove lib.target
  709. if sys.platform == 'darwin':
  710. # Mac puts target shared libraries right in the product directory.
  711. configuration = self.configuration_dirname()
  712. os.environ['DYLD_LIBRARY_PATH'] = (
  713. libdir + '.host:' + os.path.join('out', configuration))
  714. else:
  715. os.environ['LD_LIBRARY_PATH'] = libdir + '.host:' + libdir + '.target'
  716. # Enclosing the name in a list avoids prepending the original dir.
  717. program = [self.built_file_path(name, type=self.EXECUTABLE, **kw)]
  718. return self.run(program=program, *args, **kw)
  719. def built_file_path(self, name, type=None, **kw):
  720. """
  721. Returns a path to the specified file name, of the specified type,
  722. as built by Make.
  723. Built files are in the subdirectory 'out/{configuration}'.
  724. The default is 'out/Default'.
  725. A chdir= keyword argument specifies the source directory
  726. relative to which the output subdirectory can be found.
  727. "type" values of STATIC_LIB or SHARED_LIB append the necessary
  728. prefixes and suffixes to a platform-independent library base name.
  729. A subdir= keyword argument specifies a library subdirectory within
  730. the default 'obj.target'.
  731. """
  732. result = []
  733. chdir = kw.get('chdir')
  734. if chdir:
  735. result.append(chdir)
  736. configuration = self.configuration_dirname()
  737. result.extend(['out', configuration])
  738. if type == self.STATIC_LIB and sys.platform != 'darwin':
  739. result.append('obj.target')
  740. elif type == self.SHARED_LIB and sys.platform != 'darwin':
  741. result.append('lib.target')
  742. subdir = kw.get('subdir')
  743. if subdir and type != self.SHARED_LIB:
  744. result.append(subdir)
  745. result.append(self.built_file_basename(name, type, **kw))
  746. return self.workpath(*result)
  747. def ConvertToCygpath(path):
  748. """Convert to cygwin path if we are using cygwin."""
  749. if sys.platform == 'cygwin':
  750. p = subprocess.Popen(['cygpath', path], stdout=subprocess.PIPE)
  751. path = p.communicate()[0].strip()
  752. return path
  753. def FindMSBuildInstallation(msvs_version = 'auto'):
  754. """Returns path to MSBuild for msvs_version or latest available.
  755. Looks in the registry to find install location of MSBuild.
  756. MSBuild before v4.0 will not build c++ projects, so only use newer versions.
  757. """
  758. import TestWin
  759. registry = TestWin.Registry()
  760. msvs_to_msbuild = {
  761. '2013': r'12.0',
  762. '2012': r'4.0', # Really v4.0.30319 which comes with .NET 4.5.
  763. '2010': r'4.0'}
  764. msbuild_basekey = r'HKLM\SOFTWARE\Microsoft\MSBuild\ToolsVersions'
  765. if not registry.KeyExists(msbuild_basekey):
  766. print 'Error: could not find MSBuild base registry entry'
  767. return None
  768. msbuild_version = None
  769. if msvs_version in msvs_to_msbuild:
  770. msbuild_test_version = msvs_to_msbuild[msvs_version]
  771. if registry.KeyExists(msbuild_basekey + '\\' + msbuild_test_version):
  772. msbuild_version = msbuild_test_version
  773. else:
  774. print ('Warning: Environment variable GYP_MSVS_VERSION specifies "%s" '
  775. 'but corresponding MSBuild "%s" was not found.' %
  776. (msvs_version, msbuild_version))
  777. if not msbuild_version:
  778. for msvs_version in sorted(msvs_to_msbuild, reverse=True):
  779. msbuild_test_version = msvs_to_msbuild[msvs_version]
  780. if registry.KeyExists(msbuild_basekey + '\\' + msbuild_test_version):
  781. msbuild_version = msbuild_test_version
  782. break
  783. if not msbuild_version:
  784. print 'Error: could not find MSBuild registry entry'
  785. return None
  786. msbuild_path = registry.GetValue(msbuild_basekey + '\\' + msbuild_version,
  787. 'MSBuildToolsPath')
  788. if not msbuild_path:
  789. print 'Error: could not get MSBuild registry entry value'
  790. return None
  791. return os.path.join(msbuild_path, 'MSBuild.exe')
  792. def FindVisualStudioInstallation():
  793. """Returns appropriate values for .build_tool and .uses_msbuild fields
  794. of TestGypBase for Visual Studio.
  795. We use the value specified by GYP_MSVS_VERSION. If not specified, we
  796. search %PATH% and %PATHEXT% for a devenv.{exe,bat,...} executable.
  797. Failing that, we search for likely deployment paths.
  798. """
  799. possible_roots = ['%s:\\Program Files%s' % (chr(drive), suffix)
  800. for drive in range(ord('C'), ord('Z') + 1)
  801. for suffix in ['', ' (x86)']]
  802. possible_paths = {
  803. '2013': r'Microsoft Visual Studio 12.0\Common7\IDE\devenv.com',
  804. '2012': r'Microsoft Visual Studio 11.0\Common7\IDE\devenv.com',
  805. '2010': r'Microsoft Visual Studio 10.0\Common7\IDE\devenv.com',
  806. '2008': r'Microsoft Visual Studio 9.0\Common7\IDE\devenv.com',
  807. '2005': r'Microsoft Visual Studio 8\Common7\IDE\devenv.com'}
  808. possible_roots = [ConvertToCygpath(r) for r in possible_roots]
  809. msvs_version = 'auto'
  810. for flag in (f for f in sys.argv if f.startswith('msvs_version=')):
  811. msvs_version = flag.split('=')[-1]
  812. msvs_version = os.environ.get('GYP_MSVS_VERSION', msvs_version)
  813. if msvs_version in possible_paths:
  814. # Check that the path to the specified GYP_MSVS_VERSION exists.
  815. path = possible_paths[msvs_version]
  816. for r in possible_roots:
  817. build_tool = os.path.join(r, path)
  818. if os.path.exists(build_tool):
  819. uses_msbuild = msvs_version >= '2010'
  820. msbuild_path = FindMSBuildInstallation(msvs_version)
  821. return build_tool, uses_msbuild, msbuild_path
  822. else:
  823. print ('Warning: Environment variable GYP_MSVS_VERSION specifies "%s" '
  824. 'but corresponding "%s" was not found.' % (msvs_version, path))
  825. # Neither GYP_MSVS_VERSION nor the path help us out. Iterate through
  826. # the choices looking for a match.
  827. for version in sorted(possible_paths, reverse=True):
  828. path = possible_paths[version]
  829. for r in possible_roots:
  830. build_tool = os.path.join(r, path)
  831. if os.path.exists(build_tool):
  832. uses_msbuild = msvs_version >= '2010'
  833. msbuild_path = FindMSBuildInstallation(msvs_version)
  834. return build_tool, uses_msbuild, msbuild_path
  835. print 'Error: could not find devenv'
  836. sys.exit(1)
  837. class TestGypOnMSToolchain(TestGypBase):
  838. """
  839. Common subclass for testing generators that target the Microsoft Visual
  840. Studio toolchain (cl, link, dumpbin, etc.)
  841. """
  842. @staticmethod
  843. def _ComputeVsvarsPath(devenv_path):
  844. devenv_dir = os.path.split(devenv_path)[0]
  845. vsvars_path = os.path.join(devenv_path, '../../Tools/vsvars32.bat')
  846. return vsvars_path
  847. def initialize_build_tool(self):
  848. super(TestGypOnMSToolchain, self).initialize_build_tool()
  849. if sys.platform in ('win32', 'cygwin'):
  850. build_tools = FindVisualStudioInstallation()
  851. self.devenv_path, self.uses_msbuild, self.msbuild_path = build_tools
  852. self.vsvars_path = TestGypOnMSToolchain._ComputeVsvarsPath(
  853. self.devenv_path)
  854. def run_dumpbin(self, *dumpbin_args):
  855. """Run the dumpbin tool with the specified arguments, and capturing and
  856. returning stdout."""
  857. assert sys.platform in ('win32', 'cygwin')
  858. cmd = os.environ.get('COMSPEC', 'cmd.exe')
  859. arguments = [cmd, '/c', self.vsvars_path, '&&', 'dumpbin']
  860. arguments.extend(dumpbin_args)
  861. proc = subprocess.Popen(arguments, stdout=subprocess.PIPE)
  862. output = proc.communicate()[0]
  863. assert not proc.returncode
  864. return output
  865. class TestGypNinja(TestGypOnMSToolchain):
  866. """
  867. Subclass for testing the GYP Ninja generator.
  868. """
  869. format = 'ninja'
  870. build_tool_list = ['ninja']
  871. ALL = 'all'
  872. DEFAULT = 'all'
  873. def run_gyp(self, gyp_file, *args, **kw):
  874. TestGypBase.run_gyp(self, gyp_file, *args, **kw)
  875. def build(self, gyp_file, target=None, **kw):
  876. arguments = kw.get('arguments', [])[:]
  877. # Add a -C output/path to the command line.
  878. arguments.append('-C')
  879. arguments.append(os.path.join('out', self.configuration_dirname()))
  880. if target is None:
  881. target = 'all'
  882. arguments.append(target)
  883. kw['arguments'] = arguments
  884. return self.run(program=self.build_tool, **kw)
  885. def run_built_executable(self, name, *args, **kw):
  886. # Enclosing the name in a list avoids prepending the original dir.
  887. program = [self.built_file_path(name, type=self.EXECUTABLE, **kw)]
  888. if sys.platform == 'darwin':
  889. configuration = self.configuration_dirname()
  890. os.environ['DYLD_LIBRARY_PATH'] = os.path.join('out', configuration)
  891. return self.run(program=program, *args, **kw)
  892. def built_file_path(self, name, type=None, **kw):
  893. result = []
  894. chdir = kw.get('chdir')
  895. if chdir:
  896. result.append(chdir)
  897. result.append('out')
  898. result.append(self.configuration_dirname())
  899. if type == self.STATIC_LIB:
  900. if sys.platform != 'darwin':
  901. result.append('obj')
  902. elif type == self.SHARED_LIB:
  903. if sys.platform != 'darwin' and sys.platform != 'win32':
  904. result.append('lib')
  905. subdir = kw.get('subdir')
  906. if subdir and type != self.SHARED_LIB:
  907. result.append(subdir)
  908. result.append(self.built_file_basename(name, type, **kw))
  909. return self.workpath(*result)
  910. def up_to_date(self, gyp_file, target=None, **kw):
  911. result = self.build(gyp_file, target, **kw)
  912. if not result:
  913. stdout = self.stdout()
  914. if 'ninja: no work to do' not in stdout:
  915. self.report_not_up_to_date()
  916. self.fail_test()
  917. return result
  918. class TestGypMSVS(TestGypOnMSToolchain):
  919. """
  920. Subclass for testing the GYP Visual Studio generator.
  921. """
  922. format = 'msvs'
  923. u = r'=== Build: 0 succeeded, 0 failed, (\d+) up-to-date, 0 skipped ==='
  924. up_to_date_re = re.compile(u, re.M)
  925. # Initial None element will indicate to our .initialize_build_tool()
  926. # method below that 'devenv' was not found on %PATH%.
  927. #
  928. # Note: we must use devenv.com to be able to capture build output.
  929. # Directly executing devenv.exe only sends output to BuildLog.htm.
  930. build_tool_list = [None, 'devenv.com']
  931. def initialize_build_tool(self):
  932. super(TestGypMSVS, self).initialize_build_tool()
  933. self.build_tool = self.devenv_path
  934. def build(self, gyp_file, target=None, rebuild=False, clean=False, **kw):
  935. """
  936. Runs a Visual Studio build using the configuration generated
  937. from the specified gyp_file.
  938. """
  939. configuration = self.configuration_buildname()
  940. if clean:
  941. build = '/Clean'
  942. elif rebuild:
  943. build = '/Rebuild'
  944. else:
  945. build = '/Build'
  946. arguments = kw.get('arguments', [])[:]
  947. arguments.extend([gyp_file.replace('.gyp', '.sln'),
  948. build, configuration])
  949. # Note: the Visual Studio generator doesn't add an explicit 'all'
  950. # target, so we just treat it the same as the default.
  951. if target not in (None, self.ALL, self.DEFAULT):
  952. arguments.extend(['/Project', target])
  953. if self.configuration:
  954. arguments.extend(['/ProjectConfig', self.configuration])
  955. kw['arguments'] = arguments
  956. return self.run(program=self.build_tool, **kw)
  957. def up_to_date(self, gyp_file, target=None, **kw):
  958. """
  959. Verifies that a build of the specified Visual Studio target is up to date.
  960. Beware that VS2010 will behave strangely if you build under
  961. C:\USERS\yourname\AppData\Local. It will cause needless work. The ouptut
  962. will be "1 succeeded and 0 up to date". MSBuild tracing reveals that:
  963. "Project 'C:\Users\...\AppData\Local\...vcxproj' not up to date because
  964. 'C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO 10.0\VC\BIN\1033\CLUI.DLL'
  965. was modified at 02/21/2011 17:03:30, which is newer than '' which was
  966. modified at 01/01/0001 00:00:00.
  967. The workaround is to specify a workdir when instantiating the test, e.g.
  968. test = TestGyp.TestGyp(workdir='workarea')
  969. """
  970. result = self.build(gyp_file, target, **kw)
  971. if not result:
  972. stdout = self.stdout()
  973. m = self.up_to_date_re.search(stdout)
  974. up_to_date = m and int(m.group(1)) > 0
  975. if not up_to_date:
  976. self.report_not_up_to_date()
  977. self.fail_test()
  978. return result
  979. def run_built_executable(self, name, *args, **kw):
  980. """
  981. Runs an executable built by Visual Studio.
  982. """
  983. configuration = self.configuration_dirname()
  984. # Enclosing the name in a list avoids prepending the original dir.
  985. program = [self.built_file_path(name, type=self.EXECUTABLE, **kw)]
  986. return self.run(program=program, *args, **kw)
  987. def built_file_path(self, name, type=None, **kw):
  988. """
  989. Returns a path to the specified file name, of the specified type,
  990. as built by Visual Studio.
  991. Built files are in a subdirectory that matches the configuration
  992. name. The default is 'Default'.
  993. A chdir= keyword argument specifies the source directory
  994. relative to which the output subdirectory can be found.
  995. "type" values of STATIC_LIB or SHARED_LIB append the necessary
  996. prefixes and suffixes to a platform-independent library base name.
  997. """
  998. result = []
  999. chdir = kw.get('chdir')
  1000. if chdir:
  1001. result.append(chdir)
  1002. result.append(self.configuration_dirname())
  1003. if type == self.STATIC_LIB:
  1004. result.append('lib')
  1005. result.append(self.built_file_basename(name, type, **kw))
  1006. return self.workpath(*result)
  1007. class TestGypMSVSNinja(TestGypNinja):
  1008. """
  1009. Subclass for testing the GYP Visual Studio Ninja generator.
  1010. """
  1011. format = 'msvs-ninja'
  1012. def initialize_build_tool(self):
  1013. super(TestGypMSVSNinja, self).initialize_build_tool()
  1014. # When using '--build', make sure ninja is first in the format list.
  1015. self.formats.insert(0, 'ninja')
  1016. def build(self, gyp_file, target=None, rebuild=False, clean=False, **kw):
  1017. """
  1018. Runs a Visual Studio build using the configuration generated
  1019. from the specified gyp_file.
  1020. """
  1021. arguments = kw.get('arguments', [])[:]
  1022. if target in (None, self.ALL, self.DEFAULT):
  1023. # Note: the Visual Studio generator doesn't add an explicit 'all' target.
  1024. # This will build each project. This will work if projects are hermetic,
  1025. # but may fail if they are not (a project may run more than once).
  1026. # It would be nice to supply an all.metaproj for MSBuild.
  1027. arguments.extend([gyp_file.replace('.gyp', '.sln')])
  1028. else:
  1029. # MSBuild documentation claims that one can specify a sln but then build a
  1030. # project target like 'msbuild a.sln /t:proj:target' but this format only
  1031. # supports 'Clean', 'Rebuild', and 'Publish' (with none meaning Default).
  1032. # This limitation is due to the .sln -> .sln.metaproj conversion.
  1033. # The ':' is not special, 'proj:target' is a target in the metaproj.
  1034. arguments.extend([target+'.vcxproj'])
  1035. if clean:
  1036. build = 'Clean'
  1037. elif rebuild:
  1038. build = 'Rebuild'
  1039. else:
  1040. build = 'Build'
  1041. arguments.extend(['/target:'+build])
  1042. configuration = self.configuration_buildname()
  1043. config = configuration.split('|')
  1044. arguments.extend(['/property:Configuration='+config[0]])
  1045. if len(config) > 1:
  1046. arguments.extend(['/property:Platform='+config[1]])
  1047. arguments.extend(['/property:BuildInParallel=false'])
  1048. arguments.extend(['/verbosity:minimal'])
  1049. kw['arguments'] = arguments
  1050. return self.run(program=self.msbuild_path, **kw)
  1051. class TestGypXcode(TestGypBase):
  1052. """
  1053. Subclass for testing the GYP Xcode generator.
  1054. """
  1055. format = 'xcode'
  1056. build_tool_list = ['xcodebuild']
  1057. phase_script_execution = ("\n"
  1058. "PhaseScriptExecution /\\S+/Script-[0-9A-F]+\\.sh\n"
  1059. " cd /\\S+\n"
  1060. " /bin/sh -c /\\S+/Script-[0-9A-F]+\\.sh\n"
  1061. "(make: Nothing to be done for `all'\\.\n)?")
  1062. strip_up_to_date_expressions = [
  1063. # Various actions or rules can run even when the overall build target
  1064. # is up to date. Strip those phases' GYP-generated output.
  1065. re.compile(phase_script_execution, re.S),
  1066. # The message from distcc_pump can trail the "BUILD SUCCEEDED"
  1067. # message, so strip that, too.
  1068. re.compile('__________Shutting down distcc-pump include server\n', re.S),
  1069. ]
  1070. up_to_date_endings = (
  1071. 'Checking Dependencies...\n** BUILD SUCCEEDED **\n', # Xcode 3.0/3.1
  1072. 'Check dependencies\n** BUILD SUCCEEDED **\n\n', # Xcode 3.2
  1073. 'Check dependencies\n\n\n** BUILD SUCCEEDED **\n\n', # Xcode 4.2
  1074. 'Check dependencies\n\n** BUILD SUCCEEDED **\n\n', # Xcode 5.0
  1075. )
  1076. def build(self, gyp_file, target=None, **kw):
  1077. """
  1078. Runs an xcodebuild using the .xcodeproj generated from the specified
  1079. gyp_file.
  1080. """
  1081. # Be sure we're working with a copy of 'arguments' since we modify it.
  1082. # The caller may not be expecting it to be modified.
  1083. arguments = kw.get('arguments', [])[:]
  1084. arguments.extend(['-project', gyp_file.replace('.gyp', '.xcodeproj')])
  1085. if target == self.ALL:
  1086. arguments.append('-alltargets',)
  1087. elif target not in (None, self.DEFAULT):
  1088. arguments.extend(['-target', target])
  1089. if self.configuration:
  1090. arguments.extend(['-configuration', self.configuration])
  1091. symroot = kw.get('SYMROOT', '$SRCROOT/build')
  1092. if symroot:
  1093. arguments.append('SYMROOT='+symroot)
  1094. kw['arguments'] = arguments
  1095. # Work around spurious stderr output from Xcode 4, http://crbug.com/181012
  1096. match = kw.pop('match', self.match)
  1097. def match_filter_xcode(actual, expected):
  1098. if actual:
  1099. if not TestCmd.is_List(actual):
  1100. actual = actual.split('\n')
  1101. if not TestCmd.is_List(expected):
  1102. expected = expected.split('\n')
  1103. actual = [a for a in actual
  1104. if 'No recorder, buildTask: <Xcode3BuildTask:' not in a]
  1105. return match(actual, expected)
  1106. kw['match'] = match_filter_xcode
  1107. return self.run(program=self.build_tool, **kw)
  1108. def up_to_date(self, gyp_file, target=None, **kw):
  1109. """
  1110. Verifies that a build of the specified Xcode target is up to date.
  1111. """
  1112. result = self.build(gyp_file, target, **kw)
  1113. if not result:
  1114. output = self.stdout()
  1115. for expression in self.strip_up_to_date_expressions:
  1116. output = expression.sub('', output)
  1117. if not output.endswith(self.up_to_date_endings):
  1118. self.report_not_up_to_date()
  1119. self.fail_test()
  1120. return result
  1121. def run_built_executable(self, name, *args, **kw):
  1122. """
  1123. Runs an executable built by xcodebuild.
  1124. """
  1125. configuration = self.configuration_dirname()
  1126. os.environ['DYLD_LIBRARY_PATH'] = os.path.join('build', configuration)
  1127. # Enclosing the name in a list avoids prepending the original dir.
  1128. program = [self.built_file_path(name, type=self.EXECUTABLE, **kw)]
  1129. return self.run(program=program, *args, **kw)
  1130. def built_file_path(self, name, type=None, **kw):
  1131. """
  1132. Returns a path to the specified file name, of the specified type,
  1133. as built by Xcode.
  1134. Built files are in the subdirectory 'build/{configuration}'.
  1135. The default is 'build/Default'.
  1136. A chdir= keyword argument specifies the source directory
  1137. relative to which the output subdirectory can be found.
  1138. "type" values of STATIC_LIB or SHARED_LIB append the necessary
  1139. prefixes and suffixes to a platform-independent library base name.
  1140. """
  1141. result = []
  1142. chdir = kw.get('chdir')
  1143. if chdir:
  1144. result.append(chdir)
  1145. configuration = self.configuration_dirname()
  1146. result.extend(['build', configuration])
  1147. result.append(self.built_file_basename(name, type, **kw))
  1148. return self.workpath(*result)
  1149. class TestGypXcodeNinja(TestGypXcode):
  1150. """
  1151. Subclass for testing the GYP Xcode Ninja generator.
  1152. """
  1153. format = 'xcode-ninja'
  1154. def initialize_build_tool(self):
  1155. super(TestGypXcodeNinja, self).initialize_build_tool()
  1156. # When using '--build', make sure ninja is first in the format list.
  1157. self.formats.insert(0, 'ninja')
  1158. def build(self, gyp_file, target=None, **kw):
  1159. """
  1160. Runs an xcodebuild using the .xcodeproj generated from the specified
  1161. gyp_file.
  1162. """
  1163. build_config = self.configuration
  1164. if build_config and build_config.endswith(('-iphoneos',
  1165. '-iphonesimulator')):
  1166. build_config, sdk = self.configuration.split('-')
  1167. kw['arguments'] = kw.get('arguments', []) + ['-sdk', sdk]
  1168. with self._build_configuration(build_config):
  1169. return super(TestGypXcodeNinja, self).build(
  1170. gyp_file.replace('.gyp', '.ninja.gyp'), target, **kw)
  1171. @contextmanager
  1172. def _build_configuration(self, build_config):
  1173. config = self.configuration
  1174. self.configuration = build_config
  1175. try:
  1176. yield
  1177. finally:
  1178. self.configuration = config
  1179. def built_file_path(self, name, type=None, **kw):
  1180. result = []
  1181. chdir = kw.get('chdir')
  1182. if chdir:
  1183. result.append(chdir)
  1184. result.append('out')
  1185. result.append(self.configuration_dirname())
  1186. subdir = kw.get('subdir')
  1187. if subdir and type != self.SHARED_LIB:
  1188. result.append(subdir)
  1189. result.append(self.built_file_basename(name, type, **kw))
  1190. return self.workpath(*result)
  1191. def up_to_date(self, gyp_file, target=None, **kw):
  1192. result = self.build(gyp_file, target, **kw)
  1193. if not result:
  1194. stdout = self.stdout()
  1195. if 'ninja: no work to do' not in stdout:
  1196. self.report_not_up_to_date()
  1197. self.fail_test()
  1198. return result
  1199. def run_built_executable(self, name, *args, **kw):
  1200. """
  1201. Runs an executable built by xcodebuild + ninja.
  1202. """
  1203. configuration = self.configuration_dirname()
  1204. os.environ['DYLD_LIBRARY_PATH'] = os.path.join('out', configuration)
  1205. # Enclosing the name in a list avoids prepending the original dir.
  1206. program = [self.built_file_path(name, type=self.EXECUTABLE, **kw)]
  1207. return self.run(program=program, *args, **kw)
  1208. format_class_list = [
  1209. TestGypGypd,
  1210. TestGypAndroid,
  1211. TestGypCMake,
  1212. TestGypMake,
  1213. TestGypMSVS,
  1214. TestGypMSVSNinja,
  1215. TestGypNinja,
  1216. TestGypXcode,
  1217. TestGypXcodeNinja,
  1218. ]
  1219. def TestGyp(*args, **kw):
  1220. """
  1221. Returns an appropriate TestGyp* instance for a specified GYP format.
  1222. """
  1223. format = kw.pop('format', os.environ.get('TESTGYP_FORMAT'))
  1224. for format_class in format_class_list:
  1225. if format == format_class.format:
  1226. return format_class(*args, **kw)
  1227. raise Exception, "unknown format %r" % format