generated from sv-tools/go-repo-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparset_test.go
84 lines (65 loc) · 2.19 KB
/
parset_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
package conf_test
import (
"bytes"
"context"
"io"
"strings"
"testing"
"github.com/stretchr/testify/require"
"github.com/sv-tools/conf"
)
func testParseFunc(_ context.Context, r io.Reader) (interface{}, error) {
data, err := io.ReadAll(r)
if err != nil {
return nil, err
}
res := map[string]string{}
for _, line := range strings.Split(string(data), ";") {
values := strings.Split(line, ":")
res[strings.TrimSpace(values[0])] = strings.TrimSpace(values[1])
}
return res, nil
}
func testParseFuncError(_ context.Context, _ io.Reader) (interface{}, error) {
return nil, errFake
}
func TestStreamParser(t *testing.T) {
t.Parallel()
reader := bytes.NewReader([]byte(`foo:1;bar:2`))
c := conf.New().WithReaders(conf.NewStreamParser(reader).WithParser(testParseFunc).WithPrefix("pr"))
require.NoError(t, c.Load(context.Background()))
require.Equal(t, 1, c.GetInt("pr.foo"))
require.Equal(t, 2, c.GetInt("pr.bar"))
}
func TestStreamParser_ErrNoParser(t *testing.T) {
t.Parallel()
reader := bytes.NewReader([]byte(`foo:1;bar:2`))
c := conf.New().WithReaders(conf.NewStreamParser(reader))
require.ErrorIs(t, c.Load(context.Background()), conf.ErrNoParser)
}
func TestStreamParser_ErrNoStream(t *testing.T) {
t.Parallel()
c := conf.New().WithReaders(conf.NewStreamParser(nil).WithParser(testParseFunc))
require.ErrorIs(t, c.Load(context.Background()), conf.ErrNoStream)
}
func TestStreamParser_errFake(t *testing.T) {
t.Parallel()
reader := bytes.NewReader([]byte(`foo:1;bar:2`))
c := conf.New().WithReaders(conf.NewStreamParser(reader).WithParser(testParseFuncError))
require.ErrorIs(t, c.Load(context.Background()), errFake)
}
func TestFileParser(t *testing.T) {
t.Parallel()
parser, err := conf.NewFileParser(`testdata/data.txt`)
require.NoError(t, err)
c := conf.New().WithReaders(parser.WithParser(testParseFunc).WithPrefix("pr"))
require.NoError(t, c.Load(context.Background()))
require.Equal(t, 1, c.GetInt("pr.foo"))
require.Equal(t, 2, c.GetInt("pr.bar"))
}
func TestFileParser_FileNotFound(t *testing.T) {
t.Parallel()
parser, err := conf.NewFileParser(`testdata/fake.txt`)
require.EqualError(t, err, "open testdata/fake.txt: no such file or directory")
require.Nil(t, parser)
}