| 1 |
package json_test |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
stdjson "encoding/json" |
| 6 |
"testing" |
| 7 |
|
| 8 |
"github.com/goccy/go-json" |
| 9 |
) |
| 10 |
|
| 11 |
type cycleDetectionHolder struct { |
| 12 |
V any |
| 13 |
} |
| 14 |
|
| 15 |
type cycleDetectionNode struct { |
| 16 |
Next *cycleDetectionNode |
| 17 |
Any any |
| 18 |
} |
| 19 |
|
| 20 |
// nestedInterfaceValue wraps the value by the slices of an interface value. |
| 21 |
func nestedInterfaceValue(depth int, v any) any { |
| 22 |
for i := 0; i < depth; i++ { |
| 23 |
v = []any{v} |
| 24 |
} |
| 25 |
return v |
| 26 |
} |
| 27 |
|
| 28 |
// The values are checked for a cycle after the nesting gets deep. |
| 29 |
// A value which is referred to twice is not a cycle, whatever it holds. |
| 30 |
func TestEncodeSharedValueNestedDeeply(t *testing.T) { |
| 31 |
const depth = 1100 |
| 32 |
shared := &cycleDetectionHolder{V: (*int)(nil)} |
| 33 |
for _, test := range []struct { |
| 34 |
name string |
| 35 |
v any |
| 36 |
}{ |
| 37 |
{"typed nil in interface", []*cycleDetectionHolder{shared, shared}}, |
| 38 |
{"value in interface", []any{shared, shared}}, |
| 39 |
{"recursive type", []*cycleDetectionNode{{Any: shared}, {Any: shared}}}, |
| 40 |
} { |
| 41 |
t.Run(test.name, func(t *testing.T) { |
| 42 |
v := nestedInterfaceValue(depth, test.v) |
| 43 |
expected, err := stdjson.Marshal(v) |
| 44 |
if err != nil { |
| 45 |
t.Fatal(err) |
| 46 |
} |
| 47 |
got, err := json.Marshal(v) |
| 48 |
if err != nil { |
| 49 |
t.Fatal(err) |
| 50 |
} |
| 51 |
if !bytes.Equal(expected, got) { |
| 52 |
t.Fatalf("expected %d bytes but got %d bytes", len(expected), len(got)) |
| 53 |
} |
| 54 |
}) |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
func TestEncodeCycleNestedDeeply(t *testing.T) { |
| 59 |
t.Run("interface", func(t *testing.T) { |
| 60 |
cycle := []any{nil} |
| 61 |
cycle[0] = cycle |
| 62 |
for _, depth := range []int{0, 1100} { |
| 63 |
if _, err := json.Marshal(nestedInterfaceValue(depth, cycle)); err == nil { |
| 64 |
t.Fatalf("depth %d: expected an error", depth) |
| 65 |
} |
| 66 |
} |
| 67 |
}) |
| 68 |
t.Run("recursive type", func(t *testing.T) { |
| 69 |
node := &cycleDetectionNode{} |
| 70 |
node.Next = &cycleDetectionNode{Next: node} |
| 71 |
for _, depth := range []int{0, 1100} { |
| 72 |
if _, err := json.Marshal(nestedInterfaceValue(depth, node)); err == nil { |
| 73 |
t.Fatalf("depth %d: expected an error", depth) |
| 74 |
} |
| 75 |
} |
| 76 |
}) |
| 77 |
} |