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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
|
package envelope
import (
"errors"
"fmt"
"os"
"reflect"
"testing"
"git.eugenetriguba.com/checkmate/assert"
"git.eugenetriguba.com/checkmate/check"
)
type TestStruct struct {
String string `env:"TEST_STRING"`
Int int `env:"TEST_INT"`
Uint uint `env:"TEST_UINT"`
Bool bool `env:"TEST_BOOL"`
Float float64 `env:"TEST_FLOAT"`
Untagged string
unexported string `env:"TEST_UNEXPORTED"`
}
// GIVEN a struct with environment variables set for its tagged fields
// WHEN we call LoadFromEnv with a pointer to that struct
// THEN it should load all the values from environment variables
// into the struct fields
func TestLoadFromEnv(t *testing.T) {
os.Setenv("TEST_STRING", "hello")
os.Setenv("TEST_INT", "-42")
os.Setenv("TEST_UINT", "42")
os.Setenv("TEST_BOOL", "true")
os.Setenv("TEST_FLOAT", "3.14")
os.Setenv("TEST_UNEXPORTED", "unexported")
defer func() {
os.Unsetenv("TEST_STRING")
os.Unsetenv("TEST_INT")
os.Unsetenv("TEST_UINT")
os.Unsetenv("TEST_BOOL")
os.Unsetenv("TEST_FLOAT")
os.Unsetenv("TEST_UNEXPORTED")
}()
var ts TestStruct
err := LoadFromEnv(&ts)
check.Nil(t, err)
check.Equal(t, ts.String, "hello")
check.Equal(t, ts.Int, -42)
check.Equal(t, ts.Uint, uint(42))
check.True(t, ts.Bool)
check.Equal(t, ts.Float, 3.14)
check.Equal(t, ts.Untagged, "")
check.Equal(t, ts.unexported, "")
}
// GIVEN the string "not a pointer"
// WHEN we call LoadFromEnv with the string
// THEN it should return a NotPointerToStructError
func TestLoadFromEnvWithNonPointerToStruct(t *testing.T) {
var notPtrToStructErr *NotPointerToStructError
value := "not a pointer"
err := LoadFromEnv(value)
assert.True(t, errors.As(err, ¬PtrToStructErr))
assert.Equal(t, reflect.TypeOf(""), notPtrToStructErr.ActualType)
assert.Equal(t, "value must be a pointer to a struct", notPtrToStructErr.Error())
err = LoadFromEnv(&value)
assert.True(t, errors.As(err, ¬PtrToStructErr))
assert.Equal(t, reflect.TypeOf(""), notPtrToStructErr.ActualType.Elem())
}
// GIVEN an unsupported type in a struct
// WHEN we call LoadFromEnv with that struct
// THEN it should return an UnsupportedTypeError
func TestLoadFromEnvWithUnsupportedType(t *testing.T) {
type StructWithUnsupportedType struct {
Complex complex128 `env:"COMPLEX"`
}
os.Setenv("COMPLEX", "1+2i")
defer os.Unsetenv("COMPLEX")
err := LoadFromEnv(&StructWithUnsupportedType{})
var unsupportedErr *UnsupportedTypeError
assert.True(t, errors.As(err, &unsupportedErr))
assert.Equal(t, "Complex", unsupportedErr.FieldName)
assert.Equal(t, reflect.TypeOf(complex128(0)), unsupportedErr.FieldType)
}
// GIVEN invalid values for different types in environment variables
// WHEN we call LoadFromEnv with those values
// THEN it should return a ParseError with the correct field name, env name,
// value, and target type
func TestLoadFromEnvParseErrors(t *testing.T) {
tests := []struct {
name string
envName string
envValue string
input any
fieldName string
targetType reflect.Type
}{
{
name: "Invalid int",
envName: "TEST_INT",
envValue: "not-an-int",
input: &struct {
Value int `env:"TEST_INT"`
}{},
fieldName: "Value",
targetType: reflect.TypeOf(int(0)),
},
{
name: "Invalid uint (negative)",
envName: "TEST_UINT",
envValue: "-42",
input: &struct {
Value uint `env:"TEST_UINT"`
}{},
fieldName: "Value",
targetType: reflect.TypeOf(uint(0)),
},
{
name: "Invalid bool",
envName: "TEST_BOOL",
envValue: "not-a-bool",
input: &struct {
Value bool `env:"TEST_BOOL"`
}{},
fieldName: "Value",
targetType: reflect.TypeOf(bool(false)),
},
{
name: "Invalid float",
envName: "TEST_FLOAT",
envValue: "not-a-float",
input: &struct {
Value float64 `env:"TEST_FLOAT"`
}{},
fieldName: "Value",
targetType: reflect.TypeOf(float64(0)),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
os.Setenv(tt.envName, tt.envValue)
defer os.Unsetenv(tt.envName)
err := LoadFromEnv(tt.input)
var parseErr *ParseError
assert.True(t, errors.As(err, &parseErr))
assert.Equal(t, tt.fieldName, parseErr.FieldName)
assert.Equal(t, tt.envName, parseErr.EnvName)
assert.Equal(t, tt.envValue, parseErr.Value)
assert.Equal(t, tt.targetType, parseErr.TargetType)
assert.ErrorContains(t, err,
fmt.Sprintf("error parsing value '%s' to '%v' for field '%s' from environment variable '%s'",
tt.envValue, tt.targetType, tt.fieldName, tt.envName))
})
}
}
// GIVEN a struct with nested structs and a prefix
// for the parent struct
// WHEN we call LoadFromEnv with that struct
// THEN we expect it to load all nested fields correctly
func TestNestedStructs(t *testing.T) {
type ServerConfig struct {
Host string `env:"HOST"`
Port int `env:"PORT"`
}
type DatabaseConfig struct {
URL string `env:"URL"`
Username string `env:"USERNAME"`
Password string `env:"PASSWORD"`
}
type AppConfig struct {
Server ServerConfig `env:"SERVER"`
Database DatabaseConfig `env:"DB"`
LogLevel string `env:"LOG_LEVEL"`
}
os.Setenv("SERVER_HOST", "localhost")
os.Setenv("SERVER_PORT", "8080")
os.Setenv("DB_URL", "postgres://localhost:5432/mydb")
os.Setenv("DB_USERNAME", "admin")
os.Setenv("DB_PASSWORD", "secret")
os.Setenv("LOG_LEVEL", "debug")
defer func() {
os.Unsetenv("SERVER_HOST")
os.Unsetenv("SERVER_PORT")
os.Unsetenv("DB_URL")
os.Unsetenv("DB_USERNAME")
os.Unsetenv("DB_PASSWORD")
os.Unsetenv("LOG_LEVEL")
}()
var config AppConfig
err := LoadFromEnv(&config)
check.Nil(t, err)
check.Equal(t, "localhost", config.Server.Host)
check.Equal(t, 8080, config.Server.Port)
check.Equal(t, "postgres://localhost:5432/mydb", config.Database.URL)
check.Equal(t, "admin", config.Database.Username)
check.Equal(t, "secret", config.Database.Password)
check.Equal(t, "debug", config.LogLevel)
}
// GIVEN a multi-level nested struct with prefixes
// WHEN we call LoadFromEnv with that struct
// THEN it should load all nested fields correctly
func TestDeepNestedStructs(t *testing.T) {
type DeepestConfig struct {
Value string `env:"VALUE"`
}
type MiddleConfig struct {
Inner DeepestConfig `env:"INNER"`
Setting bool `env:"SETTING"`
}
type RootConfig struct {
Middle MiddleConfig `env:"MIDDLE"`
Name string `env:"NAME"`
}
os.Setenv("MIDDLE_INNER_VALUE", "deeply_nested_value")
os.Setenv("MIDDLE_SETTING", "true")
os.Setenv("NAME", "root_name")
defer func() {
os.Unsetenv("MIDDLE_INNER_VALUE")
os.Unsetenv("MIDDLE_SETTING")
os.Unsetenv("NAME")
}()
var config RootConfig
err := LoadFromEnv(&config)
check.Nil(t, err)
check.Equal(t, "deeply_nested_value", config.Middle.Inner.Value)
check.Equal(t, true, config.Middle.Setting)
check.Equal(t, "root_name", config.Name)
}
// GIVEN structs that do not have all environments variables
// set to populate them fully
// WHEN we call LoadFromEnv with those structs
// THEN it should load only the set fields and leave others at their zero values
func TestPartialNestedStructs(t *testing.T) {
type ServerConfig struct {
Host string `env:"HOST"`
Port int `env:"PORT"`
Timeout int `env:"TIMEOUT"` // Missing cooresponding environment variable
}
type AppConfig struct {
Server ServerConfig `env:"SERVER"`
LogLevel string `env:"LOG_LEVEL"`
Debug bool `env:"DEBUG"` // Missing cooresponding environment variable
}
os.Setenv("SERVER_HOST", "localhost")
os.Setenv("SERVER_PORT", "8080")
os.Setenv("LOG_LEVEL", "info")
defer func() {
os.Unsetenv("SERVER_HOST")
os.Unsetenv("SERVER_PORT")
os.Unsetenv("LOG_LEVEL")
}()
var config AppConfig
err := LoadFromEnv(&config)
check.Nil(t, err)
check.Equal(t, "localhost", config.Server.Host)
check.Equal(t, 8080, config.Server.Port)
check.Equal(t, 0, config.Server.Timeout) // Default 'zero' value
check.Equal(t, "info", config.LogLevel)
check.Equal(t, false, config.Debug) // Default 'zero' value
}
// GIVEN nested structs without any prefixes
// WHEN we call LoadFromEnv with those structs
// THEN it should load the fields correctly without using prefixes
// WHEN we call LoadFromEnv with a struct that has prefixes
// THEN it should ignore the prefixes and load the fields correctly
func TestNestedStructWithoutPrefix(t *testing.T) {
type ServerConfig struct {
Host string `env:"HOST"`
Port int `env:"PORT"`
}
type AppConfig struct {
Server ServerConfig
LogLevel string `env:"LOG_LEVEL"`
}
os.Setenv("HOST", "localhost")
os.Setenv("PORT", "8080")
os.Setenv("LOG_LEVEL", "debug")
defer func() {
os.Unsetenv("HOST")
os.Unsetenv("PORT")
os.Unsetenv("LOG_LEVEL")
}()
var config AppConfig
err := LoadFromEnv(&config)
check.Nil(t, err)
check.Equal(t, "localhost", config.Server.Host)
check.Equal(t, 8080, config.Server.Port)
check.Equal(t, "debug", config.LogLevel)
os.Setenv("SERVER_HOST", "wrong-host")
os.Setenv("SERVER_PORT", "9090")
defer func() {
os.Unsetenv("SERVER_HOST")
os.Unsetenv("SERVER_PORT")
}()
config = AppConfig{} // Reset
err = LoadFromEnv(&config)
check.Nil(t, err)
check.Equal(t, "localhost", config.Server.Host)
check.Equal(t, 8080, config.Server.Port)
}
|