From 483bbdc970b26d774ace39edfde8420aba53b742 Mon Sep 17 00:00:00 2001 From: Luke Shumaker Date: Tue, 7 Feb 2023 14:01:44 -0700 Subject: Sync borrowed code from Go 1.20 New tests mean encode.go and compat.go also need some bugfixes. --- compat/json/borrowed_stream_test.go | 54 ++++++++++++++++++++++++++----------- 1 file changed, 39 insertions(+), 15 deletions(-) (limited to 'compat/json/borrowed_stream_test.go') diff --git a/compat/json/borrowed_stream_test.go b/compat/json/borrowed_stream_test.go index 6c3a403..d90898b 100644 --- a/compat/json/borrowed_stream_test.go +++ b/compat/json/borrowed_stream_test.go @@ -13,6 +13,7 @@ import ( "net/http" "net/http/httptest" "reflect" + "runtime/debug" "strings" "testing" ) @@ -61,6 +62,44 @@ func TestEncoder(t *testing.T) { } } +//nolint:paralleltest // MODIFIED: added; can't be parallel because it fusses with the global GC. +func TestEncoderErrorAndReuseEncodeState(t *testing.T) { + // Disable the GC temporarily to prevent encodeState's in Pool being cleaned away during the test. + percent := debug.SetGCPercent(-1) + defer debug.SetGCPercent(percent) + + // Trigger an error in Marshal with cyclic data. + type Dummy struct { + Name string + Next *Dummy + } + dummy := Dummy{Name: "Dummy"} + dummy.Next = &dummy + + var buf bytes.Buffer + enc := NewEncoder(&buf) + if err := enc.Encode(dummy); err == nil { + t.Errorf("Encode(dummy) == nil; want error") + } + + type Data struct { + A string + I int + } + data := Data{A: "a", I: 1} + if err := enc.Encode(data); err != nil { + t.Errorf("Marshal(%v) = %v", data, err) + } + + var data2 Data + if err := Unmarshal(buf.Bytes(), &data2); err != nil { + t.Errorf("Unmarshal(%v) = %v", data2, err) + } + if data2 != data { + t.Errorf("expect: %v, but get: %v", data, data2) + } +} + var streamEncodedIndent = `0.1 "hello" null @@ -324,21 +363,6 @@ func TestBlocking(t *testing.T) { } } -func BenchmarkEncoderEncode(b *testing.B) { - b.ReportAllocs() - type T struct { - X, Y string - } - v := &T{"foo", "bar"} - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - if err := NewEncoder(io.Discard).Encode(v); err != nil { - b.Fatal(err) - } - } - }) -} - //nolint:dupword // False positive, this is commented-out code, not a real comment. // MODIFIED: added nolint declaration /* // MODIFIED: we don't have tokens type tokenStreamCase struct { -- cgit v1.2.3-2-g168b