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