From f0363f28c02dd38cd6173db81a3ed46c68c4c3dc Mon Sep 17 00:00:00 2001 From: ls-2018 Date: Fri, 6 Sep 2024 19:38:09 +0800 Subject: [PATCH] fix: lua encode structural error (#209) Signed-off-by: acejilam --- pkg/util/luamanager/json.go | 2 +- pkg/util/luamanager/lua_test.go | 41 +++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/pkg/util/luamanager/json.go b/pkg/util/luamanager/json.go index 75051d30..dbfc3b59 100644 --- a/pkg/util/luamanager/json.go +++ b/pkg/util/luamanager/json.go @@ -108,7 +108,7 @@ func (j jsonValue) MarshalJSON() (data []byte, err error) { switch key.Type() { case lua.LTNil: // empty table - data = []byte(`[]`) + data = []byte(`null`) case lua.LTNumber: arr := make([]jsonValue, 0, converted.Len()) expectedKey := lua.LNumber(1) diff --git a/pkg/util/luamanager/lua_test.go b/pkg/util/luamanager/lua_test.go index 11f0eb25..50027380 100644 --- a/pkg/util/luamanager/lua_test.go +++ b/pkg/util/luamanager/lua_test.go @@ -19,11 +19,13 @@ package luamanager import ( "encoding/json" "fmt" + "reflect" "testing" rolloutv1alpha1 "github.com/openkruise/rollouts/api/v1alpha1" "github.com/openkruise/rollouts/pkg/util" lua "github.com/yuin/gopher-lua" + v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" luajson "layeh.com/gopher-json" @@ -152,3 +154,42 @@ func TestRunLuaScript(t *testing.T) { }) } } +func TestEmptyMetadata(t *testing.T) { + script := ` +local x = obj +return x ` + pod := v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ + { + Name: "centos", + Image: "centos:7", + }, + }, + }, + } + unObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&pod) + if err != nil { + t.Fatal(err) + } + u := &unstructured.Unstructured{Object: unObj} + l, err := new(LuaManager).RunLuaScript(u, script) + if err != nil { + t.Fatal(err) + } + returnValue := l.Get(-1) + if returnValue.Type() == lua.LTTable { + jsonBytes, err := Encode(returnValue) + if err != nil { + t.Fatal(err) + } + p := v1.Pod{} + err = json.Unmarshal(jsonBytes, &p) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(pod, p) { + t.Fatal("return not equal before call") + } + } +}