-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexamples_test.go
More file actions
71 lines (61 loc) · 1.77 KB
/
examples_test.go
File metadata and controls
71 lines (61 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package gon_test
import (
"context"
"fmt"
"testing"
"time"
"github.com/sonalys/gon"
"github.com/sonalys/gon/encoding"
"github.com/stretchr/testify/require"
)
func Test_Expression(t *testing.T) {
type Friend struct {
Name string `gon:"name"`
Birthday time.Time `gon:"birthday"`
}
birthday := time.Now().AddDate(-15, 0, 0)
scope, err := gon.NewScope().
// Context cancellation
WithContext(t.Context()).
// Dynamic, decoupled scope for your rules.
WithValues(gon.Values{
// Support for static variables of any type.
"myName": gon.Literal("friendName"),
// Support for structs and maps for children attributes.
"friend": gon.Literal(&Friend{
Name: "friendName",
Birthday: birthday,
}),
// Support for callable function definitions, with or without implicit context.
"reply": gon.Literal(func(ctx context.Context, name string, msg any) string {
switch msg := msg.(type) {
case error:
return fmt.Sprintf("unexpected error: %s", msg.Error())
case string:
fmt.Printf("Hello %s, you are %s!\n", name, msg)
}
return "surprise!"
}),
"whoAreYou": gon.Literal(func() string {
return "I don't know you!"
}),
})
// Error on invalid key names.
// Should start with a-z and only contain alphanumeric characters.
require.NoError(t, err)
ruleStr := `if(
condition: equal(myName, friend.name),
then: call("reply"
friend.name
if(lt(friend.birthday, time("2016-10-31T11:07:39+01:00")), "old", "young")
),
else: call("whoAreYou")
)`
rule, err := encoding.Decode([]byte(ruleStr), encoding.DefaultExpressionCodex)
require.NoError(t, err)
resp, err := scope.Compute(rule)
require.NoError(t, err)
require.Equal(t, "surprise!", resp)
err = encoding.HumanEncode(t.Output(), rule)
require.NoError(t, err)
}