summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/tools/blinkpy/tool/commands/rebaseline_unittest.py
blob: 91e779b0a72b3a2fa7c0dcfdc6696d10744a75be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import json
import optparse
import unittest

from blinkpy.common.net.buildbot import Build
from blinkpy.common.net.layout_test_results import LayoutTestResults
from blinkpy.common.path_finder import RELATIVE_WEB_TESTS
from blinkpy.common.system.executive_mock import MockExecutive
from blinkpy.tool.commands.rebaseline import (
    AbstractParallelRebaselineCommand, Rebaseline, TestBaselineSet
)
from blinkpy.tool.mock_tool import MockBlinkTool
from blinkpy.web_tests.builder_list import BuilderList
from blinkpy.web_tests.port.factory_mock import MockPortFactory


class BaseTestCase(unittest.TestCase):

    WEB_PREFIX = 'https://test-results.appspot.com/data/layout_results/MOCK_Mac10_11/results/layout-test-results'

    command_constructor = lambda: None

    def setUp(self):
        self.tool = MockBlinkTool()
        self.command = self.command_constructor()
        self.command._tool = self.tool   # pylint: disable=protected-access
        self.tool.builders = BuilderList({
            'MOCK Mac10.10 (dbg)': {'port_name': 'test-mac-mac10.10', 'specifiers': ['Mac10.10', 'Debug']},
            'MOCK Mac10.10': {'port_name': 'test-mac-mac10.10', 'specifiers': ['Mac10.10', 'Release']},
            'MOCK Mac10.11 (dbg)': {'port_name': 'test-mac-mac10.11', 'specifiers': ['Mac10.11', 'Debug']},
            'MOCK Mac10.11 ASAN': {'port_name': 'test-mac-mac10.11', 'specifiers': ['Mac10.11', 'Release']},
            'MOCK Mac10.11': {'port_name': 'test-mac-mac10.11', 'specifiers': ['Mac10.11', 'Release']},
            'MOCK Precise': {'port_name': 'test-linux-precise', 'specifiers': ['Precise', 'Release']},
            'MOCK Trusty': {'port_name': 'test-linux-trusty', 'specifiers': ['Trusty', 'Release']},
            'MOCK Win10': {'port_name': 'test-win-win10', 'specifiers': ['Win10', 'Release']},
            'MOCK Win7 (dbg)': {'port_name': 'test-win-win7', 'specifiers': ['Win7', 'Debug']},
            'MOCK Win7 (dbg)(1)': {'port_name': 'test-win-win7', 'specifiers': ['Win7', 'Debug']},
            'MOCK Win7 (dbg)(2)': {'port_name': 'test-win-win7', 'specifiers': ['Win7', 'Debug']},
            'MOCK Win7': {'port_name': 'test-win-win7', 'specifiers': ['Win7', 'Release']},
        })
        self.mac_port = self.tool.port_factory.get_from_builder_name('MOCK Mac10.11')
        self.test_expectations_path = self.mac_port.path_to_generic_test_expectations_file()

        # This file must exist for Port classes to function properly.
        self._write('VirtualTestSuites', '[]')
        # Create some dummy tests (note _setup_mock_build_data uses the same test names).
        self._write('userscripts/first-test.html', 'Dummy test contents')
        self._write('userscripts/second-test.html', 'Dummy test contents')

        # In AbstractParallelRebaselineCommand._rebaseline_commands, a default port
        # object is gotten using self.tool.port_factory.get(), which is used to get
        # test paths -- and the layout tests directory may be different for the "test"
        # ports and real ports. Since only "test" ports are used in this class,
        # we can make the default port also a "test" port.
        self.original_port_factory_get = self.tool.port_factory.get
        test_port = self.tool.port_factory.get('test')

        def get_test_port(port_name=None, options=None, **kwargs):
            if not port_name:
                return test_port
            return self.original_port_factory_get(port_name, options, **kwargs)

        self.tool.port_factory.get = get_test_port

    def tearDown(self):
        self.tool.port_factory.get = self.original_port_factory_get

    def _expand(self, path):
        if self.tool.filesystem.isabs(path):
            return path
        return self.tool.filesystem.join(self.mac_port.layout_tests_dir(), path)

    def _read(self, path):
        return self.tool.filesystem.read_text_file(self._expand(path))

    def _write(self, path, contents):
        self.tool.filesystem.write_text_file(self._expand(path), contents)

    def _zero_out_test_expectations(self):
        for port_name in self.tool.port_factory.all_port_names():
            port = self.tool.port_factory.get(port_name)
            for path in port.expectations_files():
                self._write(path, '')
        self.tool.filesystem.written_files = {}

    def _setup_mock_build_data(self):
        for builder in ['MOCK Win7', 'MOCK Win7 (dbg)', 'MOCK Mac10.11']:
            self.tool.buildbot.set_results(Build(builder), LayoutTestResults({
                'tests': {
                    'userscripts': {
                        'first-test.html': {
                            'expected': 'PASS',
                            'actual': 'IMAGE+TEXT',
                            'is_unexpected': True,
                        },
                        'second-test.html': {
                            'expected': 'FAIL',
                            'actual': 'IMAGE+TEXT',
                        }
                    }
                }
            }))



