Debian Codegraph @

internal/libyaml/writer_test.go

raw symbols SCIP
1 // Copyright 2025 The go-yaml Project Contributors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Tests for the output writer.
5 // Verifies buffered write operations for the emitter.
6
7 package libyaml
8
9 import (
10 "bytes"
11 "errors"
12 "testing"
13
14 "go.yaml.in/yaml/v4/internal/testutil/assert"
15 )
16
17 func TestWriter(t *testing.T) {
18 RunTestCases(t, "writer.yaml", map[string]TestHandler{
19 "writer-flush": runWriterFlushTest,
20 "writer-error": runWriterErrorTest,
21 "writer-panic": runWriterPanicTest,
22 })
23 }
24
25 func runWriterFlushTest(t *testing.T, tc TestCase) {
26 t.Helper()
27
28 emitter := NewEmitter()
29 var output []byte
30 var buf bytes.Buffer
31
32 // Setup output handler
33 if tc.Output == "string" {
34 emitter.SetOutputString(&output)
35 } else {
36 emitter.SetOutputWriter(&buf)
37 }
38
39 // Helper to write data and flush
40 writeAndFlush := func(data string) {
41 if len(data) > 0 {
42 copy(emitter.buffer[:], []byte(data))
43 emitter.buffer_pos = len(data)
44 }
45 err := emitter.flush()
46 assert.NoErrorf(t, err, "flush() error: %v", err)
47 }
48
49 // Write and flush data (once or twice)
50 writeAndFlush(string(tc.Input))
51 if len(tc.Data2) > 0 {
52 writeAndFlush(tc.Data2)
53 }
54
55 // Check output
56 actual := output
57 if tc.Output == "writer" {
58 actual = buf.Bytes()
59 }
60 want, ok := tc.Want.(string)
61 assert.Truef(t, ok, "Want should be string, got %T", tc.Want)
62 assert.Equalf(t, want, string(actual), "flush() output = %q, want %q", string(actual), want)
63
64 // Run field checks
65 if tc.Checks != nil {
66 runFieldChecks(t, &emitter, tc.Checks)
67 }
68 }
69
70 func runWriterErrorTest(t *testing.T, tc TestCase) {
71 t.Helper()
72
73 emitter := NewEmitter()
74 emitter.SetOutputWriter(&errorWriter{})
75
76 if len(tc.Input) > 0 {
77 copy(emitter.buffer[:], tc.Input)
78 emitter.buffer_pos = len(tc.Input)
79 }
80
81 err := emitter.flush()
82 want, ok := tc.Want.(string)
83 assert.Truef(t, ok, "Want should be string, got %T", tc.Want)
84 assert.ErrorMatchesf(t, want, err, "flush() should return error matching %q, got %v", want, err)
85 }
86
87 func runWriterPanicTest(t *testing.T, tc TestCase) {
88 t.Helper()
89
90 emitter := NewEmitter()
91
92 if len(tc.Input) > 0 {
93 copy(emitter.buffer[:], tc.Input)
94 emitter.buffer_pos = len(tc.Input)
95 }
96
97 want, ok := tc.Want.(string)
98 assert.Truef(t, ok, "Want should be string, got %T", tc.Want)
99 assert.PanicMatchesf(t, want, func() {
100 _ = emitter.flush()
101 }, "Expected panic: %s", want)
102 }
103
104 // errorWriter is a writer that always returns an error
105 type errorWriter struct{}
106
107 func (w *errorWriter) Write(p []byte) (n int, err error) {
108 return 0, errors.New("write error")
109 }