File: commands_test.go

package info (click to toggle)
golang-github-google-cel-go 0.18.2%2Bds-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,888 kB
  • sloc: sh: 93; makefile: 12
file content (337 lines) | stat: -rw-r--r-- 8,359 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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package repl

import (
	"errors"
	"fmt"
	"strings"
	"testing"

	"google.golang.org/protobuf/proto"
)

func cmdMatches(t testing.TB, got Cmder, expected Cmder) (result bool) {
	t.Helper()

	defer func() {
		// catch type assertion errors
		if v := recover(); v != nil {
			result = false
		}
	}()

	switch want := expected.(type) {
	case *compileCmd:
		gotCompile := got.(*compileCmd)
		return gotCompile.expr == want.expr
	case *evalCmd:
		gotEval := got.(*evalCmd)
		return gotEval.expr == want.expr
	case *delCmd:
		gotDel := got.(*delCmd)
		return gotDel.identifier == want.identifier
	case *simpleCmd:
		gotSimple := got.(*simpleCmd)
		if len(gotSimple.args) != len(want.args) {
			return false
		}
		for i, a := range want.args {
			if gotSimple.args[i] != a {
				return false
			}
		}
		return gotSimple.cmd == want.cmd
	case *letFnCmd:
		gotLetFn := got.(*letFnCmd)
		if gotLetFn.identifier != want.identifier ||
			gotLetFn.src != want.src ||
			!proto.Equal(gotLetFn.resultType, want.resultType) ||
			len(gotLetFn.params) != len(want.params) {
			return false
		}
		for i, wantP := range want.params {
			if gotLetFn.params[i].identifier != wantP.identifier ||
				!proto.Equal(gotLetFn.params[i].typeHint, wantP.typeHint) {
				return false
			}
		}
		return true
	case *letVarCmd:
		gotLetVar := got.(*letVarCmd)
		return gotLetVar.identifier == want.identifier &&
			proto.Equal(gotLetVar.typeHint, want.typeHint) &&
			gotLetVar.src == want.src
	}
	return false
}

func (c *evalCmd) String() string {
	return fmt.Sprintf("%%eval %s", c.expr)
}

func (c *letVarCmd) String() string {
	return fmt.Sprintf("%%let %s : %s = %s", c.identifier, UnparseType(c.typeHint), c.src)
}

func fmtParam(p letFunctionParam) string {
	return fmt.Sprintf("%s : %s", p.identifier, UnparseType(p.typeHint))
}

func fmtParams(ps []letFunctionParam) string {
	buf := make([]string, len(ps))
	for i, p := range ps {
		buf[i] = fmtParam(p)
	}
	return strings.Join(buf, ", ")
}

func (c *letFnCmd) String() string {
	return fmt.Sprintf("%%let %s (%s) : %s -> %s", c.identifier, fmtParams(c.params), UnparseType(c.resultType), c.src)
}

func (c *delCmd) String() string {
	return fmt.Sprintf("%%delete %s", c.identifier)
}

func (c *simpleCmd) String() string {
	flagFmt := strings.Join(c.args, " ")
	return fmt.Sprintf("%%%s %s", c.cmd, flagFmt)
}

