Module: Minitest::HashDiff
- Defined in:
- lib/minitest/hashdiff.rb,
lib/minitest/hashdiff/version.rb
Overview
Formats the difference between two hashes as a readable, sorted, type-aware report instead of two walls of inspect output.
Constant Summary collapse
- VERSION =
"0.1.1"
Class Method Summary collapse
- .display_type(value) ⇒ Object
-
.format(expected, actual) ⇒ Object
Returns a readable diff report, or nil when nothing differs.
- .walk(expected, actual, path, lines) ⇒ Object
Class Method Details
.display_type(value) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/minitest/hashdiff.rb', line 13 def display_type(value) case value when nil then "nil" when true, false then "Boolean" when Integer then "Integer" when Float then "Float" when String then "String" when Symbol then "Symbol" when Hash then "Hash" when Array then "Array" else value.class.name end end |
.format(expected, actual) ⇒ Object
Returns a readable diff report, or nil when nothing differs.
28 29 30 31 32 33 34 |
# File 'lib/minitest/hashdiff.rb', line 28 def format(expected, actual) lines = [] walk(expected, actual, nil, lines) return nil if lines.empty? "Hash diff (expected => actual):\n#{lines.join("\n")}" end |
.walk(expected, actual, path, lines) ⇒ Object
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 |
# File 'lib/minitest/hashdiff.rb', line 36 def walk(expected, actual, path, lines) if expected.is_a?(Hash) && actual.is_a?(Hash) keys = (expected.keys | actual.keys).sort_by(&:inspect) keys.each do |key| key_path = path ? "#{path} > #{key.inspect}" : key.inspect if !expected.key?(key) lines << " added #{key_path}: #{actual[key].inspect}" elsif !actual.key?(key) lines << " removed #{key_path}: #{expected[key].inspect}" elsif expected[key] != actual[key] walk(expected[key], actual[key], key_path, lines) end end elsif expected.is_a?(Array) && actual.is_a?(Array) [expected.size, actual.size].max.times do |i| item_path = "#{path}[#{i}]" if i >= expected.size lines << " added #{item_path}: #{actual[i].inspect}" elsif i >= actual.size lines << " removed #{item_path}: #{expected[i].inspect}" elsif expected[i] != actual[i] walk(expected[i], actual[i], item_path, lines) end end else expected_type = display_type(expected) actual_type = display_type(actual) note = expected_type == actual_type ? "" : " (#{expected_type} -> #{actual_type})" lines << " changed #{path}: #{expected.inspect} => #{actual.inspect}#{note}" end end |