class TestAbstractParallelRebaselineCommand(BaseTestCase):
    """Tests for the base class of multiple rebaseline commands.

    This class only contains test cases for utility methods. Some common
    behaviours of various rebaseline commands are tested in TestRebaseline.
    """

    command_constructor = AbstractParallelRebaselineCommand

    def test_builders_to_fetch_from(self):
        # pylint: disable=protected-access
        builders_to_fetch = self.command._builders_to_fetch_from(
            ['MOCK Win10', 'MOCK Win7 (dbg)(1)', 'MOCK Win7 (dbg)(2)', 'MOCK Win7'])
        self.assertEqual(builders_to_fetch, {'MOCK Win7', 'MOCK Win10'})

    def test_generic_baseline_paths(self):
        test_baseline_set = TestBaselineSet(self.tool)
        # Multiple ports shouldn't produce duplicate baseline paths.
        test_baseline_set.add('passes/text.html', Build('MOCK Win7'))
        test_baseline_set.add('passes/text.html', Build('MOCK Win10'))

        # pylint: disable=protected-access
        baseline_paths = self.command._generic_baseline_paths(test_baseline_set)
        self.assertEqual(baseline_paths, [
            '/test.checkout/wtests/passes/text-expected.png',
            '/test.checkout/wtests/passes/text-expected.txt',
            '/test.checkout/wtests/passes/text-expected.wav',
        ])

    def test_unstaged_baselines(self):
        git = self.tool.git()
        git.unstaged_changes = lambda: {
            RELATIVE_WEB_TESTS + 'x/foo-expected.txt': 'M',
            RELATIVE_WEB_TESTS + 'x/foo-expected.something': '?',
            RELATIVE_WEB_TESTS + 'x/foo-expected.png': '?',
            RELATIVE_WEB_TESTS + 'x/foo.html': 'M',
            'docs/something.md': '?',
        }
        self.assertEqual(
            self.command.unstaged_baselines(),
            [
                '/mock-checkout/' + RELATIVE_WEB_TESTS + 'x/foo-expected.png',
                '/mock-checkout/' + RELATIVE_WEB_TESTS + 'x/foo-expected.txt',
            ])


