From 3e6682d0f191d6491b550b9c80f91ebb79597de8 Mon Sep 17 00:00:00 2001 From: c879873067877881111 Date: Sun, 19 Jul 2026 14:25:01 +0800 Subject: [PATCH] test(utils): cover EncodeToken error path in H.MarshalXML H.MarshalXML returns early when the opening e.EncodeToken(start) call fails, but no test covered that error path. Because xml.Encoder buffers its output, the underlying writer is not called until the buffer flushes. The test writes an 8KB token first to push the encoder into an error state, then calls MarshalXML and asserts the write error is propagated. --- utils_test.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/utils_test.go b/utils_test.go index e1f2c332..dedb755d 100644 --- a/utils_test.go +++ b/utils_test.go @@ -7,6 +7,7 @@ package gin import ( "bytes" "encoding/xml" + "errors" "fmt" "math" "net/http" @@ -157,6 +158,27 @@ func TestMarshalXMLforHSuccess(t *testing.T) { assert.Contains(t, string(data), "123") } +// errXMLWriter always fails, to exercise encoder write-error paths. +type errXMLWriter struct{} + +func (errXMLWriter) Write(_ []byte) (int, error) { return 0, errors.New("write failed") } + +// TestMarshalXMLEncodeTokenError covers the branch where the opening +// EncodeToken(start) fails. xml.Encoder buffers its output, so the failing +// writer is only reached once the buffer overflows; we prime it with a large +// token first, which puts the encoder into an error state. MarshalXML's very +// first EncodeToken then returns that cached write error. +func TestMarshalXMLEncodeTokenError(t *testing.T) { + enc := xml.NewEncoder(errXMLWriter{}) + + // Overflow the encoder's internal buffer so it flushes to the failing + // writer and latches the error. + require.Error(t, enc.EncodeToken(xml.CharData(bytes.Repeat([]byte("a"), 8192)))) + + err := H{"key": "value"}.MarshalXML(enc, xml.StartElement{}) + assert.Error(t, err) +} + func TestIsASCII(t *testing.T) { assert.True(t, isASCII("test")) assert.False(t, isASCII("๐Ÿงก๐Ÿ’›๐Ÿ’š๐Ÿ’™๐Ÿ’œ"))