func TestParse(t *testing.T) {
	var testCases = []struct {
		commandLine string
		wantCmd     Cmder
		wantErr     error
	}{
		{
			commandLine: "%let x = 1",
			wantCmd: &letVarCmd{
				identifier: "x",
				typeHint:   nil,
				src:        "1",
			},
		},
		{
			commandLine: "%let com.google.x = 1",
			wantCmd: &letVarCmd{
				identifier: "com.google.x",
				typeHint:   nil,
				src:        "1",
			},
		},
		{
			commandLine: "%let x: int = 1",
			wantCmd: &letVarCmd{
				identifier: "x",
				typeHint:   mustParseType(t, "int"),
				src:        "1",
			},
		},
		{
			commandLine: `%compile x + 2`,
			wantCmd:     &compileCmd{expr: "x + 2"},
		},
		{
			commandLine: `%eval x + 2`,
			wantCmd:     &evalCmd{expr: "x + 2"},
		},
		{
			commandLine: "x + 2",
			wantCmd:     &evalCmd{expr: "x + 2"},
		},
		{
			commandLine: `%exit`,
			wantCmd:     &simpleCmd{cmd: "exit"},
		},
		{
			commandLine: `%help`,
			wantErr: errors.New(`Compile emits a textproto representation of the compiled expression.
            %compile <expr>
            
            Declare introduces a variable or function for type checking, but
            doesn't define a value for it:
            %declare <identifier> : <type>
            %declare <identifier> (<param_identifier> : <param_type>, ...) : <result-type>
            
            Delete removes a variable or function declaration from the evaluation context.
            %delete <identifier>
            
            Let introduces a variable or function defined by a sub-CEL expression.
            %let <identifier> (: <type>)? = <expr>
            %let <identifier> (<param_identifier> : <param_type>, ...) : <result-type> -> <expr>
            
            Option enables a CEL environment option which enables configuration and
            optional language features.
            %option --container 'google.protobuf'
            %option --extension 'all'
            
            Help prints usage information for the commands supported by the REPL.
            %help
            
            Exit terminates the REPL.
            %exit`),
		},
		{
			commandLine: `%arbitrary --flag -FLAG 'string literal\n'`,
			wantCmd: &simpleCmd{cmd: "arbitrary",
				args: []string{
					"--flag", "--flag", "string literal\\n",
				},
			},
		},
		{
			commandLine: "   ",
			wantCmd:     &simpleCmd{cmd: "null"},
		},
		{
			commandLine: `%delete x`,
			wantCmd:     &delCmd{identifier: "x"},
		},
		{
			commandLine: `%delete com.google.x`,
			wantCmd:     &delCmd{identifier: "com.google.x"},
		},
		{
			commandLine: `%declare x: int`,
			wantCmd: &letVarCmd{
				identifier: "x",
				typeHint:   mustParseType(t, "int"),
				src:        "",
			},
		},
		{
			commandLine: `%let fn (x : int) : int -> x + 2`,
			wantCmd: &letFnCmd{
				identifier: "fn",
				params: []letFunctionParam{
					{identifier: "x", typeHint: mustParseType(t, "int")},
				},
				resultType: mustParseType(t, "int"),
				src:        "x + 2",
			},
		},
		{
			commandLine: `%let int.plus (x : int) : int -> this + x`,
			wantCmd: &letFnCmd{
				identifier: "int.plus",
				params: []letFunctionParam{
					{identifier: "x", typeHint: mustParseType(t, "int")},
				},
				resultType: mustParseType(t, "int"),
				src:        "this + x",
			},
		},
		{
			commandLine: `%let fn () : int -> 2 + 2`,
			wantCmd: &letFnCmd{
				identifier: "fn",
				params:     []letFunctionParam{},
				resultType: mustParseType(t, "int"),
				src:        "2 + 2",
			},
		},
		{
			commandLine: `%let fn (x:int, y :int) : int -> x + y`,
			wantCmd: &letFnCmd{
				identifier: "fn",
				params: []letFunctionParam{
					{identifier: "x", typeHint: mustParseType(t, "int")},
					{identifier: "y", typeHint: mustParseType(t, "int")},
				},
				resultType: mustParseType(t, "int"),
				src:        "x + y",
			},
		},
		{
			commandLine: `%declare fn (x : int) : int`,
			wantCmd: &letFnCmd{
				identifier: "fn",
				params: []letFunctionParam{
					{identifier: "x", typeHint: mustParseType(t, "int")},
				},
				resultType: mustParseType(t, "int"),
				src:        "",
			},
		},
	}

	for _, tc := range testCases {
		tc := tc
		t.Run(tc.commandLine, func(t *testing.T) {
			cmd, err := Parse(tc.commandLine)
			if err != nil {
				if tc.wantErr != nil && stripWhitespace(tc.wantErr.Error()) == stripWhitespace(err.Error()) {
					return
				}
				t.Errorf("Parse(\"%s\") failed: %s", tc.commandLine, err)
			}
			if cmd == nil || !cmdMatches(t, cmd, tc.wantCmd) {
				t.Errorf("Parse('%s') got (%s) wanted (%s)", tc.commandLine,
					cmd, tc.wantCmd)
			}
		})
	}
}

func TestParseErrors(t *testing.T) {
	var testCases = []struct {
		commandLine string
	}{
		{
			// not an identifier
			commandLine: "%let 123 = 1",
		},
		{
			// no assignment
			commandLine: "%let x: int",
		},
		{
			// no assignment
			commandLine: "%let fn() : int",
		},
		{
			// missing types
			commandLine: "%let fn (x) -> x + 1",
		},
		{
			// missing arg id
			commandLine: "%let fn (: int) : int -> x + 1",
		},
		{
			// type required for declare
			commandLine: "%declare x",
		},
		{
			// not an identifier
			commandLine: "%declare 123",
		},
		{
			// not an identifier
			commandLine: "%declare 1() : int",
		},
		{
			// not an identifier
			commandLine: "%delete 123",
		},
	}
	for _, tc := range testCases {
		_, err := Parse(tc.commandLine)
		if err == nil {
			t.Errorf("Parse(\"%s\") ok wanted error", tc.commandLine)
		}
	}
}