-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdyfields_test.go
More file actions
493 lines (442 loc) · 15.9 KB
/
Copy pathdyfields_test.go
File metadata and controls
493 lines (442 loc) · 15.9 KB
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
package dyfields_test
import (
"encoding/json"
"strings"
"testing"
df "github.com/BrobridgeOrg/dyfields"
)
func mustCompile(t *testing.T, b *df.Builder) *df.Compiled {
t.Helper()
c, err := b.Compile()
if err != nil {
t.Fatalf("compile: %v", err)
}
return c
}
func compileErrors(t *testing.T, b *df.Builder) df.SchemaErrors {
t.Helper()
_, err := b.Compile()
if err == nil {
t.Fatal("expected the schema to be rejected")
}
errs, ok := err.(df.SchemaErrors)
if !ok {
t.Fatalf("expected SchemaErrors, got %T", err)
}
return errs
}
func hasCode(errs df.SchemaErrors, code string) bool {
for _, e := range errs {
if e.Code == code {
return true
}
}
return false
}
func TestBuilderComposesAndRemovesFields(t *testing.T) {
b := df.NewBuilder()
b.AddField(df.String("cluster").Label("Cluster").Required())
b.AddField(df.List("recipients").Items(df.ItemString().Format("email")))
brokers := df.ObjectList("brokers").MinItems(1).Unique("host").ItemLabel("{host}:{port}")
brokers.AddField(df.String("host").Format("hostname").Required())
brokers.AddField(df.Int("port").Range(1, 65535).Default(9092))
b.AddField(brokers)
if !b.RemoveField("recipients") {
t.Error("RemoveField should report that it removed something")
}
if b.RemoveField("recipients") {
t.Error("removing twice should report nothing to remove")
}
port, ok := b.FieldAt("brokers.port")
if !ok {
t.Fatal("FieldAt should reach a nested field")
}
port.Label = "Port"
s, err := b.Build()
if err != nil {
t.Fatalf("build: %v", err)
}
if len(s.Groups) != 1 || s.Groups[0].Key != df.DefaultGroup {
t.Fatalf("expected one default group, got %+v", s.Groups)
}
if s.Groups[0].Fields[1].Fields[1].Label != "Port" {
t.Error("editing through FieldAt did not reach the schema")
}
}
func TestBuilderMoveFieldBetweenGroups(t *testing.T) {
b := df.NewBuilder()
b.AddField(df.String("a"))
b.AddField(df.String("b"))
b.Group("extra").Label("Extra")
if !b.MoveField("a", "extra", 0) {
t.Fatal("MoveField should find the field")
}
s := b.Schema()
if len(s.Groups[0].Fields) != 1 || s.Groups[0].Fields[0].Name != "b" {
t.Error("the field was not removed from its old group")
}
if len(s.Groups[1].Fields) != 1 || s.Groups[1].Fields[0].Name != "a" {
t.Error("the field did not arrive in the new group")
}
}
func TestFromSchemaRoundTripsThroughTheBuilder(t *testing.T) {
b := df.NewBuilder()
b.AddField(df.String("name").Required())
original, err := b.Build()
if err != nil {
t.Fatalf("build: %v", err)
}
again := df.FromSchema(original)
again.AddField(df.Bool("subscribed").Default(false))
s, err := again.Build()
if err != nil {
t.Fatalf("rebuild: %v", err)
}
if len(s.Groups[0].Fields) != 2 {
t.Fatalf("expected the loaded schema to keep its field, got %d", len(s.Groups[0].Fields))
}
}
func TestParseRejectsUnknownKeys(t *testing.T) {
// A misspelled rule must not be silently dropped: a validation that
// quietly does not exist is worse than a parse error.
_, err := df.Parse([]byte(`{"groups":[{"key":"g","fields":[
{"name":"a","type":"string","requried":true}]}]}`))
if err == nil {
t.Fatal("expected the typo to be rejected")
}
if !strings.Contains(err.Error(), "requried") {
t.Errorf("the error should name the offending key, got: %v", err)
}
}
func TestParseRejectsUnknownConditionKeys(t *testing.T) {
_, err := df.Parse([]byte(`{"groups":[{"key":"g","fields":[
{"name":"a","type":"string","visible_when":{"field":"b","eq":"x"}}]}]}`))
if err == nil || !strings.Contains(err.Error(), "eq") {
t.Fatalf("expected an unknown condition key to be rejected, got: %v", err)
}
}
func TestValidateSchemaReportsProblems(t *testing.T) {
errs := df.ValidateSchema([]byte(`{"groups":[{"key":"g","fields":[
{"name":"a","type":"string","visible_when":{"field":"nope","is_true":true}}]}]}`))
if !hasCode(errs, df.CodeUnknownRef) {
t.Fatalf("expected unknown_ref, got: %v", errs)
}
}
func TestCompileRejectsDuplicateNamesAcrossGroups(t *testing.T) {
b := df.NewBuilder()
b.Group("one").AddField(df.String("name"))
b.Group("two").AddField(df.String("name"))
// A group is a UI section, not a scope, so two groups cannot each own a
// field called "name" — the value document has nowhere to put both.
if !hasCode(compileErrors(t, b), df.CodeDuplicateName) {
t.Error("expected duplicate_name")
}
}
func TestCompileRejectsVisibilityCycle(t *testing.T) {
b := df.NewBuilder()
b.AddField(df.Bool("a").VisibleWhen(df.IsTrue("b")))
b.AddField(df.Bool("b").VisibleWhen(df.IsTrue("a")))
if !hasCode(compileErrors(t, b), df.CodeCycle) {
t.Error("expected cycle")
}
}
func TestCompileRejectsOuterReferenceIntoAnEntry(t *testing.T) {
b := df.NewBuilder()
items := df.ObjectList("rows").AddField(df.String("host"))
b.AddField(items)
// "Which entry's host?" has no answer, so the reference simply does not
// resolve.
b.AddField(df.String("summary").VisibleWhen(df.IsNotEmpty("host")))
if !hasCode(compileErrors(t, b), df.CodeUnknownRef) {
t.Error("expected unknown_ref for an inward reference")
}
}
func TestCompileRejectsRequiredOnContainers(t *testing.T) {
b := df.NewBuilder()
b.AddField(df.List("tags").Items(df.ItemString()).Required())
if !hasCode(compileErrors(t, b), df.CodeContainerReq) {
t.Error("expected container_required")
}
}
func TestCompileRejectsIncomparableOrdering(t *testing.T) {
b := df.NewBuilder()
b.AddField(df.Bool("flag"))
b.AddField(df.Int("n").Check(df.GtField("n", "flag"), "range", "must be greater"))
if !hasCode(compileErrors(t, b), df.CodeNotComparable) {
t.Error("expected not_comparable")
}
}
func TestCompileRejectsDepthBeyondTheLimit(t *testing.T) {
leaf := df.ObjectList("l0").AddField(df.String("v"))
for i := 1; i < df.MaxDepth+2; i++ {
leaf = df.ObjectList("l" + string(rune('0'+i))).AddField(leaf)
}
b := df.NewBuilder()
b.AddField(leaf)
if !hasCode(compileErrors(t, b), df.CodeDepthExceeded) {
t.Error("expected depth_exceeded")
}
}
func TestCompileRejectsARedeclaredToggleField(t *testing.T) {
b := df.NewBuilder()
b.Group("tls").Toggleable("enable_tls", "Enable TLS", false).
AddField(df.String("ca_cert"))
// The switch is declared by the toggle and nowhere else; declaring it
// again would make the UI draw it twice.
b.AddField(df.Bool("enable_tls"))
if !hasCode(compileErrors(t, b), df.CodeDuplicateName) {
t.Error("expected duplicate_name for the redeclared toggle")
}
}
func TestToggleOffClearsTheGroupButKeepsTheSwitch(t *testing.T) {
b := df.NewBuilder()
b.AddField(df.String("host").Required())
g := b.Group("proxy").Toggleable("use_proxy", "Use proxy", false)
g.AddField(df.String("proxy_url").Format("uri").Required())
g.AddField(df.Secret("proxy_password"))
c := mustCompile(t, b)
doc := df.ValueDocument{
Values: map[string]any{"host": "a.example.com", "use_proxy": false, "proxy_url": "http://old"},
Secrets: map[string]string{"proxy_password": "leftover"},
}
out, errs := c.Validate(doc)
if errs.Len() != 0 {
t.Fatalf("a switched-off group must not be validated, got: %v", errs)
}
if _, ok := out.Values["proxy_url"]; ok {
t.Error("closing the group should clear its values")
}
if _, ok := out.Secrets["proxy_password"]; ok {
t.Error("closing the group should clear its secrets")
}
if out.Values["use_proxy"] != false {
t.Error("the switch itself must survive, it is what the next open reads")
}
}
func TestDefaultsApplyOnlyToVisibleFields(t *testing.T) {
b := df.NewBuilder()
b.AddField(df.Bool("advanced").Default(false))
b.AddField(df.Int("retries").Default(3).VisibleWhen(df.IsTrue("advanced")))
c := mustCompile(t, b)
out, errs := c.Validate(df.ValueDocument{Values: map[string]any{}})
if errs.Len() != 0 {
t.Fatalf("unexpected errors: %v", errs)
}
if _, ok := out.Values["retries"]; ok {
t.Error("a hidden field must not receive its default")
}
out, _ = c.Validate(df.ValueDocument{Values: map[string]any{"advanced": true}})
if out.Values["retries"] != 3 {
t.Errorf("a visible field should receive its default, got %v", out.Values["retries"])
}
}
func TestTransientValueIsDroppedOnlyOnSuccess(t *testing.T) {
b := df.NewBuilder()
b.AddField(df.Secret("password").Required().MinLength(8))
b.AddField(df.Secret("password_confirm").Transient().Required().
Check(df.EqualsField("password_confirm", "password"), "mismatch", "the two passwords differ"))
c := mustCompile(t, b)
ok := df.ValueDocument{Secrets: map[string]string{
"password": "correct-horse", "password_confirm": "correct-horse"}}
out, errs := c.Validate(ok)
if errs.Len() != 0 {
t.Fatalf("unexpected errors: %v", errs)
}
if _, still := out.Secrets["password_confirm"]; still {
t.Error("a transient value must not survive a successful validation")
}
bad := df.ValueDocument{Secrets: map[string]string{
"password": "correct-horse", "password_confirm": "typo-horse"}}
out, errs = c.Validate(bad)
if !errs.Has("mismatch") {
t.Fatalf("expected the mismatch to be reported, got: %v", errs)
}
if _, still := out.Secrets["password_confirm"]; !still {
t.Error("on failure the value stays, so the caller can hand it back to the form")
}
}
func TestSecretsNeverTravelInValues(t *testing.T) {
b := df.NewBuilder()
b.AddField(df.Secret("token").Required())
c := mustCompile(t, b)
_, errs := c.Validate(df.ValueDocument{Values: map[string]any{"token": "in-the-wrong-place"}})
if errs.Len() == 0 {
t.Fatal("a secret sent in values should be rejected")
}
}
func TestUnknownKeysAreRejectedButJSONIsOpaque(t *testing.T) {
b := df.NewBuilder()
b.AddField(df.JSON("extra"))
c := mustCompile(t, b)
out, errs := c.Validate(df.ValueDocument{Values: map[string]any{
"extra": map[string]any{"anything": []any{1.0, "two"}},
}})
if errs.Len() != 0 {
t.Fatalf("json is an escape hatch; its contents are not inspected: %v", errs)
}
if _, ok := out.Values["extra"]; !ok {
t.Error("the json value was dropped")
}
_, errs = c.Validate(df.ValueDocument{Values: map[string]any{"typo": 1}})
if !errs.Has(df.ErrUnknownField) {
t.Fatalf("expected unknown_field, got: %v", errs)
}
}
func TestMapKeyPatternIsChecked(t *testing.T) {
b := df.NewBuilder()
b.AddField(df.Map("labels").KeyPattern(`^[a-z][a-z0-9_]{0,30}$`).Items(df.ItemString().Length(1, 64)))
c := mustCompile(t, b)
_, errs := c.Validate(df.ValueDocument{Values: map[string]any{
"labels": map[string]any{"env": "prod", "Bad Key": "x"},
}})
if !errs.Has(df.ErrKeyPattern) {
t.Fatalf("expected key_pattern, got: %v", errs)
}
for _, e := range errs {
if e.Code == df.ErrKeyPattern && e.Key != "Bad Key" {
t.Errorf("the error should name the offending key, got %q", e.Key)
}
}
}
func TestApplyKeepsWhatThePatchDoesNotMention(t *testing.T) {
b := df.NewBuilder()
rows := df.ObjectList("rows").MinItems(1)
rows.AddField(df.String("label").Required())
rows.AddField(df.Secret("token"))
b.AddField(rows)
c := mustCompile(t, b)
current := df.ValueDocument{
Values: map[string]any{"rows": []any{
map[string]any{"$id": "r1", "label": "one"},
map[string]any{"$id": "r2", "label": "two"},
}},
Secrets: map[string]string{"rows.r2.token": "keep-me"},
}
// The front end sends only the row it touched. Under "absent means
// delete" this would wipe r2 and its secret.
patch := df.Patch{Values: map[string]any{
"rows": []any{map[string]any{"$id": "r1", "label": "ONE"}},
}}
out, errs := c.Apply(current, patch)
if errs.Len() != 0 {
t.Fatalf("unexpected errors: %v", errs)
}
rowsOut := out.Values["rows"].([]any)
if len(rowsOut) != 2 {
t.Fatalf("an unmentioned entry must be retained, got %d entries", len(rowsOut))
}
if rowsOut[0].(map[string]any)["label"] != "ONE" {
t.Error("the patched entry was not updated")
}
if out.Secrets["rows.r2.token"] != "keep-me" {
t.Error("an unmentioned entry lost its secret")
}
}
func TestApplyClearsASecretOnlyWithNull(t *testing.T) {
b := df.NewBuilder()
b.AddField(df.Secret("token"))
c := mustCompile(t, b)
current := df.ValueDocument{Secrets: map[string]string{"token": "old"}}
empty := ""
out, _ := c.Apply(current, df.Patch{Secrets: map[string]*string{"token": &empty}})
if out.Secrets["token"] != "old" {
t.Error("an empty string means the user did not touch the field")
}
out, _ = c.Apply(current, df.Patch{Secrets: map[string]*string{"token": nil}})
if _, ok := out.Secrets["token"]; ok {
t.Error("null should clear the secret")
}
}
func TestPatchParsesNullAsClear(t *testing.T) {
p, err := df.ParsePatch([]byte(`{"values":{"a":1},"secrets":{"x":null,"y":""}}`))
if err != nil {
t.Fatalf("parse patch: %v", err)
}
if p.Secrets["x"] != nil {
t.Error("null should survive parsing as a distinct value")
}
if p.Secrets["y"] == nil || *p.Secrets["y"] != "" {
t.Error("an empty string should stay an empty string")
}
}
func TestConditionRoundTripsThroughJSON(t *testing.T) {
c := df.AllOf(
df.Equals("mode", "advanced"),
df.Not(df.IsEmpty("host")),
df.AnyOf(df.In("region", "eu", "us"), df.GteField("max", "min")),
)
b, err := json.Marshal(c)
if err != nil {
t.Fatalf("marshal: %v", err)
}
var back df.Condition
if err := json.Unmarshal(b, &back); err != nil {
t.Fatalf("unmarshal: %v", err)
}
b2, err := json.Marshal(&back)
if err != nil {
t.Fatalf("re-marshal: %v", err)
}
if string(b) != string(b2) {
t.Errorf("condition changed across a round trip:\n%s\n%s", b, b2)
}
}
func TestFormatsAreValidatedNotJustHinted(t *testing.T) {
b := df.NewBuilder()
b.AddField(df.String("email").Format("email"))
b.AddField(df.String("site").Format("uri"))
b.AddField(df.String("box").Format("something-only-the-ui-knows"))
c := mustCompile(t, b)
_, errs := c.Validate(df.ValueDocument{Values: map[string]any{
"email": "not-an-email", "site": "https://ok.example.com", "box": "anything",
}})
if !errs.Has(df.ErrFormat) {
t.Fatalf("a known format must be enforced, got: %v", errs)
}
if errs.Len() != 1 {
t.Errorf("an unknown format is a renderer hint, not an error: %v", errs)
}
}
// A transient value never reaches the stored document, so a condition that
// decides the document's shape cannot read one: the form and the server would
// answer it differently, and the server's answer is the one that gets
// persisted. valid_when is the exception -- it only reports a problem, and
// Apply already knows to stay quiet about it.
func TestCompileRejectsAStructuralConditionOnATransientField(t *testing.T) {
for _, tc := range []struct{ name, slot string }{
{"visible_when", `"visible_when":{"field":"confirm","is_empty":false}`},
{"required_when", `"required_when":{"field":"confirm","is_empty":true}`},
{"readonly_when", `"readonly_when":{"field":"confirm","is_empty":false}`},
} {
t.Run(tc.name, func(t *testing.T) {
errs := df.ValidateSchema([]byte(`{"schema_version":1,"groups":[{"key":"g","label":"G","fields":[
{"name":"confirm","type":"string","label":"C","transient":true},
{"name":"note","type":"string","label":"N",` + tc.slot + `}]}]}`))
if !hasCode(errs, df.CodeTransientRef) {
t.Fatalf("expected transient_ref, got: %v", errs)
}
})
}
}
func TestCompileRejectsAGroupShownByATransientField(t *testing.T) {
errs := df.ValidateSchema([]byte(`{"schema_version":1,"groups":[
{"key":"a","label":"A","fields":[{"name":"confirm","type":"string","label":"C","transient":true}]},
{"key":"b","label":"B","visible_when":{"field":"confirm","is_empty":false},
"fields":[{"name":"note","type":"string","label":"N"}]}]}`))
if !hasCode(errs, df.CodeTransientRef) {
t.Fatalf("expected transient_ref, got: %v", errs)
}
}
// The rule is about what a condition reads, not about where it is written: a
// transient field may still be required, and may still carry a valid_when.
func TestCompileAllowsATransientFieldItsOwnRules(t *testing.T) {
errs := df.ValidateSchema([]byte(`{"schema_version":1,"groups":[{"key":"g","label":"G","fields":[
{"name":"password","type":"string","label":"P"},
{"name":"confirm","type":"string","label":"C","transient":true,
"required_when":{"not":{"field":"password","is_empty":true}},
"valid_when":[{"when":{"field":"confirm","equals_field":"password"},
"code":"password_mismatch","reason":"They must match"}]}]}]}`))
if len(errs) > 0 {
t.Fatalf("expected no complaint, got: %v", errs)
}
}