Class: Happo::SnapshotComparer

Inherits:
Object
  • Object
show all
Defined in:
lib/happo/snapshot_comparer.rb

Overview

This class is responsible for comparing two Snapshots and generating a diff.

Instance Method Summary collapse

Constructor Details

#initialize(png_before, png_after) ⇒ SnapshotComparer

Returns a new instance of SnapshotComparer.

Parameters:

  • png_before (ChunkyPNG::Image)
  • png_after (ChunkyPNG::Image)


14
15
16
17
# File 'lib/happo/snapshot_comparer.rb', line 14

def initialize(png_before, png_after)
  @png_after  = png_after
  @png_before = png_before
end

Instance Method Details

#compare!Hash

Returns:

  • (Hash)


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
# File 'lib/happo/snapshot_comparer.rb', line 20

def compare!
  no_diff = {
    diff_in_percent: 0,
    diff_image: nil,
  }

  # If these images are totally identical, we don't need to do any more
  # work.
  return no_diff if @png_before == @png_after

  array_before = to_array_of_arrays(@png_before)
  array_after = to_array_of_arrays(@png_after)

  # If the arrays of arrays of colors are identical, we don't need to do any
  # more work. This might happen if some of the headers are different.
  return no_diff if array_before == array_after

  sdiff = Diff::LCS.sdiff(array_before, array_after)
  number_of_different_rows = 0

  sprite, all_comparisons = initialize_comparison_images(
    [@png_after.width, @png_before.width].max, sdiff.size)

  sdiff.each_with_index do |row, y|
    # each row is a Diff::LCS::ContextChange instance
    all_comparisons.each { |image| image.render_row(y, row) }
    number_of_different_rows += 1 unless row.unchanged?
  end

  percent_changed = number_of_different_rows.to_f / sdiff.size * 100
  {
    diff_in_percent: percent_changed,
    diff_image:      (sprite if percent_changed > 0),
  }
end