gyptest.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. #!/usr/bin/env python
  2. # Copyright (c) 2012 Google Inc. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. __doc__ = """
  6. gyptest.py -- test runner for GYP tests.
  7. """
  8. import os
  9. import optparse
  10. import subprocess
  11. import sys
  12. class CommandRunner(object):
  13. """
  14. Executor class for commands, including "commands" implemented by
  15. Python functions.
  16. """
  17. verbose = True
  18. active = True
  19. def __init__(self, dictionary={}):
  20. self.subst_dictionary(dictionary)
  21. def subst_dictionary(self, dictionary):
  22. self._subst_dictionary = dictionary
  23. def subst(self, string, dictionary=None):
  24. """
  25. Substitutes (via the format operator) the values in the specified
  26. dictionary into the specified command.
  27. The command can be an (action, string) tuple. In all cases, we
  28. perform substitution on strings and don't worry if something isn't
  29. a string. (It's probably a Python function to be executed.)
  30. """
  31. if dictionary is None:
  32. dictionary = self._subst_dictionary
  33. if dictionary:
  34. try:
  35. string = string % dictionary
  36. except TypeError:
  37. pass
  38. return string
  39. def display(self, command, stdout=None, stderr=None):
  40. if not self.verbose:
  41. return
  42. if type(command) == type(()):
  43. func = command[0]
  44. args = command[1:]
  45. s = '%s(%s)' % (func.__name__, ', '.join(map(repr, args)))
  46. if type(command) == type([]):
  47. # TODO: quote arguments containing spaces
  48. # TODO: handle meta characters?
  49. s = ' '.join(command)
  50. else:
  51. s = self.subst(command)
  52. if not s.endswith('\n'):
  53. s += '\n'
  54. sys.stdout.write(s)
  55. sys.stdout.flush()
  56. def execute(self, command, stdout=None, stderr=None):
  57. """
  58. Executes a single command.
  59. """
  60. if not self.active:
  61. return 0
  62. if type(command) == type(''):
  63. command = self.subst(command)
  64. cmdargs = shlex.split(command)
  65. if cmdargs[0] == 'cd':
  66. command = (os.chdir,) + tuple(cmdargs[1:])
  67. if type(command) == type(()):
  68. func = command[0]
  69. args = command[1:]
  70. return func(*args)
  71. else:
  72. if stdout is sys.stdout:
  73. # Same as passing sys.stdout, except python2.4 doesn't fail on it.
  74. subout = None
  75. else:
  76. # Open pipe for anything else so Popen works on python2.4.
  77. subout = subprocess.PIPE
  78. if stderr is sys.stderr:
  79. # Same as passing sys.stderr, except python2.4 doesn't fail on it.
  80. suberr = None
  81. elif stderr is None:
  82. # Merge with stdout if stderr isn't specified.
  83. suberr = subprocess.STDOUT
  84. else:
  85. # Open pipe for anything else so Popen works on python2.4.
  86. suberr = subprocess.PIPE
  87. p = subprocess.Popen(command,
  88. shell=(sys.platform == 'win32'),
  89. stdout=subout,
  90. stderr=suberr)
  91. p.wait()
  92. if stdout is None:
  93. self.stdout = p.stdout.read()
  94. elif stdout is not sys.stdout:
  95. stdout.write(p.stdout.read())
  96. if stderr not in (None, sys.stderr):
  97. stderr.write(p.stderr.read())
  98. return p.returncode
  99. def run(self, command, display=None, stdout=None, stderr=None):
  100. """
  101. Runs a single command, displaying it first.
  102. """
  103. if display is None:
  104. display = command
  105. self.display(display)
  106. return self.execute(command, stdout, stderr)
  107. class Unbuffered(object):
  108. def __init__(self, fp):
  109. self.fp = fp
  110. def write(self, arg):
  111. self.fp.write(arg)
  112. self.fp.flush()
  113. def __getattr__(self, attr):
  114. return getattr(self.fp, attr)
  115. sys.stdout = Unbuffered(sys.stdout)
  116. sys.stderr = Unbuffered(sys.stderr)
  117. def is_test_name(f):
  118. return f.startswith('gyptest') and f.endswith('.py')
  119. def find_all_gyptest_files(directory):
  120. result = []
  121. for root, dirs, files in os.walk(directory):
  122. if '.svn' in dirs:
  123. dirs.remove('.svn')
  124. result.extend([ os.path.join(root, f) for f in files if is_test_name(f) ])
  125. result.sort()
  126. return result
  127. def main(argv=None):
  128. if argv is None:
  129. argv = sys.argv
  130. usage = "gyptest.py [-ahlnq] [-f formats] [test ...]"
  131. parser = optparse.OptionParser(usage=usage)
  132. parser.add_option("-a", "--all", action="store_true",
  133. help="run all tests")
  134. parser.add_option("-C", "--chdir", action="store", default=None,
  135. help="chdir to the specified directory")
  136. parser.add_option("-f", "--format", action="store", default='',
  137. help="run tests with the specified formats")
  138. parser.add_option("-G", '--gyp_option', action="append", default=[],
  139. help="Add -G options to the gyp command line")
  140. parser.add_option("-l", "--list", action="store_true",
  141. help="list available tests and exit")
  142. parser.add_option("-n", "--no-exec", action="store_true",
  143. help="no execute, just print the command line")
  144. parser.add_option("--passed", action="store_true",
  145. help="report passed tests")
  146. parser.add_option("--path", action="append", default=[],
  147. help="additional $PATH directory")
  148. parser.add_option("-q", "--quiet", action="store_true",
  149. help="quiet, don't print test command lines")
  150. opts, args = parser.parse_args(argv[1:])
  151. if opts.chdir:
  152. os.chdir(opts.chdir)
  153. if opts.path:
  154. extra_path = [os.path.abspath(p) for p in opts.path]
  155. extra_path = os.pathsep.join(extra_path)
  156. os.environ['PATH'] = extra_path + os.pathsep + os.environ['PATH']
  157. if not args:
  158. if not opts.all:
  159. sys.stderr.write('Specify -a to get all tests.\n')
  160. return 1
  161. args = ['test']
  162. tests = []
  163. for arg in args:
  164. if os.path.isdir(arg):
  165. tests.extend(find_all_gyptest_files(os.path.normpath(arg)))
  166. else:
  167. if not is_test_name(os.path.basename(arg)):
  168. print >>sys.stderr, arg, 'is not a valid gyp test name.'
  169. sys.exit(1)
  170. tests.append(arg)
  171. if opts.list:
  172. for test in tests:
  173. print test
  174. sys.exit(0)
  175. CommandRunner.verbose = not opts.quiet
  176. CommandRunner.active = not opts.no_exec
  177. cr = CommandRunner()
  178. os.environ['PYTHONPATH'] = os.path.abspath('test/lib')
  179. if not opts.quiet:
  180. sys.stdout.write('PYTHONPATH=%s\n' % os.environ['PYTHONPATH'])
  181. passed = []
  182. failed = []
  183. no_result = []
  184. if opts.format:
  185. format_list = opts.format.split(',')
  186. else:
  187. # TODO: not duplicate this mapping from pylib/gyp/__init__.py
  188. format_list = {
  189. 'aix5': ['make'],
  190. 'freebsd7': ['make'],
  191. 'freebsd8': ['make'],
  192. 'openbsd5': ['make'],
  193. 'cygwin': ['msvs'],
  194. 'win32': ['msvs', 'ninja'],
  195. 'linux2': ['make', 'ninja'],
  196. 'linux3': ['make', 'ninja'],
  197. 'darwin': ['make', 'ninja', 'xcode', 'xcode-ninja'],
  198. }[sys.platform]
  199. for format in format_list:
  200. os.environ['TESTGYP_FORMAT'] = format
  201. if not opts.quiet:
  202. sys.stdout.write('TESTGYP_FORMAT=%s\n' % format)
  203. gyp_options = []
  204. for option in opts.gyp_option:
  205. gyp_options += ['-G', option]
  206. if gyp_options and not opts.quiet:
  207. sys.stdout.write('Extra Gyp options: %s\n' % gyp_options)
  208. for test in tests:
  209. status = cr.run([sys.executable, test] + gyp_options,
  210. stdout=sys.stdout,
  211. stderr=sys.stderr)
  212. if status == 2:
  213. no_result.append(test)
  214. elif status:
  215. failed.append(test)
  216. else:
  217. passed.append(test)
  218. if not opts.quiet:
  219. def report(description, tests):
  220. if tests:
  221. if len(tests) == 1:
  222. sys.stdout.write("\n%s the following test:\n" % description)
  223. else:
  224. fmt = "\n%s the following %d tests:\n"
  225. sys.stdout.write(fmt % (description, len(tests)))
  226. sys.stdout.write("\t" + "\n\t".join(tests) + "\n")
  227. if opts.passed:
  228. report("Passed", passed)
  229. report("Failed", failed)
  230. report("No result from", no_result)
  231. if failed:
  232. return 1
  233. else:
  234. return 0
  235. if __name__ == "__main__":
  236. sys.exit(main())