From 27f53db0f44855b64423dc18b918d8fe576b7e5e Mon Sep 17 00:00:00 2001 From: Celestino Amoroso Date: Thu, 28 Mar 2024 06:33:14 +0100 Subject: [PATCH] helpers_test.go: tests on the helper functions --- helpers_test.go | 80 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 helpers_test.go diff --git a/helpers_test.go b/helpers_test.go new file mode 100644 index 0000000..daa40c3 --- /dev/null +++ b/helpers_test.go @@ -0,0 +1,80 @@ +// helpers_test.go +package expr + +import ( + "fmt" + "testing" +) + +func subtract(ctx exprContext, name string, args []any) (result any, err error) { + if len(args) != 2 { + err = fmt.Errorf("%s(): requires exactly two arguments", name) + return + } + x, xok := args[0].(int64) + y, yok := args[1].(int64) + if xok && yok { + result = x - y + } else { + err = fmt.Errorf("expected integer (int64) arguments, got %T and %T values", x, y) + } + return +} + +func TestEvalStringA(t *testing.T) { + + source := `a + b * subtract(4,2)` + args := []EvalArg{ + {"a", uint8(1)}, + {"b", int8(2)}, + {"subtract", FuncTemplate(subtract)}, + // enforce coverage + {"a16", uint16(1)}, + {"b16", int16(2)}, + {"a32", uint32(1)}, + {"b32", int32(2)}, + {"a64", uint64(1)}, + {"b64", int64(2)}, + {"f32", float32(1.0)}, + {"f64", float64(1.0)}, + } + + wantResult := int64(5) + gotResult, gotErr := EvalStringA(source, args...) + if value, ok := gotResult.(int64); ok && value != wantResult { + t.Errorf("Source %q got %v, want %v", source, gotResult, wantResult) + t.Errorf("Error: %v", gotErr) + } + fmt.Println("Hello World!") +} + +func TestEvalString(t *testing.T) { + + ctx := NewSimpleVarStore() + ctx.SetValue("a", uint8(1)) + ctx.SetValue("b", int8(2)) + ctx.SetValue("f", 2.0) + // enforce coverage + ctx.SetValue("a16", uint16(1)) + ctx.SetValue("b16", int16(2)) + ctx.SetValue("a32", uint32(1)) + ctx.SetValue("b32", int32(2)) + ctx.SetValue("a64", uint64(1)) + ctx.SetValue("b64", int64(2)) + ctx.SetValue("f32", float32(1.0)) + ctx.SetValue("f64", float64(1.0)) + + // enforce coverage + ctx.GetFuncInfo("dummy") + ctx.Call("dummy", []any{}) + + source := `a + b * f` + + wantResult := float64(5) + gotResult, gotErr := EvalString(ctx, source) + if value, ok := gotResult.(float64); ok && value != wantResult { + t.Errorf("Source %q got %v, want %v", source, gotResult, wantResult) + t.Errorf("Error: %v", gotErr) + } + fmt.Println("Hello World!") +}