Debian Codegraph @

encode_value_lifetime_test.go

raw
1 package json_test
2
3 import (
4 "runtime"
5 "testing"
6 "time"
7
8 "github.com/goccy/go-json"
9 )
10
11 type lifetimeNode struct {
12 Name string
13 Next *lifetimeNode
14 Any any
15 Map map[string]*lifetimeNode
16 Slice []*lifetimeNode
17 }
18
19 // The encoder refers to the values being encoded from its context, which is pooled.
20 // The context must not keep them alive after the encoding.
21 func TestEncodedValueIsNotKeptAlive(t *testing.T) {
22 for _, test := range []struct {
23 name string
24 marshal func(any) ([]byte, error)
25 }{
26 {"Marshal", json.Marshal},
27 {"MarshalIndent", func(v any) ([]byte, error) { return json.MarshalIndent(v, "", " ") }},
28 {"Error", func(v any) ([]byte, error) {
29 // the encoding stops at the last value, so the context still refers to the values.
30 values := v.(*lifetimeNode).Slice
31 values[len(values)-1].Any = make(chan int)
32 if _, err := json.Marshal(v); err == nil {
33 t.Error("expected an error")
34 }
35 return nil, nil
36 }},
37 } {
38 t.Run(test.name, func(t *testing.T) {
39 const num = 4
40 collected := make(chan struct{}, num)
41 func() {
42 leaf := &lifetimeNode{Name: "leaf"}
43 // a finalizer of a value is not called until the values referring to it are freed,
44 // so the leaf has no finalizer.
45 values := []*lifetimeNode{
46 {Name: "next", Next: leaf},
47 {Name: "any", Any: leaf},
48 {Name: "map", Map: map[string]*lifetimeNode{"a": leaf}},
49 {Name: "slice", Slice: []*lifetimeNode{leaf}},
50 }
51 for _, v := range values {
52 runtime.SetFinalizer(v, func(*lifetimeNode) { collected <- struct{}{} })
53 }
54 if _, err := test.marshal(&lifetimeNode{Name: "root", Slice: values}); err != nil {
55 t.Fatal(err)
56 }
57 }()
58 // Only one GC: the pool releases what it has after a few, whatever it holds.
59 runtime.GC()
60 for i := 0; i < num; i++ {
61 select {
62 case <-collected:
63 case <-time.After(10 * time.Second):
64 t.Fatalf("%d of %d values are kept alive after the encoding", num-i, num)
65 }
66 }
67 })
68 }
69 }