forked from google/go-jsonnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonnet_test.go
352 lines (323 loc) · 9.74 KB
/
jsonnet_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
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package jsonnet
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"strings"
"testing"
"unicode/utf8"
"github.com/google/go-jsonnet/ast"
)
type errorFormattingTest struct {
name string
input string
errString string
}
func genericTestErrorMessage(t *testing.T, tests []errorFormattingTest, format func(RuntimeError) string) {
for _, test := range tests {
vm := MakeVM()
rawOutput, err := vm.evaluateSnippet(ast.DiagnosticFileName(test.name), "", test.input, evalKindRegular)
var errString string
if err != nil {
switch typedErr := err.(type) {
case RuntimeError:
errString = format(typedErr)
default:
t.Errorf("%s: unexpected error: %v", test.name, err)
}
}
output := rawOutput.(string)
if errString != test.errString {
t.Errorf("%s: error result does not match. got\n\t%+#v\nexpected\n\t%+#v",
test.name, errString, test.errString)
}
if err == nil {
t.Errorf("%s, Expected error, but execution succeded and the here's the result:\n %v\n", test.name, output)
}
}
}
// TODO(sbarzowski) Perhaps we should have just one set of tests with all the variants?
// TODO(sbarzowski) Perhaps this should be handled in external tests?
var oneLineTests = []errorFormattingTest{
{"error", `error "x"`, "RUNTIME ERROR: x"},
}
func TestOneLineError(t *testing.T) {
genericTestErrorMessage(t, oneLineTests, func(r RuntimeError) string {
return r.Error()
})
}
// TODO(sbarzowski) checking if the whitespace is right is quite unpleasant, what can we do about it?
var minimalErrorTests = []errorFormattingTest{
{"error", `error "x"`, "RUNTIME ERROR: x\n" +
" error:1:1-10 $\n" + // TODO(sbarzowski) if seems we have off-by-one in location
" During evaluation \n" +
""},
{"error_in_func", `local x(n) = if n == 0 then error "x" else x(n - 1); x(3)`, "RUNTIME ERROR: x\n" +
" error_in_func:1:29-38 function <x>\n" +
" error_in_func:1:44-52 function <x>\n" +
" error_in_func:1:44-52 function <x>\n" +
" error_in_func:1:44-52 function <x>\n" +
" error_in_func:1:54-58 $\n" +
" During evaluation \n" +
""},
{"error_in_error", `error (error "x")`, "RUNTIME ERROR: x\n" +
" error_in_error:1:8-17 $\n" +
" During evaluation \n" +
""},
}
func TestMinimalError(t *testing.T) {
formatter := termErrorFormatter{maxStackTraceSize: 20}
genericTestErrorMessage(t, minimalErrorTests, func(r RuntimeError) string {
return formatter.Format(r)
})
}
// TODO(sbarzowski) test pretty errors once they are stable-ish
// probably "golden" pattern is the right one for that
func removeExcessiveWhitespace(s string) string {
var buf bytes.Buffer
needsSeparation := false
for i, w := 0, 0; i < len(s); i += w {
runeValue, width := utf8.DecodeRuneInString(s[i:])
if runeValue == '\n' || runeValue == ' ' {
needsSeparation = true
} else {
if needsSeparation {
buf.WriteString(" ")
needsSeparation = false
}
buf.WriteRune(runeValue)
}
w = width
}
return buf.String()
}
func TestCustomImporter(t *testing.T) {
vm := MakeVM()
vm.Importer(&MemoryImporter{
map[string]Contents{
"a.jsonnet": MakeContents("2 + 2"),
"b.jsonnet": MakeContents("3 + 3"),
"c.bin": MakeContentsRaw([]byte{0xff, 0xfe, 0xfd}),
},
})
input := `[import "a.jsonnet", importstr "b.jsonnet", importbin "c.bin"]`
expected := `[ 4, "3 + 3", [ 255, 254, 253 ] ]`
actual, err := vm.EvaluateSnippet("custom_import.jsonnet", input)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
actual = removeExcessiveWhitespace(actual)
if actual != expected {
t.Errorf("Expected %q, but got %q", expected, actual)
}
}
type importHistoryEntry struct {
importedFrom string
importedPath string
}
type importerWithHistory struct {
i MemoryImporter
history []importHistoryEntry
}
func (importer *importerWithHistory) Import(importedFrom, importedPath string) (contents Contents, foundAt string, err error) {
importer.history = append(importer.history, importHistoryEntry{importedFrom, importedPath})
return importer.i.Import(importedFrom, importedPath)
}
func TestExtVarImportedFrom(t *testing.T) {
vm := MakeVM()
vm.ExtCode("aaa", "import 'a.jsonnet'")
importer := importerWithHistory{
i: MemoryImporter{
map[string]Contents{
"a.jsonnet": MakeContents("2 + 2"),
},
},
}
vm.Importer(&importer)
input := `std.extVar('aaa')`
expected := `4`
actual, err := vm.EvaluateSnippet("blah.jsonnet", input)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
actual = removeExcessiveWhitespace(actual)
if actual != expected {
t.Errorf("Expected %q, but got %q", expected, actual)
}
expectedImportHistory := []importHistoryEntry{{"", "a.jsonnet"}}
if !reflect.DeepEqual(importer.history, expectedImportHistory) {
t.Errorf("Expected %q, but got %q", expectedImportHistory, importer.history)
}
}
func TestTLAImportedFrom(t *testing.T) {
vm := MakeVM()
vm.TLACode("aaa", "import 'a.jsonnet'")
importer := importerWithHistory{
i: MemoryImporter{
map[string]Contents{
"a.jsonnet": MakeContents("2 + 2"),
},
},
}
vm.Importer(&importer)
input := `function(aaa) aaa`
expected := `4`
actual, err := vm.EvaluateSnippet("blah.jsonnet", input)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
actual = removeExcessiveWhitespace(actual)
if actual != expected {
t.Errorf("Expected %q, but got %q", expected, actual)
}
expectedImportHistory := []importHistoryEntry{{"", "a.jsonnet"}}
if !reflect.DeepEqual(importer.history, expectedImportHistory) {
t.Errorf("Expected %q, but got %q", expectedImportHistory, importer.history)
}
}
func TestAnonymousImportedFrom(t *testing.T) {
vm := MakeVM()
importer := importerWithHistory{
i: MemoryImporter{
map[string]Contents{
"a.jsonnet": MakeContents("2 + 2"),
},
},
}
vm.Importer(&importer)
input := `import "a.jsonnet"`
expected := `4`
actual, err := vm.EvaluateAnonymousSnippet("blah.jsonnet", input)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
actual = removeExcessiveWhitespace(actual)
if actual != expected {
t.Errorf("Expected %q, but got %q", expected, actual)
}
expectedImportHistory := []importHistoryEntry{{"", "a.jsonnet"}}
if !reflect.DeepEqual(importer.history, expectedImportHistory) {
t.Errorf("Expected %q, but got %q", expectedImportHistory, importer.history)
}
}
func TestContents(t *testing.T) {
a := "aaa"
c1 := MakeContents(a)
a = "bbb"
if c1.String() != "aaa" {
t.Errorf("Contents should be immutable")
}
c2 := MakeContents(a)
c3 := MakeContents(a)
if c2 == c3 {
t.Errorf("Contents should distinguish between different instances even if they have the same data inside")
}
}
func TestExtReset(t *testing.T) {
vm := MakeVM()
vm.ExtVar("fooString", "bar")
vm.ExtCode("fooCode", "true")
_, err := vm.EvaluateAnonymousSnippet("test.jsonnet", `{ str: std.extVar('fooString'), code: std.extVar('fooCode') }`)
if err != nil {
t.Fatalf("unexpected error %v", err)
}
vm.ExtReset()
_, err = vm.EvaluateAnonymousSnippet("test.jsonnet", `{ str: std.extVat('fooString'), code: std.extVar('fooCode') }`)
if err == nil {
t.Fatalf("expected error, got nil")
}
if !strings.Contains(err.Error(), "Undefined external variable") {
t.Errorf("unexpected error %v", err)
}
}
func TestTLAReset(t *testing.T) {
vm := MakeVM()
vm.TLAVar("fooString", "bar")
vm.TLACode("fooCode", "true")
_, err := vm.EvaluateAnonymousSnippet("test.jsonnet", `function (fooString, fooCode) { str: fooString, code: fooCode }`)
if err != nil {
t.Fatalf("unexpected error %v", err)
}
vm.TLAReset()
_, err = vm.EvaluateAnonymousSnippet("test.jsonnet", `function(fooString, fooCode) { str: fooString, code: fooCode }`)
if err == nil {
t.Fatalf("expected error, got nil")
}
if !strings.Contains(err.Error(), "Missing argument") {
t.Errorf("unexpected error %v", err)
}
}
func assertVarOutput(t *testing.T, jsonStr string) {
var data struct {
Var string `json:"var"`
Code string `json:"code"`
Node string `json:"node"`
}
err := json.Unmarshal([]byte(jsonStr), &data)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if data.Var != "var" {
t.Errorf("var attribute not correct, want '%s' got '%s'", "var", data.Var)
}
if data.Code != "code" {
t.Errorf("code attribute not correct, want '%s' got '%s'", "code", data.Code)
}
if data.Node != "node" {
t.Errorf("node attribute not correct, want '%s' got '%s'", "node", data.Node)
}
}
func TestExtTypes(t *testing.T) {
node, err := SnippetToAST("var.jsonnet", `{ node: 'node' }`)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
vm := MakeVM()
vm.ExtVar("var", "var")
vm.ExtCode("code", `{ code: 'code'}`)
vm.ExtNode("node", node)
jsonStr, err := vm.EvaluateAnonymousSnippet(
"caller.jsonnet",
`{ var: std.extVar('var') } + std.extVar('code') + std.extVar('node')`,
)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
assertVarOutput(t, jsonStr)
}
func TestTLATypes(t *testing.T) {
node, err := SnippetToAST("var.jsonnet", `{ node: 'node' }`)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
vm := MakeVM()
vm.TLAVar("var", "var")
vm.TLACode("code", `{ code: 'code'}`)
vm.TLANode("node", node)
jsonStr, err := vm.EvaluateAnonymousSnippet(
"caller.jsonnet",
`function (var, code, node) { var: var } + code + node`,
)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
assertVarOutput(t, jsonStr)
}
func TestSetTraceOut(t *testing.T) {
traceOut := &strings.Builder{}
vm := MakeVM()
vm.SetTraceOut(traceOut)
const filename = "blah.jsonnet"
const msg = "TestSetTraceOut Trace Message"
expected := fmt.Sprintf("TRACE: %s:1 %s", filename, msg)
input := fmt.Sprintf("std.trace('%s', 'rest')", msg)
_, err := vm.EvaluateAnonymousSnippet(filename, input)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
actual := removeExcessiveWhitespace(traceOut.String())
if actual != expected {
t.Errorf("Expected %q, but got %q", expected, actual)
}
}