package cast_test import ( "testing" "apigo.cc/go/cast" ) type DBConfig struct { Host string Port int } func TestMapStructMerge(t *testing.T) { // Initial configuration with default values dst := map[string]DBConfig{ "mysql": {Host: "localhost", Port: 3306}, } // New data (e.g., from environment variables) that only overrides Host src := map[string]any{ "mysql": map[string]any{ "Host": "127.0.0.1", }, } // Perform conversion/merge cast.Convert(&dst, src) // Verify results mysql, ok := dst["mysql"] if !ok { t.Fatal("mysql config not found") } if mysql.Host != "127.0.0.1" { t.Errorf("Expected Host 127.0.0.1, got %s", mysql.Host) } if mysql.Port != 3306 { t.Errorf("Expected Port 3306, got %d", mysql.Port) } } func TestMapStructPointerMerge(t *testing.T) { // Initial configuration with default values (using pointers) dst := map[string]*DBConfig{ "mysql": {Host: "localhost", Port: 3306}, } // New data that only overrides Host src := map[string]any{ "mysql": map[string]any{ "Host": "127.0.0.1", }, } // Perform conversion/merge cast.Convert(&dst, src) // Verify results mysql, ok := dst["mysql"] if !ok { t.Fatal("mysql config not found") } if mysql.Host != "127.0.0.1" { t.Errorf("Expected Host 127.0.0.1, got %s", mysql.Host) } if mysql.Port != 3306 { t.Errorf("Expected Port 3306, got %d", mysql.Port) } } func TestSliceToMapMerge(t *testing.T) { dst := map[string]int{ "a": 1, "b": 2, } src := []any{"b", 20, "c", 30} cast.Convert(&dst, src) if dst["a"] != 1 { t.Errorf("Expected a=1, got %d", dst["a"]) } if dst["b"] != 20 { t.Errorf("Expected b=20, got %d", dst["b"]) } if dst["c"] != 30 { t.Errorf("Expected c=30, got %d", dst["c"]) } } func TestStructToMapMerge(t *testing.T) { type Config struct { Host string Port int } dst := map[string]any{ "host": "localhost", "port": 3306, "user": "root", } // Note: Struct fields are always "present", so Port:0 will overwrite port:3306 src := Config{Host: "127.0.0.1", Port: 8080} cast.Convert(&dst, src) if dst["host"] != "127.0.0.1" { t.Errorf("Expected host 127.0.0.1, got %v", dst["host"]) } if cast.Int(dst["port"]) != 8080 { t.Errorf("Expected port 8080, got %v", dst["port"]) } if dst["user"] != "root" { t.Errorf("Expected user root, got %v", dst["user"]) } }