File: eval_test.go

package info (click to toggle)
golang-github-go-restruct-restruct 1.2.0-alpha-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 344 kB
  • sloc: makefile: 2
file content (149 lines) | stat: -rw-r--r-- 2,164 bytes parent folder | download
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package expr

import (
	"reflect"
	"testing"

	"github.com/stretchr/testify/assert"
)

type TestStruct1 struct {
	A int
	B float64
}

func TestEvalSimple(t *testing.T) {
	tests := []struct {
		struc  interface{}
		expr   string
		result interface{}
	}{
		{
			TestStruct1{A: 42},
			"A",
			42,
		},
		{
			TestStruct1{A: 42},
			"A * 2",
			84,
		},
		{
			TestStruct1{B: 10.5},
			"B * 2",
			21.0,
		},
		{
			TestStruct1{B: 10.5},
			"-(B * 2)",
			-21.0,
		},
		{
			TestStruct1{A: 0xf0},
			"^0xf0 | A",
			-1,
		},
		{
			TestStruct1{},
			"2 << 2",
			8,
		},
		{
			TestStruct1{},
			"true",
			true,
		},
		{
			TestStruct1{},
			"false",
			false,
		},
		{
			TestStruct1{},
			"true ? 1.0 : 0.0",
			1.0,
		},
		{
			TestStruct1{},
			"false ? 1.0 : 0.0",
			0.0,
		},
		{
			TestStruct1{},
			`"string value!"`,
			"string value!",
		},
		{
			TestStruct1{},
			`"equal" == "equal"`,
			true,
		},
		{
			TestStruct1{},
			`"equal" == "not equal"`,
			false,
		},
		{
			TestStruct1{},
			`"equal" != "not equal"`,
			true,
		},
		{
			TestStruct1{},
			`"equal" != "equal"`,
			false,
		},
		{
			TestStruct1{},
			`"equal"[1] == 'q'`,
			true,
		},
	}

	for _, test := range tests {
		resolver := NewStructResolver(reflect.ValueOf(test.struc))
		result, err := Eval(resolver, test.expr)
		assert.Nil(t, err)
		assert.Equal(t, test.result, result)
	}
}

func TestError(t *testing.T) {
	tests := []struct {
		struc interface{}
		expr  string
		err   string
	}{
		{
			TestStruct1{A: 42},
			"!A",
			"invalid operation: operator ! not defined for 42 (int)",
		},
		{
			TestStruct1{},
			"!42",
			"invalid operation: operator ! not defined for 42 (untyped int constant)",
		},
		{
			TestStruct1{A: 1, B: 1.0},
			"A == B",
			"cannot convert int to float64",
		},
		{
			TestStruct1{A: 1, B: 1.0},
			"A == true",
			"cannot convert int to untyped bool constant",
		},
		{
			TestStruct1{A: 1, B: 1.0},
			"A > true",
			"cannot convert int to untyped bool constant",
		},
	}

	for _, test := range tests {
		resolver := NewStructResolver(reflect.ValueOf(test.struc))
		_, err := Eval(resolver, test.expr)
		assert.EqualError(t, err, test.err)
	}
}