class TestRebaseline(BaseTestCase):
    """Tests for the blink_tool.py rebaseline command.

    Also tests some common behaviours of all rebaseline commands.
    """

    command_constructor = Rebaseline

    def setUp(self):
        super(TestRebaseline, self).setUp()
        self.tool.executive = MockExecutive()
        self._setup_mock_build_data()

    def tearDown(self):
        super(TestRebaseline, self).tearDown()

    @staticmethod
    def options(**kwargs):
        return optparse.Values(dict({
            'optimize': True,
            'verbose': True,
            'results_directory': None
        }, **kwargs))

    def test_rebaseline_test_passes_on_all_builders(self):
        self.tool.buildbot.set_results(Build('MOCK Win7'), LayoutTestResults({
            'tests': {
                'userscripts': {
                    'first-test.html': {
                        'expected': 'REBASELINE',
                        'actual': 'PASS'
                    }
                }
            }
        }))

        self._write(self.test_expectations_path, 'Bug(x) userscripts/first-test.html [ Failure ]\n')
        test_baseline_set = TestBaselineSet(self.tool)
        test_baseline_set.add('userscripts/first-test.html', Build('MOCK Win7'))
        self.command.rebaseline(self.options(), test_baseline_set)

        self.assertEqual(self.tool.executive.calls, [])

    def test_rebaseline_all(self):
        test_baseline_set = TestBaselineSet(self.tool)
        test_baseline_set.add('userscripts/first-test.html', Build('MOCK Win7'))
        self.command.rebaseline(self.options(), test_baseline_set)

        self.assertEqual(
            self.tool.executive.calls,
            [
                [[
                    'python', 'echo', 'copy-existing-baselines-internal',
                    '--verbose',
                    '--test', 'userscripts/first-test.html',
                    '--suffixes', 'txt,png',
                    '--port-name', 'test-win-win7',
                ]],
                [[
                    'python', 'echo', 'rebaseline-test-internal',
                    '--verbose',
                    '--test', 'userscripts/first-test.html',
                    '--suffixes', 'txt,png',
                    '--port-name', 'test-win-win7',
                    '--builder', 'MOCK Win7',
                    '--step-name', 'webkit_layout_tests (with patch)',
                ]],
                [[
                    'python', 'echo', 'optimize-baselines',
                    '--verbose',
                    '--suffixes', 'txt,png',
                    'userscripts/first-test.html',
                ]]
            ])

    def test_rebaseline_debug(self):
        test_baseline_set = TestBaselineSet(self.tool)
        test_baseline_set.add('userscripts/first-test.html', Build('MOCK Win7 (dbg)'))

        self.command.rebaseline(self.options(), test_baseline_set)

        self.assertEqual(
            self.tool.executive.calls,
            [
                [[
                    'python', 'echo', 'copy-existing-baselines-internal',
                    '--verbose',
                    '--test', 'userscripts/first-test.html',
                    '--suffixes', 'txt,png',
                    '--port-name', 'test-win-win7',
                ]],
                [[
                    'python', 'echo', 'rebaseline-test-internal',
                    '--verbose',
                    '--test', 'userscripts/first-test.html',
                    '--suffixes', 'txt,png',
                    '--port-name', 'test-win-win7',
                    '--builder', 'MOCK Win7 (dbg)',
                    '--step-name', 'webkit_layout_tests (with patch)',
                ]],
                [[
                    'python', 'echo', 'optimize-baselines',
                    '--verbose',
                    '--suffixes', 'txt,png',
                    'userscripts/first-test.html',
                ]]
            ])

    def test_no_optimize(self):
        test_baseline_set = TestBaselineSet(self.tool)
        test_baseline_set.add('userscripts/first-test.html', Build('MOCK Win7'))
        self.command.rebaseline(self.options(optimize=False), test_baseline_set)

        self.assertEqual(
            self.tool.executive.calls,
            [
                [[
                    'python', 'echo', 'copy-existing-baselines-internal',
                    '--verbose',
                    '--test', 'userscripts/first-test.html',
                    '--suffixes', 'txt,png',
                    '--port-name', 'test-win-win7',

                ]],
                [[
                    'python', 'echo', 'rebaseline-test-internal',
                    '--verbose',
                    '--test', 'userscripts/first-test.html',
                    '--suffixes', 'txt,png',
                    '--port-name', 'test-win-win7',
                    '--builder', 'MOCK Win7',
                    '--step-name', 'webkit_layout_tests (with patch)',
                ]]
            ])

    def test_results_directory(self):
        test_baseline_set = TestBaselineSet(self.tool)
        test_baseline_set.add('userscripts/first-test.html', Build('MOCK Win7'))
        self.command.rebaseline(self.options(optimize=False, results_directory='/tmp'), test_baseline_set)

        self.assertEqual(
            self.tool.executive.calls,
            [
                [[
                    'python', 'echo', 'copy-existing-baselines-internal',
                    '--verbose',
                    '--test', 'userscripts/first-test.html',
                    '--suffixes', 'txt,png',
                    '--port-name', 'test-win-win7',
                ]],
                [[
                    'python', 'echo', 'rebaseline-test-internal',
                    '--verbose',
                    '--test', 'userscripts/first-test.html',
                    '--suffixes', 'txt,png',
                    '--port-name', 'test-win-win7',
                    '--builder', 'MOCK Win7',
                    '--results-directory', '/tmp',
                    '--step-name', 'webkit_layout_tests (with patch)',
                ]],
            ])

    def test_rebaseline_with_different_port_name(self):
        test_baseline_set = TestBaselineSet(self.tool)
        test_baseline_set.add('userscripts/first-test.html', Build('MOCK Win7'), 'test-win-win10')
        self.command.rebaseline(self.options(), test_baseline_set)

        self.assertEqual(
            self.tool.executive.calls,
            [
                [[
                    'python', 'echo', 'copy-existing-baselines-internal',
                    '--verbose',
                    '--test', 'userscripts/first-test.html',
                    '--suffixes', 'txt,png',
                    '--port-name', 'test-win-win10',

                ]],
                [[
                    'python', 'echo', 'rebaseline-test-internal',
                    '--verbose',
                    '--test', 'userscripts/first-test.html',
                    '--suffixes', 'txt,png',
                    '--port-name', 'test-win-win10',
                    '--builder', 'MOCK Win7',
                    '--step-name', 'webkit_layout_tests (with patch)',
                ]],
                [[
                    'python', 'echo', 'optimize-baselines',
                    '--verbose',
                    '--suffixes', 'txt,png',
                    'userscripts/first-test.html',
                ]]
            ])


