native_tests.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. from __future__ import print_function
  2. import os
  3. import subprocess
  4. import sys
  5. from lib.util import SRC_DIR
  6. PYYAML_LIB_DIR = os.path.join(SRC_DIR, 'third_party', 'pyyaml', 'lib')
  7. sys.path.append(PYYAML_LIB_DIR)
  8. import yaml #pylint: disable=wrong-import-position,wrong-import-order
  9. try:
  10. basestring # Python 2
  11. except NameError: # Python 3
  12. basestring = str # pylint: disable=redefined-builtin
  13. class Verbosity:
  14. CHATTY = 'chatty' # stdout and stderr
  15. ERRORS = 'errors' # stderr only
  16. SILENT = 'silent' # no output
  17. @staticmethod
  18. def get_all():
  19. return Verbosity.__get_all_in_order()
  20. @staticmethod
  21. def __get_all_in_order():
  22. return [Verbosity.SILENT, Verbosity.ERRORS, Verbosity.CHATTY]
  23. @staticmethod
  24. def __get_indices(*values):
  25. ordered = Verbosity.__get_all_in_order()
  26. indices = map(ordered.index, values)
  27. return indices
  28. @staticmethod
  29. def ge(a, b):
  30. """Greater or equal"""
  31. a_index, b_index = Verbosity.__get_indices(a, b)
  32. return a_index >= b_index
  33. @staticmethod
  34. def le(a, b):
  35. """Less or equal"""
  36. a_index, b_index = Verbosity.__get_indices(a, b)
  37. return a_index <= b_index
  38. class DisabledTestsPolicy:
  39. DISABLE = 'disable' # Disabled tests are disabled. Wow. Much sense.
  40. ONLY = 'only' # Only disabled tests should be run.
  41. INCLUDE = 'include' # Do not disable any tests.
  42. class Platform:
  43. LINUX = 'linux'
  44. MAC = 'mac'
  45. WINDOWS = 'windows'
  46. @staticmethod
  47. def get_current():
  48. platform = sys.platform
  49. if platform in ('linux', 'linux2'):
  50. return Platform.LINUX
  51. if platform == 'darwin':
  52. return Platform.MAC
  53. if platform in ('cygwin', 'win32'):
  54. return Platform.WINDOWS
  55. assert False, "unexpected current platform '{}'".format(platform)
  56. @staticmethod
  57. def get_all():
  58. return [Platform.LINUX, Platform.MAC, Platform.WINDOWS]
  59. @staticmethod
  60. def is_valid(platform):
  61. return platform in Platform.get_all()
  62. class TestsList():
  63. def __init__(self, config_path, tests_dir):
  64. self.config_path = config_path
  65. self.tests_dir = tests_dir
  66. # A dict with binary names (e.g. 'base_unittests') as keys
  67. # and various test data as values of dict type.
  68. self.tests = TestsList.__get_tests_list(config_path)
  69. def __len__(self):
  70. return len(self.tests)
  71. def get_for_current_platform(self):
  72. all_binaries = self.tests.keys()
  73. supported_binaries = filter(self.__platform_supports, all_binaries)
  74. return supported_binaries
  75. def run(self, binaries, output_dir=None, verbosity=Verbosity.CHATTY,
  76. disabled_tests_policy=DisabledTestsPolicy.DISABLE):
  77. # Don't run anything twice.
  78. binaries = set(binaries)
  79. # First check that all names are present in the config.
  80. for binary_name in binaries:
  81. if binary_name not in self.tests:
  82. raise Exception("binary {0} not found in config '{1}'".format(
  83. binary_name, self.config_path))
  84. # Respect the "platform" setting.
  85. for binary_name in binaries:
  86. if not self.__platform_supports(binary_name):
  87. raise Exception(
  88. "binary {0} cannot be run on {1}, check the config".format(
  89. binary_name, Platform.get_current()))
  90. suite_returncode = sum(
  91. [self.__run(binary, output_dir, verbosity, disabled_tests_policy)
  92. for binary in binaries])
  93. return suite_returncode
  94. def run_only(self, binary_name, output_dir=None, verbosity=Verbosity.CHATTY,
  95. disabled_tests_policy=DisabledTestsPolicy.DISABLE):
  96. return self.run([binary_name], output_dir, verbosity,
  97. disabled_tests_policy)
  98. def run_all(self, output_dir=None, verbosity=Verbosity.CHATTY,
  99. disabled_tests_policy=DisabledTestsPolicy.DISABLE):
  100. return self.run(self.get_for_current_platform(), output_dir, verbosity,
  101. disabled_tests_policy)
  102. @staticmethod
  103. def __get_tests_list(config_path):
  104. tests_list = {}
  105. config_data = TestsList.__get_config_data(config_path)
  106. for data_item in config_data['tests']:
  107. (binary_name, test_data) = TestsList.__get_test_data(data_item)
  108. tests_list[binary_name] = test_data
  109. return tests_list
  110. @staticmethod
  111. def __get_config_data(config_path):
  112. with open(config_path, 'r') as stream:
  113. return yaml.load(stream)
  114. @staticmethod
  115. def __expand_shorthand(value):
  116. """ Treat a string as {'string_value': None}."""
  117. if isinstance(value, dict):
  118. return value
  119. if isinstance(value, basestring):
  120. return {value: None}
  121. assert False, "unexpected shorthand type: {}".format(type(value))
  122. @staticmethod
  123. def __make_a_list(value):
  124. """Make a list if not already a list."""
  125. if isinstance(value, list):
  126. return value
  127. return [value]
  128. @staticmethod
  129. def __merge_nested_lists(value):
  130. """Converts a dict of lists to a list."""
  131. if isinstance(value, list):
  132. return value
  133. if isinstance(value, dict):
  134. # It looks ugly as hell, but it does the job.
  135. return [list_item for key in value for list_item in value[key]]
  136. assert False, "unexpected type for list merging: {}".format(type(value))
  137. def __platform_supports(self, binary_name):
  138. return Platform.get_current() in self.tests[binary_name]['platforms']
  139. @staticmethod
  140. def __get_test_data(data_item):
  141. data_item = TestsList.__expand_shorthand(data_item)
  142. binary_name = data_item.keys()[0]
  143. test_data = {
  144. 'excluded_tests': [],
  145. 'platforms': Platform.get_all()
  146. }
  147. configs = data_item[binary_name]
  148. if configs is not None:
  149. # List of excluded tests.
  150. if 'disabled' in configs:
  151. excluded_tests = TestsList.__merge_nested_lists(configs['disabled'])
  152. test_data['excluded_tests'] = excluded_tests
  153. # List of platforms to run the tests on.
  154. if 'platform' in configs:
  155. platforms = TestsList.__make_a_list(configs['platform'])
  156. for platform in platforms:
  157. assert Platform.is_valid(platform), \
  158. "platform '{0}' is not supported, check {1} config" \
  159. .format(platform, binary_name)
  160. test_data['platforms'] = platforms
  161. return (binary_name, test_data)
  162. def __run(self, binary_name, output_dir, verbosity,
  163. disabled_tests_policy):
  164. binary_path = os.path.join(self.tests_dir, binary_name)
  165. test_binary = TestBinary(binary_path)
  166. test_data = self.tests[binary_name]
  167. included_tests = []
  168. excluded_tests = test_data['excluded_tests']
  169. if disabled_tests_policy == DisabledTestsPolicy.ONLY:
  170. if len(excluded_tests) == 0:
  171. # There is nothing to run.
  172. return 0
  173. included_tests, excluded_tests = excluded_tests, included_tests
  174. if disabled_tests_policy == DisabledTestsPolicy.INCLUDE:
  175. excluded_tests = []
  176. output_file_path = TestsList.__get_output_path(binary_name, output_dir)
  177. return test_binary.run(included_tests=included_tests,
  178. excluded_tests=excluded_tests,
  179. output_file_path=output_file_path,
  180. verbosity=verbosity)
  181. @staticmethod
  182. def __get_output_path(binary_name, output_dir=None):
  183. if output_dir is None:
  184. return None
  185. return os.path.join(output_dir, "results_{}.xml".format(binary_name))
  186. class TestBinary():
  187. # Is only used when writing to a file.
  188. output_format = 'xml'
  189. def __init__(self, binary_path):
  190. self.binary_path = binary_path
  191. def run(self, included_tests=None, excluded_tests=None,
  192. output_file_path=None, verbosity=Verbosity.CHATTY):
  193. gtest_filter = TestBinary.__get_gtest_filter(included_tests,
  194. excluded_tests)
  195. gtest_output = TestBinary.__get_gtest_output(output_file_path)
  196. args = [self.binary_path, gtest_filter, gtest_output]
  197. stdout, stderr = TestBinary.__get_stdout_and_stderr(verbosity)
  198. returncode = 0
  199. try:
  200. returncode = subprocess.call(args, stdout=stdout, stderr=stderr)
  201. except Exception as exception:
  202. if Verbosity.ge(verbosity, Verbosity.ERRORS):
  203. print("An error occurred while running '{}':".format(self.binary_path),
  204. '\n', exception, file=sys.stderr)
  205. returncode = 1
  206. return returncode
  207. @staticmethod
  208. def __get_gtest_filter(included_tests, excluded_tests):
  209. included_tests_string = TestBinary.__list_tests(included_tests)
  210. excluded_tests_string = TestBinary.__list_tests(excluded_tests)
  211. gtest_filter = "--gtest_filter={}-{}".format(included_tests_string,
  212. excluded_tests_string)
  213. return gtest_filter
  214. @staticmethod
  215. def __get_gtest_output(output_file_path):
  216. gtest_output = ""
  217. if output_file_path is not None:
  218. gtest_output = "--gtest_output={0}:{1}".format(TestBinary.output_format,
  219. output_file_path)
  220. return gtest_output
  221. @staticmethod
  222. def __list_tests(tests):
  223. if tests is None:
  224. return ''
  225. return ':'.join(tests)
  226. @staticmethod
  227. def __get_stdout_and_stderr(verbosity):
  228. stdout = stderr = None
  229. if Verbosity.le(verbosity, Verbosity.ERRORS):
  230. devnull = open(os.devnull, 'w')
  231. stdout = devnull
  232. if verbosity == Verbosity.SILENT:
  233. stderr = devnull
  234. return (stdout, stderr)