Files
query-orchestration/internal/serviceconfig/common_test.go
T
Jay Brown 720a84be92 Merged in feature/doc_import (pull request #177)
integration of background processor

* integration part 1

* feature working

* fix mimetype issue
2025-08-20 19:01:13 +00:00

232 lines
6.5 KiB
Go

package serviceconfig
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
// Struct specifically for initialize config testing
type initializeConfigTestStruct struct {
BaseConfig
AppEnv string `env:"APP_ENV"`
BoolTest bool `env:"BOOL_TEST"`
IntTest int `env:"INT_TEST,required,notEmpty"`
}
func TestInitializeConfig(t *testing.T) {
tests := []struct {
name string
envVars map[string]string
wantErr bool
errMessageContains string
}{
{
name: "valid configuration",
envVars: map[string]string{
"APP_ENV": "testing",
"BOOL_TEST": "true",
"INT_TEST": "42",
"PGUSER": "postgres",
"PGPASSWORD": "pass",
"PGHOST": "localhost",
"PGPORT": "5432",
"PGDATABASE": "query_orchestration",
"DB_NOSSL": "true",
"AWS_ACCESS_KEY_ID": "key",
"AWS_SECRET_ACCESS_KEY": "secret",
"AWS_REGION": "region",
"SUB_FIELD1:": "value1",
"SUB_FIELD2": "42",
"PWD": "/foo",
"COGNITO_USER_POOL_ID": "poolid",
"COGNITO_CLIENT_SECRET": "secret",
"COGNITO_DOMAIN": "domain",
"COGNITO_CLIENT_ID": "clientid",
},
wantErr: false,
},
{
name: "missing required env var",
envVars: map[string]string{
"APP_ENV": "testing",
"BOOL_TEST": "true",
"PGUSER": "postgres",
"PGPASSWORD": "pass",
"PGHOST": "localhost",
"PGPORT": "5432",
"PGDATABASE": "query_orchestration",
"DB_NOSSL": "true",
"AWS_ACCESS_KEY_ID": "key",
"AWS_SECRET_ACCESS_KEY": "secret",
"AWS_REGION": "region",
"PWD": "/foo",
// INT_TEST intentionally omitted
},
wantErr: true,
errMessageContains: "INT_TEST",
},
{
name: "invalid boolean value",
envVars: map[string]string{
"APP_ENV": "testing",
"BOOL_TEST": "notabool",
"PWD": "/foo",
"INT_TEST": "42",
},
wantErr: true,
errMessageContains: "BoolTest",
},
{
name: "invalid integer value",
envVars: map[string]string{
"APP_ENV": "testing",
"BOOL_TEST": "true",
"PWD": "/foo",
"INT_TEST": "notanint",
},
wantErr: true,
errMessageContains: "parse error on field \"IntTest\"",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
for k, v := range tt.envVars {
t.Setenv(k, v)
}
// Use the test-specific config struct
cfg := &initializeConfigTestStruct{}
err := initializeConfigPrivate(cfg)
logger := cfg.GetLogger()
assert.NotNil(t, logger)
logger.Info("Logger initialized")
if tt.wantErr {
if err == nil {
t.Errorf("InitializeConfig() error = nil, wantErr %v", tt.wantErr)
return
}
// Check error message contains expected string
if tt.errMessageContains != "" && !strings.Contains(err.Error(), tt.errMessageContains) {
t.Errorf("InitializeConfig() error = %v, want error containing %v", err, tt.errMessageContains)
}
} else {
if err != nil {
t.Errorf("InitializeConfig() unexpected error = %v", err)
return
}
// Verify the values were set correctly
if cfg.AppEnv != tt.envVars["APP_ENV"] {
t.Errorf("AppEnv = %v, want %v", cfg.AppEnv, tt.envVars["APP_ENV"])
}
if cfg.BoolTest != (tt.envVars["BOOL_TEST"] == "true") {
t.Errorf("BoolTest = %v, want %v", cfg.BoolTest, tt.envVars["BOOL_TEST"] == "true")
}
expectedInt := 42 // Known value from test cases
if cfg.IntTest != expectedInt {
t.Errorf("IntTest = %v, want %v", cfg.IntTest, expectedInt)
}
}
})
}
}
func TestGetBaseConfig(t *testing.T) {
assert.NotNil(t, getBaseConfig(&BaseConfig{}))
assert.Nil(t, getBaseConfig(nil))
assert.NotNil(t, getBaseConfig(&initializeConfigTestStruct{}))
}
// TestConfigToMap tests the safe conversion of config to map
func TestConfigToMap(t *testing.T) {
cfg := &BaseConfig{}
cfg.SetDefaultLogger() // Initialize logger
// Set some test values
cfg.Port = 8080
cfg.BaseURL = "http://localhost"
// Test config to map conversion
configMap, err := cfg.configToMap(cfg)
assert.NoError(t, err)
assert.NotNil(t, configMap)
}
// TestMaskSecretsInMap tests the secret masking functionality
func TestMaskSecretsInMap(t *testing.T) {
cfg := &BaseConfig{}
cfg.SetDefaultLogger()
// Create a test map with sensitive fields
testMap := map[string]interface{}{
"password": "mysecretpass",
"secret": "mysecret",
"api_key": "myapikey",
"token": "mytoken",
"normal_field": "normalvalue",
"nested": map[string]interface{}{
"secret_key": "nestedsecret",
"public_data": "publicvalue",
},
}
// Mask secrets
cfg.maskSecretsInMap(testMap, "custom")
// Check that secrets are masked
assert.Equal(t, "***MASKED***", testMap["password"])
assert.Equal(t, "***MASKED***", testMap["secret"])
assert.Equal(t, "***MASKED***", testMap["api_key"])
assert.Equal(t, "***MASKED***", testMap["token"])
// Check that normal fields are not masked
assert.Equal(t, "normalvalue", testMap["normal_field"])
// Check nested secrets
nested, ok := testMap["nested"].(map[string]interface{})
assert.True(t, ok, "nested should be a map")
assert.Equal(t, "***MASKED***", nested["secret_key"])
assert.Equal(t, "publicvalue", nested["public_data"])
}
// TestPrintConfigPanicRecovery tests that PrintConfig recovers from panics
func TestPrintConfigPanicRecovery(t *testing.T) {
cfg := &BaseConfig{}
cfg.SetDefaultLogger()
// This should not panic even with nil or invalid data
// The panic recovery in PrintConfig should handle any issues
defer func() {
if r := recover(); r != nil {
t.Errorf("PrintConfig should not panic, but did: %v", r)
}
}()
cfg.PrintConfig("secret")
}
// TestConfigToMapWithInvalidInput tests configToMap with various inputs
func TestConfigToMapWithInvalidInput(t *testing.T) {
cfg := &BaseConfig{}
cfg.SetDefaultLogger()
// Test with nil input (will fail in JSON marshal)
_, err := cfg.configToMap(nil)
assert.Error(t, err, "Should error on nil input")
// Test with a channel (cannot be marshaled to JSON)
ch := make(chan int)
_, err = cfg.configToMap(ch)
assert.Error(t, err, "Should error on channel input")
// Test with a function (cannot be marshaled to JSON)
fn := func() {}
_, err = cfg.configToMap(fn)
assert.Error(t, err, "Should error on function input")
}