-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarshal_test.go
120 lines (102 loc) · 2.37 KB
/
marshal_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 goflat_test
import (
"bytes"
"context"
"encoding/csv"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/lzambarda/goflat"
)
func TestMarshal(t *testing.T) {
t.Run("success", testMarshalSuccess)
t.Run("success pointer", testMarshalSuccessPointer)
}
func testMarshalSuccess(t *testing.T) {
expected, err := testdata.ReadFile("testdata/marshal/success.csv")
if err != nil {
t.Fatalf("read test file: %v", err)
}
type record struct {
FirstName string `flat:"first_name"`
LastName string `flat:"last_name"`
Ignore uint8 `flat:"-"`
Age int `flat:"age"`
Height float32 `flat:"height"`
}
input := []record{
{
FirstName: "John",
LastName: "Doe",
Ignore: 123,
Age: 30,
Height: 1.75,
},
{
FirstName: "Jane",
LastName: "Doe",
Ignore: 123,
Age: 25,
Height: 1.65,
},
}
tcs := map[string]goflat.Options{
"simple": {},
"strict": {
ErrorIfTaglessField: true,
ErrorIfDuplicateHeaders: true,
ErrorIfMissingHeaders: true,
UnmarshalIgnoreEmpty: true,
},
}
for name, options := range tcs {
t.Run(name, func(t *testing.T) {
var got bytes.Buffer
writer := csv.NewWriter(&got)
err = goflat.MarshalSliceToWriter(context.Background(), input, writer, options)
if err != nil {
t.Fatalf("marshal: %v", err)
}
if diff := cmp.Diff(string(expected), got.String()); diff != "" {
t.Errorf("(-expected, +got):\n%s", diff)
}
})
}
}
func testMarshalSuccessPointer(t *testing.T) {
expected, err := testdata.ReadFile("testdata/marshal/success.csv")
if err != nil {
t.Fatalf("read test file: %v", err)
}
type record struct {
FirstName string `flat:"first_name"`
LastName string `flat:"last_name"`
Ignore uint8 `flat:"-"`
Age int `flat:"age"`
Height float32 `flat:"height"`
}
input := []*record{
{
FirstName: "John",
LastName: "Doe",
Ignore: 123,
Age: 30,
Height: 1.75,
},
{
FirstName: "Jane",
LastName: "Doe",
Ignore: 123,
Age: 25,
Height: 1.65,
},
}
var got bytes.Buffer
writer := csv.NewWriter(&got)
err = goflat.MarshalSliceToWriter(context.Background(), input, writer, goflat.Options{})
if err != nil {
t.Fatalf("marshal: %v", err)
}
if diff := cmp.Diff(string(expected), got.String()); diff != "" {
t.Errorf("(-expected, +got):\n%s", diff)
}
}