Created
June 1, 2020 12:17
-
-
Save gabteles/d2f8dd3ce3ecaa0a6f754d85d06c18c5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
class PDFSnapshotComparator | |
def initialize(generated) | |
@generated = generated | |
end | |
def same?(expectation) | |
out1 = Tempfile.new(['', '.png']) | |
out2 = Tempfile.new(['', '.png']) | |
convert(@generated, out1.path) | |
File.binwrite(expectation, File.binread(out1.path)) unless File.exist?(expectation) | |
diff(out1.path, expectation_path, out2.path) | |
histogram(out2.path).lines.count == 1 | |
end | |
private | |
def convert(pdf, output) | |
MiniMagick::Tool::Convert.new do |convert| | |
convert.density('300') | |
convert << pdf | |
convert.alpha('remove') | |
convert.quality('150') | |
convert.append.+ # rubocop:disable Lint/Void | |
convert << output | |
end | |
end | |
def diff(generated, expectation, output) | |
MiniMagick::Tool::Convert.new do |convert| | |
convert << generated | |
convert << expectation | |
convert.alpha('remove') | |
convert.compose('difference') | |
convert.composite | |
convert << "png8:#{output}" | |
end | |
end | |
def histogram(file) | |
MiniMagick::Tool::Convert.new do |convert| | |
convert << file | |
convert.define('histogram:unique-colors=true') | |
convert.format('%c') # rubocop:disable Style/FormatStringToken | |
convert << 'histogram:info:-' | |
end | |
end | |
end | |
# USAGE: | |
PDFSnapshotComparator.new(generated_file.path).same?(expected_file.path) | |
# If expected file does not exists, it'll pass automatically, by creating it with generated file's content |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment