gunk-dev/the-valley

project_test.go

source060db0650c2bmain's published tip history
21.5 KiB
1package export_test
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "reflect"
11 "runtime"
12 "slices"
13 "strings"
14 "testing"
15 "time"
16
17 "the-valley/web/export"
18 "the-valley/web/export/exporttest"
19)
20
21// Nothing the anonymous reader may not see reaches export.json: not the
22// hidden project's knots or changes, not the plan's operator sections,
23// not drafts, branches, older versions, repository URLs or request refs,
24// not a knot's storage path, and not one principal's own name.
25func TestBuildLeavesOutWhatIsNotTheReaders(t *testing.T) {
26 f := exporttest.New(t)
27 for _, leak := range []string{
28 `"path"`, "outcomes/", "waiting_on_you", `"operator":`, "changes_error",
29 "The site deploys the app", "The site serves the docs", "Hidden.", "site-operator",
30 "lmnoplmnop", "deploy: a hidden change",
31 "zyxwvutsrq", "wip: a draft", "app-agent-draft", "scratch",
32 "plan: list milestones", "4c4c4c4c", "app-agent-session",
33 "git@", "valley-host", "integration-requests", `"record"`, `"seq"`, `"restack"`,
34 "app-operator", "app-agent", "drive-by",
35 } {
36 if bytes.Contains(f.ExportJSON, []byte(leak)) {
37 t.Errorf("export.json holds %q", leak)
38 }
39 }
40 if len(f.Export.Projects) != 1 || f.Export.Projects[0].Name != "app" {
41 t.Fatalf("exported %v, want app alone", f.Export.Projects)
42 }
43}
44
45func knotOf(t *testing.T, e *export.Export, id string) export.Knot {
46 t.Helper()
47 for _, k := range e.Projects[0].Knots {
48 if k.ID == id {
49 return k
50 }
51 }
52 t.Fatalf("the export holds no knot %s", id)
53 return export.Knot{}
54}
55
56// A reference to the hidden project's knot keeps only the reference. It
57// still holds its knot up: a knot it blocks stays blocked, and is never
58// shown as free to start. A knot that waits on it says so with
59// waiting_on_hidden alone, and no other knot carries the field.
60func TestBuildHidesForeignEdges(t *testing.T) {
61 f := exporttest.New(t)
62 k := knotOf(t, f.Export, "oc-a000003")
63 if len(k.Edges) != 1 {
64 t.Fatalf("edges %v", k.Edges)
65 }
66 e := k.Edges[0]
67 if e.State != export.EdgeHidden || e.Status != nil || e.Title != nil || e.Why != nil || e.Ref != "site:oc-b000001" {
68 t.Errorf("the hidden edge is %+v", e)
69 }
70 if slices.Contains(k.WaitingOn, "site:oc-b000001") || !slices.Contains(k.WaitingOn, "oc-a000002") {
71 t.Errorf("waiting_on is %v; it keeps the local blocker and drops the hidden one", k.WaitingOn)
72 }
73 if !k.WaitingOnHidden {
74 t.Error("waiting_on_hidden is not set on the knot that waits on a hidden knot")
75 }
76 for _, other := range f.Export.Projects[0].Knots {
77 if other.ID != k.ID && other.WaitingOnHidden {
78 t.Errorf("%s carries waiting_on_hidden, and waits on no hidden knot", other.ID)
79 }
80 }
81 if n := strings.Count(string(f.ExportJSON), `"waiting_on_hidden"`); n != 1 {
82 t.Errorf("export.json holds waiting_on_hidden %d times, not once", n)
83 }
84 if k.State != "blocked" || k.Ready {
85 t.Errorf("the knot is %s, ready %v; it stays blocked", k.State, k.Ready)
86 }
87 if !slices.Equal(k.BlockedBy, []string{"oc-a000002", "site:oc-b000001"}) {
88 t.Errorf("blocked_by is %v; it is the knot's own field, as written", k.BlockedBy)
89 }
90 if target := knotOf(t, f.Export, "bd-a000004").Edges; len(target) != 1 || target[0].State != export.EdgeHidden || target[0].Field != "target" {
91 t.Errorf("the target edge is %+v", target)
92 }
93}
94
95// The export keeps each hidden reference's ID, in blocked_by and edges,
96// and waiting_on_hidden says whether the knot still waits on a hidden
97// knot. So for a knot that names one hidden blocker, as oc-a000003 names
98// site:oc-b000001, the field says whether that hidden knot still blocks.
99// The export permits this inference: the field is set while
100// site:oc-b000001 is open, and gone once it is done, though oc-a000003
101// stays blocked by its published blocker and still names site:oc-b000001.
102func TestWaitingOnHiddenFollowsAHiddenBlocker(t *testing.T) {
103 f := exporttest.New(t)
104 if !knotOf(t, f.Export, "oc-a000003").WaitingOnHidden {
105 t.Fatal("waiting_on_hidden is not set while the hidden blocker is open")
106 }
107
108 in := f.Inputs
109 var plan map[string]any
110 if err := json.Unmarshal(in.Plan, &plan); err != nil {
111 t.Fatal(err)
112 }
113 knot := func(project, id string) map[string]any {
114 for _, p := range plan["projects"].([]any) {
115 p := p.(map[string]any)
116 for _, k := range p["knots"].([]any) {
117 if k := k.(map[string]any); p["project"] == project && k["id"] == id {
118 return k
119 }
120 }
121 }
122 t.Fatalf("the plan holds no knot %s:%s", project, id)
123 return nil
124 }
125 hidden := knot("site", "oc-b000001")
126 hidden["status"], hidden["active"], hidden["state"], hidden["ready"] = "done", false, "done", false
127 k := knot("app", "oc-a000003")
128 k["waiting_on"] = []string{"oc-a000002"}
129 k["edges"].([]any)[0].(map[string]any)["status"] = "done"
130 var err error
131 if in.Plan, err = json.Marshal(plan); err != nil {
132 t.Fatal(err)
133 }
134 e, err := export.Build(in)
135 if err != nil {
136 t.Fatal(err)
137 }
138 x := knotOf(t, e, "oc-a000003")
139 if x.WaitingOnHidden {
140 t.Error("waiting_on_hidden is still set once the hidden blocker is done")
141 }
142 if x.State != "blocked" || !slices.Equal(x.WaitingOn, []string{"oc-a000002"}) {
143 t.Errorf("the knot is %s, waiting on %v; its published blocker still holds it", x.State, x.WaitingOn)
144 }
145 if !slices.Contains(x.BlockedBy, "site:oc-b000001") || len(x.Edges) != 1 || x.Edges[0].Ref != "site:oc-b000001" {
146 t.Errorf("blocked_by is %v and edges %+v; both still name the hidden blocker", x.BlockedBy, x.Edges)
147 }
148}
149
150// A reference to another exported project's knot keeps what the plan
151// says of it.
152func TestBuildKeepsEdgesBetweenExportedProjects(t *testing.T) {
153 f := exporttest.New(t)
154 in := f.Inputs
155 in.Visibility = map[string]export.Visibility{"app": export.Public, "site": export.Public}
156 in.SourceTips = map[string]string{"app": in.SourceTips["app"], "site": strings.Repeat("e", 40)}
157 in.Details = append(in.Details,
158 detail("site", "8c2e4a6b0d1f3e5a7c9b1d3f5e7a9c0b2d4f6e81", "oc-b000001"),
159 detail("site", "8c2e4a6b0d1f3e5a7c9b1d3f5e7a9c0b2d4f6e81", "oc-b000002"))
160 e, err := export.Build(in)
161 if err != nil {
162 t.Fatal(err)
163 }
164 edge := knotOf(t, e, "oc-a000003").Edges[0]
165 if edge.State != export.EdgeResolved || edge.Title == nil || *edge.Title != "The site deploys the app" {
166 t.Errorf("the edge is %+v", edge)
167 }
168 if !slices.Contains(knotOf(t, e, "oc-a000003").WaitingOn, "site:oc-b000001") {
169 t.Error("waiting_on dropped an exported project's blocker")
170 }
171 if knotOf(t, e, "oc-a000003").WaitingOnHidden {
172 t.Error("waiting_on_hidden is set for a blocker in an exported project")
173 }
174}
175
176func detail(project, tip, id string) []byte {
177 b, _ := json.Marshal(map[string]any{"schema": "valley-knot/v1", "project": project, "tip": tip,
178 "knot": map[string]any{"id": id, "body": "", "comments": []any{}}})
179 return b
180}
181
182// In flight is the plan's claimed knots, oldest claim first, and then the
183// knots explicitly in progress that nobody claims.
184func TestBuildInFlight(t *testing.T) {
185 f := exporttest.New(t)
186 if got := f.Export.Projects[0].InFlight; !slices.Equal(got, []string{"oc-a000002", "oc-a000006"}) {
187 t.Errorf("in_flight is %v", got)
188 }
189}
190
191// Principal names pass through the display mapping, and a name it does
192// not map shows as the generic role. An edited comment's editor is a
193// principal too, and a comment never edited names no editor.
194func TestBuildMapsPrincipals(t *testing.T) {
195 f := exporttest.New(t)
196 claimed := knotOf(t, f.Export, "oc-a000002")
197 if claimed.CreatedBy != "operator" || claimed.Claim.By != "agent" || claimed.Comments[1].Author != "agent" {
198 t.Errorf("the claimed knot shows %q, %q, %q", claimed.CreatedBy, claimed.Claim.By, claimed.Comments[1].Author)
199 }
200 if c := claimed.Comments[1]; c.Edited != "2026-10-25T10:30:00Z" || c.EditedBy != "agent" {
201 t.Errorf("the edited comment shows edited %q by %q", c.Edited, c.EditedBy)
202 }
203 if c := claimed.Comments[0]; c.Edited != "" || c.EditedBy != "" {
204 t.Errorf("a comment never edited shows edited %q by %q", c.Edited, c.EditedBy)
205 }
206 bug := knotOf(t, f.Export, "bd-a000004")
207 if bug.CreatedBy != export.Unmapped || bug.Comments[0].Author != export.Unmapped {
208 t.Errorf("an unmapped principal shows as %q and %q", bug.CreatedBy, bug.Comments[0].Author)
209 }
210 c := f.Export.Projects[0].Changes[0]
211 if c.Owner != "agent" || c.Version.Uploader != "agent" {
212 t.Errorf("the change shows %q and %q", c.Owner, c.Version.Uploader)
213 }
214}
215
216// A change keeps its active version alone, with its request and outcome,
217// and includes only changes the export carries.
218func TestBuildKeepsTheActiveVersion(t *testing.T) {
219 f := exporttest.New(t)
220 changes := f.Export.Projects[0].Changes
221 if len(changes) != 1 {
222 t.Fatalf("changes %v", changes)
223 }
224 v := changes[0].Version
225 if v.N != 2 || v.Request == nil || v.Outcome == nil || v.Outcome.Decision != "stale" {
226 t.Errorf("the version is %+v", v)
227 }
228 if len(changes[0].Includes) != 0 {
229 t.Errorf("includes %v names a draft", changes[0].Includes)
230 }
231}
232
233// A field the valley adds is not exported until the projection names it.
234func TestBuildReadsNamedFieldsAlone(t *testing.T) {
235 f := exporttest.New(t)
236 in := f.Inputs
237 in.Plan = bytes.Replace(in.Plan, []byte(`"id": "oc-a000001",`), []byte(`"id": "oc-a000001", "secret_field": "do not export",`), 1)
238 e, err := export.Build(in)
239 if err != nil {
240 t.Fatal(err)
241 }
242 data, err := e.Encode()
243 if err != nil {
244 t.Fatal(err)
245 }
246 if bytes.Contains(data, []byte("do not export")) {
247 t.Error("an unnamed field reached the export")
248 }
249}
250
251// What the projection refuses, so that a partial or inconsistent export
252// is never published.
253func TestBuildRefuses(t *testing.T) {
254 f := exporttest.New(t)
255 cases := []struct {
256 name string
257 change func(in *export.Inputs)
258 want string
259 }{
260 {"a detail read at another graph tip", func(in *export.Inputs) {
261 in.Details[0] = bytes.Replace(in.Details[0], []byte("3f6a0c1d"), []byte("3f6a0c1e"), 1)
262 }, "different graph tips"},
263 {"a knot without its detail", func(in *export.Inputs) { in.Details = in.Details[1:] }, "has no detail"},
264 {"a detail twice", func(in *export.Inputs) { in.Details = append(in.Details, in.Details[0]) }, "twice"},
265 {"a public project the plan could not read", func(in *export.Inputs) {
266 in.Plan = bytes.Replace(in.Plan, []byte(`"project": "app",
267 "error": null`), []byte(`"project": "app",
268 "error": "unreadable"`), 1)
269 }, "could not read public project app"},
270 {"a public project the pending listing could not read", func(in *export.Inputs) {
271 in.Pending = bytes.Replace(in.Pending, []byte(`"url": "git@valley-host:app.git",
272 "error": null`), []byte(`"url": "git@valley-host:app.git",
273 "error": "unreadable"`), 1)
274 }, "pending listing could not read public project app"},
275 {"a public project the plan does not list", func(in *export.Inputs) {
276 in.Visibility = map[string]export.Visibility{"app": export.Public, "other": export.Public}
277 }, "not in the plan"},
278 {"a visibility v1 does not export", func(in *export.Inputs) {
279 in.Visibility = map[string]export.Visibility{"app": "private"}
280 }, "public projects alone"},
281 {"a public project with no source tip", func(in *export.Inputs) { in.SourceTips = nil }, "no source tip"},
282 {"a display name with a control character", func(in *export.Inputs) {
283 in.Principals = export.Principals{"app-agent": "agent\x1b"}
284 }, "display mapping"},
285 {"a plan of another schema", func(in *export.Inputs) {
286 in.Plan = bytes.Replace(in.Plan, []byte("valley-plan/v1"), []byte("valley-plan/v2"), 1)
287 }, "schema"},
288 {"knot text with a control character", func(in *export.Inputs) {
289 for i, d := range in.Details {
290 in.Details[i] = bytes.Replace(d, []byte(`"body": "`), []byte(`"body": "\u0007`), 1)
291 }
292 }, "control character"},
293 }
294 for _, c := range cases {
295 t.Run(c.name, func(t *testing.T) {
296 in := f.Inputs
297 in.Details = slices.Clone(in.Details)
298 c.change(&in)
299 _, err := export.Build(in)
300 if err == nil || !strings.Contains(err.Error(), c.want) {
301 t.Fatalf("Build gave %v, want an error saying %q", err, c.want)
302 }
303 })
304 }
305 in := f.Inputs
306 in.Details = slices.Clone(in.Details)
307 in.Details[0] = bytes.Replace(in.Details[0], []byte("3f6a0c1d"), []byte("3f6a0c1e"), 1)
308 if _, err := export.Build(in); !errors.Is(err, export.ErrInconsistent) {
309 t.Errorf("a detail at another tip gave %v, want ErrInconsistent", err)
310 }
311}
312
313// With no public project, the export is empty and valid.
314func TestBuildExportsNothingWhenNothingIsPublic(t *testing.T) {
315 f := exporttest.New(t)
316 in := f.Inputs
317 in.Visibility = nil
318 e, err := export.Build(in)
319 if err != nil {
320 t.Fatal(err)
321 }
322 if len(e.Projects) != 0 {
323 t.Errorf("exported %v", e.Projects)
324 }
325}
326
327// export.json is read strictly: a field the schema does not name, or a
328// project name that is not safe as a file name, fails it.
329func TestDecodeIsStrict(t *testing.T) {
330 f := exporttest.New(t)
331 if _, err := export.Decode(f.ExportJSON); err != nil {
332 t.Fatal(err)
333 }
334 for name, data := range map[string][]byte{
335 "an unknown field": bytes.Replace(f.ExportJSON, []byte(`"collected"`), []byte(`"extra":1,"collected"`), 1),
336 "an unsafe name": bytes.Replace(f.ExportJSON, []byte(`"project":"app"`), []byte(`"project":"../app"`), 1),
337 "a second document": append(append([]byte{}, f.ExportJSON...), f.ExportJSON...),
338 "another schema": bytes.Replace(f.ExportJSON, []byte(export.Schema), []byte("valley-web-export/v0"), 1),
339 } {
340 if _, err := export.Decode(data); err == nil {
341 t.Errorf("Decode took %s", name)
342 }
343 }
344}
345
346// Nothing but white space may follow export.json's document: not a
347// closing bracket or brace, which ends a document without starting
348// another, and not a malformed suffix. A receiver refuses such an
349// export.json as bad-export even when the manifest declares its bytes.
350func TestDecodeRefusesTrailingInput(t *testing.T) {
351 f := exporttest.New(t)
352 for _, suffix := range []string{"]", "}", "]garbage", "}}", "],", "garbage", ",", "{", `"`, "nul", "\x00", "{}", "[]", "1"} {
353 data := append(append([]byte{}, f.ExportJSON...), suffix...)
354 if _, err := export.Decode(data); err == nil {
355 t.Errorf("Decode took export.json followed by %q", suffix)
356 }
357 m := *f.Manifest
358 m.File = export.BodyOf(export.ExportFile, data)
359 if _, err := m.CheckExport(data); export.CodeOf(err) != export.CodeBadExport {
360 t.Errorf("CheckExport gave %v for export.json followed by %q, want bad-export", err, suffix)
361 }
362 }
363 data := append(append([]byte{}, f.ExportJSON...), " \t\r\n\n"...)
364 if _, err := export.Decode(data); err != nil {
365 t.Errorf("Decode refused export.json followed by white space: %v", err)
366 }
367}
368
369// The content digest ignores display-time fields and nothing else.
370func TestDigest(t *testing.T) {
371 f := exporttest.New(t)
372 base, err := f.Export.Digest()
373 if err != nil {
374 t.Fatal(err)
375 }
376 reread := func() *export.Export {
377 e, err := export.Decode(f.ExportJSON)
378 if err != nil {
379 t.Fatal(err)
380 }
381 return e
382 }
383 same := map[string]func(e *export.Export){
384 "collected": func(e *export.Export) { e.Collected = "2026-10-26T00:00:00Z" },
385 "a claim's age": func(e *export.Export) {
386 for i := range e.Projects[0].Knots {
387 if c := e.Projects[0].Knots[i].Claim; c != nil {
388 c.AgeSeconds, c.Stale = 999999, true
389 }
390 }
391 },
392 }
393 for name, change := range same {
394 e := reread()
395 change(e)
396 if got, _ := e.Digest(); got != base {
397 t.Errorf("changing %s changed the digest", name)
398 }
399 }
400 differs := map[string]func(e *export.Export){
401 "a title": func(e *export.Export) { e.Projects[0].Knots[0].Title += "!" },
402 "a source tip": func(e *export.Export) { e.Projects[0].SourceTip = strings.Repeat("a", 40) },
403 "a claim's at": func(e *export.Export) { e.Projects[0].Knots[1].Claim.At = "2026-10-25T11:00:00Z" },
404 "a comment": func(e *export.Export) { e.Projects[0].Knots[1].Comments[0].Body += "." },
405 "waiting on a hidden knot": func(e *export.Export) {
406 e.Projects[0].Knots[0].WaitingOnHidden = !e.Projects[0].Knots[0].WaitingOnHidden
407 },
408 }
409 for name, change := range differs {
410 e := reread()
411 change(e)
412 if got, _ := e.Digest(); got == base {
413 t.Errorf("changing %s left the digest as it was", name)
414 }
415 }
416 // Digest copies what it clears: the export it was given is unchanged.
417 if f.Export.Collected == "" || knotOf(t, f.Export, "oc-a000002").Claim.AgeSeconds == 0 {
418 t.Error("Digest changed the export it read")
419 }
420}
421
422// Incremental decoding preserves the export's values and rejects malformed
423// fields, including nested fields and integer overflow.
424func TestDecodeContextValues(t *testing.T) {
425 f := exporttest.New(t)
426 for _, data := range [][]byte{
427 f.ExportJSON,
428 []byte(`{"schema":"valley-web-export/v1","projects":null}`),
429 []byte(`{"schema":"valley-web-export/v1","projects":[]}`),
430 } {
431 var want export.Export
432 if err := json.Unmarshal(data, &want); err != nil {
433 t.Fatal(err)
434 }
435 got, err := export.DecodeContext(context.Background(), bytes.NewReader(data))
436 if err != nil {
437 t.Fatal(err)
438 }
439 if !reflect.DeepEqual(got, &want) {
440 t.Fatal("incremental decoding changed export values")
441 }
442 }
443 for _, field := range []string{
444 `"knots":{}`, `"roots":[1]`, `"knots":[{"id":"oc-a000001","active":1}]`,
445 `"knots":[{"id":"oc-a000001","comment_count":9223372036854775808}]`,
446 `"knots":[{"id":"oc-a000001","comment_count":1.5}]`, `"knots":[{"id":"oc-a000001","unknown":true}]`,
447 } {
448 data := []byte(`{"schema":"valley-web-export/v1","projects":[{"project":"app","visibility":"public","source_tip":"` + strings.Repeat("a", 40) + `",` + field + `}]}`)
449 if _, err := export.DecodeContext(context.Background(), bytes.NewReader(data)); err == nil {
450 t.Errorf("accepted %s", field)
451 }
452 }
453}
454
455// A token that spans many reads observes cancellation before consuming its
456// remaining bytes.
457func TestDecodeContextDuringToken(t *testing.T) {
458 ctx, cancel := context.WithCancel(context.Background())
459 defer cancel()
460 r := &cancelDecodeReader{Reader: strings.NewReader(`{"schema":"` + strings.Repeat("x", 1<<20) + `"}`), cancel: cancel}
461 if _, err := export.DecodeContext(ctx, r); !errors.Is(err, context.Canceled) {
462 t.Fatalf("error = %v", err)
463 }
464 if r.n > 8192 {
465 t.Fatalf("read %d bytes after cancellation", r.n)
466 }
467}
468
469type cancelDecodeReader struct {
470 io.Reader
471 cancel context.CancelFunc
472 n int
473}
474
475func (r *cancelDecodeReader) Read(p []byte) (int, error) {
476 n, err := r.Reader.Read(p)
477 r.n += n
478 if r.n >= 4096 {
479 r.cancel()
480 }
481 return n, err
482}
483
484// The final input read arms cancellation. The string scanner must observe
485// it while decoding bytes already in its buffer, without another source read.
486func TestDecodeContextFinalStringChunk(t *testing.T) {
487 for _, key := range []bool{false, true} {
488 t.Run(fmt.Sprint(key), func(t *testing.T) {
489 base, cancel := context.WithCancel(context.Background())
490 defer cancel()
491 ctx := &finalStringContext{Context: base, cancel: cancel}
492 value := strings.Repeat(`\u0061`, 1<<17)
493 data := `{"schema":"valley-web-export/v1","collected":"` + value + `"}`
494 if key {
495 data = `{"` + value + `":null}`
496 }
497 r := &finalStringReader{Reader: strings.NewReader(data), ctx: ctx}
498 started := time.Now()
499 got, err := export.DecodeContext(ctx, r)
500 if got != nil || !errors.Is(err, context.Canceled) {
501 t.Fatalf("DecodeContext = %v, %v", got, err)
502 }
503 if !ctx.inString {
504 t.Fatal("cancellation was not observed inside string decoding")
505 }
506 if r.extraRead {
507 t.Fatal("decoder requested more input after the final chunk")
508 }
509 if time.Since(started) > 2*time.Second {
510 t.Fatal("string decoding did not stop promptly")
511 }
512 })
513 }
514}
515
516type finalStringContext struct {
517 context.Context
518 cancel context.CancelFunc
519 armed bool
520 checks int
521 inString bool
522}
523
524func (c *finalStringContext) Err() error {
525 if c.armed {
526 c.checks++
527 if c.checks == 3 {
528 var pcs [16]uintptr
529 n := runtime.Callers(2, pcs[:])
530 frames := runtime.CallersFrames(pcs[:n])
531 for {
532 f, more := frames.Next()
533 if strings.HasSuffix(f.Function, ".(*stringInput).readString") {
534 c.inString = true
535 }
536 if !more {
537 break
538 }
539 }
540 c.cancel()
541 }
542 }
543 return c.Context.Err()
544}
545
546type finalStringReader struct {
547 *strings.Reader
548 ctx *finalStringContext
549 extraRead bool
550}
551
552func (r *finalStringReader) Read(p []byte) (int, error) {
553 if r.ctx.armed {
554 r.extraRead = true
555 }
556 n, err := r.Reader.Read(p)
557 if r.Len() == 0 {
558 r.ctx.armed = true
559 }
560 return n, err
561}
562
563// String decoding matches encoding/json for escapes, invalid UTF-8 and
564// surrogate pairs, including sequences split across input chunks.
565func TestDecodeStringValues(t *testing.T) {
566 values := []string{
567 `"plain"`, `"\"\\\/\b\f\n\r\t"`, `"\uD834\uDD1E"`,
568 `"\uD834x"`, `"\uDD1E"`, `"\uD834\u0061"`, `"\uD834\uD834\uDD1E"`,
569 "\"\xff\"", `"รฉ็•Œ๐„ž"`,
570 }
571 prefixes := []string{""}
572 for offset := 0; offset < 12; offset++ {
573 prefixes = append(prefixes, strings.Repeat("a", 4096-len(`{"schema":"valley-web-export/v1","collected":"`)-offset))
574 }
575 for _, prefix := range prefixes {
576 for _, value := range values {
577 data := []byte(`{"schema":"valley-web-export/v1","collected":"` + prefix + value[1:] + `}`)
578 var want export.Export
579 if err := json.Unmarshal(data, &want); err != nil {
580 t.Fatal(err)
581 }
582 got, err := export.DecodeContext(context.Background(), bytes.NewReader(data))
583 if err != nil {
584 t.Fatal(err)
585 }
586 if !reflect.DeepEqual(got, &want) {
587 t.Errorf("string %q differs from encoding/json", value)
588 }
589 }
590 }
591 for _, value := range []string{`"\x"`, `"\uZZZZ"`, `"\u123"`, `"unterminated`, "\"\n\"", `"\uD834\uZZZZ"`} {
592 data := []byte(`{"schema":"valley-web-export/v1","collected":` + value + `}`)
593 if _, err := export.Decode(data); err == nil {
594 t.Errorf("accepted invalid string %q", value)
595 }
596 }
597}
598
599// More must not consume and hide a string error before a closing delimiter.
600func TestDecodeRetainsStringError(t *testing.T) {
601 for _, data := range []string{
602 `{"schema":"valley-web-export/v1","projects":["\x]}`,
603 `{"schema":"valley-web-export/v1","\x}`,
604 } {
605 if _, err := export.Decode([]byte(data)); err == nil {
606 t.Errorf("accepted malformed document %q", data)
607 }
608 }
609}