From 9bcb25193b5aa8b0ec881dcf58ac2ae920049ba1 Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Sun, 17 Sep 2023 00:52:33 +0200 Subject: [PATCH] Convert nested array to primitive types Add tests for CastToPrimitiveTypes and NewCommand --- plugin/utils.go | 14 +++++++++++++ plugin/utils_test.go | 49 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/plugin/utils.go b/plugin/utils.go index e7771f4d..52e9e667 100644 --- a/plugin/utils.go +++ b/plugin/utils.go @@ -34,10 +34,24 @@ func CastToPrimitiveTypes(args map[string]interface{}) map[string]interface{} { for key, value := range args { switch value := value.(type) { case time.Duration: + // Cast time.Duration to string. args[key] = value.String() case map[string]interface{}: // Recursively cast nested maps. args[key] = CastToPrimitiveTypes(value) + case []interface{}: + // Recursively cast nested arrays. + array := make([]interface{}, len(value)) + for idx, v := range value { + result := v + if v, ok := v.(time.Duration); ok { + // Cast time.Duration to string. + array[idx] = v.String() + } else { + array[idx] = result + } + } + args[key] = array // TODO: Add more types here as needed. default: args[key] = value diff --git a/plugin/utils_test.go b/plugin/utils_test.go index 0e3e695a..5c0d12ea 100644 --- a/plugin/utils_test.go +++ b/plugin/utils_test.go @@ -2,6 +2,7 @@ package plugin import ( "testing" + "time" v1 "github.com/gatewayd-io/gatewayd-plugin-sdk/plugin/v1" "github.com/stretchr/testify/assert" @@ -73,3 +74,51 @@ func Test_Verify_fail(t *testing.T) { func Test_Verify_nil(t *testing.T) { assert.True(t, Verify(nil, nil)) } + +func Test_NewCommand(t *testing.T) { + cmd := NewCommand("/test", []string{"--test"}, []string{"test=123"}) + assert.NotNil(t, cmd) + assert.Equal(t, "/test", cmd.Path) + // Command.Args[0] is always set to the command name itself. + assert.Equal(t, []string{"/test", "--test"}, cmd.Args) + assert.Equal(t, []string{"test=123"}, cmd.Env) +} + +// Test_CastToPrimitiveTypes tests the CastToPrimitiveTypes function. +func Test_CastToPrimitiveTypes(t *testing.T) { + actual := map[string]interface{}{ + "string": "test", + "int": 123, + "bool": true, + "map": map[string]interface{}{"test": "test"}, + "duration": time.Duration(123), + "array": []interface{}{ + "test", + 123, + true, + map[string]interface{}{ + "test": "test", + }, + time.Duration(123), + }, + } + expected := map[string]interface{}{ + "string": "test", + "int": 123, + "bool": true, + "map": map[string]interface{}{"test": "test"}, + "duration": "123ns", // time.Duration is casted to string. + "array": []interface{}{ + "test", + 123, + true, + map[string]interface{}{ + "test": "test", + }, + "123ns", // time.Duration is casted to string. + }, + } + + casted := CastToPrimitiveTypes(actual) + assert.Equal(t, expected, casted) +}