condition/engine/engine_test.go
2024-05-09 10:21:15 +08:00

107 lines
2.7 KiB
Go

package engine
import (
"testing"
"git.fsdpf.net/go/condition"
"git.fsdpf.net/go/req"
)
type TestTable struct {
Null any
Age int64 `db:"age"`
Name string `db:"name"`
Map map[string]any `db:"map"`
Bool bool `db:"bool"`
Struct *struct{ Name string } `db:"json"`
Array []any `db:"array"`
}
func TestEngine(t *testing.T) {
engine := Engine[any]{
code: "TestTable",
g: req.NewGlobalParam(`{"age": 30}`, nil),
}
cond1 := condition.New(condition.Describe("条件1"))
cond1.SetExpr(condition.NewExpr("TestTable", "age", condition.Token("age", condition.PARAM)))
engine.Case(cond1, func(data any, g req.GlobalParams) error {
t.Log("cond1", data)
return nil
})
engine.Default(func(data any, g req.GlobalParams) error {
t.Log("default", data)
return nil
})
engine.Execute(map[string]any{
"null": nil,
"age": 30,
"name": "张三",
"map": map[string]any{
"field": 1,
},
"bool": false,
"struct": &struct{ Name string }{"李四"},
"array": []any{1, "a", false},
})
t.Log("execute error", engine.Execute(TestTable{nil, 30, "张三", map[string]any{"field": 1}, false, &struct{ Name string }{"李四"}, []any{1, "a", false}}))
}
func TestRelationEngine(t *testing.T) {
engine := Engine[any]{
code: "TestTable",
g: req.NewGlobalParam(`{"age": 30}`, nil),
opts: engineOptions{
debug: false,
relations: []string{"TestTableA"},
},
}
cond1 := condition.New(condition.Describe("条件1")).
SetExpr(condition.NewExpr("TestTable", "age", condition.Token("age", condition.PARAM)))
engine.Case(cond1, func(data any, g req.GlobalParams) error {
t.Log("cond1", data)
return nil
})
cond2 := condition.New(condition.Type(condition.OR), condition.Describe("条件2")).
SetExpr(condition.NewExpr("TestTableA", "age", condition.Token("age", condition.PARAM))).
SetExpr(condition.NewExpr("TestTable", "age", condition.Token("age", condition.PARAM)))
engine.Case(cond2, func(data any, g req.GlobalParams) error {
t.Log("cond2", data)
return nil
})
engine.Default(func(data any, g req.GlobalParams) error {
t.Log("default", data)
return nil
})
engine.Execute(map[string]any{
"null": nil,
"age": 31,
"name": "张三",
"map": map[string]any{
"field": 1,
},
"bool": false,
"struct": &struct{ Name string }{"李四"},
"array": []any{1, "a", false},
"TestTableA": map[string]any{
"age": 30,
"TestTableA": map[string]any{
"age": 22,
},
},
})
// t.Log("execute error", engine.Execute(TestTable{nil, 30, "张三", map[string]any{"field": 1}, false, &struct{ Name string }{"李四"}, []any{1, "a", false}}))
}