package envelope import ( "errors" "fmt" "os" "reflect" "testing" "git.sr.ht/~eugenetriguba/checkmate/assert" "git.sr.ht/~eugenetriguba/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) }