diff options
Diffstat (limited to 'env_test.go')
| -rw-r--r-- | env_test.go | 305 |
1 files changed, 255 insertions, 50 deletions
diff --git a/env_test.go b/env_test.go index 4009b59..984ef2a 100644 --- a/env_test.go +++ b/env_test.go @@ -1,12 +1,14 @@ package envelope import ( + "errors" + "fmt" "os" + "reflect" "testing" - "time" - "github.com/eugenetriguba/checkmate/assert" - "github.com/eugenetriguba/checkmate/check" + "git.sr.ht/~eugenetriguba/checkmate/assert" + "git.sr.ht/~eugenetriguba/checkmate/check" ) type TestStruct struct { @@ -16,15 +18,20 @@ type TestStruct struct { Bool bool `env:"TEST_BOOL"` Float float64 `env:"TEST_FLOAT"` Untagged string - Unexported string `env:"TEST_UNEXPORTED"` + 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") @@ -45,79 +52,277 @@ func TestLoadFromEnv(t *testing.T) { check.True(t, ts.Bool) check.Equal(t, ts.Float, 3.14) check.Equal(t, ts.Untagged, "") - check.Equal(t, ts.Unexported, "") + check.Equal(t, ts.unexported, "") } -func TestLoadFromEnvErrors(t *testing.T) { +// 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 - input interface{} - envVars map[string]string - expectedErr string + name string + envName string + envValue string + input any + fieldName string + targetType reflect.Type }{ { - name: "Non-pointer input", - input: TestStruct{}, - expectedErr: "ptr must be a pointer to a struct", - }, - { - name: "Pointer to non-struct", - input: new(string), - expectedErr: "ptr must be a pointer to a struct", - }, - { - name: "Invalid int", - input: &struct { - Int int `env:"TEST_INT"` - }{}, - envVars: map[string]string{"TEST_INT": "not an int"}, - expectedErr: "error while setting field Int from environment variable TEST_INT", - }, - { - name: "Invalid uint", + name: "Invalid int", + envName: "TEST_INT", + envValue: "not-an-int", input: &struct { - Uint uint `env:"TEST_UINT"` + Value int `env:"TEST_INT"` }{}, - envVars: map[string]string{"TEST_UINT": "-42"}, - expectedErr: "error while setting field Uint from environment variable TEST_UINT", + fieldName: "Value", + targetType: reflect.TypeOf(int(0)), }, { - name: "Invalid bool", + name: "Invalid uint (negative)", + envName: "TEST_UINT", + envValue: "-42", input: &struct { - Bool bool `env:"TEST_BOOL"` + Value uint `env:"TEST_UINT"` }{}, - envVars: map[string]string{"TEST_BOOL": "not a bool"}, - expectedErr: "error while setting field Bool from environment variable TEST_BOOL", + fieldName: "Value", + targetType: reflect.TypeOf(uint(0)), }, { - name: "Invalid float", + name: "Invalid bool", + envName: "TEST_BOOL", + envValue: "not-a-bool", input: &struct { - Float float64 `env:"TEST_FLOAT"` + Value bool `env:"TEST_BOOL"` }{}, - envVars: map[string]string{"TEST_FLOAT": "not a float"}, - expectedErr: "error while setting field Float from environment variable TEST_FLOAT", + fieldName: "Value", + targetType: reflect.TypeOf(bool(false)), }, { - name: "Unsupported type", + name: "Invalid float", + envName: "TEST_FLOAT", + envValue: "not-a-float", input: &struct { - Unsupported time.Time `env:"TEST_UNSUPPORTED"` + Value float64 `env:"TEST_FLOAT"` }{}, - envVars: map[string]string{"TEST_UNSUPPORTED": "2023-08-31T12:34:56Z"}, - expectedErr: "error while setting field Unsupported from environment variable TEST_UNSUPPORTED", + fieldName: "Value", + targetType: reflect.TypeOf(float64(0)), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - for k, v := range tt.envVars { - os.Setenv(k, v) - defer os.Unsetenv(k) - } + os.Setenv(tt.envName, tt.envValue) + defer os.Unsetenv(tt.envName) err := LoadFromEnv(tt.input) - assert.NotNil(t, err) - assert.ErrorContains(t, err, tt.expectedErr) + 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) +} |