Created
September 22, 2015 11:47
-
-
Save bpardee/513b4a15e5ebdc596e0b to your computer and use it in GitHub Desktop.
assert csv file
This file contains 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
module AssertCSV | |
def assert_csv(expected_csv_path, options={}, &block) | |
ignore = options[:ignore] || [] | |
actual_csv_string = CSV.generate { |actual_csv| yield actual_csv } | |
actual_rows = CSV.parse(actual_csv_string) | |
expected_rows = CSV.read(expected_csv_path) | |
if ENV['STORE_ACTUAL_CSV'] && actual_rows != expected_rows | |
CSV.open("#{expected_csv_path}.actual", "wb") {|csv| actual_rows.each {|row| csv << row}} | |
end | |
assert_equal expected_rows.size, actual_rows.size | |
actual_header = actual_rows.first | |
expected_header = expected_rows.first | |
errors = [] | |
if actual_header != expected_header | |
missing = expected_header - actual_header | |
errors << "Missing columns: #{missing.inspect}" unless missing.empty? | |
unexpected = actual_header - expected_header | |
errors << "Unexpected columns: #{unexpected.inspect}" unless unexpected.empty? | |
end | |
common_header = actual_header & expected_header | |
(1...actual_rows.size).each do |i| | |
if actual_rows[i] != expected_rows[i] | |
row_errors = [] | |
actual_header.each_with_index do |column, actual_i| | |
next if ignore.include?(column) | |
if expected_i = expected_header.index(column) | |
if actual_rows[i][actual_i] != expected_rows[i][expected_i] | |
row_errors << " #{column} actual=#{actual_rows[i][actual_i]} expected=#{expected_rows[i][expected_i]}" | |
end | |
end | |
end | |
unless row_errors.empty? | |
errors << "The following mismatches were found in line #{i+1}:" | |
errors += row_errors | |
end | |
end | |
end | |
assert errors.empty?, errors.join("\n") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment