118 lines
2.8 KiB
Go
118 lines
2.8 KiB
Go
package processor
|
|
|
|
import (
|
|
"cook/utils"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
)
|
|
|
|
func TestProcessJSON(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
input string
|
|
luaExpression string
|
|
expectedOutput string
|
|
expectedMods int
|
|
}{
|
|
{
|
|
name: "Basic JSON object modification",
|
|
input: `{"name": "test", "value": 42}`,
|
|
luaExpression: `data.value = data.value * 2; return true`,
|
|
expectedOutput: `{
|
|
"name": "test",
|
|
"value": 84
|
|
}`,
|
|
expectedMods: 1,
|
|
},
|
|
{
|
|
name: "JSON array modification",
|
|
input: `{"items": [{"id": 1, "value": 10}, {"id": 2, "value": 20}]}`,
|
|
luaExpression: `for i, item in ipairs(data.items) do data.items[i].value = item.value * 1.5 end; return true`,
|
|
expectedOutput: `{
|
|
"items": [
|
|
{
|
|
"id": 1,
|
|
"value": 15
|
|
},
|
|
{
|
|
"id": 2,
|
|
"value": 30
|
|
}
|
|
]
|
|
}`,
|
|
expectedMods: 1,
|
|
},
|
|
{
|
|
name: "JSON nested object modification",
|
|
input: `{"config": {"settings": {"enabled": false, "timeout": 30}}}`,
|
|
luaExpression: `data.config.settings.enabled = true; data.config.settings.timeout = 60; return true`,
|
|
expectedOutput: `{
|
|
"config": {
|
|
"settings": {
|
|
"enabled": true,
|
|
"timeout": 60
|
|
}
|
|
}
|
|
}`,
|
|
expectedMods: 1,
|
|
},
|
|
{
|
|
name: "JSON no modification",
|
|
input: `{"name": "test", "value": 42}`,
|
|
luaExpression: `return false`,
|
|
expectedOutput: `{"name": "test", "value": 42}`,
|
|
expectedMods: 0,
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
command := utils.ModifyCommand{
|
|
Name: tt.name,
|
|
JSON: true,
|
|
Lua: tt.luaExpression,
|
|
}
|
|
|
|
modifications, err := ProcessJSON(tt.input, command, "test.json")
|
|
assert.NoError(t, err, "ProcessJSON failed: %v", err)
|
|
|
|
if len(modifications) > 0 {
|
|
// Execute modifications
|
|
result, count := utils.ExecuteModifications(modifications, tt.input)
|
|
assert.Equal(t, tt.expectedMods, count, "Expected %d modifications, got %d", tt.expectedMods, count)
|
|
assert.Equal(t, tt.expectedOutput, result, "Expected output: %s, got: %s", tt.expectedOutput, result)
|
|
} else {
|
|
assert.Equal(t, 0, tt.expectedMods, "Expected no modifications but got some")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestToLuaValue(t *testing.T) {
|
|
L, err := NewLuaState()
|
|
if err != nil {
|
|
t.Fatalf("Failed to create Lua state: %v", err)
|
|
}
|
|
defer L.Close()
|
|
|
|
tests := []struct {
|
|
name string
|
|
input interface{}
|
|
expected string
|
|
}{
|
|
{"string", "hello", "hello"},
|
|
{"number", 42.0, "42"},
|
|
{"boolean", true, "true"},
|
|
{"nil", nil, "nil"},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result, err := ToLuaValue(L, tt.input)
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, tt.expected, result.String())
|
|
})
|
|
}
|
|
}
|