Class: DiffuxCI::SnapshotComparer

Inherits:
Object
  • Object
show all
Defined in:
lib/diffux_ci/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)


10
11
12
13
# File 'lib/diffux_ci/snapshot_comparer.rb', line 10

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

Instance Method Details

#compare!Hash

Returns:

  • (Hash)


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

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

  # 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)
  cluster_finder  = DiffClusterFinder.new(sdiff.size)
  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) }
    cluster_finder.row_is_different(y) unless row.unchanged?
  end

  percent_changed = cluster_finder.percent_of_rows_different
  {
    diff_in_percent: percent_changed,
    diff_image:      (sprite if percent_changed > 0),
    diff_clusters:   cluster_finder.clusters,
  }
end