-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathencode_test.go
More file actions
110 lines (89 loc) · 1.89 KB
/
encode_test.go
File metadata and controls
110 lines (89 loc) · 1.89 KB
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
package csv
import (
"bytes"
"reflect"
"testing"
)
type X struct {
First string
}
type P struct {
First string
Last string
}
func (p P) MarshalCSV() ([]byte, error) {
return []byte(p.First + " " + p.Last), nil
}
func TestMarshal_without_a_slice(t *testing.T) {
_, err := Marshal(simple{})
if err == nil {
t.Error("Non slice produced no error")
}
}
func TestEncodeFieldValue(t *testing.T) {
var encTests = []struct {
val interface{}
expected string
tag string
}{
// Strings
{"ABC", "ABC", ""},
{byte(123), "123", ""},
// Numerics
{int(1), "1", ""},
{float32(3.2), "3.2", ""},
{uint32(123), "123", ""},
{complex64(1 + 2i), "(+1+2i)", ""},
// Boolean
{true, "Yes", `true:"Yes" false:"No"`},
{false, "No", `true:"Yes" false:"No"`},
// TODO Array
// Interface with Marshaler
{P{"Jay", "Zee"}, "Jay Zee", ""},
// Struct without Marshaler will produce nothing
{X{"Jay"}, "", ""},
}
enc := &encoder{}
for _, test := range encTests {
fv := reflect.ValueOf(test.val)
st := reflect.StructTag(test.tag)
res := enc.encodeCol(fv, st)
if res != test.expected {
t.Errorf("%s does not match %s", res, test.expected)
}
}
}
func TestMarshalCSVOfStructs(t *testing.T) {
type ST struct {
Label string
}
expected := []byte(`Label
Value 1
Value 2
`)
data := []ST{{"Value 1"}, {"Value 2"}}
out, err := Marshal(data)
if err != nil {
t.Logf("Failed to marshal to csv ")
t.Fail()
}
if !bytes.Equal(out, expected) {
t.Logf("Failed to marshal to correct format")
t.Fail()
}
}
func TestMarshalCSVOfPointers(t *testing.T) {
expected := []byte(`Label
Value 1
`)
tPointer := []interface{}{}
tPointer = append(tPointer, struct{ Label string }{"Value 1"})
out, err := Marshal(tPointer)
if err != nil {
t.Logf("Failed to marshal to csv ")
}
if !bytes.Equal(out, expected) {
t.Logf("Failed to marshal to correct format")
t.Fail()
}
}