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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
|
package cuesonnet_test
import (
"reflect"
"strings"
"testing"
"go.jolheiser.com/cuesonnet"
)
// checkDecode decodes data into T via sc and compares with expected using reflect.DeepEqual.
func checkDecode[T any](t *testing.T, sc cuesonnet.Schema, data string, expected T) {
t.Helper()
var got T
if err := sc.Decode(strings.NewReader(data), &got); err != nil {
t.Fatalf("decode error: %v", err)
}
if !reflect.DeepEqual(got, expected) {
t.Errorf("value mismatch:\n got: %+v\n want: %+v", got, expected)
}
}
// decode wraps checkDecode into a check func for use in table-driven tests.
func decode[T any](expected T) func(*testing.T, cuesonnet.Schema, string) {
return func(t *testing.T, sc cuesonnet.Schema, data string) {
t.Helper()
checkDecode(t, sc, data, expected)
}
}
type (
PersonDecode struct {
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Age int `json:"age"`
Birthday string `json:"birthday"`
Gopher bool `json:"gopher"`
}
PrimitivesDecode struct {
Str string `json:"str"`
Num int `json:"num"`
Dec float64 `json:"dec"`
Flag bool `json:"flag"`
Qty float64 `json:"qty"`
}
ConstraintsDecode struct {
Age int `json:"age"`
Score float64 `json:"score"`
Username string `json:"username"`
Bio string `json:"bio"`
Level int `json:"level"`
Slug string `json:"slug"`
}
// Metadata and Annotations are _ in CUE; decoded type depends on the data.
AnyDecode struct {
Name string `json:"name"`
Metadata any `json:"metadata"`
Annotations any `json:"annotations,omitempty"`
}
ClosedDecode struct {
Name string `json:"name"`
Age int `json:"age"`
}
OptionalDecode struct {
Name string `json:"name"`
Email string `json:"email"`
Phone string `json:"phone,omitempty"`
Bio string `json:"bio,omitempty"`
}
AddressDecode struct {
Street string `json:"street"`
City string `json:"city"`
Zip string `json:"zip"`
}
ContactDecode struct {
Label string `json:"label"`
Value string `json:"value"`
}
NestedDecode struct {
Name string `json:"name"`
Address AddressDecode `json:"address"`
Contacts []ContactDecode `json:"contacts"`
}
ListItemDecode struct {
ID int `json:"id"`
Label string `json:"label"`
}
ListsDecode struct {
Items []ListItemDecode `json:"items"`
Tags []string `json:"tags"`
Counts []int `json:"counts"`
Limited []string `json:"limited"`
}
// Value and Nullable are disjunction types; any holds the concrete runtime value.
DisjunctionsDecode struct {
Value any `json:"value"`
Mode string `json:"mode"`
Priority int `json:"priority"`
Nullable any `json:"nullable"`
}
DefaultsDecode struct {
Name string `json:"name"`
Role string `json:"role"`
Enabled bool `json:"enabled"`
Timeout int `json:"timeout"`
Tags []string `json:"tags"`
}
EnumsDecode struct {
Color string `json:"color"`
Status string `json:"status"`
Priority int `json:"priority"`
Flags []string `json:"flags"`
}
DefNameDecode struct {
First string `json:"first"`
Last string `json:"last"`
}
DefContactDecode struct {
Email string `json:"email,omitempty"`
Phone string `json:"phone,omitempty"`
}
DefPersonDecode struct {
Name DefNameDecode `json:"name"`
Age int `json:"age"`
Contact DefContactDecode `json:"contact"`
}
StdlibDecode struct {
CreatedAt string `json:"createdAt"`
Birthday string `json:"birthday"`
Username string `json:"username"`
Tags []string `json:"tags"`
Initials string `json:"initials"`
Angle float64 `json:"angle"`
}
CompositionDecode struct {
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
CreatedAt string `json:"createdAt"`
UpdatedAt string `json:"updatedAt"`
Age int `json:"age"`
}
PatternsDecode struct {
Name string `json:"name"`
Labels map[string]string `json:"labels"`
Counts map[string]int `json:"counts"`
}
// CUE fixed-length tuples decode positionally; Tag is [string, int] so []any.
TuplesDecode struct {
Color []int `json:"color"`
Position []float64 `json:"position"`
Tag []any `json:"tag"`
}
FunctionUserDecode struct {
Name string `json:"name"`
Greeting string `json:"greeting"`
Age int `json:"age"`
}
ComprehensionItemDecode struct {
Index int `json:"index"`
Squared int `json:"squared"`
Label string `json:"label"`
}
ConditionalEntryDecode struct {
Value int `json:"value"`
Category string `json:"category"`
Doubled int `json:"doubled"`
}
InheritanceDecode struct {
Kind string `json:"kind"`
Version string `json:"version"`
Name string `json:"name"`
Replicas int `json:"replicas"`
Image string `json:"image"`
}
MultilineDecode struct {
Description string `json:"description"`
Template string `json:"template"`
}
SelfRefDecode struct {
Width int `json:"width"`
Height int `json:"height"`
Area int `json:"area"`
Perimeter int `json:"perimeter"`
}
JStdlibDecode struct {
Upper string `json:"upper"`
Joined string `json:"joined"`
Formatted string `json:"formatted"`
Count int `json:"count"`
Words []string `json:"words"`
Mapped []string `json:"mapped"`
Filtered []string `json:"filtered"`
}
)
func TestCUEsonnetDecode(t *testing.T) {
type decodeTest struct {
name string
schema string
data string
check func(*testing.T, cuesonnet.Schema, string)
}
jim := PersonDecode{
FirstName: "Jim",
LastName: "Jimbly",
Age: 45,
Birthday: "01/02/2003",
Gopher: true,
}
tests := []decodeTest{
// person
{
name: "person/valid",
schema: "testdata/person/schema.cue",
data: "testdata/person/valid.jsonnet",
check: decode(jim),
},
{
name: "person/functions",
schema: "testdata/person/schema.cue",
data: "testdata/person/functions.jsonnet",
check: decode(jim),
},
{
name: "person/list",
schema: "testdata/person/schema_list.cue",
data: "testdata/person/functions_list.jsonnet",
check: decode([]PersonDecode{jim}),
},
// primitives
{
name: "primitives/valid",
schema: "testdata/primitives/schema.cue",
data: "testdata/primitives/valid.jsonnet",
check: decode(PrimitivesDecode{Str: "hello", Num: 42, Dec: 3.14, Flag: true, Qty: 2.718}),
},
// constraints
{
name: "constraints/valid",
schema: "testdata/constraints/schema.cue",
data: "testdata/constraints/valid.jsonnet",
check: decode(ConstraintsDecode{Age: 30, Score: 95.5, Username: "john_doe", Bio: "A software engineer.", Level: 5, Slug: "my-slug"}),
},
// structs/any
// valid_scalar: metadata is a plain string — no type ambiguity.
{
name: "structs/any/valid_scalar",
schema: "testdata/structs/any/schema.cue",
data: "testdata/structs/any/valid_scalar.jsonnet",
check: decode(AnyDecode{Name: "Alice", Metadata: "just a plain string"}),
},
// valid_object: metadata is a JSON object; CUE decodes it to map[string]any.
{
name: "structs/any/valid_object",
schema: "testdata/structs/any/schema.cue",
data: "testdata/structs/any/valid_object.jsonnet",
check: func(t *testing.T, sc cuesonnet.Schema, data string) {
t.Helper()
var got AnyDecode
if err := sc.Decode(strings.NewReader(data), &got); err != nil {
t.Fatalf("decode error: %v", err)
}
if got.Name != "Alice" {
t.Errorf("Name: got %q, want %q", got.Name, "Alice")
}
meta, ok := got.Metadata.(map[string]any)
if !ok {
t.Fatalf("Metadata: got %T, want map[string]any", got.Metadata)
}
if meta["role"] != "admin" {
t.Errorf("Metadata.role: got %v, want %q", meta["role"], "admin")
}
if _, ok := got.Annotations.(map[string]any); !ok {
t.Errorf("Annotations: got %T, want map[string]any", got.Annotations)
}
},
},
// structs/closed
{
name: "structs/closed/valid",
schema: "testdata/structs/closed/schema.cue",
data: "testdata/structs/closed/valid.jsonnet",
check: decode(ClosedDecode{Name: "Alice", Age: 30}),
},
// structs/optional
{
name: "structs/optional/full",
schema: "testdata/structs/optional/schema.cue",
data: "testdata/structs/optional/valid_full.jsonnet",
check: decode(OptionalDecode{Name: "Alice", Email: "alice@example.com", Phone: "555-1234", Bio: "Software engineer."}),
},
{
name: "structs/optional/minimal",
schema: "testdata/structs/optional/schema.cue",
data: "testdata/structs/optional/valid_minimal.jsonnet",
check: decode(OptionalDecode{Name: "Alice", Email: "alice@example.com"}),
},
// structs/nested
{
name: "structs/nested/valid",
schema: "testdata/structs/nested/schema.cue",
data: "testdata/structs/nested/valid.jsonnet",
check: decode(NestedDecode{
Name: "Alice",
Address: AddressDecode{Street: "123 Main St", City: "Springfield", Zip: "12345"},
Contacts: []ContactDecode{
{Label: "email", Value: "alice@example.com"},
{Label: "phone", Value: "555-1234"},
},
}),
},
// lists
{
name: "lists/valid",
schema: "testdata/lists/schema.cue",
data: "testdata/lists/valid.jsonnet",
check: decode(ListsDecode{
Items: []ListItemDecode{{ID: 1, Label: "first"}, {ID: 2, Label: "second"}},
Tags: []string{"go", "cue", "jsonnet"},
Counts: []int{0, 1, 2, 100},
Limited: []string{"only", "a", "few"},
}),
},
// disjunctions
// valid_a: all any fields hold strings — no type ambiguity.
{
name: "disjunctions/valid_a",
schema: "testdata/disjunctions/schema.cue",
data: "testdata/disjunctions/valid_a.jsonnet",
check: decode(DisjunctionsDecode{Value: "text", Mode: "read", Priority: 1, Nullable: "present"}),
},
// valid_b: Value is an integer and Nullable is null.
// CUE decodes integers into any as int64; null becomes nil.
{
name: "disjunctions/valid_b",
schema: "testdata/disjunctions/schema.cue",
data: "testdata/disjunctions/valid_b.jsonnet",
check: func(t *testing.T, sc cuesonnet.Schema, data string) {
t.Helper()
var got DisjunctionsDecode
if err := sc.Decode(strings.NewReader(data), &got); err != nil {
t.Fatalf("decode error: %v", err)
}
if got.Mode != "write" {
t.Errorf("Mode: got %q, want %q", got.Mode, "write")
}
if got.Priority != 3 {
t.Errorf("Priority: got %d, want 3", got.Priority)
}
if got.Nullable != nil {
t.Errorf("Nullable: got %v, want nil", got.Nullable)
}
switch v := got.Value.(type) {
case int64:
if v != 42 {
t.Errorf("Value: got %d, want 42", v)
}
case float64:
if v != 42 {
t.Errorf("Value: got %g, want 42", v)
}
default:
t.Errorf("Value: unexpected type %T (value %v)", got.Value, got.Value)
}
},
},
// defaults
// minimal: only name provided; CUE fills role="user", enabled=true, timeout=30, tags=[].
{
name: "defaults/minimal",
schema: "testdata/defaults/schema.cue",
data: "testdata/defaults/valid_minimal.jsonnet",
check: decode(DefaultsDecode{Name: "Alice", Role: "user", Enabled: true, Timeout: 30, Tags: []string{}}),
},
{
name: "defaults/override",
schema: "testdata/defaults/schema.cue",
data: "testdata/defaults/valid_override.jsonnet",
check: decode(DefaultsDecode{Name: "Alice", Role: "admin", Enabled: false, Timeout: 60, Tags: []string{"api", "v2"}}),
},
// enums
{
name: "enums/valid",
schema: "testdata/enums/schema.cue",
data: "testdata/enums/valid.jsonnet",
check: decode(EnumsDecode{Color: "red", Status: "active", Priority: 3, Flags: []string{"a", "b"}}),
},
// definitions
{
name: "definitions/valid",
schema: "testdata/definitions/schema.cue",
data: "testdata/definitions/valid.jsonnet",
check: decode([]DefPersonDecode{
{Name: DefNameDecode{First: "Alice", Last: "Smith"}, Age: 30, Contact: DefContactDecode{Email: "alice@example.com"}},
{Name: DefNameDecode{First: "Bob", Last: "Jones"}, Age: 25, Contact: DefContactDecode{Phone: "555-123-4567"}},
{Name: DefNameDecode{First: "Carol", Last: "White"}, Age: 42, Contact: DefContactDecode{Email: "carol@example.com", Phone: "123-456-7890"}},
}),
},
// stdlib
{
name: "stdlib/valid",
schema: "testdata/stdlib/schema.cue",
data: "testdata/stdlib/valid.jsonnet",
check: decode(StdlibDecode{
CreatedAt: "2024-01-15T10:30:00Z",
Birthday: "01/15/1990",
Username: "alice42",
Tags: []string{"go", "cue", "jsonnet"},
Initials: "AB",
Angle: 3.14,
}),
},
// composition
{
name: "composition/valid",
schema: "testdata/composition/schema.cue",
data: "testdata/composition/valid.jsonnet",
check: decode([]CompositionDecode{
{FirstName: "Alice", LastName: "Smith", CreatedAt: "2024-01-15T10:00:00Z", UpdatedAt: "2024-06-01T12:00:00Z", Age: 30},
{FirstName: "Bob", LastName: "Jones", CreatedAt: "2023-05-20T08:30:00Z", UpdatedAt: "2023-05-20T08:30:00Z", Age: 25},
}),
},
// patterns
{
name: "patterns/valid",
schema: "testdata/patterns/schema.cue",
data: "testdata/patterns/valid.jsonnet",
check: decode(PatternsDecode{
Name: "service-a",
Labels: map[string]string{
"env": "production",
"region": "us-east-1",
"team": "platform",
},
Counts: map[string]int{
"requests": 1000,
"errors": 5,
"warnings": 42,
},
}),
},
// tuples
// Color and Position are uniformly typed; Tag is [string, int] so []any.
// The int element decodes as int64 or float64 depending on CUE version.
{
name: "tuples/valid",
schema: "testdata/tuples/schema.cue",
data: "testdata/tuples/valid.jsonnet",
check: func(t *testing.T, sc cuesonnet.Schema, data string) {
t.Helper()
var got TuplesDecode
if err := sc.Decode(strings.NewReader(data), &got); err != nil {
t.Fatalf("decode error: %v", err)
}
if !reflect.DeepEqual(got.Color, []int{255, 128, 0}) {
t.Errorf("Color: got %v, want [255 128 0]", got.Color)
}
if !reflect.DeepEqual(got.Position, []float64{1.5, 2.7}) {
t.Errorf("Position: got %v, want [1.5 2.7]", got.Position)
}
if len(got.Tag) != 2 {
t.Fatalf("Tag: got len %d, want 2", len(got.Tag))
}
if got.Tag[0] != "priority" {
t.Errorf("Tag[0]: got %v, want %q", got.Tag[0], "priority")
}
switch v := got.Tag[1].(type) {
case int64:
if v != 1 {
t.Errorf("Tag[1]: got %d, want 1", v)
}
case float64:
if v != 1 {
t.Errorf("Tag[1]: got %g, want 1", v)
}
default:
t.Errorf("Tag[1]: unexpected type %T (value %v)", got.Tag[1], got.Tag[1])
}
},
},
// jsonnet/functions
{
name: "jsonnet/functions",
schema: "testdata/jsonnet/functions/schema.cue",
data: "testdata/jsonnet/functions/data.jsonnet",
check: decode([]FunctionUserDecode{
{Name: "Alice", Greeting: "Hello, Alice!", Age: 30},
{Name: "Bob", Greeting: "Hello, Bob!", Age: 25},
{Name: "Carol", Greeting: "Hello, Carol!", Age: 35},
}),
},
// jsonnet/comprehensions
{
name: "jsonnet/comprehensions",
schema: "testdata/jsonnet/comprehensions/schema.cue",
data: "testdata/jsonnet/comprehensions/data.jsonnet",
check: decode([]ComprehensionItemDecode{
{Index: 0, Squared: 1, Label: "item-1"},
{Index: 1, Squared: 4, Label: "item-2"},
{Index: 2, Squared: 9, Label: "item-3"},
{Index: 3, Squared: 16, Label: "item-4"},
{Index: 4, Squared: 25, Label: "item-5"},
}),
},
// jsonnet/conditionals
{
name: "jsonnet/conditionals",
schema: "testdata/jsonnet/conditionals/schema.cue",
data: "testdata/jsonnet/conditionals/data.jsonnet",
check: decode([]ConditionalEntryDecode{
{Value: 3, Category: "small", Doubled: 6},
{Value: 42, Category: "medium", Doubled: 84},
{Value: 150, Category: "large", Doubled: 300},
}),
},
// jsonnet/inheritance
{
name: "jsonnet/inheritance",
schema: "testdata/jsonnet/inheritance/schema.cue",
data: "testdata/jsonnet/inheritance/data.jsonnet",
check: decode(InheritanceDecode{Kind: "Deployment", Version: "v1", Name: "my-app", Replicas: 3, Image: "myapp:latest"}),
},
// jsonnet/multiline
{
name: "jsonnet/multiline",
schema: "testdata/jsonnet/multiline/schema.cue",
data: "testdata/jsonnet/multiline/data.jsonnet",
check: decode(MultilineDecode{
Description: "This is a multi-line\nstring in Jsonnet.\nIt supports indentation.\n",
Template: "Name: my-app\nVersion: v1.0\n",
}),
},
// jsonnet/self_reference
{
name: "jsonnet/self_reference",
schema: "testdata/jsonnet/self_reference/schema.cue",
data: "testdata/jsonnet/self_reference/data.jsonnet",
check: decode(SelfRefDecode{Width: 10, Height: 20, Area: 200, Perimeter: 60}),
},
// jsonnet/object_comprehension
// Schema is [string]: int; decode directly into map[string]int.
{
name: "jsonnet/object_comprehension",
schema: "testdata/jsonnet/object_comprehension/schema.cue",
data: "testdata/jsonnet/object_comprehension/data.jsonnet",
check: decode(map[string]int{"alice_score": 95, "bob_score": 87, "carol_score": 92}),
},
// jsonnet/stdlib
{
name: "jsonnet/stdlib",
schema: "testdata/jsonnet/stdlib/schema.cue",
data: "testdata/jsonnet/stdlib/data.jsonnet",
check: decode(JStdlibDecode{
Upper: "HELLO",
Joined: "hello, world, jsonnet",
Formatted: "count=3, first=hello",
Count: 3,
Words: []string{"hello", "world", "jsonnet"},
Mapped: []string{"HELLO", "WORLD", "JSONNET"},
Filtered: []string{"jsonnet"},
}),
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
tc.check(t, cuesonnet.Schema(mustReadFile(t, tc.schema)), mustReadFile(t, tc.data))
})
}
}
|