summaryrefslogtreecommitdiff
path: root/test/csv/interface/test_read_write.rb
blob: c371e9c5fcf2aae9b99264826d5c0ec5694d33f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# frozen_string_literal: false

require_relative "../helper"

class TestCSVInterfaceReadWrite < Test::Unit::TestCase
  extend DifferentOFS

  def test_filter
    input = <<-CSV.freeze
1;2;3
4;5
    CSV
    output = ""
    CSV.filter(input, output,
               in_col_sep: ";",
               out_col_sep: ",",
               converters: :all) do |row|
      row.map! {|n| n * 2}
      row << "Added\r"
    end
    assert_equal(<<-CSV, output)
2,4,6,"Added\r"
8,10,"Added\r"
    CSV
  end

  def test_filter_headers_true
    input = <<-CSV.freeze
Name,Value
foo,0
bar,1
baz,2
    CSV
    output = ""
    CSV.filter(input, output, headers: true) do |row|
      row[0] += "X"
      row[1] = row[1].to_i + 1
    end
    assert_equal(<<-CSV, output)
fooX,1
barX,2
bazX,3
    CSV
  end

  def test_filter_headers_true_write_headers
    input = <<-CSV.freeze
Name,Value
foo,0
bar,1
baz,2
    CSV
    output = ""
    CSV.filter(input, output, headers: true, out_write_headers: true) do |row|
      if row.is_a?(Array)
        row[0] += "X"
        row[1] += "Y"
      else
        row[0] += "X"
        row[1] = row[1].to_i + 1
      end
    end
    assert_equal(<<-CSV, output)
NameX,ValueY
fooX,1
barX,2
bazX,3
    CSV
  end

  def test_filter_headers_array_write_headers
    input = <<-CSV.freeze
foo,0
bar,1
baz,2
    CSV
    output = ""
    CSV.filter(input, output,
               headers: ["Name", "Value"],
               out_write_headers: true) do |row|
      row[0] += "X"
      row[1] = row[1].to_i + 1
    end
    assert_equal(<<-CSV, output)
Name,Value
fooX,1
barX,2
bazX,3
    CSV
  end

  def test_instance_same
    data = ""
    assert_equal(CSV.instance(data, col_sep: ";").object_id,
                 CSV.instance(data, col_sep: ";").object_id)
  end

  def test_instance_append
    output = ""
    CSV.instance(output, col_sep: ";") << ["a", "b", "c"]
    assert_equal(<<-CSV, output)
a;b;c
    CSV
    CSV.instance(output, col_sep: ";") << [1, 2, 3]
    assert_equal(<<-CSV, output)
a;b;c
1;2;3
    CSV
  end

  def test_instance_shortcut
    assert_equal(CSV.instance,
                 CSV {|csv| csv})
  end

  def test_instance_shortcut_with_io
    io = StringIO.new
    from_instance = CSV.instance(io, col_sep: ";") { |csv| csv << ["a", "b", "c"] }
    from_shortcut = CSV(io, col_sep: ";") { |csv| csv << ["e", "f", "g"] }

    assert_equal(from_instance, from_shortcut)
    assert_equal(from_instance.string, "a;b;c\ne;f;g\n")
  end
end