-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgora_test.go
112 lines (91 loc) · 2.15 KB
/
gora_test.go
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package gora_test
import (
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"sync/atomic"
"testing"
"github.com/stretchr/testify/require"
"github.com/binalyze/gora"
"github.com/binalyze/gora/variables"
)
func TestCompileString(t *testing.T) {
comp := gora.NewCompiled()
err := comp.CompileString(`rule x{`, "")
require.Error(t, err)
require.Nil(t, comp.Rules())
comp = gora.NewCompiled()
err = comp.CompileString(rulestrFs, "")
require.NoError(t, err)
require.NotNil(t, comp.Rules())
}
func TestCompileFile(t *testing.T) {
tempDir := t.TempDir()
comp := gora.NewCompiled()
path := genFile(t, tempDir, `rule x{`)
err := comp.CompileFiles(true, path)
require.Error(t, err)
require.Nil(t, comp.Rules())
comp = gora.NewCompiled()
path = genFile(t, tempDir, rulestrFs)
err = comp.CompileFiles(true, path)
require.NoError(t, err)
require.NotNil(t, comp.Rules())
}
func TestBuildRuleWithAllVars(t *testing.T) {
tempDir := t.TempDir()
const ee = " == "
vars := variables.List()
var sb strings.Builder
for i, v := range vars {
sb.WriteString(v.String())
switch m := v.Meta(); {
case m&variables.MetaBool != 0:
case m&variables.MetaFloat != 0, m&variables.MetaInt != 0:
sb.WriteString(ee)
sb.WriteString("0")
case m&variables.MetaString != 0:
sb.WriteString(ee)
sb.WriteString("\"\"")
}
if i < len(vars)-1 {
sb.WriteString(" and ")
}
}
rs := fmt.Sprintf(ruleAllVarsTmpl, sb.String())
comp := gora.NewCompiled()
path := genFile(t, tempDir, rs)
err := comp.CompileFiles(true, path)
require.NoError(t, err)
require.NotNil(t, comp.Rules())
}
const rulestrFs = `
rule test_fs
{
strings:
$my_text_string = "test"
condition:
$my_text_string
}
`
const ruleAllVarsTmpl = `
rule all_vars
{
condition:
%s
}
`
var atomicFileCounter int64
func genFile(t *testing.T, dir, rulestr string) string {
t.Helper()
p := filepath.Join(dir, strconv.FormatInt(atomic.AddInt64(&atomicFileCounter, 1), 10))
f, err := os.OpenFile(p, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o777)
require.NoError(t, err)
_, err = io.WriteString(f, rulestr)
require.NoError(t, err)
require.NoError(t, f.Close())
return p
}