-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprovider_test.go
104 lines (88 loc) · 2.45 KB
/
provider_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
package cfg_test
import (
"context"
"fmt"
"io"
"os"
"testing"
"github.com/pkg/errors"
"github.com/zpatrick/cfg"
"github.com/zpatrick/cfg/envvar"
"github.com/zpatrick/testx/assert"
)
func ExampleSchema_multiProvider() {
var userName string
schema := cfg.Schema[string]{
Dest: &userName,
// Note that order matters when using MultiProvider:
// We first will use USERNAME_ALPHA if that envvar is set,
// falling back to using USERNAME_BRAVO if not.
Provider: cfg.MultiProvider[string]{
envvar.New("USERNAME_ALPHA"),
envvar.New("USERNAME_BRAVO"),
},
}
os.Setenv("USERNAME_ALPHA", "foo")
os.Setenv("USERNAME_BRAVO", "bar")
if err := schema.Load(context.Background()); err != nil {
panic(err)
}
fmt.Println(userName)
// Output: foo
}
func TestMultiProvider_returnsFirstError(t *testing.T) {
p := cfg.MultiProvider[int]{
cfg.ProviderFunc[int](func(context.Context) (int, error) {
return 0, io.EOF
}),
cfg.ProviderFunc[int](func(context.Context) (int, error) {
return 0, nil
}),
}
_, err := p.Provide(context.Background())
assert.ErrorIs(t, err, io.EOF)
}
func TestMultiProvider_returnsFirstValue(t *testing.T) {
p := cfg.MultiProvider[int]{
cfg.ProviderFunc[int](func(context.Context) (int, error) {
return 1, nil
}),
cfg.ProviderFunc[int](func(context.Context) (int, error) {
return 0, errors.New("we shouldn't have gotten this far")
}),
}
out, err := p.Provide(context.Background())
assert.NilError(t, err)
assert.Equal(t, out, 1)
}
func TestMultiProvider_iteratesThroughNoValueProvidedError(t *testing.T) {
p := cfg.MultiProvider[int]{
cfg.ProviderFunc[int](func(context.Context) (int, error) {
return 1, cfg.NoValueProvidedError
}),
cfg.ProviderFunc[int](func(context.Context) (int, error) {
return 2, nil
}),
}
out, err := p.Provide(context.Background())
assert.NilError(t, err)
assert.Equal(t, out, 2)
}
func TestMultiProvider_returnsNoValueProvidedErrorWhenDoneIterating(t *testing.T) {
p := cfg.MultiProvider[int]{
cfg.ProviderFunc[int](func(context.Context) (int, error) {
return 0, cfg.NoValueProvidedError
}),
cfg.ProviderFunc[int](func(context.Context) (int, error) {
return 0, cfg.NoValueProvidedError
}),
}
_, err := p.Provide(context.Background())
assert.ErrorIs(t, err, cfg.NoValueProvidedError)
}
func TestStaticProvider(t *testing.T) {
p := cfg.StaticProvider(5, false)
out, err := p.Provide(context.Background())
assert.NilError(t, err)
assert.Equal(t, out, 5)
}