-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv_test.go
120 lines (102 loc) · 2.56 KB
/
csv_test.go
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
package objcsv
import (
"bytes"
"encoding/csv"
"io"
"reflect"
"testing"
)
type dumbStruct struct {
FName string
LName string
Age int
Worth float64
}
func TestWriteHeader(t *testing.T) {
d := dumbStruct{"Hello", "World", 42, 10.01}
buf := new(bytes.Buffer)
cw := csv.NewWriter(buf)
err := writeHeader(cw, d)
if err != nil {
t.Fatalf("Unexpected error from writeHeader: %v", err)
}
cw.Flush()
actual := buf.String()
expected := "FName,LName,Age,Worth\n"
if actual != expected {
t.Errorf("Header is wrong, expected %q, got %q", expected, actual)
}
}
func TestWriteRow(t *testing.T) {
d := dumbStruct{"Matt", "Palmer", 23, 40000.00}
buf := new(bytes.Buffer)
cw := csv.NewWriter(buf)
err := writeRow(cw, d)
if err != nil {
t.Fatalf("Unexpected error from writeRow: %v", err)
}
cw.Flush()
actual := buf.String()
expected := "Matt,Palmer,23,40000.00\n"
if actual != expected {
t.Errorf("Row is wrong, expected %q, got %q", expected, actual)
}
}
func TestReadCSV(t *testing.T) {
data := `FName,LName,Age,Worth
Matt,Palmer,23,40000.00
Robert,Sesek,23,60000.00
Barack,Obama,51,80000000.00
Mitt,Romney,59,9950000000.00`
buf := new(bytes.Buffer)
_, err := buf.WriteString(data)
if err != nil {
t.Fatalf("Error in testing data: %v", err)
}
slice := make([]dumbStruct, 0)
err = ReadCSV(buf, &slice)
if err != nil {
t.Fatalf("Unexpected error from ReadCSV: %v", err)
}
expected := []dumbStruct{
{"Matt", "Palmer", 23, 40000.00},
{"Robert", "Sesek", 23, 60000.00},
{"Barack", "Obama", 51, 80000000.00},
{"Mitt", "Romney", 59, 9950000000.00},
}
if !reflect.DeepEqual(slice, expected) {
t.Errorf("Expected %v but got %v", expected, slice)
}
}
func TestWriteCSV(t *testing.T) {
d := []dumbStruct{
{"Matt", "Palmer", 23, 40000.00},
{"Robert", "Sesek", 23, 60000.00},
{"Barack", "Obama", 51, 80000000.00},
{"Mitt", "Romney", 59, 9950000000.00},
}
buf := new(bytes.Buffer)
if err := WriteCSV(buf, d); err != nil {
t.Fatalf("Unexpected error from WriteCSV: %v", err)
}
expected := []string{
"FName,LName,Age,Worth\n",
"Matt,Palmer,23,40000.00\n",
"Robert,Sesek,23,60000.00\n",
"Barack,Obama,51,80000000.00\n",
"Mitt,Romney,59,9950000000.00\n",
}
for i := 0; i < 5; i++ {
actual, err := buf.ReadString('\n')
if err != nil {
t.Fatalf("Unexpected output at line %d: %v", i, err)
}
if actual != expected[i] {
t.Errorf("Row %d is wrong, expected %q, got %q", i, expected[i], actual)
}
}
s, err := buf.ReadString('\n')
if s != "" || err != io.EOF {
t.Errorf("Got unexpected data %q where expected EOF", s)
}
}