class TestRebaselineUpdatesExpectationsFiles(BaseTestCase):
    """Tests for the logic related to updating the test expectations file."""

    command_constructor = Rebaseline

    def setUp(self):
        super(TestRebaselineUpdatesExpectationsFiles, self).setUp()

        def mock_run_command(*args, **kwargs):  # pylint: disable=unused-argument
            return '{"add": [], "remove-lines": [{"test": "userscripts/first-test.html", "port_name": "test-mac-mac10.11"}]}\n'
        self.tool.executive = MockExecutive(run_command_fn=mock_run_command)

    @staticmethod
    def options():
        return optparse.Values({
            'optimize': False,
            'verbose': True,
            'results_directory': None
        })

    # In the following test cases, we use a mock rebaseline-test-internal to
    # pretend userscripts/first-test.html can be rebaselined on Mac10.11, so
    # the corresponding expectation (if exists) should be updated.

    def test_rebaseline_updates_expectations_file(self):
        self._write(
            self.test_expectations_path,
            ('Bug(x) [ Mac ] userscripts/first-test.html [ Failure ]\n'
             'bug(z) [ Linux ] userscripts/first-test.html [ Failure ]\n'))
        self._setup_mock_build_data()
        test_baseline_set = TestBaselineSet(self.tool)
        test_baseline_set.add('userscripts/first-test.html', Build('MOCK Mac10.11'))

        self.command.rebaseline(self.options(), test_baseline_set)

        new_expectations = self._read(self.test_expectations_path)
        self.assertMultiLineEqual(
            new_expectations,
            ('Bug(x) [ Mac10.10 ] userscripts/first-test.html [ Failure ]\n'
             'bug(z) [ Linux ] userscripts/first-test.html [ Failure ]\n'))

    def test_rebaseline_updates_expectations_file_all_platforms(self):
        self._write(self.test_expectations_path, 'Bug(x) userscripts/first-test.html [ Failure ]\n')
        self._setup_mock_build_data()
        test_baseline_set = TestBaselineSet(self.tool)
        test_baseline_set.add('userscripts/first-test.html', Build('MOCK Mac10.11'))

        self.command.rebaseline(self.options(), test_baseline_set)

        new_expectations = self._read(self.test_expectations_path)
        self.assertMultiLineEqual(
            new_expectations, 'Bug(x) [ Linux Mac10.10 Win ] userscripts/first-test.html [ Failure ]\n')

    def test_rebaseline_handles_platform_skips(self):
        # This test is just like test_rebaseline_updates_expectations_file_all_platforms(),
        # except that if a particular port happens to SKIP a test in an overrides file,
        # we count that as passing, and do not think that we still need to rebaseline it.
        self._write(self.test_expectations_path, 'Bug(x) userscripts/first-test.html [ Failure ]\n')
        self._write('NeverFixTests', 'Bug(y) [ Android ] userscripts [ WontFix ]\n')
        self._setup_mock_build_data()
        test_baseline_set = TestBaselineSet(self.tool)
        test_baseline_set.add('userscripts/first-test.html', Build('MOCK Mac10.11'))

        self.command.rebaseline(self.options(), test_baseline_set)

        new_expectations = self._read(self.test_expectations_path)
        self.assertMultiLineEqual(
            new_expectations, 'Bug(x) [ Linux Mac10.10 Win ] userscripts/first-test.html [ Failure ]\n')

    def test_rebaseline_handles_skips_in_file(self):
        # This test is like test_rebaseline_handles_platform_skips, except that the
        # Skip is in the same (generic) file rather than a platform file. In this case,
        # the Skip line should be left unmodified. Note that the first line is now
        # qualified as "[Linux Mac Win]"; if it was unqualified, it would conflict with
        # the second line.
        self._write(self.test_expectations_path,
                    ('Bug(x) [ Linux Mac ] userscripts/first-test.html [ Failure ]\n'
                     'Bug(y) [ Win ] userscripts/first-test.html [ Skip ]\n'))
        self._setup_mock_build_data()
        test_baseline_set = TestBaselineSet(self.tool)
        test_baseline_set.add('userscripts/first-test.html', Build('MOCK Mac10.11'))

        self.command.rebaseline(self.options(), test_baseline_set)

        new_expectations = self._read(self.test_expectations_path)
        self.assertMultiLineEqual(
            new_expectations,
            ('Bug(x) [ Linux Mac10.10 ] userscripts/first-test.html [ Failure ]\n'
             'Bug(y) [ Win ] userscripts/first-test.html [ Skip ]\n'))

    def test_rebaseline_handles_smoke_tests(self):
        # This test is just like test_rebaseline_handles_platform_skips, except that we check for
        # a test not being in the SmokeTests file, instead of using overrides files.
        # If a test is not part of the smoke tests, we count that as passing on ports that only
        # run smoke tests, and do not think that we still need to rebaseline it.
        self._write(self.test_expectations_path, 'Bug(x) userscripts/first-test.html [ Failure ]\n')
        self._write('SmokeTests', 'fast/html/article-element.html')
        self._setup_mock_build_data()
        test_baseline_set = TestBaselineSet(self.tool)
        test_baseline_set.add('userscripts/first-test.html', Build('MOCK Mac10.11'))

        self.command.rebaseline(self.options(), test_baseline_set)

        new_expectations = self._read(self.test_expectations_path)
        self.assertMultiLineEqual(
            new_expectations, 'Bug(x) [ Linux Mac10.10 Win ] userscripts/first-test.html [ Failure ]\n')

    # In the following test cases, the tests produce no outputs (e.g. clean
    # passing reftests, skipped tests, etc.). Hence, there are no baselines to
    # fetch (empty baseline suffixes), and rebaseline-test-internal wouldn't be
    # called. However, in some cases the expectations still need to be updated.

    def test_rebaseline_keeps_skip_expectations(self):
        # [ Skip ], [ WontFix ] expectations should always be kept.
        self._write(self.test_expectations_path,
                    ('Bug(x) [ Mac ] userscripts/skipped-test.html [ WontFix ]\n'
                     'Bug(y) [ Win ] userscripts/skipped-test.html [ Skip ]\n'))
        self._write('userscripts/skipped-test.html', 'Dummy test contents')
        self.tool.buildbot.set_results(Build('MOCK Mac10.11'), LayoutTestResults({
            'tests': {
                'userscripts': {
                    'skipped-test.html': {
                        'expected': 'WONTFIX',
                        'actual': 'SKIP',
                    }
                }
            }
        }))
        self.tool.buildbot.set_results(Build('MOCK Win7'), LayoutTestResults({
            'tests': {
                'userscripts': {
                    'skipped-test.html': {
                        'expected': 'SKIP',
                        'actual': 'SKIP',
                    }
                }
            }
        }))
        test_baseline_set = TestBaselineSet(self.tool)
        test_baseline_set.add('userscripts/skipped-test.html', Build('MOCK Mac10.11'))
        test_baseline_set.add('userscripts/skipped-test.html', Build('MOCK Win7'))

        self.command.rebaseline(self.options(), test_baseline_set)

        new_expectations = self._read(self.test_expectations_path)
        self.assertMultiLineEqual(
            new_expectations,
            ('Bug(x) [ Mac ] userscripts/skipped-test.html [ WontFix ]\n'
             'Bug(y) [ Win ] userscripts/skipped-test.html [ Skip ]\n'))
        self.assertEqual(self.tool.executive.calls, [])

    def test_rebaseline_keeps_flaky_expectations(self):
        # Flaky expectations should be kept even if the test passes.
        self._write(self.test_expectations_path, 'Bug(x) userscripts/flaky-test.html [ Pass Failure ]\n')
        self._write('userscripts/flaky-test.html', 'Dummy test contents')
        self.tool.buildbot.set_results(Build('MOCK Mac10.11'), LayoutTestResults({
            'tests': {
                'userscripts': {
                    'flaky-test.html': {
                        'expected': 'PASS FAIL',
                        'actual': 'PASS',
                    }
                }
            }
        }))
        test_baseline_set = TestBaselineSet(self.tool)
        test_baseline_set.add('userscripts/flaky-test.html', Build('MOCK Mac10.11'))

        self.command.rebaseline(self.options(), test_baseline_set)

        new_expectations = self._read(self.test_expectations_path)
        self.assertMultiLineEqual(
            new_expectations, 'Bug(x) userscripts/flaky-test.html [ Pass Failure ]\n')
        self.assertEqual(self.tool.executive.calls, [])

    def test_rebaseline_test_passes_unexpectedly(self):
        # The test passes without any output. Its expectation should be updated
        # without calling rebaseline-test-internal.
        self._write(self.test_expectations_path, 'Bug(foo) userscripts/all-pass.html [ Failure ]\n')
        self._write('userscripts/all-pass.html', 'Dummy test contents')
        test_baseline_set = TestBaselineSet(self.tool)
        self.tool.buildbot.set_results(Build('MOCK Mac10.11'), LayoutTestResults({
            'tests': {
                'userscripts': {
                    'all-pass.html': {
                        'expected': 'FAIL',
                        'actual': 'PASS',
                        'is_unexpected': True
                    }
                }
            }
        }))
        test_baseline_set.add('userscripts/all-pass.html', Build('MOCK Mac10.11'))

        self.command.rebaseline(self.options(), test_baseline_set)

        new_expectations = self._read(self.test_expectations_path)
        self.assertMultiLineEqual(
            new_expectations, 'Bug(foo) [ Linux Mac10.10 Win ] userscripts/all-pass.html [ Failure ]\n')
        self.assertEqual(self.tool.executive.calls, [])

    def test_rebaseline_test_passes_unexpectedly_everywhere(self):
        # Similar to test_rebaseline_test_passes_unexpectedly, except that the
        # test passes on all ports.
        self._write(self.test_expectations_path, 'Bug(foo) userscripts/all-pass.html [ Failure ]\n')
        self._write('userscripts/all-pass.html', 'Dummy test contents')
        test_baseline_set = TestBaselineSet(self.tool)
        for builder in ['MOCK Win7', 'MOCK Win10', 'MOCK Mac10.10', 'MOCK Mac10.11', 'MOCK Precise', 'MOCK Trusty']:
            self.tool.buildbot.set_results(Build(builder), LayoutTestResults({
                'tests': {
                    'userscripts': {
                        'all-pass.html': {
                            'expected': 'FAIL',
                            'actual': 'PASS',
                            'is_unexpected': True
                        }
                    }
                }
            }))
            test_baseline_set.add('userscripts/all-pass.html', Build(builder))

        self.command.rebaseline(self.options(), test_baseline_set)

        new_expectations = self._read(self.test_expectations_path)
        self.assertMultiLineEqual(new_expectations, '')
        self.assertEqual(self.tool.executive.calls, [])

    def test_rebaseline_test_passes_unexpectedly_but_on_another_port(self):
        # Similar to test_rebaseline_test_passes_unexpectedly, except that the
        # build was run on a different port than the port we are rebaselining
        # (possible when rebaseline-cl --fill-missing), in which case we don't
        # update the expectations.
        self._write(self.test_expectations_path, 'Bug(foo) userscripts/all-pass.html [ Failure ]\n')
        self._write('userscripts/all-pass.html', 'Dummy test contents')
        test_baseline_set = TestBaselineSet(self.tool)
        self.tool.buildbot.set_results(Build('MOCK Mac10.11'), LayoutTestResults({
            'tests': {
                'userscripts': {
                    'all-pass.html': {
                        'expected': 'FAIL',
                        'actual': 'PASS',
                        'is_unexpected': True
                    }
                }
            }
        }))
        test_baseline_set.add('userscripts/all-pass.html', Build('MOCK Mac10.11'), 'MOCK Mac10.10')

        self.command.rebaseline(self.options(), test_baseline_set)

        new_expectations = self._read(self.test_expectations_path)
        self.assertMultiLineEqual(
            new_expectations, 'Bug(foo) userscripts/all-pass.html [ Failure ]\n')
        self.assertEqual(self.tool.executive.calls, [])


