test_expectations.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. # Copyright (C) 2010 Google Inc. All rights reserved.
  2. #
  3. # Redistribution and use in source and binary forms, with or without
  4. # modification, are permitted provided that the following conditions are
  5. # met:
  6. #
  7. # * Redistributions of source code must retain the above copyright
  8. # notice, this list of conditions and the following disclaimer.
  9. # * Redistributions in binary form must reproduce the above
  10. # copyright notice, this list of conditions and the following disclaimer
  11. # in the documentation and/or other materials provided with the
  12. # distribution.
  13. # * Neither the name of Google Inc. nor the names of its
  14. # contributors may be used to endorse or promote products derived from
  15. # this software without specific prior written permission.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  20. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  21. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  22. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  23. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  24. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  25. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  27. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. """A helper class for reading in and dealing with tests expectations
  29. for layout tests.
  30. """
  31. import logging
  32. import re
  33. from webkitpy.layout_tests.models.test_configuration import TestConfigurationConverter
  34. _log = logging.getLogger(__name__)
  35. # Test expectation and modifier constants.
  36. #
  37. # FIXME: range() starts with 0 which makes if expectation checks harder
  38. # as PASS is 0.
  39. (PASS, FAIL, TEXT, IMAGE, IMAGE_PLUS_TEXT, AUDIO, TIMEOUT, CRASH, SKIP, WONTFIX,
  40. SLOW, REBASELINE, MISSING, FLAKY, NOW, NONE) = range(16)
  41. # FIXME: Perhas these two routines should be part of the Port instead?
  42. BASELINE_SUFFIX_LIST = ('png', 'wav', 'txt')
  43. class ParseError(Exception):
  44. def __init__(self, warnings):
  45. super(ParseError, self).__init__()
  46. self.warnings = warnings
  47. def __str__(self):
  48. return '\n'.join(map(str, self.warnings))
  49. def __repr__(self):
  50. return 'ParseError(warnings=%s)' % self.warnings
  51. class TestExpectationParser(object):
  52. """Provides parsing facilities for lines in the test_expectation.txt file."""
  53. DUMMY_BUG_MODIFIER = "bug_dummy"
  54. BUG_MODIFIER_PREFIX = 'bug'
  55. BUG_MODIFIER_REGEX = 'bug\d+'
  56. REBASELINE_MODIFIER = 'rebaseline'
  57. PASS_EXPECTATION = 'pass'
  58. SKIP_MODIFIER = 'skip'
  59. SLOW_MODIFIER = 'slow'
  60. WONTFIX_MODIFIER = 'wontfix'
  61. TIMEOUT_EXPECTATION = 'timeout'
  62. MISSING_BUG_WARNING = 'Test lacks BUG modifier.'
  63. def __init__(self, port, full_test_list, allow_rebaseline_modifier):
  64. self._port = port
  65. self._test_configuration_converter = TestConfigurationConverter(set(port.all_test_configurations()), port.configuration_specifier_macros())
  66. self._full_test_list = full_test_list
  67. self._allow_rebaseline_modifier = allow_rebaseline_modifier
  68. def parse(self, filename, expectations_string):
  69. expectation_lines = []
  70. line_number = 0
  71. for line in expectations_string.split("\n"):
  72. line_number += 1
  73. test_expectation = self._tokenize_line(filename, line, line_number)
  74. self._parse_line(test_expectation)
  75. expectation_lines.append(test_expectation)
  76. return expectation_lines
  77. def expectation_for_skipped_test(self, test_name):
  78. if not self._port.test_exists(test_name):
  79. _log.warning('The following test %s from the Skipped list doesn\'t exist' % test_name)
  80. expectation_line = TestExpectationLine()
  81. expectation_line.original_string = test_name
  82. expectation_line.modifiers = [TestExpectationParser.DUMMY_BUG_MODIFIER, TestExpectationParser.SKIP_MODIFIER]
  83. # FIXME: It's not clear what the expectations for a skipped test should be; the expectations
  84. # might be different for different entries in a Skipped file, or from the command line, or from
  85. # only running parts of the tests. It's also not clear if it matters much.
  86. expectation_line.modifiers.append(TestExpectationParser.WONTFIX_MODIFIER)
  87. expectation_line.name = test_name
  88. # FIXME: we should pass in a more descriptive string here.
  89. expectation_line.filename = '<Skipped file>'
  90. expectation_line.line_number = 0
  91. expectation_line.expectations = [TestExpectationParser.PASS_EXPECTATION]
  92. self._parse_line(expectation_line)
  93. return expectation_line
  94. def _parse_line(self, expectation_line):
  95. if not expectation_line.name:
  96. return
  97. if not self._check_test_exists(expectation_line):
  98. return
  99. expectation_line.is_file = self._port.test_isfile(expectation_line.name)
  100. if expectation_line.is_file:
  101. expectation_line.path = expectation_line.name
  102. else:
  103. expectation_line.path = self._port.normalize_test_name(expectation_line.name)
  104. self._collect_matching_tests(expectation_line)
  105. self._parse_modifiers(expectation_line)
  106. self._parse_expectations(expectation_line)
  107. def _parse_modifiers(self, expectation_line):
  108. has_wontfix = False
  109. has_bugid = False
  110. parsed_specifiers = set()
  111. modifiers = [modifier.lower() for modifier in expectation_line.modifiers]
  112. expectations = [expectation.lower() for expectation in expectation_line.expectations]
  113. if self.SLOW_MODIFIER in modifiers and self.TIMEOUT_EXPECTATION in expectations:
  114. expectation_line.warnings.append('A test can not be both SLOW and TIMEOUT. If it times out indefinitely, then it should be just TIMEOUT.')
  115. for modifier in modifiers:
  116. if modifier in TestExpectations.MODIFIERS:
  117. expectation_line.parsed_modifiers.append(modifier)
  118. if modifier == self.WONTFIX_MODIFIER:
  119. has_wontfix = True
  120. elif modifier.startswith(self.BUG_MODIFIER_PREFIX):
  121. has_bugid = True
  122. if re.match(self.BUG_MODIFIER_REGEX, modifier):
  123. expectation_line.warnings.append('BUG\d+ is not allowed, must be one of BUGCR\d+, BUGWK\d+, BUGV8_\d+, or a non-numeric bug identifier.')
  124. else:
  125. expectation_line.parsed_bug_modifiers.append(modifier)
  126. else:
  127. parsed_specifiers.add(modifier)
  128. if not expectation_line.parsed_bug_modifiers and not has_wontfix and not has_bugid and self._port.warn_if_bug_missing_in_test_expectations():
  129. expectation_line.warnings.append(self.MISSING_BUG_WARNING)
  130. if self._allow_rebaseline_modifier and self.REBASELINE_MODIFIER in modifiers:
  131. expectation_line.warnings.append('REBASELINE should only be used for running rebaseline.py. Cannot be checked in.')
  132. expectation_line.matching_configurations = self._test_configuration_converter.to_config_set(parsed_specifiers, expectation_line.warnings)
  133. def _parse_expectations(self, expectation_line):
  134. result = set()
  135. for part in expectation_line.expectations:
  136. expectation = TestExpectations.expectation_from_string(part)
  137. if expectation is None: # Careful, PASS is currently 0.
  138. expectation_line.warnings.append('Unsupported expectation: %s' % part)
  139. continue
  140. result.add(expectation)
  141. expectation_line.parsed_expectations = result
  142. def _check_test_exists(self, expectation_line):
  143. # WebKit's way of skipping tests is to add a -disabled suffix.
  144. # So we should consider the path existing if the path or the
  145. # -disabled version exists.
  146. if not self._port.test_exists(expectation_line.name) and not self._port.test_exists(expectation_line.name + '-disabled'):
  147. # Log a warning here since you hit this case any
  148. # time you update TestExpectations without syncing
  149. # the LayoutTests directory
  150. expectation_line.warnings.append('Path does not exist.')
  151. return False
  152. return True
  153. def _collect_matching_tests(self, expectation_line):
  154. """Convert the test specification to an absolute, normalized
  155. path and make sure directories end with the OS path separator."""
  156. # FIXME: full_test_list can quickly contain a big amount of
  157. # elements. We should consider at some point to use a more
  158. # efficient structure instead of a list. Maybe a dictionary of
  159. # lists to represent the tree of tests, leaves being test
  160. # files and nodes being categories.
  161. if not self._full_test_list:
  162. expectation_line.matching_tests = [expectation_line.path]
  163. return
  164. if not expectation_line.is_file:
  165. # this is a test category, return all the tests of the category.
  166. expectation_line.matching_tests = [test for test in self._full_test_list if test.startswith(expectation_line.path)]
  167. return
  168. # this is a test file, do a quick check if it's in the
  169. # full test suite.
  170. if expectation_line.path in self._full_test_list:
  171. expectation_line.matching_tests.append(expectation_line.path)
  172. # FIXME: Update the original modifiers and remove this once the old syntax is gone.
  173. _configuration_tokens_list = [
  174. 'Mac', 'SnowLeopard', 'Lion', 'MountainLion',
  175. 'Win', 'XP', 'Vista', 'Win7',
  176. 'Linux',
  177. 'Android',
  178. 'Release',
  179. 'Debug',
  180. ]
  181. _configuration_tokens = dict((token, token.upper()) for token in _configuration_tokens_list)
  182. _inverted_configuration_tokens = dict((value, name) for name, value in _configuration_tokens.iteritems())
  183. # FIXME: Update the original modifiers list and remove this once the old syntax is gone.
  184. _expectation_tokens = {
  185. 'Crash': 'CRASH',
  186. 'Failure': 'FAIL',
  187. 'ImageOnlyFailure': 'IMAGE',
  188. 'Missing': 'MISSING',
  189. 'Pass': 'PASS',
  190. 'Rebaseline': 'REBASELINE',
  191. 'Skip': 'SKIP',
  192. 'Slow': 'SLOW',
  193. 'Timeout': 'TIMEOUT',
  194. 'WontFix': 'WONTFIX',
  195. }
  196. _inverted_expectation_tokens = dict([(value, name) for name, value in _expectation_tokens.iteritems()] +
  197. [('TEXT', 'Failure'), ('IMAGE+TEXT', 'Failure'), ('AUDIO', 'Failure')])
  198. # FIXME: Seems like these should be classmethods on TestExpectationLine instead of TestExpectationParser.
  199. @classmethod
  200. def _tokenize_line(cls, filename, expectation_string, line_number):
  201. """Tokenizes a line from TestExpectations and returns an unparsed TestExpectationLine instance using the old format.
  202. The new format for a test expectation line is:
  203. [[bugs] [ "[" <configuration modifiers> "]" <name> [ "[" <expectations> "]" ["#" <comment>]
  204. Any errant whitespace is not preserved.
  205. """
  206. expectation_line = TestExpectationLine()
  207. expectation_line.original_string = expectation_string
  208. expectation_line.filename = filename
  209. expectation_line.line_number = line_number
  210. comment_index = expectation_string.find("#")
  211. if comment_index == -1:
  212. comment_index = len(expectation_string)
  213. else:
  214. expectation_line.comment = expectation_string[comment_index + 1:]
  215. remaining_string = re.sub(r"\s+", " ", expectation_string[:comment_index].strip())
  216. if len(remaining_string) == 0:
  217. return expectation_line
  218. # special-case parsing this so that we fail immediately instead of treating this as a test name
  219. if remaining_string.startswith('//'):
  220. expectation_line.warnings = ['use "#" instead of "//" for comments']
  221. return expectation_line
  222. bugs = []
  223. modifiers = []
  224. name = None
  225. expectations = []
  226. warnings = []
  227. WEBKIT_BUG_PREFIX = 'webkit.org/b/'
  228. tokens = remaining_string.split()
  229. state = 'start'
  230. for token in tokens:
  231. if token.startswith(WEBKIT_BUG_PREFIX) or token.startswith('Bug('):
  232. if state != 'start':
  233. warnings.append('"%s" is not at the start of the line.' % token)
  234. break
  235. if token.startswith(WEBKIT_BUG_PREFIX):
  236. bugs.append(token.replace(WEBKIT_BUG_PREFIX, 'BUGWK'))
  237. else:
  238. match = re.match('Bug\((\w+)\)$', token)
  239. if not match:
  240. warnings.append('unrecognized bug identifier "%s"' % token)
  241. break
  242. else:
  243. bugs.append('BUG' + match.group(1).upper())
  244. elif token.startswith('BUG'):
  245. warnings.append('unrecognized old-style bug identifier "%s"' % token)
  246. break
  247. elif token == '[':
  248. if state == 'start':
  249. state = 'configuration'
  250. elif state == 'name_found':
  251. state = 'expectations'
  252. else:
  253. warnings.append('unexpected "["')
  254. break
  255. elif token == ']':
  256. if state == 'configuration':
  257. state = 'name'
  258. elif state == 'expectations':
  259. state = 'done'
  260. else:
  261. warnings.append('unexpected "]"')
  262. break
  263. elif token in ('//', ':', '='):
  264. warnings.append('"%s" is not legal in the new TestExpectations syntax.' % token)
  265. break
  266. elif state == 'configuration':
  267. modifiers.append(cls._configuration_tokens.get(token, token))
  268. elif state == 'expectations':
  269. if token in ('Rebaseline', 'Skip', 'Slow', 'WontFix'):
  270. modifiers.append(token.upper())
  271. elif token not in cls._expectation_tokens:
  272. warnings.append('Unrecognized expectation "%s"' % token)
  273. else:
  274. expectations.append(cls._expectation_tokens.get(token, token))
  275. elif state == 'name_found':
  276. warnings.append('expecting "[", "#", or end of line instead of "%s"' % token)
  277. break
  278. else:
  279. name = token
  280. state = 'name_found'
  281. if not warnings:
  282. if not name:
  283. warnings.append('Did not find a test name.')
  284. elif state not in ('name_found', 'done'):
  285. warnings.append('Missing a "]"')
  286. if 'WONTFIX' in modifiers and 'SKIP' not in modifiers and not expectations:
  287. modifiers.append('SKIP')
  288. if 'SKIP' in modifiers and expectations:
  289. # FIXME: This is really a semantic warning and shouldn't be here. Remove when we drop the old syntax.
  290. warnings.append('A test marked Skip must not have other expectations.')
  291. elif not expectations:
  292. if 'SKIP' not in modifiers and 'REBASELINE' not in modifiers and 'SLOW' not in modifiers:
  293. modifiers.append('SKIP')
  294. expectations = ['PASS']
  295. # FIXME: expectation line should just store bugs and modifiers separately.
  296. expectation_line.modifiers = bugs + modifiers
  297. expectation_line.expectations = expectations
  298. expectation_line.name = name
  299. expectation_line.warnings = warnings
  300. return expectation_line
  301. @classmethod
  302. def _split_space_separated(cls, space_separated_string):
  303. """Splits a space-separated string into an array."""
  304. return [part.strip() for part in space_separated_string.strip().split(' ')]
  305. class TestExpectationLine(object):
  306. """Represents a line in test expectations file."""
  307. def __init__(self):
  308. """Initializes a blank-line equivalent of an expectation."""
  309. self.original_string = None
  310. self.filename = None # this is the path to the expectations file for this line
  311. self.line_number = None
  312. self.name = None # this is the path in the line itself
  313. self.path = None # this is the normpath of self.name
  314. self.modifiers = []
  315. self.parsed_modifiers = []
  316. self.parsed_bug_modifiers = []
  317. self.matching_configurations = set()
  318. self.expectations = []
  319. self.parsed_expectations = set()
  320. self.comment = None
  321. self.matching_tests = []
  322. self.warnings = []
  323. def is_invalid(self):
  324. return self.warnings and self.warnings != [TestExpectationParser.MISSING_BUG_WARNING]
  325. def is_flaky(self):
  326. return len(self.parsed_expectations) > 1
  327. @staticmethod
  328. def create_passing_expectation(test):
  329. expectation_line = TestExpectationLine()
  330. expectation_line.name = test
  331. expectation_line.path = test
  332. expectation_line.parsed_expectations = set([PASS])
  333. expectation_line.expectations = set(['PASS'])
  334. expectation_line.matching_tests = [test]
  335. return expectation_line
  336. def to_string(self, test_configuration_converter, include_modifiers=True, include_expectations=True, include_comment=True):
  337. parsed_expectation_to_string = dict([[parsed_expectation, expectation_string] for expectation_string, parsed_expectation in TestExpectations.EXPECTATIONS.items()])
  338. if self.is_invalid():
  339. return self.original_string or ''
  340. if self.name is None:
  341. return '' if self.comment is None else "#%s" % self.comment
  342. if test_configuration_converter and self.parsed_bug_modifiers:
  343. specifiers_list = test_configuration_converter.to_specifiers_list(self.matching_configurations)
  344. result = []
  345. for specifiers in specifiers_list:
  346. # FIXME: this is silly that we join the modifiers and then immediately split them.
  347. modifiers = self._serialize_parsed_modifiers(test_configuration_converter, specifiers).split()
  348. expectations = self._serialize_parsed_expectations(parsed_expectation_to_string).split()
  349. result.append(self._format_line(modifiers, self.name, expectations, self.comment))
  350. return "\n".join(result) if result else None
  351. return self._format_line(self.modifiers, self.name, self.expectations, self.comment,
  352. include_modifiers, include_expectations, include_comment)
  353. def to_csv(self):
  354. # Note that this doesn't include the comments.
  355. return '%s,%s,%s' % (self.name, ' '.join(self.modifiers), ' '.join(self.expectations))
  356. def _serialize_parsed_expectations(self, parsed_expectation_to_string):
  357. result = []
  358. for index in TestExpectations.EXPECTATION_ORDER:
  359. if index in self.parsed_expectations:
  360. result.append(parsed_expectation_to_string[index])
  361. return ' '.join(result)
  362. def _serialize_parsed_modifiers(self, test_configuration_converter, specifiers):
  363. result = []
  364. if self.parsed_bug_modifiers:
  365. result.extend(sorted(self.parsed_bug_modifiers))
  366. result.extend(sorted(self.parsed_modifiers))
  367. result.extend(test_configuration_converter.specifier_sorter().sort_specifiers(specifiers))
  368. return ' '.join(result)
  369. @staticmethod
  370. def _format_line(modifiers, name, expectations, comment, include_modifiers=True, include_expectations=True, include_comment=True):
  371. bugs = []
  372. new_modifiers = []
  373. new_expectations = []
  374. for modifier in modifiers:
  375. modifier = modifier.upper()
  376. if modifier.startswith('BUGWK'):
  377. bugs.append('webkit.org/b/' + modifier.replace('BUGWK', ''))
  378. elif modifier.startswith('BUGCR'):
  379. bugs.append('crbug.com/' + modifier.replace('BUGCR', ''))
  380. elif modifier.startswith('BUG'):
  381. # FIXME: we should preserve case once we can drop the old syntax.
  382. bugs.append('Bug(' + modifier[3:].lower() + ')')
  383. elif modifier in ('SLOW', 'SKIP', 'REBASELINE', 'WONTFIX'):
  384. new_expectations.append(TestExpectationParser._inverted_expectation_tokens.get(modifier))
  385. else:
  386. new_modifiers.append(TestExpectationParser._inverted_configuration_tokens.get(modifier, modifier))
  387. for expectation in expectations:
  388. expectation = expectation.upper()
  389. new_expectations.append(TestExpectationParser._inverted_expectation_tokens.get(expectation, expectation))
  390. result = ''
  391. if include_modifiers and (bugs or new_modifiers):
  392. if bugs:
  393. result += ' '.join(bugs) + ' '
  394. if new_modifiers:
  395. result += '[ %s ] ' % ' '.join(new_modifiers)
  396. result += name
  397. if include_expectations and new_expectations and set(new_expectations) != set(['Skip', 'Pass']):
  398. result += ' [ %s ]' % ' '.join(sorted(set(new_expectations)))
  399. if include_comment and comment is not None:
  400. result += " #%s" % comment
  401. return result
  402. # FIXME: Refactor API to be a proper CRUD.
  403. class TestExpectationsModel(object):
  404. """Represents relational store of all expectations and provides CRUD semantics to manage it."""
  405. def __init__(self, shorten_filename=None):
  406. # Maps a test to its list of expectations.
  407. self._test_to_expectations = {}
  408. # Maps a test to list of its modifiers (string values)
  409. self._test_to_modifiers = {}
  410. # Maps a test to a TestExpectationLine instance.
  411. self._test_to_expectation_line = {}
  412. self._modifier_to_tests = self._dict_of_sets(TestExpectations.MODIFIERS)
  413. self._expectation_to_tests = self._dict_of_sets(TestExpectations.EXPECTATIONS)
  414. self._timeline_to_tests = self._dict_of_sets(TestExpectations.TIMELINES)
  415. self._result_type_to_tests = self._dict_of_sets(TestExpectations.RESULT_TYPES)
  416. self._shorten_filename = shorten_filename or (lambda x: x)
  417. def _dict_of_sets(self, strings_to_constants):
  418. """Takes a dict of strings->constants and returns a dict mapping
  419. each constant to an empty set."""
  420. d = {}
  421. for c in strings_to_constants.values():
  422. d[c] = set()
  423. return d
  424. def get_test_set(self, modifier, expectation=None, include_skips=True):
  425. if expectation is None:
  426. tests = self._modifier_to_tests[modifier]
  427. else:
  428. tests = (self._expectation_to_tests[expectation] &
  429. self._modifier_to_tests[modifier])
  430. if not include_skips:
  431. tests = tests - self.get_test_set(SKIP, expectation)
  432. return tests
  433. def get_test_set_for_keyword(self, keyword):
  434. # FIXME: get_test_set() is an awkward public interface because it requires
  435. # callers to know the difference between modifiers and expectations. We
  436. # should replace that with this where possible.
  437. expectation_enum = TestExpectations.EXPECTATIONS.get(keyword.lower(), None)
  438. if expectation_enum is not None:
  439. return self._expectation_to_tests[expectation_enum]
  440. modifier_enum = TestExpectations.MODIFIERS.get(keyword.lower(), None)
  441. if modifier_enum is not None:
  442. return self._modifier_to_tests[modifier_enum]
  443. # We must not have an index on this modifier.
  444. matching_tests = set()
  445. for test, modifiers in self._test_to_modifiers.iteritems():
  446. if keyword.lower() in modifiers:
  447. matching_tests.add(test)
  448. return matching_tests
  449. def get_tests_with_result_type(self, result_type):
  450. return self._result_type_to_tests[result_type]
  451. def get_tests_with_timeline(self, timeline):
  452. return self._timeline_to_tests[timeline]
  453. def get_modifiers(self, test):
  454. """This returns modifiers for the given test (the modifiers plus the BUGXXXX identifier). This is used by the LTTF dashboard."""
  455. return self._test_to_modifiers[test]
  456. def has_modifier(self, test, modifier):
  457. return test in self._modifier_to_tests[modifier]
  458. def has_keyword(self, test, keyword):
  459. return (keyword.upper() in self.get_expectations_string(test) or
  460. keyword.lower() in self.get_modifiers(test))
  461. def has_test(self, test):
  462. return test in self._test_to_expectation_line
  463. def get_expectation_line(self, test):
  464. return self._test_to_expectation_line.get(test)
  465. def get_expectations(self, test):
  466. return self._test_to_expectations[test]
  467. def get_expectations_string(self, test):
  468. """Returns the expectatons for the given test as an uppercase string.
  469. If there are no expectations for the test, then "PASS" is returned."""
  470. expectations = self.get_expectations(test)
  471. retval = []
  472. for expectation in expectations:
  473. retval.append(self.expectation_to_string(expectation))
  474. return " ".join(retval)
  475. def expectation_to_string(self, expectation):
  476. """Return the uppercased string equivalent of a given expectation."""
  477. for item in TestExpectations.EXPECTATIONS.items():
  478. if item[1] == expectation:
  479. return item[0].upper()
  480. raise ValueError(expectation)
  481. def add_expectation_line(self, expectation_line, in_skipped=False):
  482. """Returns a list of warnings encountered while matching modifiers."""
  483. if expectation_line.is_invalid():
  484. return
  485. for test in expectation_line.matching_tests:
  486. if not in_skipped and self._already_seen_better_match(test, expectation_line):
  487. continue
  488. self._clear_expectations_for_test(test)
  489. self._test_to_expectation_line[test] = expectation_line
  490. self._add_test(test, expectation_line)
  491. def _add_test(self, test, expectation_line):
  492. """Sets the expected state for a given test.
  493. This routine assumes the test has not been added before. If it has,
  494. use _clear_expectations_for_test() to reset the state prior to
  495. calling this."""
  496. self._test_to_expectations[test] = expectation_line.parsed_expectations
  497. for expectation in expectation_line.parsed_expectations:
  498. self._expectation_to_tests[expectation].add(test)
  499. self._test_to_modifiers[test] = expectation_line.modifiers
  500. for modifier in expectation_line.parsed_modifiers:
  501. mod_value = TestExpectations.MODIFIERS[modifier]
  502. self._modifier_to_tests[mod_value].add(test)
  503. if TestExpectationParser.WONTFIX_MODIFIER in expectation_line.parsed_modifiers:
  504. self._timeline_to_tests[WONTFIX].add(test)
  505. else:
  506. self._timeline_to_tests[NOW].add(test)
  507. if TestExpectationParser.SKIP_MODIFIER in expectation_line.parsed_modifiers:
  508. self._result_type_to_tests[SKIP].add(test)
  509. elif expectation_line.parsed_expectations == set([PASS]):
  510. self._result_type_to_tests[PASS].add(test)
  511. elif expectation_line.is_flaky():
  512. self._result_type_to_tests[FLAKY].add(test)
  513. else:
  514. # FIXME: What is this?
  515. self._result_type_to_tests[FAIL].add(test)
  516. def _clear_expectations_for_test(self, test):
  517. """Remove prexisting expectations for this test.
  518. This happens if we are seeing a more precise path
  519. than a previous listing.
  520. """
  521. if self.has_test(test):
  522. self._test_to_expectations.pop(test, '')
  523. self._remove_from_sets(test, self._expectation_to_tests)
  524. self._remove_from_sets(test, self._modifier_to_tests)
  525. self._remove_from_sets(test, self._timeline_to_tests)
  526. self._remove_from_sets(test, self._result_type_to_tests)
  527. def _remove_from_sets(self, test, dict_of_sets_of_tests):
  528. """Removes the given test from the sets in the dictionary.
  529. Args:
  530. test: test to look for
  531. dict: dict of sets of files"""
  532. for set_of_tests in dict_of_sets_of_tests.itervalues():
  533. if test in set_of_tests:
  534. set_of_tests.remove(test)
  535. def _already_seen_better_match(self, test, expectation_line):
  536. """Returns whether we've seen a better match already in the file.
  537. Returns True if we've already seen a expectation_line.name that matches more of the test
  538. than this path does
  539. """
  540. # FIXME: See comment below about matching test configs and specificity.
  541. if not self.has_test(test):
  542. # We've never seen this test before.
  543. return False
  544. prev_expectation_line = self._test_to_expectation_line[test]
  545. if prev_expectation_line.filename != expectation_line.filename:
  546. # We've moved on to a new expectation file, which overrides older ones.
  547. return False
  548. if len(prev_expectation_line.path) > len(expectation_line.path):
  549. # The previous path matched more of the test.
  550. return True
  551. if len(prev_expectation_line.path) < len(expectation_line.path):
  552. # This path matches more of the test.
  553. return False
  554. # At this point we know we have seen a previous exact match on this
  555. # base path, so we need to check the two sets of modifiers.
  556. # FIXME: This code was originally designed to allow lines that matched
  557. # more modifiers to override lines that matched fewer modifiers.
  558. # However, we currently view these as errors.
  559. #
  560. # To use the "more modifiers wins" policy, change the errors for overrides
  561. # to be warnings and return False".
  562. if prev_expectation_line.matching_configurations == expectation_line.matching_configurations:
  563. expectation_line.warnings.append('Duplicate or ambiguous entry lines %s:%d and %s:%d.' % (
  564. self._shorten_filename(prev_expectation_line.filename), prev_expectation_line.line_number,
  565. self._shorten_filename(expectation_line.filename), expectation_line.line_number))
  566. return True
  567. if prev_expectation_line.matching_configurations >= expectation_line.matching_configurations:
  568. expectation_line.warnings.append('More specific entry for %s on line %s:%d overrides line %s:%d.' % (expectation_line.name,
  569. self._shorten_filename(prev_expectation_line.filename), prev_expectation_line.line_number,
  570. self._shorten_filename(expectation_line.filename), expectation_line.line_number))
  571. # FIXME: return False if we want more specific to win.
  572. return True
  573. if prev_expectation_line.matching_configurations <= expectation_line.matching_configurations:
  574. expectation_line.warnings.append('More specific entry for %s on line %s:%d overrides line %s:%d.' % (expectation_line.name,
  575. self._shorten_filename(expectation_line.filename), expectation_line.line_number,
  576. self._shorten_filename(prev_expectation_line.filename), prev_expectation_line.line_number))
  577. return True
  578. if prev_expectation_line.matching_configurations & expectation_line.matching_configurations:
  579. expectation_line.warnings.append('Entries for %s on lines %s:%d and %s:%d match overlapping sets of configurations.' % (expectation_line.name,
  580. self._shorten_filename(prev_expectation_line.filename), prev_expectation_line.line_number,
  581. self._shorten_filename(expectation_line.filename), expectation_line.line_number))
  582. return True
  583. # Configuration sets are disjoint, then.
  584. return False
  585. class TestExpectations(object):
  586. """Test expectations consist of lines with specifications of what
  587. to expect from layout test cases. The test cases can be directories
  588. in which case the expectations apply to all test cases in that
  589. directory and any subdirectory. The format is along the lines of:
  590. LayoutTests/fast/js/fixme.js [ Failure ]
  591. LayoutTests/fast/js/flaky.js [ Failure Pass ]
  592. LayoutTests/fast/js/crash.js [ Crash Failure Pass Timeout ]
  593. ...
  594. To add modifiers:
  595. LayoutTests/fast/js/no-good.js
  596. [ Debug ] LayoutTests/fast/js/no-good.js [ Pass Timeout ]
  597. [ Debug ] LayoutTests/fast/js/no-good.js [ Pass Skip Timeout ]
  598. [ Linux Debug ] LayoutTests/fast/js/no-good.js [ Pass Skip Timeout ]
  599. [ Linux Win ] LayoutTests/fast/js/no-good.js [ Pass Skip Timeout ]
  600. Skip: Doesn't run the test.
  601. Slow: The test takes a long time to run, but does not timeout indefinitely.
  602. WontFix: For tests that we never intend to pass on a given platform (treated like Skip).
  603. Notes:
  604. -A test cannot be both SLOW and TIMEOUT
  605. -A test can be included twice, but not via the same path.
  606. -If a test is included twice, then the more precise path wins.
  607. -CRASH tests cannot be WONTFIX
  608. """
  609. # FIXME: Update to new syntax once the old format is no longer supported.
  610. EXPECTATIONS = {'pass': PASS,
  611. 'audio': AUDIO,
  612. 'fail': FAIL,
  613. 'image': IMAGE,
  614. 'image+text': IMAGE_PLUS_TEXT,
  615. 'text': TEXT,
  616. 'timeout': TIMEOUT,
  617. 'crash': CRASH,
  618. 'missing': MISSING,
  619. 'skip': SKIP}
  620. # (aggregated by category, pass/fail/skip, type)
  621. EXPECTATION_DESCRIPTIONS = {SKIP: 'skipped',
  622. PASS: 'passes',
  623. FAIL: 'failures',
  624. IMAGE: 'image-only failures',
  625. TEXT: 'text-only failures',
  626. IMAGE_PLUS_TEXT: 'image and text failures',
  627. AUDIO: 'audio failures',
  628. CRASH: 'crashes',
  629. TIMEOUT: 'timeouts',
  630. MISSING: 'missing results'}
  631. EXPECTATION_ORDER = (PASS, CRASH, TIMEOUT, MISSING, FAIL, IMAGE, SKIP)
  632. BUILD_TYPES = ('debug', 'release')
  633. MODIFIERS = {TestExpectationParser.SKIP_MODIFIER: SKIP,
  634. TestExpectationParser.WONTFIX_MODIFIER: WONTFIX,
  635. TestExpectationParser.SLOW_MODIFIER: SLOW,
  636. TestExpectationParser.REBASELINE_MODIFIER: REBASELINE,
  637. 'none': NONE}
  638. TIMELINES = {TestExpectationParser.WONTFIX_MODIFIER: WONTFIX,
  639. 'now': NOW}
  640. RESULT_TYPES = {'skip': SKIP,
  641. 'pass': PASS,
  642. 'fail': FAIL,
  643. 'flaky': FLAKY}
  644. @classmethod
  645. def expectation_from_string(cls, string):
  646. assert(' ' not in string) # This only handles one expectation at a time.
  647. return cls.EXPECTATIONS.get(string.lower())
  648. @staticmethod
  649. def result_was_expected(result, expected_results, test_needs_rebaselining, test_is_skipped):
  650. """Returns whether we got a result we were expecting.
  651. Args:
  652. result: actual result of a test execution
  653. expected_results: set of results listed in test_expectations
  654. test_needs_rebaselining: whether test was marked as REBASELINE
  655. test_is_skipped: whether test was marked as SKIP"""
  656. if result in expected_results:
  657. return True
  658. if result in (TEXT, IMAGE_PLUS_TEXT, AUDIO) and (FAIL in expected_results):
  659. return True
  660. if result == MISSING and test_needs_rebaselining:
  661. return True
  662. if result == SKIP and test_is_skipped:
  663. return True
  664. return False
  665. @staticmethod
  666. def remove_pixel_failures(expected_results):
  667. """Returns a copy of the expected results for a test, except that we
  668. drop any pixel failures and return the remaining expectations. For example,
  669. if we're not running pixel tests, then tests expected to fail as IMAGE
  670. will PASS."""
  671. expected_results = expected_results.copy()
  672. if IMAGE in expected_results:
  673. expected_results.remove(IMAGE)
  674. expected_results.add(PASS)
  675. return expected_results
  676. @staticmethod
  677. def has_pixel_failures(actual_results):
  678. return IMAGE in actual_results or FAIL in actual_results
  679. @staticmethod
  680. def suffixes_for_expectations(expectations):
  681. suffixes = set()
  682. if IMAGE in expectations:
  683. suffixes.add('png')
  684. if FAIL in expectations:
  685. suffixes.add('txt')
  686. suffixes.add('png')
  687. suffixes.add('wav')
  688. return set(suffixes)
  689. # FIXME: This constructor does too much work. We should move the actual parsing of
  690. # the expectations into separate routines so that linting and handling overrides
  691. # can be controlled separately, and the constructor can be more of a no-op.
  692. def __init__(self, port, tests=None, include_generic=True, include_overrides=True, expectations_to_lint=None):
  693. self._full_test_list = tests
  694. self._test_config = port.test_configuration()
  695. self._is_lint_mode = expectations_to_lint is not None
  696. self._model = TestExpectationsModel(self._shorten_filename)
  697. self._parser = TestExpectationParser(port, tests, self._is_lint_mode)
  698. self._port = port
  699. self._skipped_tests_warnings = []
  700. self._expectations = []
  701. expectations_dict = expectations_to_lint or port.expectations_dict()
  702. expectations_dict_index = 0
  703. # Populate generic expectations (if enabled by include_generic).
  704. if port.path_to_generic_test_expectations_file() in expectations_dict:
  705. if include_generic:
  706. expectations = self._parser.parse(expectations_dict.keys()[expectations_dict_index], expectations_dict.values()[expectations_dict_index])
  707. self._add_expectations(expectations)
  708. self._expectations += expectations
  709. expectations_dict_index += 1
  710. # Populate default port expectations (always enabled).
  711. if len(expectations_dict) > expectations_dict_index:
  712. expectations = self._parser.parse(expectations_dict.keys()[expectations_dict_index], expectations_dict.values()[expectations_dict_index])
  713. self._add_expectations(expectations)
  714. self._expectations += expectations
  715. expectations_dict_index += 1
  716. # Populate override expectations (if enabled by include_overrides).
  717. while len(expectations_dict) > expectations_dict_index and include_overrides:
  718. expectations = self._parser.parse(expectations_dict.keys()[expectations_dict_index], expectations_dict.values()[expectations_dict_index])
  719. self._add_expectations(expectations)
  720. self._expectations += expectations
  721. expectations_dict_index += 1
  722. # FIXME: move ignore_tests into port.skipped_layout_tests()
  723. self.add_skipped_tests(port.skipped_layout_tests(tests).union(set(port.get_option('ignore_tests', []))))
  724. self._has_warnings = False
  725. self._report_warnings()
  726. self._process_tests_without_expectations()
  727. # TODO(ojan): Allow for removing skipped tests when getting the list of
  728. # tests to run, but not when getting metrics.
  729. def model(self):
  730. return self._model
  731. def get_rebaselining_failures(self):
  732. return self._model.get_test_set(REBASELINE)
  733. # FIXME: Change the callsites to use TestExpectationsModel and remove.
  734. def get_expectations(self, test):
  735. return self._model.get_expectations(test)
  736. # FIXME: Change the callsites to use TestExpectationsModel and remove.
  737. def has_modifier(self, test, modifier):
  738. return self._model.has_modifier(test, modifier)
  739. # FIXME: Change the callsites to use TestExpectationsModel and remove.
  740. def get_tests_with_result_type(self, result_type):
  741. return self._model.get_tests_with_result_type(result_type)
  742. # FIXME: Change the callsites to use TestExpectationsModel and remove.
  743. def get_test_set(self, modifier, expectation=None, include_skips=True):
  744. return self._model.get_test_set(modifier, expectation, include_skips)
  745. # FIXME: Change the callsites to use TestExpectationsModel and remove.
  746. def get_modifiers(self, test):
  747. return self._model.get_modifiers(test)
  748. # FIXME: Change the callsites to use TestExpectationsModel and remove.
  749. def get_tests_with_timeline(self, timeline):
  750. return self._model.get_tests_with_timeline(timeline)
  751. def get_expectations_string(self, test):
  752. return self._model.get_expectations_string(test)
  753. def expectation_to_string(self, expectation):
  754. return self._model.expectation_to_string(expectation)
  755. def matches_an_expected_result(self, test, result, pixel_tests_are_enabled):
  756. expected_results = self._model.get_expectations(test)
  757. if not pixel_tests_are_enabled:
  758. expected_results = self.remove_pixel_failures(expected_results)
  759. return self.result_was_expected(result,
  760. expected_results,
  761. self.is_rebaselining(test),
  762. self._model.has_modifier(test, SKIP))
  763. def is_rebaselining(self, test):
  764. return self._model.has_modifier(test, REBASELINE)
  765. def _shorten_filename(self, filename):
  766. if filename.startswith(self._port.path_from_webkit_base()):
  767. return self._port.host.filesystem.relpath(filename, self._port.path_from_webkit_base())
  768. return filename
  769. def _report_warnings(self):
  770. warnings = []
  771. for expectation in self._expectations:
  772. for warning in expectation.warnings:
  773. warnings.append('%s:%d %s %s' % (self._shorten_filename(expectation.filename), expectation.line_number,
  774. warning, expectation.name if expectation.expectations else expectation.original_string))
  775. if warnings:
  776. self._has_warnings = True
  777. if self._is_lint_mode:
  778. raise ParseError(warnings)
  779. _log.warning('--lint-test-files warnings:')
  780. for warning in warnings:
  781. _log.warning(warning)
  782. _log.warning('')
  783. def _process_tests_without_expectations(self):
  784. if self._full_test_list:
  785. for test in self._full_test_list:
  786. if not self._model.has_test(test):
  787. self._model.add_expectation_line(TestExpectationLine.create_passing_expectation(test))
  788. def has_warnings(self):
  789. return self._has_warnings
  790. def remove_configuration_from_test(self, test, test_configuration):
  791. expectations_to_remove = []
  792. modified_expectations = []
  793. for expectation in self._expectations:
  794. if expectation.name != test or expectation.is_flaky() or not expectation.parsed_expectations:
  795. continue
  796. if iter(expectation.parsed_expectations).next() not in (FAIL, IMAGE):
  797. continue
  798. if test_configuration not in expectation.matching_configurations:
  799. continue
  800. expectation.matching_configurations.remove(test_configuration)
  801. if expectation.matching_configurations:
  802. modified_expectations.append(expectation)
  803. else:
  804. expectations_to_remove.append(expectation)
  805. for expectation in expectations_to_remove:
  806. self._expectations.remove(expectation)
  807. return self.list_to_string(self._expectations, self._parser._test_configuration_converter, modified_expectations)
  808. def remove_rebaselined_tests(self, except_these_tests, filename):
  809. """Returns a copy of the expectations in the file with the tests removed."""
  810. def without_rebaseline_modifier(expectation):
  811. return (expectation.filename == filename and
  812. not (not expectation.is_invalid() and
  813. expectation.name in except_these_tests and
  814. 'rebaseline' in expectation.parsed_modifiers))
  815. return self.list_to_string(filter(without_rebaseline_modifier, self._expectations), reconstitute_only_these=[])
  816. def _add_expectations(self, expectation_list):
  817. for expectation_line in expectation_list:
  818. if not expectation_line.expectations:
  819. continue
  820. if self._is_lint_mode or self._test_config in expectation_line.matching_configurations:
  821. self._model.add_expectation_line(expectation_line)
  822. def add_skipped_tests(self, tests_to_skip):
  823. if not tests_to_skip:
  824. return
  825. for test in self._expectations:
  826. if test.name and test.name in tests_to_skip:
  827. test.warnings.append('%s:%d %s is also in a Skipped file.' % (test.filename, test.line_number, test.name))
  828. for test_name in tests_to_skip:
  829. expectation_line = self._parser.expectation_for_skipped_test(test_name)
  830. self._model.add_expectation_line(expectation_line, in_skipped=True)
  831. @staticmethod
  832. def list_to_string(expectation_lines, test_configuration_converter=None, reconstitute_only_these=None):
  833. def serialize(expectation_line):
  834. # If reconstitute_only_these is an empty list, we want to return original_string.
  835. # So we need to compare reconstitute_only_these to None, not just check if it's falsey.
  836. if reconstitute_only_these is None or expectation_line in reconstitute_only_these:
  837. return expectation_line.to_string(test_configuration_converter)
  838. return expectation_line.original_string
  839. def nones_out(expectation_line):
  840. return expectation_line is not None
  841. return "\n".join(filter(nones_out, map(serialize, expectation_lines)))