-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtinyviper_test.go
102 lines (90 loc) · 2.34 KB
/
tinyviper_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
package tinyviper
import (
"errors"
"os"
"testing"
)
type Config struct {
UserConfig struct {
Email string `env:"MY_APP_EMAIL"`
Password string `env:"MY_APP_PASSWORD"`
}
Endpoint string `env:"MY_APP_ENDPOINT"`
AppUrl string `env:"MY_APP_URL"`
Undefined string `env:"MY_UNDEFINED"`
}
type testEnvResolver struct{}
func (t testEnvResolver) Get(key string) string {
switch key {
case "MY_APP_EMAIL":
return "[email protected]"
case "MY_APP_PASSWORD":
return "[email protected]"
default:
return ""
}
}
func TestConfigErrors(t *testing.T) {
cfg := Config{
Undefined: "foo",
}
err := LoadFromResolver(&cfg, testEnvResolver{})
if err == nil {
t.Fatalf("Expected error, got none")
}
if err.Error() != "missing config variables: MY_APP_ENDPOINT,MY_APP_URL" {
t.Error("Expected error, got wrong one: " + err.Error())
}
}
func TestConfigNew(t *testing.T) {
cfg := Config{
Undefined: "foo",
}
err := LoadFromResolver(&cfg, NewEnvResolver(), NewEnvFileResolver(".env.sample"))
if err != nil {
t.Error(err)
}
if cfg.UserConfig.Email != "[email protected]" {
t.Error(errors.New("unexpected email"))
}
if cfg.UserConfig.Password != "password2" {
t.Error(errors.New("unexpected password"))
}
if cfg.Endpoint != "some-endpoint" {
t.Error(errors.New("unexpected endpoint"))
}
if cfg.AppUrl != "https://some.exmpale.org/foo?token=bar" {
t.Error(errors.New("unexpected url"))
}
}
func TestConfigNewWithoutFile(t *testing.T) {
cfg := Config{
Undefined: "foo",
}
err := LoadFromResolver(&cfg, EnvResolver{}, NewEnvFileResolver(".env.sample2"))
if err == nil {
t.Fatalf("Expected error, got none")
}
if err.Error() != "missing config variables: MY_APP_EMAIL,MY_APP_PASSWORD,MY_APP_ENDPOINT,MY_APP_URL" {
t.Error("Expected error, got wrong one: " + err.Error())
}
}
func TestConfigOverride(t *testing.T) {
_ = os.Setenv("MY_APP_EMAIL", "[email protected]")
cfg := Config{
Undefined: "foo",
}
err := LoadFromResolver(&cfg, NewEnvResolver(), NewEnvFileResolver(".env.sample"))
if err != nil {
t.Error(err)
}
if cfg.UserConfig.Email != "[email protected]" {
t.Error(errors.New("unexpected email"))
}
if cfg.Undefined != "foo" {
t.Error(errors.New("unexpected app url"))
}
if cfg.UserConfig.Password != "password2" {
t.Error(errors.New("unexpected password"))
}
}