Remove workarounds for versions of Python before 2.7
[WebKit-https.git] / Tools / Scripts / webkitpy / layout_tests / models / test_expectations_unittest.py
1 # Copyright (C) 2010 Google Inc. All rights reserved.
2 # Copyright (C) 2013 Apple Inc. All rights reserved.
3 #
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are
6 # met:
7 #
8 #     * Redistributions of source code must retain the above copyright
9 # notice, this list of conditions and the following disclaimer.
10 #     * Redistributions in binary form must reproduce the above
11 # copyright notice, this list of conditions and the following disclaimer
12 # in the documentation and/or other materials provided with the
13 # distribution.
14 #     * Neither the name of Google Inc. nor the names of its
15 # contributors may be used to endorse or promote products derived from
16 # this software without specific prior written permission.
17 #
18 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30 import unittest
31
32 from collections import OrderedDict
33
34 from webkitpy.common.host_mock import MockHost
35 from webkitpy.common.system.outputcapture import OutputCapture
36
37 from webkitpy.layout_tests.models.test_configuration import *
38 from webkitpy.layout_tests.models.test_expectations import *
39 from webkitpy.layout_tests.models.test_configuration import *
40
41
42 class Base(unittest.TestCase):
43     # Note that all of these tests are written assuming the configuration
44     # being tested is Windows XP, Release build.
45
46     def __init__(self, testFunc):
47         host = MockHost()
48         self._port = host.port_factory.get('test-win-xp', None)
49         self._exp = None
50         unittest.TestCase.__init__(self, testFunc)
51
52     def get_basic_tests(self):
53         return ['failures/expected/text.html',
54                 'failures/expected/image_checksum.html',
55                 'failures/expected/crash.html',
56                 'failures/expected/missing_text.html',
57                 'failures/expected/image.html',
58                 'passes/text.html']
59
60     def get_basic_expectations(self):
61         return """
62 Bug(test) failures/expected/text.html [ Failure ]
63 Bug(test) failures/expected/crash.html [ WontFix ]
64 Bug(test) failures/expected/missing_image.html [ Rebaseline Missing ]
65 Bug(test) failures/expected/image_checksum.html [ WontFix ]
66 Bug(test) failures/expected/image.html [ WontFix Mac ]
67 """
68
69     def parse_exp(self, expectations, overrides=None, is_lint_mode=False):
70         expectations_dict = OrderedDict()
71         expectations_dict['expectations'] = expectations
72         if overrides:
73             expectations_dict['overrides'] = overrides
74         self._port.expectations_dict = lambda: expectations_dict
75         expectations_to_lint = expectations_dict if is_lint_mode else None
76         self._exp = TestExpectations(self._port, self.get_basic_tests(), expectations_to_lint=expectations_to_lint)
77         self._exp.parse_all_expectations()
78
79     def assert_exp(self, test, result):
80         self.assertEqual(self._exp.model().get_expectations(test),
81                           set([result]))
82
83     def assert_bad_expectations(self, expectations, overrides=None):
84         self.assertRaises(ParseError, self.parse_exp, expectations, is_lint_mode=True, overrides=overrides)
85
86
87 class BasicTests(Base):
88     def test_basic(self):
89         self.parse_exp(self.get_basic_expectations())
90         self.assert_exp('failures/expected/text.html', FAIL)
91         self.assert_exp('failures/expected/image_checksum.html', PASS)
92         self.assert_exp('passes/text.html', PASS)
93         self.assert_exp('failures/expected/image.html', PASS)
94
95
96 class MiscTests(Base):
97     def test_multiple_results(self):
98         self.parse_exp('Bug(x) failures/expected/text.html [ Crash Failure ]')
99         self.assertEqual(self._exp.model().get_expectations(
100             'failures/expected/text.html'),
101             set([FAIL, CRASH]))
102
103     def test_result_was_expected(self):
104         # test basics
105         self.assertEqual(TestExpectations.result_was_expected(PASS, set([PASS]), test_needs_rebaselining=False, test_is_skipped=False), True)
106         self.assertEqual(TestExpectations.result_was_expected(FAIL, set([PASS]), test_needs_rebaselining=False, test_is_skipped=False), False)
107
108         # test handling of SKIPped tests and results
109         self.assertEqual(TestExpectations.result_was_expected(SKIP, set([CRASH]), test_needs_rebaselining=False, test_is_skipped=True), True)
110         self.assertEqual(TestExpectations.result_was_expected(SKIP, set([CRASH]), test_needs_rebaselining=False, test_is_skipped=False), False)
111
112         # test handling of MISSING results and the REBASELINE modifier
113         self.assertEqual(TestExpectations.result_was_expected(MISSING, set([PASS]), test_needs_rebaselining=True, test_is_skipped=False), True)
114         self.assertEqual(TestExpectations.result_was_expected(MISSING, set([PASS]), test_needs_rebaselining=False, test_is_skipped=False), False)
115
116     def test_remove_pixel_failures(self):
117         self.assertEqual(TestExpectations.remove_pixel_failures(set([FAIL])), set([FAIL]))
118         self.assertEqual(TestExpectations.remove_pixel_failures(set([PASS])), set([PASS]))
119         self.assertEqual(TestExpectations.remove_pixel_failures(set([IMAGE])), set([PASS]))
120         self.assertEqual(TestExpectations.remove_pixel_failures(set([FAIL])), set([FAIL]))
121         self.assertEqual(TestExpectations.remove_pixel_failures(set([PASS, IMAGE, CRASH])), set([PASS, CRASH]))
122
123     def test_suffixes_for_expectations(self):
124         self.assertEqual(TestExpectations.suffixes_for_expectations(set([FAIL])), set(['txt', 'png', 'wav']))
125         self.assertEqual(TestExpectations.suffixes_for_expectations(set([IMAGE])), set(['png']))
126         self.assertEqual(TestExpectations.suffixes_for_expectations(set([FAIL, IMAGE, CRASH])), set(['txt', 'png', 'wav']))
127         self.assertEqual(TestExpectations.suffixes_for_expectations(set()), set())
128
129     def test_category_expectations(self):
130         # This test checks unknown tests are not present in the
131         # expectations and that known test part of a test category is
132         # present in the expectations.
133         exp_str = 'Bug(x) failures/expected [ WontFix ]'
134         self.parse_exp(exp_str)
135         test_name = 'failures/expected/unknown-test.html'
136         unknown_test = test_name
137         self.assertRaises(KeyError, self._exp.model().get_expectations,
138                           unknown_test)
139         self.assert_exp('failures/expected/crash.html', PASS)
140
141     def test_get_modifiers(self):
142         self.parse_exp(self.get_basic_expectations())
143         self.assertEqual(self._exp.model().get_modifiers('passes/text.html'), [])
144
145     def test_get_expectations_string(self):
146         self.parse_exp(self.get_basic_expectations())
147         self.assertEqual(self._exp.model().get_expectations_string('failures/expected/text.html'), 'FAIL')
148
149     def test_expectation_to_string(self):
150         # Normal cases are handled by other tests.
151         self.parse_exp(self.get_basic_expectations())
152         self.assertRaises(ValueError, self._exp.model().expectation_to_string,
153                           -1)
154
155     def test_get_test_set(self):
156         # Handle some corner cases for this routine not covered by other tests.
157         self.parse_exp(self.get_basic_expectations())
158         s = self._exp.model().get_test_set(WONTFIX)
159         self.assertEqual(s,
160             set(['failures/expected/crash.html',
161                  'failures/expected/image_checksum.html']))
162
163     def test_parse_warning(self):
164         try:
165             filesystem = self._port.host.filesystem
166             filesystem.write_text_file(filesystem.join(self._port.layout_tests_dir(), 'disabled-test.html-disabled'), 'content')
167             self.parse_exp("[ FOO ] failures/expected/text.html [ Failure ]\n"
168                 "Bug(rniwa) non-existent-test.html [ Failure ]\n"
169                 "Bug(rniwa) disabled-test.html-disabled [ ImageOnlyFailure ]", is_lint_mode=True)
170             self.assertFalse(True, "ParseError wasn't raised")
171         except ParseError, e:
172             warnings = ("expectations:1 Unrecognized modifier 'foo' failures/expected/text.html\n"
173                         "expectations:2 Path does not exist. non-existent-test.html")
174             self.assertEqual(str(e), warnings)
175
176     def test_parse_warnings_are_logged_if_not_in_lint_mode(self):
177         oc = OutputCapture()
178         try:
179             oc.capture_output()
180             self.parse_exp('-- this should be a syntax error', is_lint_mode=False)
181         finally:
182             _, _, logs = oc.restore_output()
183             self.assertNotEquals(logs, '')
184
185     def test_error_on_different_platform(self):
186         # parse_exp uses a Windows port. Assert errors on Mac show up in lint mode.
187         self.assertRaises(ParseError, self.parse_exp,
188             'Bug(test) [ Mac ] failures/expected/text.html [ Failure ]\nBug(test) [ Mac ] failures/expected/text.html [ Failure ]',
189             is_lint_mode=True)
190
191     def test_error_on_different_build_type(self):
192         # parse_exp uses a Release port. Assert errors on DEBUG show up in lint mode.
193         self.assertRaises(ParseError, self.parse_exp,
194             'Bug(test) [ Debug ] failures/expected/text.html [ Failure ]\nBug(test) [ Debug ] failures/expected/text.html [ Failure ]',
195             is_lint_mode=True)
196
197     def test_overrides(self):
198         self.parse_exp("Bug(exp) failures/expected/text.html [ Failure ]",
199                        "Bug(override) failures/expected/text.html [ ImageOnlyFailure ]")
200         self.assert_exp('failures/expected/text.html', IMAGE)
201
202     def test_overrides__directory(self):
203         self.parse_exp("Bug(exp) failures/expected/text.html [ Failure ]",
204                        "Bug(override) failures/expected [ Crash ]")
205         self.assert_exp('failures/expected/text.html', CRASH)
206         self.assert_exp('failures/expected/image.html', CRASH)
207
208     def test_overrides__duplicate(self):
209         self.assert_bad_expectations("Bug(exp) failures/expected/text.html [ Failure ]",
210                                      "Bug(override) failures/expected/text.html [ ImageOnlyFailure ]\n"
211                                      "Bug(override) failures/expected/text.html [ Crash ]\n")
212
213     def test_pixel_tests_flag(self):
214         def match(test, result, pixel_tests_enabled):
215             return self._exp.matches_an_expected_result(
216                 test, result, pixel_tests_enabled)
217
218         self.parse_exp(self.get_basic_expectations())
219         self.assertTrue(match('failures/expected/text.html', FAIL, True))
220         self.assertTrue(match('failures/expected/text.html', FAIL, False))
221         self.assertFalse(match('failures/expected/text.html', CRASH, True))
222         self.assertFalse(match('failures/expected/text.html', CRASH, False))
223         self.assertTrue(match('failures/expected/image_checksum.html', PASS,
224                               True))
225         self.assertTrue(match('failures/expected/image_checksum.html', PASS,
226                               False))
227         self.assertTrue(match('failures/expected/crash.html', PASS, False))
228         self.assertTrue(match('passes/text.html', PASS, False))
229
230     def test_more_specific_override_resets_skip(self):
231         self.parse_exp("Bug(x) failures/expected [ Skip ]\n"
232                        "Bug(x) failures/expected/text.html [ ImageOnlyFailure ]\n")
233         self.assert_exp('failures/expected/text.html', IMAGE)
234         self.assertFalse(self._port._filesystem.join(self._port.layout_tests_dir(),
235                                                      'failures/expected/text.html') in
236                          self._exp.model().get_tests_with_result_type(SKIP))
237
238
239 class SkippedTests(Base):
240     def check(self, expectations, overrides, skips, lint=False):
241         port = MockHost().port_factory.get('mac')
242         port._filesystem.write_text_file(port._filesystem.join(port.layout_tests_dir(), 'failures/expected/text.html'), 'foo')
243         expectations_dict = OrderedDict()
244         expectations_dict['expectations'] = expectations
245         if overrides:
246             expectations_dict['overrides'] = overrides
247         port.expectations_dict = lambda: expectations_dict
248         port.skipped_layout_tests = lambda tests: set(skips)
249         expectations_to_lint = expectations_dict if lint else None
250         exp = TestExpectations(port, ['failures/expected/text.html'], expectations_to_lint=expectations_to_lint)
251         exp.parse_all_expectations()
252
253         # Check that the expectation is for BUG_DUMMY SKIP : ... [ Pass ]
254         self.assertEqual(exp.model().get_modifiers('failures/expected/text.html'),
255                           [TestExpectationParser.DUMMY_BUG_MODIFIER, TestExpectationParser.SKIP_MODIFIER, TestExpectationParser.WONTFIX_MODIFIER])
256         self.assertEqual(exp.model().get_expectations('failures/expected/text.html'), set([PASS]))
257
258     def test_skipped_tests_work(self):
259         self.check(expectations='', overrides=None, skips=['failures/expected/text.html'])
260
261     def test_duplicate_skipped_test_fails_lint(self):
262         self.assertRaises(ParseError, self.check, expectations='Bug(x) failures/expected/text.html [ Failure ]\n', overrides=None, skips=['failures/expected/text.html'], lint=True)
263
264     def test_skipped_file_overrides_expectations(self):
265         self.check(expectations='Bug(x) failures/expected/text.html [ Failure ]\n', overrides=None,
266                    skips=['failures/expected/text.html'])
267
268     def test_skipped_dir_overrides_expectations(self):
269         self.check(expectations='Bug(x) failures/expected/text.html [ Failure ]\n', overrides=None,
270                    skips=['failures/expected'])
271
272     def test_skipped_file_overrides_overrides(self):
273         self.check(expectations='', overrides='Bug(x) failures/expected/text.html [ Failure ]\n',
274                    skips=['failures/expected/text.html'])
275
276     def test_skipped_dir_overrides_overrides(self):
277         self.check(expectations='', overrides='Bug(x) failures/expected/text.html [ Failure ]\n',
278                    skips=['failures/expected'])
279
280     def test_skipped_entry_dont_exist(self):
281         port = MockHost().port_factory.get('mac')
282         expectations_dict = OrderedDict()
283         expectations_dict['expectations'] = ''
284         port.expectations_dict = lambda: expectations_dict
285         port.skipped_layout_tests = lambda tests: set(['foo/bar/baz.html'])
286         capture = OutputCapture()
287         capture.capture_output()
288         exp = TestExpectations(port)
289         exp.parse_all_expectations()
290         _, _, logs = capture.restore_output()
291         self.assertEqual('The following test foo/bar/baz.html from the Skipped list doesn\'t exist\n', logs)
292
293
294 class ExpectationSyntaxTests(Base):
295     def test_unrecognized_expectation(self):
296         self.assert_bad_expectations('Bug(test) failures/expected/text.html [ Unknown ]')
297
298     def test_macro(self):
299         exp_str = 'Bug(test) [ Win ] failures/expected/text.html [ Failure ]'
300         self.parse_exp(exp_str)
301         self.assert_exp('failures/expected/text.html', FAIL)
302
303     def assert_tokenize_exp(self, line, bugs=None, modifiers=None, expectations=None, warnings=None, comment=None, name='foo.html'):
304         bugs = bugs or []
305         modifiers = modifiers or []
306         expectations = expectations or []
307         warnings = warnings or []
308         filename = 'TestExpectations'
309         line_number = 1
310         expectation_line = TestExpectationParser._tokenize_line(filename, line, line_number)
311         self.assertEqual(expectation_line.warnings, warnings)
312         self.assertEqual(expectation_line.name, name)
313         self.assertEqual(expectation_line.filename, filename)
314         self.assertEqual(expectation_line.line_number, line_number)
315         if not warnings:
316             self.assertEqual(expectation_line.modifiers, modifiers)
317             self.assertEqual(expectation_line.expectations, expectations)
318
319     def test_bare_name(self):
320         self.assert_tokenize_exp('foo.html', modifiers=['SKIP'], expectations=['PASS'])
321
322     def test_bare_name_and_bugs(self):
323         self.assert_tokenize_exp('webkit.org/b/12345 foo.html', modifiers=['BUGWK12345', 'SKIP'], expectations=['PASS'])
324         self.assert_tokenize_exp('Bug(dpranke) foo.html', modifiers=['BUGDPRANKE', 'SKIP'], expectations=['PASS'])
325         self.assert_tokenize_exp('webkit.org/b/12345 webkit.org/b/34567 foo.html', modifiers=['BUGWK12345', 'BUGWK34567', 'SKIP'], expectations=['PASS'])
326
327     def test_comments(self):
328         self.assert_tokenize_exp("# comment", name=None, comment="# comment")
329         self.assert_tokenize_exp("foo.html # comment", comment="# comment", expectations=['PASS'], modifiers=['SKIP'])
330
331     def test_config_modifiers(self):
332         self.assert_tokenize_exp('[ Mac ] foo.html', modifiers=['MAC', 'SKIP'], expectations=['PASS'])
333         self.assert_tokenize_exp('[ Mac Vista ] foo.html', modifiers=['MAC', 'VISTA', 'SKIP'], expectations=['PASS'])
334         self.assert_tokenize_exp('[ Mac ] foo.html [ Failure ] ', modifiers=['MAC'], expectations=['FAIL'])
335
336     def test_unknown_config(self):
337         self.assert_tokenize_exp('[ Foo ] foo.html ', modifiers=['Foo', 'SKIP'], expectations=['PASS'])
338
339     def test_unknown_expectation(self):
340         self.assert_tokenize_exp('foo.html [ Audio ]', warnings=['Unrecognized expectation "Audio"'])
341
342     def test_skip(self):
343         self.assert_tokenize_exp('foo.html [ Skip ]', modifiers=['SKIP'], expectations=['PASS'])
344
345     def test_slow(self):
346         self.assert_tokenize_exp('foo.html [ Slow ]', modifiers=['SLOW'], expectations=['PASS'])
347
348     def test_wontfix(self):
349         self.assert_tokenize_exp('foo.html [ WontFix ]', modifiers=['WONTFIX', 'SKIP'], expectations=['PASS'])
350         self.assert_tokenize_exp('foo.html [ WontFix ImageOnlyFailure ]', modifiers=['WONTFIX'], expectations=['IMAGE'])
351         self.assert_tokenize_exp('foo.html [ WontFix Pass Failure ]', modifiers=['WONTFIX'], expectations=['PASS', 'FAIL'])
352
353     def test_blank_line(self):
354         self.assert_tokenize_exp('', name=None)
355
356     def test_warnings(self):
357         self.assert_tokenize_exp('[ Mac ]', warnings=['Did not find a test name.'], name=None)
358         self.assert_tokenize_exp('[ [', warnings=['unexpected "["'], name=None)
359         self.assert_tokenize_exp('webkit.org/b/12345 ]', warnings=['unexpected "]"'], name=None)
360
361         self.assert_tokenize_exp('foo.html webkit.org/b/12345 ]', warnings=['"webkit.org/b/12345" is not at the start of the line.'])
362
363
364 class SemanticTests(Base):
365     def test_bug_format(self):
366         self.assertRaises(ParseError, self.parse_exp, 'BUG1234 failures/expected/text.html [ Failure ]', is_lint_mode=True)
367
368     def test_bad_bugid(self):
369         try:
370             self.parse_exp('BUG1234 failures/expected/text.html [ Failure ]', is_lint_mode=True)
371             self.fail('should have raised an error about a bad bug identifier')
372         except ParseError, exp:
373             self.assertEqual(len(exp.warnings), 1)
374
375     def test_missing_bugid(self):
376         self.parse_exp('failures/expected/text.html [ Failure ]')
377         self.assertFalse(self._exp.has_warnings())
378
379         self._port.warn_if_bug_missing_in_test_expectations = lambda: True
380
381         self.parse_exp('failures/expected/text.html [ Failure ]')
382         line = self._exp._model.get_expectation_line('failures/expected/text.html')
383         self.assertFalse(line.is_invalid())
384         self.assertEqual(line.warnings, ['Test lacks BUG modifier.'])
385
386     def test_skip_and_wontfix(self):
387         # Skip is not allowed to have other expectations as well, because those
388         # expectations won't be exercised and may become stale .
389         self.parse_exp('failures/expected/text.html [ Failure Skip ]')
390         self.assertTrue(self._exp.has_warnings())
391
392         self.parse_exp('failures/expected/text.html [ Crash WontFix ]')
393         self.assertFalse(self._exp.has_warnings())
394
395         self.parse_exp('failures/expected/text.html [ Pass WontFix ]')
396         self.assertFalse(self._exp.has_warnings())
397
398     def test_slow_and_timeout(self):
399         # A test cannot be SLOW and expected to TIMEOUT.
400         self.assertRaises(ParseError, self.parse_exp,
401             'Bug(test) failures/expected/timeout.html [ Slow Timeout ]', is_lint_mode=True)
402
403     def test_rebaseline(self):
404         # Can't lint a file w/ 'REBASELINE' in it.
405         self.assertRaises(ParseError, self.parse_exp,
406             'Bug(test) failures/expected/text.html [ Failure Rebaseline ]',
407             is_lint_mode=True)
408
409     def test_duplicates(self):
410         self.assertRaises(ParseError, self.parse_exp, """
411 Bug(exp) failures/expected/text.html [ Failure ]
412 Bug(exp) failures/expected/text.html [ ImageOnlyFailure ]""", is_lint_mode=True)
413
414         self.assertRaises(ParseError, self.parse_exp,
415             self.get_basic_expectations(), overrides="""
416 Bug(override) failures/expected/text.html [ Failure ]
417 Bug(override) failures/expected/text.html [ ImageOnlyFailure ]""", is_lint_mode=True)
418
419     def test_missing_file(self):
420         self.parse_exp('Bug(test) missing_file.html [ Failure ]')
421         self.assertTrue(self._exp.has_warnings(), 1)
422
423
424 class PrecedenceTests(Base):
425     def test_file_over_directory(self):
426         # This tests handling precedence of specific lines over directories
427         # and tests expectations covering entire directories.
428         exp_str = """
429 Bug(x) failures/expected/text.html [ Failure ]
430 Bug(y) failures/expected [ WontFix ]
431 """
432         self.parse_exp(exp_str)
433         self.assert_exp('failures/expected/text.html', FAIL)
434         self.assert_exp('failures/expected/crash.html', PASS)
435
436         exp_str = """
437 Bug(x) failures/expected [ WontFix ]
438 Bug(y) failures/expected/text.html [ Failure ]
439 """
440         self.parse_exp(exp_str)
441         self.assert_exp('failures/expected/text.html', FAIL)
442         self.assert_exp('failures/expected/crash.html', PASS)
443
444     def test_ambiguous(self):
445         self.assert_bad_expectations("Bug(test) [ Release ] passes/text.html [ Pass ]\n"
446                                      "Bug(test) [ Win ] passes/text.html [ Failure ]\n")
447
448     def test_more_modifiers(self):
449         self.assert_bad_expectations("Bug(test) [ Release ] passes/text.html [ Pass ]\n"
450                                      "Bug(test) [ Win Release ] passes/text.html [ Failure ]\n")
451
452     def test_order_in_file(self):
453         self.assert_bad_expectations("Bug(test) [ Win Release ] : passes/text.html [ Failure ]\n"
454                                      "Bug(test) [ Release ] : passes/text.html [ Pass ]\n")
455
456     def test_macro_overrides(self):
457         self.assert_bad_expectations("Bug(test) [ Win ] passes/text.html [ Pass ]\n"
458                                      "Bug(test) [ XP ] passes/text.html [ Failure ]\n")
459
460
461 class RemoveConfigurationsTest(Base):
462     def test_remove(self):
463         host = MockHost()
464         test_port = host.port_factory.get('test-win-xp', None)
465         test_port.test_exists = lambda test: True
466         test_port.test_isfile = lambda test: True
467
468         test_config = test_port.test_configuration()
469         test_port.expectations_dict = lambda: {"expectations": """Bug(x) [ Linux Win Release ] failures/expected/foo.html [ Failure ]
470 Bug(y) [ Win Mac Debug ] failures/expected/foo.html [ Crash ]
471 """}
472         expectations = TestExpectations(test_port, self.get_basic_tests())
473         expectations.parse_all_expectations()
474
475         actual_expectations = expectations.remove_configuration_from_test('failures/expected/foo.html', test_config)
476
477         self.assertEqual("""Bug(x) [ Linux Vista Win7 Release ] failures/expected/foo.html [ Failure ]
478 Bug(y) [ Win Mac Debug ] failures/expected/foo.html [ Crash ]
479 """, actual_expectations)
480
481     def test_remove_line(self):
482         host = MockHost()
483         test_port = host.port_factory.get('test-win-xp', None)
484         test_port.test_exists = lambda test: True
485         test_port.test_isfile = lambda test: True
486
487         test_config = test_port.test_configuration()
488         test_port.expectations_dict = lambda: {'expectations': """Bug(x) [ Win Release ] failures/expected/foo.html [ Failure ]
489 Bug(y) [ Win Debug ] failures/expected/foo.html [ Crash ]
490 """}
491         expectations = TestExpectations(test_port)
492         expectations.parse_all_expectations()
493
494         actual_expectations = expectations.remove_configuration_from_test('failures/expected/foo.html', test_config)
495         actual_expectations = expectations.remove_configuration_from_test('failures/expected/foo.html', host.port_factory.get('test-win-vista', None).test_configuration())
496         actual_expectations = expectations.remove_configuration_from_test('failures/expected/foo.html', host.port_factory.get('test-win-win7', None).test_configuration())
497
498         self.assertEqual("""Bug(y) [ Win Debug ] failures/expected/foo.html [ Crash ]
499 """, actual_expectations)
500
501
502 class RebaseliningTest(Base):
503     """Test rebaselining-specific functionality."""
504     def assertRemove(self, input_expectations, input_overrides, tests, expected_expectations, expected_overrides):
505         self.parse_exp(input_expectations, is_lint_mode=False, overrides=input_overrides)
506         actual_expectations = self._exp.remove_rebaselined_tests(tests, 'expectations')
507         self.assertEqual(expected_expectations, actual_expectations)
508         actual_overrides = self._exp.remove_rebaselined_tests(tests, 'overrides')
509         self.assertEqual(expected_overrides, actual_overrides)
510
511     def test_remove(self):
512         self.assertRemove('Bug(x) failures/expected/text.html [ Failure Rebaseline ]\n'
513                           'Bug(y) failures/expected/image.html [ ImageOnlyFailure Rebaseline ]\n'
514                           'Bug(z) failures/expected/crash.html [ Crash ]\n',
515                           'Bug(x0) failures/expected/image.html [ Crash ]\n',
516                           ['failures/expected/text.html'],
517                           'Bug(y) failures/expected/image.html [ ImageOnlyFailure Rebaseline ]\n'
518                           'Bug(z) failures/expected/crash.html [ Crash ]\n',
519                           'Bug(x0) failures/expected/image.html [ Crash ]\n')
520
521         # Ensure that we don't modify unrelated lines, even if we could rewrite them.
522         # i.e., the second line doesn't get rewritten to "Bug(y) failures/expected/skip.html"
523         self.assertRemove('Bug(x) failures/expected/text.html [ Failure Rebaseline ]\n'
524                           'Bug(Y) failures/expected/image.html [ Skip   ]\n'
525                           'Bug(z) failures/expected/crash.html\n',
526                           '',
527                           ['failures/expected/text.html'],
528                           'Bug(Y) failures/expected/image.html [ Skip   ]\n'
529                           'Bug(z) failures/expected/crash.html\n',
530                           '')
531
532     def test_get_rebaselining_failures(self):
533         # Make sure we find a test as needing a rebaseline even if it is not marked as a failure.
534         self.parse_exp('Bug(x) failures/expected/text.html [ Rebaseline ]\n')
535         self.assertEqual(len(self._exp.get_rebaselining_failures()), 1)
536
537         self.parse_exp(self.get_basic_expectations())
538         self.assertEqual(len(self._exp.get_rebaselining_failures()), 0)
539
540
541 class TestExpectationSerializationTests(unittest.TestCase):
542     def __init__(self, testFunc):
543         host = MockHost()
544         test_port = host.port_factory.get('test-win-xp', None)
545         self._converter = TestConfigurationConverter(test_port.all_test_configurations(), test_port.configuration_specifier_macros())
546         unittest.TestCase.__init__(self, testFunc)
547
548     def _tokenize(self, line):
549         return TestExpectationParser._tokenize_line('path', line, 0)
550
551     def assert_round_trip(self, in_string, expected_string=None):
552         expectation = self._tokenize(in_string)
553         if expected_string is None:
554             expected_string = in_string
555         self.assertEqual(expected_string, expectation.to_string(self._converter))
556
557     def assert_list_round_trip(self, in_string, expected_string=None):
558         host = MockHost()
559         parser = TestExpectationParser(host.port_factory.get('test-win-xp', None), [], allow_rebaseline_modifier=False)
560         expectations = parser.parse('path', in_string)
561         if expected_string is None:
562             expected_string = in_string
563         self.assertEqual(expected_string, TestExpectations.list_to_string(expectations, self._converter))
564
565     def test_unparsed_to_string(self):
566         expectation = TestExpectationLine()
567
568         self.assertEqual(expectation.to_string(self._converter), '')
569         expectation.comment = ' Qux.'
570         self.assertEqual(expectation.to_string(self._converter), '# Qux.')
571         expectation.name = 'bar'
572         self.assertEqual(expectation.to_string(self._converter), 'bar # Qux.')
573         expectation.modifiers = ['foo']
574         # FIXME: case should be preserved here but we can't until we drop the old syntax.
575         self.assertEqual(expectation.to_string(self._converter), '[ FOO ] bar # Qux.')
576         expectation.expectations = ['bAz']
577         self.assertEqual(expectation.to_string(self._converter), '[ FOO ] bar [ BAZ ] # Qux.')
578         expectation.expectations = ['bAz1', 'baZ2']
579         self.assertEqual(expectation.to_string(self._converter), '[ FOO ] bar [ BAZ1 BAZ2 ] # Qux.')
580         expectation.modifiers = ['foo1', 'foO2']
581         self.assertEqual(expectation.to_string(self._converter), '[ FOO1 FOO2 ] bar [ BAZ1 BAZ2 ] # Qux.')
582         expectation.warnings.append('Oh the horror.')
583         self.assertEqual(expectation.to_string(self._converter), '')
584         expectation.original_string = 'Yes it is!'
585         self.assertEqual(expectation.to_string(self._converter), 'Yes it is!')
586
587     def test_unparsed_list_to_string(self):
588         expectation = TestExpectationLine()
589         expectation.comment = 'Qux.'
590         expectation.name = 'bar'
591         expectation.modifiers = ['foo']
592         expectation.expectations = ['bAz1', 'baZ2']
593         # FIXME: case should be preserved here but we can't until we drop the old syntax.
594         self.assertEqual(TestExpectations.list_to_string([expectation]), '[ FOO ] bar [ BAZ1 BAZ2 ] #Qux.')
595
596     def test_parsed_to_string(self):
597         expectation_line = TestExpectationLine()
598         expectation_line.parsed_bug_modifiers = ['BUGX']
599         expectation_line.name = 'test/name/for/realz.html'
600         expectation_line.parsed_expectations = set([IMAGE])
601         self.assertEqual(expectation_line.to_string(self._converter), None)
602         expectation_line.matching_configurations = set([TestConfiguration('xp', 'x86', 'release')])
603         self.assertEqual(expectation_line.to_string(self._converter), 'Bug(x) [ XP Release ] test/name/for/realz.html [ ImageOnlyFailure ]')
604         expectation_line.matching_configurations = set([TestConfiguration('xp', 'x86', 'release'), TestConfiguration('xp', 'x86', 'debug')])
605         self.assertEqual(expectation_line.to_string(self._converter), 'Bug(x) [ XP ] test/name/for/realz.html [ ImageOnlyFailure ]')
606
607     def test_serialize_parsed_expectations(self):
608         expectation_line = TestExpectationLine()
609         expectation_line.parsed_expectations = set([])
610         parsed_expectation_to_string = dict([[parsed_expectation, expectation_string] for expectation_string, parsed_expectation in TestExpectations.EXPECTATIONS.items()])
611         self.assertEqual(expectation_line._serialize_parsed_expectations(parsed_expectation_to_string), '')
612         expectation_line.parsed_expectations = set([FAIL])
613         self.assertEqual(expectation_line._serialize_parsed_expectations(parsed_expectation_to_string), 'fail')
614         expectation_line.parsed_expectations = set([PASS, IMAGE])
615         self.assertEqual(expectation_line._serialize_parsed_expectations(parsed_expectation_to_string), 'pass image')
616         expectation_line.parsed_expectations = set([FAIL, PASS])
617         self.assertEqual(expectation_line._serialize_parsed_expectations(parsed_expectation_to_string), 'pass fail')
618
619     def test_serialize_parsed_modifier_string(self):
620         expectation_line = TestExpectationLine()
621         expectation_line.parsed_bug_modifiers = ['garden-o-matic']
622         expectation_line.parsed_modifiers = ['for', 'the']
623         self.assertEqual(expectation_line._serialize_parsed_modifiers(self._converter, []), 'garden-o-matic for the')
624         self.assertEqual(expectation_line._serialize_parsed_modifiers(self._converter, ['win']), 'garden-o-matic for the win')
625         expectation_line.parsed_bug_modifiers = []
626         expectation_line.parsed_modifiers = []
627         self.assertEqual(expectation_line._serialize_parsed_modifiers(self._converter, []), '')
628         self.assertEqual(expectation_line._serialize_parsed_modifiers(self._converter, ['win']), 'win')
629         expectation_line.parsed_bug_modifiers = ['garden-o-matic', 'total', 'is']
630         self.assertEqual(expectation_line._serialize_parsed_modifiers(self._converter, ['win']), 'garden-o-matic is total win')
631         expectation_line.parsed_bug_modifiers = []
632         expectation_line.parsed_modifiers = ['garden-o-matic', 'total', 'is']
633         self.assertEqual(expectation_line._serialize_parsed_modifiers(self._converter, ['win']), 'garden-o-matic is total win')
634
635     def test_format_line(self):
636         self.assertEqual(TestExpectationLine._format_line(['MODIFIERS'], 'name', ['EXPECTATIONS'], 'comment'), '[ MODIFIERS ] name [ EXPECTATIONS ] #comment')
637         self.assertEqual(TestExpectationLine._format_line(['MODIFIERS'], 'name', ['EXPECTATIONS'], None), '[ MODIFIERS ] name [ EXPECTATIONS ]')
638
639     def test_string_roundtrip(self):
640         self.assert_round_trip('')
641         self.assert_round_trip('FOO')
642         self.assert_round_trip('[')
643         self.assert_round_trip('FOO [')
644         self.assert_round_trip('FOO ] bar')
645         self.assert_round_trip('  FOO [')
646         self.assert_round_trip('    [ FOO ] ')
647         self.assert_round_trip('[ FOO ] bar [ BAZ ]')
648         self.assert_round_trip('[ FOO ] bar [ BAZ ] # Qux.')
649         self.assert_round_trip('[ FOO ] bar [ BAZ ] # Qux.')
650         self.assert_round_trip('[ FOO ] bar [ BAZ ] # Qux.     ')
651         self.assert_round_trip('[ FOO ] bar [ BAZ ] #        Qux.     ')
652         self.assert_round_trip('[ FOO ] ] ] bar BAZ')
653         self.assert_round_trip('[ FOO ] ] ] bar [ BAZ ]')
654         self.assert_round_trip('FOO ] ] bar ==== BAZ')
655         self.assert_round_trip('=')
656         self.assert_round_trip('#')
657         self.assert_round_trip('# ')
658         self.assert_round_trip('# Foo')
659         self.assert_round_trip('# Foo')
660         self.assert_round_trip('# Foo :')
661         self.assert_round_trip('# Foo : =')
662
663     def test_list_roundtrip(self):
664         self.assert_list_round_trip('')
665         self.assert_list_round_trip('\n')
666         self.assert_list_round_trip('\n\n')
667         self.assert_list_round_trip('bar')
668         self.assert_list_round_trip('bar\n# Qux.')
669         self.assert_list_round_trip('bar\n# Qux.\n')
670
671     def test_reconstitute_only_these(self):
672         lines = []
673         reconstitute_only_these = []
674
675         def add_line(matching_configurations, reconstitute):
676             expectation_line = TestExpectationLine()
677             expectation_line.original_string = "Nay"
678             expectation_line.parsed_bug_modifiers = ['BUGX']
679             expectation_line.name = 'Yay'
680             expectation_line.parsed_expectations = set([IMAGE])
681             expectation_line.matching_configurations = matching_configurations
682             lines.append(expectation_line)
683             if reconstitute:
684                 reconstitute_only_these.append(expectation_line)
685
686         add_line(set([TestConfiguration('xp', 'x86', 'release')]), True)
687         add_line(set([TestConfiguration('xp', 'x86', 'release'), TestConfiguration('xp', 'x86', 'debug')]), False)
688         serialized = TestExpectations.list_to_string(lines, self._converter)
689         self.assertEqual(serialized, "Bug(x) [ XP Release ] Yay [ ImageOnlyFailure ]\nBug(x) [ XP ] Yay [ ImageOnlyFailure ]")
690         serialized = TestExpectations.list_to_string(lines, self._converter, reconstitute_only_these=reconstitute_only_these)
691         self.assertEqual(serialized, "Bug(x) [ XP Release ] Yay [ ImageOnlyFailure ]\nNay")
692
693     def disabled_test_string_whitespace_stripping(self):
694         # FIXME: Re-enable this test once we rework the code to no longer support the old syntax.
695         self.assert_round_trip('\n', '')
696         self.assert_round_trip('  [ FOO ] bar [ BAZ ]', '[ FOO ] bar [ BAZ ]')
697         self.assert_round_trip('[ FOO ]    bar [ BAZ ]', '[ FOO ] bar [ BAZ ]')
698         self.assert_round_trip('[ FOO ] bar [ BAZ ]       # Qux.', '[ FOO ] bar [ BAZ ] # Qux.')
699         self.assert_round_trip('[ FOO ] bar [        BAZ ]  # Qux.', '[ FOO ] bar [ BAZ ] # Qux.')
700         self.assert_round_trip('[ FOO ]       bar [    BAZ ]  # Qux.', '[ FOO ] bar [ BAZ ] # Qux.')
701         self.assert_round_trip('[ FOO ]       bar     [    BAZ ]  # Qux.', '[ FOO ] bar [ BAZ ] # Qux.')