summaryrefslogtreecommitdiffstats
path: root/WebKitTools/Scripts/webkitpy/layout_tests/test_types/image_diff.py
blob: b0bf189f81986a0eaa270cab05ce08bde28945f6 (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
#!/usr/bin/env python
# Copyright (C) 2010 The Chromium Authors. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#     * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
#     * Neither the Chromium name nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Compares the image output of a test to the expected image output.

Compares hashes for the generated and expected images. If the output doesn't
match, returns FailureImageHashMismatch and outputs both hashes into the layout
test results directory.
"""

import errno
import logging
import os
import shutil
import subprocess

from layout_package import path_utils
from layout_package import test_failures
from test_types import test_type_base

# Cache whether we have the image_diff executable available.
_compare_available = True
_compare_msg_printed = False


class ImageDiff(test_type_base.TestTypeBase):

    def _copy_output_png(self, test_filename, source_image, extension):
        """Copies result files into the output directory with appropriate
        names.

        Args:
          test_filename: the test filename
          source_file: path to the image file (either actual or expected)
          extension: extension to indicate -actual.png or -expected.png
        """
        self._make_output_directory(test_filename)
        dest_image = self.output_filename(test_filename, extension)

        try:
            shutil.copyfile(source_image, dest_image)
        except IOError, e:
            # A missing expected PNG has already been recorded as an error.
            if errno.ENOENT != e.errno:
                raise

    def _save_baseline_files(self, filename, png_path, checksum):
        """Saves new baselines for the PNG and checksum.

        Args:
          filename: test filename
          png_path: path to the actual PNG result file
          checksum: value of the actual checksum result
        """
        png_file = open(png_path, "rb")
        png_data = png_file.read()
        png_file.close()
        self._save_baseline_data(filename, png_data, ".png")
        self._save_baseline_data(filename, checksum, ".checksum")

    def _create_image_diff(self, filename, target):
        """Creates the visual diff of the expected/actual PNGs.

        Args:
          filename: the name of the test
          target: Debug or Release
        """
        diff_filename = self.output_filename(filename,
          self.FILENAME_SUFFIX_COMPARE)
        actual_filename = self.output_filename(filename,
          self.FILENAME_SUFFIX_ACTUAL + '.png')
        expected_filename = self.output_filename(filename,
          self.FILENAME_SUFFIX_EXPECTED + '.png')

        global _compare_available
        cmd = ''

        try:
            executable = path_utils.image_diff_path(target)
            cmd = [executable, '--diff', actual_filename, expected_filename,
                   diff_filename]
        except Exception, e:
            _compare_available = False

        result = 1
        if _compare_available:
            try:
                result = subprocess.call(cmd)
            except OSError, e:
                if e.errno == errno.ENOENT or e.errno == errno.EACCES:
                    _compare_available = False
                else:
                    raise e
            except ValueError:
                # work around a race condition in Python 2.4's implementation
                # of subprocess.Popen
                pass

        global _compare_msg_printed

        if not _compare_available and not _compare_msg_printed:
            _compare_msg_printed = True
            print('image_diff not found. Make sure you have a ' + target +
                  ' build of the image_diff executable.')

        return result

    def compare_output(self, filename, proc, output, test_args, target):
        """Implementation of CompareOutput that checks the output image and
        checksum against the expected files from the LayoutTest directory.
        """
        failures = []

        # If we didn't produce a hash file, this test must be text-only.
        if test_args.hash is None:
            return failures

        # If we're generating a new baseline, we pass.
        if test_args.new_baseline:
            self._save_baseline_files(filename, test_args.png_path,
                                    test_args.hash)
            return failures

        # Compare hashes.
        expected_hash_file = path_utils.expected_filename(filename,
                                                          '.checksum')
        expected_png_file = path_utils.expected_filename(filename, '.png')

        if test_args.show_sources:
            logging.debug('Using %s' % expected_hash_file)
            logging.debug('Using %s' % expected_png_file)

        try:
            expected_hash = open(expected_hash_file, "r").read()
        except IOError, e:
            if errno.ENOENT != e.errno:
                raise
            expected_hash = ''


        if not os.path.isfile(expected_png_file):
            # Report a missing expected PNG file.
            self.write_output_files(filename, '', '.checksum', test_args.hash,
                                    expected_hash, diff=False, wdiff=False)
            self._copy_output_png(filename, test_args.png_path, '-actual.png')
            failures.append(test_failures.FailureMissingImage(self))
            return failures
        elif test_args.hash == expected_hash:
            # Hash matched (no diff needed, okay to return).
            return failures


        self.write_output_files(filename, '', '.checksum', test_args.hash,
                                expected_hash, diff=False, wdiff=False)
        self._copy_output_png(filename, test_args.png_path, '-actual.png')
        self._copy_output_png(filename, expected_png_file, '-expected.png')

        # Even though we only use result in one codepath below but we
        # still need to call CreateImageDiff for other codepaths.
        result = self._create_image_diff(filename, target)
        if expected_hash == '':
            failures.append(test_failures.FailureMissingImageHash(self))
        elif test_args.hash != expected_hash:
            # Hashes don't match, so see if the images match. If they do, then
            # the hash is wrong.
            if result == 0:
                failures.append(test_failures.FailureImageHashIncorrect(self))
            else:
                failures.append(test_failures.FailureImageHashMismatch(self))

        return failures

    def diff_files(self, file1, file2):
        """Diff two image files.

        Args:
          file1, file2: full paths of the files to compare.

        Returns:
          True if two files are different.
          False otherwise.
        """

        try:
            executable = path_utils.image_diff_path('Debug')
        except Exception, e:
            logging.warn('Failed to find image diff executable.')
            return True

        cmd = [executable, file1, file2]
        result = 1
        try:
            result = subprocess.call(cmd)
        except OSError, e:
            logging.warn('Failed to compare image diff: %s', e)
            return True

        return result == 1