-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathconfig_test.go
81 lines (72 loc) · 1.67 KB
/
config_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
package toml
import (
"bytes"
"reflect"
"strings"
"testing"
)
func TestConfigNormField(t *testing.T) {
cfg := Config{NormFieldName: func(reflect.Type, string) string { return "a" }}
var x struct{ B int }
input := []byte(`a = 1`)
if err := cfg.Unmarshal(input, &x); err != nil {
t.Fatal(err)
}
if x.B != 1 {
t.Fatalf("wrong value after Unmarshal: got %d, want %d", x.B, 1)
}
dec := cfg.NewDecoder(strings.NewReader(`a = 2`))
if err := dec.Decode(&x); err != nil {
t.Fatal(err)
}
if x.B != 2 {
t.Fatalf("wrong value after Decode: got %d, want %d", x.B, 2)
}
tbl, _ := Parse([]byte(`a = 3`))
if err := cfg.UnmarshalTable(tbl, &x); err != nil {
t.Fatal(err)
}
if x.B != 3 {
t.Fatalf("wrong value after UnmarshalTable: got %d, want %d", x.B, 3)
}
}
func TestConfigFieldToKey(t *testing.T) {
cfg := Config{FieldToKey: func(reflect.Type, string) string { return "A" }}
x := struct{ B int }{B: 999}
enc, err := cfg.Marshal(&x)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(enc, []byte("A = 999\n")) {
t.Fatalf(`got %q, want "A = 999"`, enc)
}
}
func TestConfigMissingField(t *testing.T) {
calls := make(map[string]bool)
cfg := Config{
NormFieldName: func(rt reflect.Type, field string) string {
return field
},
MissingField: func(rt reflect.Type, field string) error {
calls[field] = true
return nil
},
}
var x struct{ B int }
input := []byte(`
A = 1
B = 2
`)
if err := cfg.Unmarshal(input, &x); err != nil {
t.Fatal(err)
}
if x.B != 2 {
t.Errorf("wrong value after Unmarshal: got %d, want %d", x.B, 1)
}
if !calls["A"] {
t.Error("MissingField not called for 'A'")
}
if calls["B"] {
t.Error("MissingField called for 'B'")
}
}