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("๐Ÿงก๐Ÿ’›๐Ÿ’š๐Ÿ’™๐Ÿ’œ"))