class TestRebaselineExecute(BaseTestCase):
    """Tests for the main execute function of the blink_tool.py rebaseline command."""

    command_constructor = Rebaseline

    @staticmethod
    def options():
        return optparse.Values({
            'results_directory': False,
            'optimize': False,
            'builders': None,
            'suffixes': 'txt,png',
            'verbose': True
        })

    def test_rebaseline(self):
        # pylint: disable=protected-access
        self.command._builders_to_pull_from = lambda: ['MOCK Win7']
        self._setup_mock_build_data()
        self.command.execute(self.options(), ['userscripts/first-test.html'], self.tool)

        self.assertEqual(
            self.tool.executive.calls,
            [
                [[
                    'python', 'echo', 'copy-existing-baselines-internal',
                    '--verbose',
                    '--test', 'userscripts/first-test.html',
                    '--suffixes', 'txt,png',
                    '--port-name', 'test-win-win7',
                ]],
                [[
                    'python', 'echo', 'rebaseline-test-internal',
                    '--verbose',
                    '--test', 'userscripts/first-test.html',
                    '--suffixes', 'txt,png',
                    '--port-name', 'test-win-win7',
                    '--builder', 'MOCK Win7',
                    '--step-name', 'webkit_layout_tests (with patch)',
                ]]
            ])

    def test_rebaseline_directory(self):
        # pylint: disable=protected-access
        self.command._builders_to_pull_from = lambda: ['MOCK Win7']

        self._setup_mock_build_data()
        self.command.execute(self.options(), ['userscripts'], self.tool)

        self.assertEqual(
            self.tool.executive.calls,
            [
                [
                    [
                        'python', 'echo', 'copy-existing-baselines-internal',
                        '--verbose',
                        '--test', 'userscripts/first-test.html',
                        '--suffixes', 'txt,png',
                        '--port-name', 'test-win-win7',
                    ],
                    [
                        'python', 'echo', 'copy-existing-baselines-internal',
                        '--verbose',
                        '--test', 'userscripts/second-test.html',
                        '--suffixes', 'txt,png',
                        '--port-name', 'test-win-win7',
                    ]
                ],
                [
                    [
                        'python', 'echo', 'rebaseline-test-internal',
                        '--verbose',
                        '--test', 'userscripts/first-test.html',
                        '--suffixes', 'txt,png',
                        '--port-name', 'test-win-win7',
                        '--builder', 'MOCK Win7',
                        '--step-name', 'webkit_layout_tests (with patch)',
                    ],
                    [
                        'python', 'echo', 'rebaseline-test-internal',
                        '--verbose',
                        '--test', 'userscripts/second-test.html',
                        '--suffixes', 'txt,png',
                        '--port-name', 'test-win-win7',
                        '--builder', 'MOCK Win7',
                        '--step-name', 'webkit_layout_tests (with patch)',
                    ]
                ]
            ])


