fix: lua encode structural error (#209)

Signed-off-by: acejilam <acejilam@gmail.com>
This commit is contained in:
ls-2018 2024-09-06 19:38:09 +08:00 committed by GitHub
parent d2613132aa
commit f0363f28c0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 42 additions and 1 deletions

View File

@ -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)

View File

@ -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")
}
}
}