class TestBaselineSetTest(unittest.TestCase):

    def setUp(self):
        host = MockBlinkTool()
        host.port_factory = MockPortFactory(host)
        port = host.port_factory.get()
        base_dir = port.layout_tests_dir()
        host.filesystem.write_text_file(base_dir + '/a/x.html', '<html>')
        host.filesystem.write_text_file(base_dir + '/a/y.html', '<html>')
        host.filesystem.write_text_file(base_dir + '/a/z.html', '<html>')
        host.builders = BuilderList({
            'MOCK Mac10.12': {'port_name': 'test-mac-mac10.12', 'specifiers': ['Mac10.12', 'Release']},
            'MOCK Trusty': {'port_name': 'test-linux-trusty', 'specifiers': ['Trusty', 'Release']},
            'MOCK Win10': {'port_name': 'test-win-win10', 'specifiers': ['Win10', 'Release']},
        })
        self.host = host

    def test_add_and_iter_tests(self):
        test_baseline_set = TestBaselineSet(host=self.host)
        test_baseline_set.add('a', Build('MOCK Trusty'))
        test_baseline_set.add('a/z.html', Build('MOCK Win10'))
        self.assertEqual(
            list(test_baseline_set),
            [
                ('a/x.html', Build(builder_name='MOCK Trusty'), 'test-linux-trusty'),
                ('a/y.html', Build(builder_name='MOCK Trusty'), 'test-linux-trusty'),
                ('a/z.html', Build(builder_name='MOCK Trusty'), 'test-linux-trusty'),
                ('a/z.html', Build(builder_name='MOCK Win10'), 'test-win-win10'),
            ])
        self.assertEqual(
            test_baseline_set.all_tests(), ['a/x.html', 'a/y.html', 'a/z.html'])

    def test_str_empty(self):
        test_baseline_set = TestBaselineSet(host=self.host)
        self.assertEqual(str(test_baseline_set), '<Empty TestBaselineSet>')

    def test_str_basic(self):
        test_baseline_set = TestBaselineSet(host=self.host)
        test_baseline_set.add('a/x.html', Build('MOCK Mac10.12'))
        test_baseline_set.add('a/x.html', Build('MOCK Win10'))
        self.assertEqual(
            str(test_baseline_set),
            ('<TestBaselineSet with:\n'
             '  a/x.html: Build(builder_name=\'MOCK Mac10.12\', build_number=None), test-mac-mac10.12\n'
             '  a/x.html: Build(builder_name=\'MOCK Win10\', build_number=None), test-win-win10>'))

    def test_getters(self):
        test_baseline_set = TestBaselineSet(host=self.host)
        test_baseline_set.add('a/x.html', Build('MOCK Mac10.12'))
        test_baseline_set.add('a/x.html', Build('MOCK Win10'))
        self.assertEqual(test_baseline_set.test_prefixes(), ['a/x.html'])
        self.assertEqual(
            test_baseline_set.build_port_pairs('a/x.html'),
            [
                (Build(builder_name='MOCK Mac10.12'), 'test-mac-mac10.12'),
                (Build(builder_name='MOCK Win10'), 'test-win-win10')
            ])