Debian Codegraph @

internal/libyaml/testdata_test.go

raw symbols SCIP
1 // Copyright 2025 The go-yaml Project Contributors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Tests for YAML test data loading.
5 // Verifies test data loading utilities and scalar coercion functions.
6
7 package libyaml
8
9 import (
10 "bytes"
11 "errors"
12 "fmt"
13 "io"
14 "os"
15 "path/filepath"
16 "reflect"
17 "runtime"
18 "strconv"
19 "strings"
20 "testing"
21
22 "go.yaml.in/yaml/v4/internal/testutil/assert"
23 "go.yaml.in/yaml/v4/internal/testutil/datatest"
24 )
25
26 // NodeSpec describes an input node for pipeline stage tests.
27 // Used in nested test format for representer, desolver, and serializer tests.
28 type NodeSpec struct {
29 Tag string `yaml:"tag"` // YAML tag (e.g., "!!int", "!!str")
30 Value string `yaml:"value"` // Scalar value
31 Kind string `yaml:"kind"` // Node kind: Scalar, Mapping, Sequence, Document
32 Style string `yaml:"style"` // Style: Tagged, SingleQuoted, DoubleQuoted, Flow
33 Content any `yaml:"content"` // Nested content for collections
34 }
35
36 // WantSpec describes expected test results for pipeline stage tests.
37 // Used in nested test format for representer, desolver, and serializer tests.
38 type WantSpec struct {
39 Tag string `yaml:"tag"` // Expected tag
40 Value string `yaml:"value"` // Expected scalar value
41 Kind string `yaml:"kind"` // Expected node kind
42 Quoted bool `yaml:"quoted"` // Whether scalar should be quoted
43 ContentCount int `yaml:"content_count"` // Expected number of content children
44 Yaml string `yaml:"yaml"` // Expected YAML output
45 }
46
47 // TestCase represents a single test case loaded from YAML
48 type TestCase struct {
49 Name string `yaml:"name"`
50 Type string `yaml:"type"`
51
52 // Common fields
53 Yaml string `yaml:"yaml"`
54 InputHex string `yaml:"input_hex"`
55 InputBytes string `yaml:"input_bytes"`
56 From any `yaml:"from"` // Input data for tests
57 Want any `yaml:"want"` // Expected output
58 Also string `yaml:"also"` // Test modifiers (e.g., "unwrap")
59 Like string `yaml:"like"` // Regex pattern to match error message
60 WantSpecs []EventSpec // Populated from Want for detailed tests
61
62 // scan_tokens_detailed
63 WantTokens []TokenSpec // Populated from Want for detailed tests
64
65 // emit tests
66 Events []EventSpec `yaml:"data"`
67 WantContains []string // Populated from Want for emit tests
68 Config EmitterConfig `yaml:"conf"`
69
70 // style_accessor tests (must come before Checks due to shared yaml:"test" tag)
71 StyleTest []any `yaml:"test"` // [Method, STYLE] where Method is string and STYLE is int or string constant
72
73 // api_new tests
74 Constructor string `yaml:"with"`
75 Checks []FieldCheck `yaml:"test"`
76
77 // encoding_detect tests
78 WantEncoding string `yaml:"want_encoding"`
79
80 // char_classify tests
81 Cases []CharTestCase `yaml:"cases"`
82
83 // yamlprivate tests (char-predicate, char-convert)
84 Function string `yaml:"func"` // Function to call
85 Input ByteInput `yaml:"data"` // Can be string or []int (hex bytes)
86 Index int `yaml:"index"` // Defaults to 0
87
88 // reader tests
89 Args Args `yaml:"args"` // Arguments to pass to method (can be scalar or array)
90
91 // writer tests
92 Output string `yaml:"output_type"` // Output handler type (string, writer, error-writer)
93 Data2 string `yaml:"data2"` // Second data chunk for multi-flush tests
94
95 // read_handler tests
96 Handler string `yaml:"handler"`
97 ReadSize int `yaml:"read_size"`
98 WantData string `yaml:"want_data"`
99 WantEOF bool `yaml:"want_eof"`
100
101 // enum_string tests
102 Enum []any `yaml:"enum"` // [Type, Value] where Type is string and Value is int or string
103
104 // api_method, api_panic, api_delete tests, and reader tests
105 Bytes bool `yaml:"byte"`
106 Method []any `yaml:"call"`
107 Setup any `yaml:"init"` // Can be []interface{} (api tests) or map[string]interface{} (reader tests)
108
109 // Pipeline stage tests (representer, desolver, serializer) - nested format
110 // For representer: use From for input value
111 // For desolver: use Node for input node to desolve
112 // For serializer: use Node for input node to serialize, Yaml for expected output
113 // Note: Want field (type any) is used - cast to map in test handlers for representer/desolver
114 Node NodeSpec `yaml:"node"` // Input/expected node specification
115 Indent int `yaml:"indent"` // Indentation setting for serializer tests
116
117 // Error test specific fields
118 As string `yaml:"as"` // Type name for errors.As tests
119 Is string `yaml:"is"` // Error message for errors.Is tests
120 WantAs bool `yaml:"want_as"` // Expected result for errors.As
121 WantIs bool `yaml:"want_is"` // Expected result for errors.Is
122 WantMessages []any `yaml:"want_messages"` // Expected messages for TypeError
123 }
124
125 // constantRegistry holds libyaml-specific constants
126 var constantRegistry = datatest.NewConstantRegistry()
127
128 // constantMap maps constant names to their integer values (for backward compatibility)
129 var constantMap = map[string]int{
130 // ScalarStyle (bit-shifted starting at iota=1)
131 "ANY_SCALAR_STYLE": 0,
132 "PLAIN_SCALAR_STYLE": 2,
133 "SINGLE_QUOTED_SCALAR_STYLE": 4,
134 "DOUBLE_QUOTED_SCALAR_STYLE": 8,
135 "LITERAL_SCALAR_STYLE": 16,
136 "FOLDED_SCALAR_STYLE": 32,
137
138 // TokenType
139 "NO_TOKEN": 0,
140 "STREAM_START_TOKEN": 1,
141 "STREAM_END_TOKEN": 2,
142 "VERSION_DIRECTIVE_TOKEN": 3,
143 "TAG_DIRECTIVE_TOKEN": 4,
144 "DOCUMENT_START_TOKEN": 5,
145 "DOCUMENT_END_TOKEN": 6,
146 "BLOCK_SEQUENCE_START_TOKEN": 7,
147 "BLOCK_MAPPING_START_TOKEN": 8,
148 "BLOCK_END_TOKEN": 9,
149 "FLOW_SEQUENCE_START_TOKEN": 10,
150 "FLOW_SEQUENCE_END_TOKEN": 11,
151 "FLOW_MAPPING_START_TOKEN": 12,
152 "FLOW_MAPPING_END_TOKEN": 13,
153 "BLOCK_ENTRY_TOKEN": 14,
154 "FLOW_ENTRY_TOKEN": 15,
155 "KEY_TOKEN": 16,
156 "VALUE_TOKEN": 17,
157 "ALIAS_TOKEN": 18,
158 "ANCHOR_TOKEN": 19,
159 "TAG_TOKEN": 20,
160 "SCALAR_TOKEN": 21,
161
162 // EventType
163 "NO_EVENT": 0,
164 "STREAM_START_EVENT": 1,
165 "STREAM_END_EVENT": 2,
166 "DOCUMENT_START_EVENT": 3,
167 "DOCUMENT_END_EVENT": 4,
168 "ALIAS_EVENT": 5,
169 "SCALAR_EVENT": 6,
170 "SEQUENCE_START_EVENT": 7,
171 "SEQUENCE_END_EVENT": 8,
172 "MAPPING_START_EVENT": 9,
173 "MAPPING_END_EVENT": 10,
174 "TAIL_COMMENT_EVENT": 11,
175
176 // ParserState
177 "PARSE_STREAM_START_STATE": 0,
178 "PARSE_IMPLICIT_DOCUMENT_START_STATE": 1,
179 "PARSE_DOCUMENT_START_STATE": 2,
180 "PARSE_DOCUMENT_CONTENT_STATE": 3,
181 "PARSE_DOCUMENT_END_STATE": 4,
182 "PARSE_BLOCK_NODE_STATE": 5,
183 "PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE": 6,
184 "PARSE_BLOCK_SEQUENCE_ENTRY_STATE": 7,
185 "PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE": 8,
186 "PARSE_BLOCK_MAPPING_FIRST_KEY_STATE": 9,
187 "PARSE_BLOCK_MAPPING_KEY_STATE": 10,
188 "PARSE_BLOCK_MAPPING_VALUE_STATE": 11,
189 "PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE": 12,
190 "PARSE_FLOW_SEQUENCE_ENTRY_STATE": 13,
191 "PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE": 14,
192 "PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE": 15,
193 "PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE": 16,
194 "PARSE_FLOW_MAPPING_FIRST_KEY_STATE": 17,
195 "PARSE_FLOW_MAPPING_KEY_STATE": 18,
196 "PARSE_FLOW_MAPPING_VALUE_STATE": 19,
197 "PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE": 20,
198 "PARSE_END_STATE": 21,
199
200 // SequenceStyle / MappingStyle
201 "ANY_SEQUENCE_STYLE": 0,
202 "BLOCK_SEQUENCE_STYLE": 1,
203 "FLOW_SEQUENCE_STYLE": 2,
204 "ANY_MAPPING_STYLE": 0,
205 "BLOCK_MAPPING_STYLE": 1,
206 "FLOW_MAPPING_STYLE": 2,
207
208 // Encoding
209 "ANY_ENCODING": 0,
210 "UTF8_ENCODING": 1,
211 "UTF16LE_ENCODING": 2,
212 "UTF16BE_ENCODING": 3,
213
214 // LineBreak
215 "ANY_BREAK": 0,
216 "CR_BREAK": 1,
217 "LN_BREAK": 2,
218 "CRLN_BREAK": 3,
219
220 // ErrorType
221 "NO_ERROR": 0,
222 "MEMORY_ERROR": 1,
223 "READER_ERROR": 2,
224 "SCANNER_ERROR": 3,
225 "PARSER_ERROR": 4,
226 "COMPOSER_ERROR": 5,
227 "WRITER_ERROR": 6,
228 "EMITTER_ERROR": 7,
229 }
230
231 func init() {
232 // Populate constantRegistry with all constants from constantMap
233 for name, value := range constantMap {
234 constantRegistry.Register(name, value)
235 }
236 }
237
238 // resolveConstant converts a constant name string to its integer value
239 func resolveConstant(t *testing.T, name string) int {
240 t.Helper()
241 val, ok := constantMap[name]
242 if !ok {
243 t.Fatalf("unknown constant name: %s", name)
244 }
245 return val
246 }
247
248 // IntOrStr wraps the shared datatest.IntOrStr with libyaml's constant registry
249 type IntOrStr struct {
250 datatest.IntOrStr
251 }
252
253 func (ios *IntOrStr) FromValue(v any) error {
254 ios.Registry = constantRegistry
255 return ios.IntOrStr.FromValue(v)
256 }
257
258 // ByteInput is an alias to the shared datatest.ByteInput
259 type ByteInput = datatest.ByteInput
260
261 // Args is an alias to the shared datatest.Args
262 type Args = datatest.Args
263
264 // EventSpec specifies an event in YAML format
265 type EventSpec struct {
266 Type string `yaml:"type"`
267 Encoding string `yaml:"encoding"`
268 Implicit bool `yaml:"implicit"`
269 QuotedImplicit bool `yaml:"quoted_implicit"`
270 Anchor string `yaml:"anchor"`
271 Tag string `yaml:"tag"`
272 Value string `yaml:"value"`
273 Style string `yaml:"style"`
274 VersionDirective *VersionDirectiveSpec `yaml:"version-directive"`
275 TagDirectives []TagDirectiveSpec `yaml:"tag-directives"`
276 }
277
278 // VersionDirectiveSpec specifies a version directive
279 type VersionDirectiveSpec struct {
280 Major int `yaml:"major"`
281 Minor int `yaml:"minor"`
282 }
283
284 // TagDirectiveSpec specifies a tag directive
285 type TagDirectiveSpec struct {
286 Handle string `yaml:"handle"`
287 Prefix string `yaml:"prefix"`
288 }
289
290 // TokenSpec specifies a token in YAML format
291 type TokenSpec struct {
292 Type string `yaml:"type"`
293 Value string `yaml:"value"`
294 Style string `yaml:"style"`
295 }
296
297 // EmitterConfig specifies emitter configuration
298 type EmitterConfig struct {
299 Canonical bool `yaml:"canonical"`
300 Indent int `yaml:"indent"`
301 Width int `yaml:"width"`
302 Unicode bool `yaml:"unicode"`
303 LineBreak string `yaml:"line_break"`
304 }
305
306 // SetupSpec specifies test setup
307 type SetupSpec struct {
308 Constructor string `yaml:"constructor"`
309 Calls []CallSpec `yaml:"calls"`
310 }
311
312 // CallSpec specifies a method call
313 type CallSpec struct {
314 Method string `yaml:"method"`
315 Args []ArgSpec `yaml:"args"`
316 }
317
318 // ArgSpec specifies a method argument
319 type ArgSpec struct {
320 Bytes string `yaml:"bytes"`
321 String string `yaml:"string"`
322 Int int `yaml:"int"`
323 Bool bool `yaml:"bool"`
324 Hex string `yaml:"hex"`
325 Reader bool `yaml:"reader"` // Creates a strings.Reader from String field
326 Writer bool `yaml:"writer"` // Creates a bytes.Buffer
327 }
328
329 // FieldCheck specifies a field check
330 type FieldCheck struct {
331 Nil []any `yaml:"nil"`
332 Cap []any `yaml:"cap"`
333 Len []any `yaml:"len"`
334 LenGt []any `yaml:"len-gt"` // Length greater than
335 Eq []any `yaml:"eq"`
336 Gte []any `yaml:"gte"` // Greater than or equal
337 }
338
339 // CharTestCase represents a character classification test case
340 type CharTestCase struct {
341 InputHex string `yaml:"input_hex"`
342 Pos int `yaml:"pos"`
343 Want any `yaml:"want"` // Can be bool or int
344 }
345
346 // unmarshalTestCases converts raw YAML data to TestCase structs using yamltest
347 func unmarshalTestCases(data any) ([]TestCase, error) {
348 casesSlice, ok := data.([]any)
349 if !ok {
350 return nil, fmt.Errorf("expected []interface{}, got %T", data)
351 }
352
353 var testCases []TestCase
354 for i, item := range casesSlice {
355 caseMap, ok := item.(map[string]any)
356 if !ok {
357 return nil, fmt.Errorf("test case %d: expected map[string]interface{}, got %T", i, item)
358 }
359
360 // Normalize type-as-key format for top-level test cases
361 caseMap = datatest.NormalizeTypeAsKey(caseMap)
362
363 var tc TestCase
364 if err := datatest.UnmarshalStruct(&tc, caseMap); err != nil {
365 return nil, fmt.Errorf("test case %d: %w", i, err)
366 }
367 testCases = append(testCases, tc)
368 }
369
370 return testCases, nil
371 }
372
373 func LoadTestCases(filename string) ([]TestCase, error) {
374 // Get the path relative to this file
375 _, thisFile, _, _ := runtime.Caller(0)
376 dir := filepath.Dir(thisFile)
377 path := filepath.Join(dir, "testdata", filename)
378
379 data, err := os.ReadFile(path)
380 if err != nil {
381 return nil, fmt.Errorf("failed to read %s: %w", filename, err)
382 }
383
384 // Load YAML using LoadAny from loader.go
385 rawData, err := LoadAny(data)
386 if err != nil {
387 return nil, fmt.Errorf("failed to parse %s: %w", filename, err)
388 }
389
390 // Convert to TestCase structs
391 cases, err := unmarshalTestCases(rawData)
392 if err != nil {
393 return nil, fmt.Errorf("failed to unmarshal test cases from %s: %w", filename, err)
394 }
395
396 // Post-process: convert Want to WantSpecs/WantTokens for detailed tests
397 for i := range cases {
398 // Determine which field to populate based on test type
399 switch cases[i].Type {
400 case "parse-events-detailed":
401 if cases[i].Want != nil {
402 // Want should be []interface{} of maps, convert to []EventSpec
403 wantSlice, ok := cases[i].Want.([]any)
404 if !ok {
405 return nil, fmt.Errorf("test %s: want should be a sequence, got %T", cases[i].Name, cases[i].Want)
406 }
407 cases[i].WantSpecs = make([]EventSpec, len(wantSlice))
408 for j, item := range wantSlice {
409 var itemMap map[string]any
410 // Check if item is a scalar string (simplified format)
411 if strVal, ok := item.(string); ok {
412 // Convert scalar to map with type field
413 itemMap = map[string]any{"type": strVal}
414 } else {
415 itemMap, ok = item.(map[string]any)
416 if !ok {
417 return nil, fmt.Errorf("test %s: want[%d] should be a map or string, got %T", cases[i].Name, j, item)
418 }
419 // Normalize type-as-key format
420 itemMap = datatest.NormalizeTypeAsKey(itemMap)
421 }
422 if err := datatest.UnmarshalStruct(&cases[i].WantSpecs[j], itemMap); err != nil {
423 return nil, fmt.Errorf("test %s: want[%d]: %w", cases[i].Name, j, err)
424 }
425 }
426 }
427 case "scan-tokens-detailed":
428 if cases[i].Want != nil {
429 // Want should be []interface{} of maps, convert to []TokenSpec
430 wantSlice, ok := cases[i].Want.([]any)
431 if !ok {
432 return nil, fmt.Errorf("test %s: want should be a sequence, got %T", cases[i].Name, cases[i].Want)
433 }
434 cases[i].WantTokens = make([]TokenSpec, len(wantSlice))
435 for j, item := range wantSlice {
436 var itemMap map[string]any
437 // Check if item is a scalar string (simplified format)
438 if strVal, ok := item.(string); ok {
439 // Convert scalar to map with type field
440 itemMap = map[string]any{"type": strVal}
441 } else {
442 itemMap, ok = item.(map[string]any)
443 if !ok {
444 return nil, fmt.Errorf("test %s: want[%d] should be a map or string, got %T", cases[i].Name, j, item)
445 }
446 // Normalize type-as-key format
447 itemMap = datatest.NormalizeTypeAsKey(itemMap)
448 }
449 if err := datatest.UnmarshalStruct(&cases[i].WantTokens[j], itemMap); err != nil {
450 return nil, fmt.Errorf("test %s: want[%d]: %w", cases[i].Name, j, err)
451 }
452 }
453 }
454 }
455
456 // Post-process: convert Want to WantContains for emit tests
457 switch cases[i].Type {
458 case "emit", "emit-config", "roundtrip", "emit-writer":
459 if cases[i].Want != nil {
460 switch v := cases[i].Want.(type) {
461 case string:
462 // Scalar want value
463 cases[i].WantContains = []string{v}
464 case []any:
465 // Sequence want values
466 for _, item := range v {
467 if str, ok := item.(string); ok {
468 cases[i].WantContains = append(cases[i].WantContains, str)
469 }
470 }
471 }
472 }
473 }
474 }
475
476 return cases, nil
477 }
478
479 // ParseEventType converts a string to EventType
480 func ParseEventType(t *testing.T, s string) EventType {
481 t.Helper()
482 switch s {
483 case "NO_EVENT":
484 return NO_EVENT
485 case "STREAM_START_EVENT":
486 return STREAM_START_EVENT
487 case "STREAM_END_EVENT":
488 return STREAM_END_EVENT
489 case "DOCUMENT_START_EVENT":
490 return DOCUMENT_START_EVENT
491 case "DOCUMENT_END_EVENT":
492 return DOCUMENT_END_EVENT
493 case "ALIAS_EVENT":
494 return ALIAS_EVENT
495 case "SCALAR_EVENT":
496 return SCALAR_EVENT
497 case "SEQUENCE_START_EVENT":
498 return SEQUENCE_START_EVENT
499 case "SEQUENCE_END_EVENT":
500 return SEQUENCE_END_EVENT
501 case "MAPPING_START_EVENT":
502 return MAPPING_START_EVENT
503 case "MAPPING_END_EVENT":
504 return MAPPING_END_EVENT
505 default:
506 t.Fatalf("unknown event type: %s", s)
507 return NO_EVENT
508 }
509 }
510
511 // ParseTokenType converts a string to TokenType
512 func ParseTokenType(t *testing.T, s string) TokenType {
513 t.Helper()
514 switch s {
515 case "NO_TOKEN":
516 return NO_TOKEN
517 case "STREAM_START_TOKEN":
518 return STREAM_START_TOKEN
519 case "STREAM_END_TOKEN":
520 return STREAM_END_TOKEN
521 case "VERSION_DIRECTIVE_TOKEN":
522 return VERSION_DIRECTIVE_TOKEN
523 case "TAG_DIRECTIVE_TOKEN":
524 return TAG_DIRECTIVE_TOKEN
525 case "DOCUMENT_START_TOKEN":
526 return DOCUMENT_START_TOKEN
527 case "DOCUMENT_END_TOKEN":
528 return DOCUMENT_END_TOKEN
529 case "BLOCK_SEQUENCE_START_TOKEN":
530 return BLOCK_SEQUENCE_START_TOKEN
531 case "BLOCK_MAPPING_START_TOKEN":
532 return BLOCK_MAPPING_START_TOKEN
533 case "BLOCK_END_TOKEN":
534 return BLOCK_END_TOKEN
535 case "FLOW_SEQUENCE_START_TOKEN":
536 return FLOW_SEQUENCE_START_TOKEN
537 case "FLOW_SEQUENCE_END_TOKEN":
538 return FLOW_SEQUENCE_END_TOKEN
539 case "FLOW_MAPPING_START_TOKEN":
540 return FLOW_MAPPING_START_TOKEN
541 case "FLOW_MAPPING_END_TOKEN":
542 return FLOW_MAPPING_END_TOKEN
543 case "BLOCK_ENTRY_TOKEN":
544 return BLOCK_ENTRY_TOKEN
545 case "FLOW_ENTRY_TOKEN":
546 return FLOW_ENTRY_TOKEN
547 case "KEY_TOKEN":
548 return KEY_TOKEN
549 case "VALUE_TOKEN":
550 return VALUE_TOKEN
551 case "ALIAS_TOKEN":
552 return ALIAS_TOKEN
553 case "ANCHOR_TOKEN":
554 return ANCHOR_TOKEN
555 case "TAG_TOKEN":
556 return TAG_TOKEN
557 case "SCALAR_TOKEN":
558 return SCALAR_TOKEN
559 default:
560 t.Fatalf("unknown token type: %s", s)
561 return NO_TOKEN
562 }
563 }
564
565 // ParseEncoding converts a string to Encoding
566 func ParseEncoding(t *testing.T, s string) Encoding {
567 t.Helper()
568 switch s {
569 case "ANY_ENCODING":
570 return ANY_ENCODING
571 case "UTF8_ENCODING":
572 return UTF8_ENCODING
573 case "UTF16LE_ENCODING":
574 return UTF16LE_ENCODING
575 case "UTF16BE_ENCODING":
576 return UTF16BE_ENCODING
577 default:
578 t.Fatalf("unknown encoding: %s", s)
579 return ANY_ENCODING
580 }
581 }
582
583 // ParseScalarStyle converts a string to ScalarStyle
584 func ParseScalarStyle(t *testing.T, s string) ScalarStyle {
585 t.Helper()
586 switch s {
587 case "ANY_SCALAR_STYLE":
588 return ANY_SCALAR_STYLE
589 case "PLAIN_SCALAR_STYLE":
590 return PLAIN_SCALAR_STYLE
591 case "SINGLE_QUOTED_SCALAR_STYLE":
592 return SINGLE_QUOTED_SCALAR_STYLE
593 case "DOUBLE_QUOTED_SCALAR_STYLE":
594 return DOUBLE_QUOTED_SCALAR_STYLE
595 case "LITERAL_SCALAR_STYLE":
596 return LITERAL_SCALAR_STYLE
597 case "FOLDED_SCALAR_STYLE":
598 return FOLDED_SCALAR_STYLE
599 default:
600 t.Fatalf("unknown scalar style: %s", s)
601 return ANY_SCALAR_STYLE
602 }
603 }
604
605 // ParseSequenceStyle converts a string to SequenceStyle
606 func ParseSequenceStyle(t *testing.T, s string) SequenceStyle {
607 t.Helper()
608 switch s {
609 case "ANY_SEQUENCE_STYLE":
610 return ANY_SEQUENCE_STYLE
611 case "BLOCK_SEQUENCE_STYLE":
612 return BLOCK_SEQUENCE_STYLE
613 case "FLOW_SEQUENCE_STYLE":
614 return FLOW_SEQUENCE_STYLE
615 default:
616 t.Fatalf("unknown sequence style: %s", s)
617 return ANY_SEQUENCE_STYLE
618 }
619 }
620
621 // ParseMappingStyle converts a string to MappingStyle
622 func ParseMappingStyle(t *testing.T, s string) MappingStyle {
623 t.Helper()
624 switch s {
625 case "ANY_MAPPING_STYLE":
626 return ANY_MAPPING_STYLE
627 case "BLOCK_MAPPING_STYLE":
628 return BLOCK_MAPPING_STYLE
629 case "FLOW_MAPPING_STYLE":
630 return FLOW_MAPPING_STYLE
631 default:
632 t.Fatalf("unknown mapping style: %s", s)
633 return ANY_MAPPING_STYLE
634 }
635 }
636
637 // CreateEventFromSpec creates an Event from an EventSpec
638 func CreateEventFromSpec(t *testing.T, spec EventSpec) Event {
639 t.Helper()
640 eventType := ParseEventType(t, spec.Type)
641
642 switch eventType {
643 case STREAM_START_EVENT:
644 encoding := UTF8_ENCODING
645 if spec.Encoding != "" {
646 encoding = ParseEncoding(t, spec.Encoding)
647 }
648 return NewStreamStartEvent(encoding)
649
650 case STREAM_END_EVENT:
651 return NewStreamEndEvent()
652
653 case DOCUMENT_START_EVENT:
654 var vd *VersionDirective
655 if spec.VersionDirective != nil {
656 vd = &VersionDirective{
657 major: int8(spec.VersionDirective.Major),
658 minor: int8(spec.VersionDirective.Minor),
659 }
660 }
661 var td []TagDirective
662 for _, tagSpec := range spec.TagDirectives {
663 td = append(td, TagDirective{
664 handle: []byte(tagSpec.Handle),
665 prefix: []byte(tagSpec.Prefix),
666 })
667 }
668 return NewDocumentStartEvent(vd, td, spec.Implicit)
669
670 case DOCUMENT_END_EVENT:
671 return NewDocumentEndEvent(spec.Implicit)
672
673 case ALIAS_EVENT:
674 return NewAliasEvent([]byte(spec.Anchor))
675
676 case SCALAR_EVENT:
677 style := PLAIN_SCALAR_STYLE
678 if spec.Style != "" {
679 style = ParseScalarStyle(t, spec.Style)
680 }
681 return NewScalarEvent(
682 []byte(spec.Anchor),
683 []byte(spec.Tag),
684 []byte(spec.Value),
685 spec.Implicit,
686 spec.QuotedImplicit,
687 style,
688 )
689
690 case SEQUENCE_START_EVENT:
691 style := BLOCK_SEQUENCE_STYLE
692 if spec.Style != "" {
693 style = ParseSequenceStyle(t, spec.Style)
694 }
695 return NewSequenceStartEvent(
696 []byte(spec.Anchor),
697 []byte(spec.Tag),
698 spec.Implicit,
699 style,
700 )
701
702 case SEQUENCE_END_EVENT:
703 return NewSequenceEndEvent()
704
705 case MAPPING_START_EVENT:
706 style := BLOCK_MAPPING_STYLE
707 if spec.Style != "" {
708 style = ParseMappingStyle(t, spec.Style)
709 }
710 return NewMappingStartEvent(
711 []byte(spec.Anchor),
712 []byte(spec.Tag),
713 spec.Implicit,
714 style,
715 )
716
717 case MAPPING_END_EVENT:
718 return NewMappingEndEvent()
719
720 default:
721 t.Fatalf("unsupported event type: %v", eventType)
722 return Event{}
723 }
724 }
725
726 // HexToBytes converts a hex string to bytes
727 // HexToBytes is now provided by the shared datatest package
728 var HexToBytes = datatest.HexToBytes
729
730 // GetField is now provided by the shared datatest package
731 var GetField = datatest.GetField
732
733 // CreateArgValue creates a value from an ArgSpec
734 func CreateArgValue(t *testing.T, spec ArgSpec) any {
735 t.Helper()
736 if spec.Bytes != "" {
737 return []byte(spec.Bytes)
738 }
739 if spec.String != "" {
740 if spec.Reader {
741 return bytes.NewReader([]byte(spec.String))
742 }
743 return spec.String
744 }
745 if spec.Hex != "" {
746 return HexToBytes(t, spec.Hex)
747 }
748 if spec.Writer {
749 return new(bytes.Buffer)
750 }
751 // Default to the first non-zero value
752 if spec.Int != 0 {
753 return spec.Int
754 }
755 if spec.Bool {
756 return spec.Bool
757 }
758 return nil
759 }
760
761 // CallMethod is now provided by the shared datatest package
762 var CallMethod = datatest.CallMethod
763
764 // CreateObject creates an object using a constructor function
765 func CreateObject(t *testing.T, constructorName string) any {
766 t.Helper()
767 switch constructorName {
768 case "NewParser":
769 return NewParser()
770 case "NewEmitter":
771 return NewEmitter()
772 default:
773 t.Fatalf("unknown constructor: %s", constructorName)
774 return nil
775 }
776 }
777
778 // emitEvents is a helper to emit events and return the output
779 func emitEvents(events []Event) (string, error) {
780 emitter := NewEmitter()
781 var output []byte
782 emitter.SetOutputString(&output)
783
784 for i := range events {
785 if err := emitter.Emit(&events[i]); err != nil {
786 return "", err
787 }
788 }
789
790 return string(output), nil
791 }
792
793 // parseEvents is a helper to parse input and return event types
794 func parseEvents(input string) ([]EventType, bool) {
795 parser := NewParser()
796 parser.SetInputString([]byte(input))
797
798 var types []EventType
799 for {
800 var event Event
801 if err := parser.Parse(&event); err != nil {
802 if errors.Is(err, io.EOF) {
803 return types, true
804 }
805 return nil, false
806 }
807 types = append(types, event.Type)
808 if event.Type == STREAM_END_EVENT {
809 break
810 }
811 }
812 return types, true
813 }
814
815 // parseEventsDetailed is a helper to parse input and return full events
816 func parseEventsDetailed(input string) ([]Event, bool) {
817 parser := NewParser()
818 parser.SetInputString([]byte(input))
819
820 var events []Event
821 for {
822 var event Event
823 if err := parser.Parse(&event); err != nil {
824 if errors.Is(err, io.EOF) {
825 return events, true
826 }
827 return nil, false
828 }
829 events = append(events, event)
830 if event.Type == STREAM_END_EVENT {
831 break
832 }
833 }
834 return events, true
835 }
836
837 // scanTokens is a helper to scan input and return token types
838 func scanTokens(input string) ([]TokenType, bool) {
839 parser := NewParser()
840 parser.SetInputString([]byte(input))
841
842 var types []TokenType
843 for {
844 var token Token
845 if err := parser.Scan(&token); err != nil {
846 if errors.Is(err, io.EOF) {
847 return types, true
848 }
849 return nil, false
850 }
851 types = append(types, token.Type)
852 if token.Type == STREAM_END_TOKEN {
853 break
854 }
855 }
856 return types, true
857 }
858
859 // scanTokensDetailed is a helper to scan input and return full tokens
860 func scanTokensDetailed(input string) ([]Token, bool) {
861 parser := NewParser()
862 parser.SetInputString([]byte(input))
863
864 var tokens []Token
865 for {
866 var token Token
867 if err := parser.Scan(&token); err != nil {
868 if errors.Is(err, io.EOF) {
869 return tokens, true
870 }
871 return nil, false
872 }
873 tokens = append(tokens, token)
874 if token.Type == STREAM_END_TOKEN {
875 break
876 }
877 }
878 return tokens, true
879 }
880
881 // ConfigureEmitter configures an emitter from an EmitterConfig
882 func ConfigureEmitter(emitter *Emitter, config EmitterConfig) {
883 if config.Canonical {
884 emitter.SetCanonical(true)
885 }
886 if config.Indent > 0 {
887 emitter.SetIndent(config.Indent)
888 }
889 if config.Width != 0 {
890 emitter.SetWidth(config.Width)
891 }
892 if config.Unicode {
893 emitter.SetUnicode(true)
894 }
895 if config.LineBreak != "" {
896 // Parse line break style if needed
897 switch config.LineBreak {
898 case "LN":
899 emitter.SetLineBreak(LN_BREAK)
900 case "CR":
901 emitter.SetLineBreak(CR_BREAK)
902 case "CRLF":
903 emitter.SetLineBreak(CRLN_BREAK)
904 }
905 }
906 }
907
908 // RunEmitTest runs an emit test case
909 func RunEmitTest(t *testing.T, tc TestCase) {
910 t.Helper()
911
912 var events []Event
913 for _, eventSpec := range tc.Events {
914 events = append(events, CreateEventFromSpec(t, eventSpec))
915 }
916
917 var output []byte
918 var emitter *Emitter
919
920 if tc.Type == "emit-config" {
921 e := NewEmitter()
922 emitter = &e
923 emitter.SetOutputString(&output)
924 ConfigureEmitter(emitter, tc.Config)
925
926 for i := range events {
927 err := emitter.Emit(&events[i])
928 assert.NoErrorf(t, err, "Emit() error: %v", err)
929 }
930 } else {
931 result, err := emitEvents(events)
932 assert.NoErrorf(t, err, "emitEvents() error: %v", err)
933 output = []byte(result)
934 }
935
936 for _, expected := range tc.WantContains {
937 assert.Truef(t, bytes.Contains(output, []byte(expected)),
938 "output should contain %q, got %q", expected, string(output))
939 }
940 }
941
942 // RunRoundTripTest runs a roundtrip test case
943 func RunRoundTripTest(t *testing.T, tc TestCase) {
944 t.Helper()
945
946 parser := NewParser()
947 parser.SetInputString([]byte(tc.Yaml))
948
949 var events []Event
950 for {
951 var event Event
952 if err := parser.Parse(&event); err != nil {
953 break
954 }
955 events = append(events, event)
956 if event.Type == STREAM_END_EVENT {
957 break
958 }
959 }
960
961 emitter := NewEmitter()
962 var output []byte
963 emitter.SetOutputString(&output)
964
965 for i := range events {
966 err := emitter.Emit(&events[i])
967 assert.NoErrorf(t, err, "Emit() error: %v", err)
968 }
969
970 result := string(output)
971 for _, expected := range tc.WantContains {
972 assert.Truef(t, bytes.Contains(output, []byte(expected)),
973 "output should contain %q, got %q", expected, result)
974 }
975 }
976
977 // GetWriter extracts an [io.Writer] from an interface value
978 func GetWriter(t *testing.T, v any) io.Writer {
979 t.Helper()
980 if w, ok := v.(io.Writer); ok {
981 return w
982 }
983 t.Fatalf("value is not an io.Writer: %T", v)
984 return nil
985 }
986
987 // GetReader extracts an [io.Reader] from an interface value
988 func GetReader(t *testing.T, v any) io.Reader {
989 t.Helper()
990 if r, ok := v.(io.Reader); ok {
991 return r
992 }
993 t.Fatalf("value is not an io.Reader: %T", v)
994 return nil
995 }
996
997 // TestHandler is a function that runs a specific test type
998 type TestHandler func(*testing.T, TestCase)
999
1000 // RunTestCases loads test cases from a YAML file and runs them using the provided handlers
1001 func RunTestCases(t *testing.T, filename string, handlers map[string]TestHandler) {
1002 t.Helper()
1003 cases, err := LoadTestCases(filename)
1004 assert.NoErrorf(t, err, "Failed to load test cases: %v", err)
1005
1006 for _, tc := range cases {
1007 tc := tc
1008 t.Run(tc.Name, func(t *testing.T) {
1009 handler, ok := handlers[tc.Type]
1010 if !ok {
1011 t.Fatalf("unknown test type: %s", tc.Type)
1012 }
1013 handler(t, tc)
1014 })
1015 }
1016 }
1017
1018 // WantBool extracts a bool from tc.Want, returning defaultVal if Want is nil
1019 // WantBool is now provided by the shared datatest package
1020 var WantBool = datatest.WantBool
1021
1022 // API test handlers
1023 // These test runner functions are used by both parser and emitter tests
1024
1025 func runAPINewTest(t *testing.T, tc TestCase) {
1026 t.Helper()
1027
1028 obj := createObject(t, tc.Constructor)
1029 runFieldChecks(t, obj, tc.Checks)
1030 }
1031
1032 func runAPIMethodTest(t *testing.T, tc TestCase) {
1033 t.Helper()
1034
1035 obj := createObject(t, tc.Constructor)
1036
1037 // Run setup if any
1038 if tc.Setup != nil {
1039 if setupList, ok := tc.Setup.([]any); ok && len(setupList) > 0 {
1040 callMethodFromList(t, obj, setupList, tc.Bytes)
1041 }
1042 }
1043
1044 // Call the main method
1045 callMethodFromList(t, obj, tc.Method, tc.Bytes)
1046
1047 // Run checks
1048 runFieldChecks(t, obj, tc.Checks)
1049 }
1050
1051 func runAPIPanicTest(t *testing.T, tc TestCase) {
1052 t.Helper()
1053
1054 obj := createObject(t, tc.Constructor)
1055
1056 // Run setup if any
1057 if tc.Setup != nil {
1058 if setupList, ok := tc.Setup.([]any); ok && len(setupList) > 0 {
1059 callMethodFromList(t, obj, setupList, tc.Bytes)
1060 }
1061 }
1062
1063 // The main method call should panic
1064 // Want can be either a string or a single-element sequence
1065 var wantMsg string
1066 switch v := tc.Want.(type) {
1067 case string:
1068 wantMsg = v
1069 case []any:
1070 if len(v) > 0 {
1071 msg, ok := v[0].(string)
1072 assert.Truef(t, ok, "Want[0] should be string, got %T", v[0])
1073 wantMsg = msg
1074 } else {
1075 t.Fatalf("Want slice is empty, expected at least one element")
1076 }
1077 default:
1078 t.Fatalf("want must be a string or sequence, got %T", tc.Want)
1079 }
1080 assert.PanicMatchesf(t, wantMsg, func() {
1081 callMethodFromList(t, obj, tc.Method, tc.Bytes)
1082 }, "Expected panic: %s", wantMsg)
1083 }
1084
1085 func runAPIDeleteTest(t *testing.T, tc TestCase) {
1086 t.Helper()
1087
1088 obj := createObject(t, tc.Constructor)
1089
1090 // Run setup if any
1091 if tc.Setup != nil {
1092 if setupList, ok := tc.Setup.([]any); ok && len(setupList) > 0 {
1093 callMethodFromList(t, obj, setupList, tc.Bytes)
1094 }
1095 }
1096
1097 // Call Delete method
1098 callMethodFromList(t, obj, []any{"Delete"}, false)
1099
1100 // Run checks after delete
1101 runFieldChecks(t, obj, tc.Checks)
1102 }
1103
1104 func runAPINewEventTest(t *testing.T, tc TestCase) {
1105 t.Helper()
1106
1107 event := createEventFromList(t, tc.Method, tc.Bytes)
1108 runFieldChecks(t, &event, tc.Checks)
1109 }
1110
1111 // API test helper functions
1112 // These functions support both parser and emitter API tests
1113
1114 // createObject creates a Parser or Emitter based on constructor name
1115 func createObject(t *testing.T, constructor string) any {
1116 t.Helper()
1117 switch constructor {
1118 case "NewParser":
1119 p := NewParser()
1120 return &p
1121 case "NewEmitter":
1122 e := NewEmitter()
1123 return &e
1124 default:
1125 t.Fatalf("unknown constructor: %s", constructor)
1126 }
1127 return nil
1128 }
1129
1130 // createEventFromList creates an Event from a method list [constructor, args...]
1131 func createEventFromList(t *testing.T, methodList []any, useBytes bool) Event {
1132 t.Helper()
1133 if len(methodList) == 0 {
1134 t.Fatalf("empty method list")
1135 }
1136
1137 constructor, ok := methodList[0].(string)
1138 if !ok {
1139 t.Fatalf("constructor should be string, got %T", methodList[0])
1140 }
1141 args := methodList[1:]
1142
1143 switch constructor {
1144 case "NewStreamStartEvent":
1145 if len(args) != 1 {
1146 t.Fatalf("%s expects 1 argument, got %d", constructor, len(args))
1147 }
1148 encoding := parseArg(t, args[0])
1149 return NewStreamStartEvent(Encoding(encoding))
1150 case "NewStreamEndEvent":
1151 if len(args) != 0 {
1152 t.Fatalf("%s expects 0 arguments, got %d", constructor, len(args))
1153 }
1154 return NewStreamEndEvent()
1155 case "NewDocumentEndEvent":
1156 if len(args) != 1 {
1157 t.Fatalf("%s expects 1 argument, got %d", constructor, len(args))
1158 }
1159 implicit := parseBoolArg(t, args[0])
1160 return NewDocumentEndEvent(implicit)
1161 case "NewAliasEvent":
1162 if len(args) != 1 {
1163 t.Fatalf("%s expects 1 argument, got %d", constructor, len(args))
1164 }
1165 anchor := parseStringArg(t, args[0], useBytes)
1166 return NewAliasEvent([]byte(anchor))
1167 case "NewSequenceEndEvent":
1168 if len(args) != 0 {
1169 t.Fatalf("%s expects 0 arguments, got %d", constructor, len(args))
1170 }
1171 return NewSequenceEndEvent()
1172 case "NewMappingEndEvent":
1173 if len(args) != 0 {
1174 t.Fatalf("%s expects 0 arguments, got %d", constructor, len(args))
1175 }
1176 return NewMappingEndEvent()
1177 default:
1178 t.Fatalf("unknown event constructor: %s", constructor)
1179 }
1180 return Event{}
1181 }
1182
1183 // callMethodFromList calls a method from a list [methodName, args...]
1184 func callMethodFromList(t *testing.T, obj any, methodList []any, useBytes bool) {
1185 t.Helper()
1186 if len(methodList) == 0 {
1187 t.Fatalf("empty method list")
1188 }
1189
1190 methodName, ok := methodList[0].(string)
1191 if !ok {
1192 t.Fatalf("method name should be string, got %T", methodList[0])
1193 }
1194 args := methodList[1:]
1195
1196 v := reflect.ValueOf(obj)
1197 if v.Kind() == reflect.Ptr {
1198 v = v.Elem()
1199 }
1200
1201 m := v.Addr().MethodByName(methodName)
1202 if !m.IsValid() {
1203 t.Fatalf("method not found: %s", methodName)
1204 }
1205
1206 methodType := m.Type()
1207 numParams := methodType.NumIn()
1208
1209 // Validate argument count
1210 if len(args) != numParams {
1211 t.Fatalf("method %s expects %d arguments, got %d", methodName, numParams, len(args))
1212 }
1213
1214 // Build argument list
1215 var callArgs []reflect.Value
1216 for i, arg := range args {
1217 paramType := methodType.In(i)
1218
1219 // Handle different parameter types
1220 if paramType.Kind() == reflect.Bool {
1221 val := parseBoolArg(t, arg)
1222 callArgs = append(callArgs, reflect.ValueOf(val))
1223 } else if paramType.Kind() == reflect.Slice && paramType.Elem().Kind() == reflect.Uint8 {
1224 // Byte slice parameter
1225 str := parseStringArg(t, arg, useBytes)
1226 callArgs = append(callArgs, reflect.ValueOf([]byte(str)))
1227 } else {
1228 // Try parsing as constant/int
1229 val := parseArg(t, arg)
1230 convertedVal := reflect.ValueOf(val).Convert(paramType)
1231 callArgs = append(callArgs, convertedVal)
1232 }
1233 }
1234
1235 // Call the method
1236 m.Call(callArgs)
1237 }
1238
1239 // parseArg parses an argument which could be int, bool, or string constant
1240 func parseArg(t *testing.T, arg any) int {
1241 t.Helper()
1242 switch v := arg.(type) {
1243 case int:
1244 return v
1245 case string:
1246 if looksLikeConstant(v) {
1247 return parseConstant(t, v)
1248 }
1249 // Try parsing as int
1250 if val, err := strconv.Atoi(v); err == nil {
1251 return val
1252 }
1253 t.Fatalf("cannot parse arg as int: %v", arg)
1254 default:
1255 t.Fatalf("unsupported arg type: %T", arg)
1256 }
1257 return 0
1258 }
1259
1260 // parseBoolArg parses a boolean argument
1261 func parseBoolArg(t *testing.T, arg any) bool {
1262 t.Helper()
1263 switch v := arg.(type) {
1264 case bool:
1265 return v
1266 case string:
1267 switch v {
1268 case "true":
1269 return true
1270 case "false":
1271 return false
1272 default:
1273 t.Fatalf("cannot parse string as bool (expected 'true' or 'false'): %q", v)
1274 }
1275 default:
1276 t.Fatalf("cannot parse arg as bool: %v (type %T)", arg, arg)
1277 }
1278 return false
1279 }
1280
1281 // parseStringArg parses a string argument
1282 func parseStringArg(t *testing.T, arg any, useBytes bool) string {
1283 t.Helper()
1284 switch v := arg.(type) {
1285 case string:
1286 return v
1287 default:
1288 t.Fatalf("cannot parse arg as string: %v (type %T)", arg, arg)
1289 }
1290 return ""
1291 }
1292
1293 // looksLikeConstant checks if a string looks like a constant name
1294 func looksLikeConstant(s string) bool {
1295 if len(s) == 0 {
1296 return false
1297 }
1298 // Check if it's all uppercase letters, digits, and underscores
1299 for _, c := range s {
1300 if !((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_') {
1301 return false
1302 }
1303 }
1304 return true
1305 }
1306
1307 // parseConstant parses a constant name to its integer value
1308 func parseConstant(t *testing.T, name string) int {
1309 t.Helper()
1310 // Handle boolean values
1311 if name == "true" {
1312 return 1
1313 }
1314 if name == "false" {
1315 return 0
1316 }
1317
1318 // Try parsing as int first
1319 if val, err := strconv.Atoi(name); err == nil {
1320 return val
1321 }
1322
1323 // Use IntOrStr to parse other constants
1324 ios := IntOrStr{}
1325 err := ios.FromValue(name)
1326 if err != nil {
1327 t.Fatalf("failed to parse constant %q: %v", name, err)
1328 }
1329 return ios.Value
1330 }
1331
1332 // hasLength checks if a slice has exactly the expected length
1333 // Returns true if length matches, false if empty, and fails fatally otherwise
1334 func hasLength(t *testing.T, slice []any, expected int) bool {
1335 t.Helper()
1336 if len(slice) == 0 {
1337 return false
1338 }
1339 if len(slice) != expected {
1340 t.Fatalf("expected exactly %d args, got %d", expected, len(slice))
1341 }
1342 return true
1343 }
1344
1345 // runFieldChecks runs field checks on an object
1346 func runFieldChecks(t *testing.T, obj any, checks []FieldCheck) {
1347 t.Helper()
1348
1349 v := reflect.ValueOf(obj)
1350 if v.Kind() == reflect.Ptr {
1351 v = v.Elem()
1352 }
1353
1354 for _, check := range checks {
1355 // Handle nil checks
1356 if hasLength(t, check.Nil, 2) {
1357 fieldName, ok := check.Nil[0].(string)
1358 if !ok {
1359 t.Fatalf("Nil[0] should be string, got %T", check.Nil[0])
1360 }
1361 wantNil, ok := check.Nil[1].(bool)
1362 if !ok {
1363 t.Fatalf("Nil[1] should be bool, got %T", check.Nil[1])
1364 }
1365 field := getField(t, v, fieldName)
1366 if field.IsValid() {
1367 isNil := field.IsNil()
1368 if wantNil != isNil {
1369 if wantNil {
1370 t.Errorf("%s should be nil", fieldName)
1371 } else {
1372 t.Errorf("%s should not be nil", fieldName)
1373 }
1374 }
1375 }
1376 }
1377
1378 // Handle cap checks
1379 if hasLength(t, check.Cap, 2) {
1380 fieldName, ok := check.Cap[0].(string)
1381 if !ok {
1382 t.Fatalf("Cap[0] should be string, got %T", check.Cap[0])
1383 }
1384 wantCap, ok := check.Cap[1].(int)
1385 if !ok {
1386 t.Fatalf("Cap[1] should be int, got %T", check.Cap[1])
1387 }
1388 field := getField(t, v, fieldName)
1389 if field.IsValid() && wantCap > 0 {
1390 if field.Cap() != wantCap {
1391 t.Errorf("%s cap = %d, want %d", fieldName, field.Cap(), wantCap)
1392 }
1393 }
1394 }
1395
1396 // Handle len checks
1397 if hasLength(t, check.Len, 2) {
1398 fieldName, ok := check.Len[0].(string)
1399 if !ok {
1400 t.Fatalf("Len[0] should be string, got %T", check.Len[0])
1401 }
1402 wantLen, ok := check.Len[1].(int)
1403 if !ok {
1404 t.Fatalf("Len[1] should be int, got %T", check.Len[1])
1405 }
1406 field := getField(t, v, fieldName)
1407 if field.IsValid() && wantLen > 0 {
1408 if field.Len() != wantLen {
1409 t.Errorf("%s len = %d, want %d", fieldName, field.Len(), wantLen)
1410 }
1411 }
1412 }
1413
1414 // Handle len-gt checks
1415 if hasLength(t, check.LenGt, 2) {
1416 fieldName, ok := check.LenGt[0].(string)
1417 if !ok {
1418 t.Fatalf("LenGt[0] should be string, got %T", check.LenGt[0])
1419 }
1420 minLen, ok := check.LenGt[1].(int)
1421 if !ok {
1422 t.Fatalf("LenGt[1] should be int, got %T", check.LenGt[1])
1423 }
1424 field := getField(t, v, fieldName)
1425 if field.IsValid() && minLen > 0 {
1426 if field.Len() <= minLen {
1427 t.Errorf("%s len = %d, want > %d", fieldName, field.Len(), minLen)
1428 }
1429 }
1430 }
1431
1432 // Handle eq checks
1433 if hasLength(t, check.Eq, 2) {
1434 fieldName, ok := check.Eq[0].(string)
1435 if !ok {
1436 t.Fatalf("Eq[0] should be string, got %T", check.Eq[0])
1437 }
1438 expectedValue := check.Eq[1]
1439 checkEqual(t, v, fieldName, expectedValue)
1440 }
1441
1442 // Handle gte checks
1443 if hasLength(t, check.Gte, 2) {
1444 fieldName, ok := check.Gte[0].(string)
1445 if !ok {
1446 t.Fatalf("Gte[0] should be string, got %T", check.Gte[0])
1447 }
1448 minValue, ok := check.Gte[1].(int)
1449 if !ok {
1450 t.Fatalf("Gte[1] should be int, got %T", check.Gte[1])
1451 }
1452 field := getField(t, v, fieldName)
1453 if field.IsValid() {
1454 got := getIntValue(t, field, fieldName)
1455 if got < minValue {
1456 t.Errorf("%s = %d, want >= %d", fieldName, got, minValue)
1457 }
1458 }
1459 }
1460 }
1461 }
1462
1463 // getField retrieves a field from a struct, handling special field names
1464 func getField(t *testing.T, v reflect.Value, fieldName string) reflect.Value {
1465 t.Helper()
1466
1467 // Handle special field names like buffer-0, buffer-1
1468 if strings.HasPrefix(fieldName, "buffer-") {
1469 var bufferIndex int
1470 _, err := fmt.Sscanf(fieldName, "buffer-%d", &bufferIndex)
1471 if err == nil {
1472 // Validate that buffer index is non-negative
1473 if bufferIndex < 0 {
1474 t.Fatalf("invalid buffer index: %s (index must be non-negative)", fieldName)
1475 }
1476 // Return invalid value - buffer index checks are handled separately
1477 return reflect.Value{}
1478 }
1479 }
1480
1481 // Convert hyphenated YAML key to underscored Go field name
1482 goFieldName := strings.ReplaceAll(fieldName, "-", "_")
1483 field := v.FieldByName(goFieldName)
1484 if !field.IsValid() {
1485 t.Fatalf("field not found: %s (looking for %s)", fieldName, goFieldName)
1486 }
1487 return field
1488 }
1489
1490 // getIntValue extracts an integer value from a field
1491 func getIntValue(t *testing.T, field reflect.Value, fieldName string) int {
1492 t.Helper()
1493
1494 // Use reflection Kind() instead of type assertions
1495 switch field.Kind() {
1496 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
1497 return int(field.Int())
1498 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
1499 return int(field.Uint())
1500 default:
1501 t.Fatalf("%s: expected numeric field, got %s", fieldName, field.Kind())
1502 }
1503 return 0
1504 }
1505
1506 // checkEqual performs an equality check on a field
1507 func checkEqual(t *testing.T, v reflect.Value, fieldName string, expectedValue any) {
1508 t.Helper()
1509
1510 // Handle buffer-N special case
1511 var bufferIndex int
1512 isBufferIndex := false
1513 if strings.HasPrefix(fieldName, "buffer-") {
1514 _, err := fmt.Sscanf(fieldName, "buffer-%d", &bufferIndex)
1515 if err == nil {
1516 // Validate that buffer index is non-negative
1517 if bufferIndex < 0 {
1518 t.Fatalf("invalid buffer index: %s (index must be non-negative)", fieldName)
1519 }
1520 isBufferIndex = true
1521 }
1522 }
1523
1524 var field reflect.Value
1525 if isBufferIndex {
1526 field = v.FieldByName("buffer")
1527 if !field.IsValid() {
1528 t.Fatalf("buffer field not found for %s", fieldName)
1529 }
1530 // Check specific byte in buffer
1531 if field.Kind() == reflect.Slice && field.Type().Elem().Kind() == reflect.Uint8 {
1532 if bufferIndex >= field.Len() {
1533 t.Errorf("%s: index %d out of range (buffer len=%d)", fieldName, bufferIndex, field.Len())
1534 return
1535 }
1536 got := int(field.Index(bufferIndex).Uint())
1537 expected := expectedValue
1538 if str, ok := expectedValue.(string); ok && looksLikeConstant(str) {
1539 expected = parseConstant(t, str)
1540 } else if intVal, ok := expectedValue.(int); ok {
1541 expected = intVal
1542 }
1543 if got != expected {
1544 t.Errorf("%s = %v, want %v", fieldName, got, expected)
1545 }
1546 return
1547 } else {
1548 t.Errorf("%s: buffer field is not a byte slice", fieldName)
1549 return
1550 }
1551 }
1552
1553 field = getField(t, v, fieldName)
1554 if !field.IsValid() {
1555 return
1556 }
1557
1558 // Parse constant if it's a string that looks like a constant name
1559 var expectedInt int
1560 var hasExpectedInt bool
1561 expected := expectedValue
1562 if str, ok := expectedValue.(string); ok && looksLikeConstant(str) {
1563 expectedInt = parseConstant(t, str)
1564 hasExpectedInt = true
1565 } else if intVal, ok := expectedValue.(int); ok {
1566 expectedInt = intVal
1567 hasExpectedInt = true
1568 }
1569
1570 // Get value based on type (handle unexported fields)
1571 var got any
1572
1573 if field.CanInterface() {
1574 // For exported fields, convert expected to field's type
1575 if hasExpectedInt {
1576 expected = reflect.ValueOf(expectedInt).Convert(field.Type()).Interface()
1577 }
1578 got = field.Interface()
1579
1580 // Handle byte slice comparison
1581 if field.Type().Kind() == reflect.Slice && field.Type().Elem().Kind() == reflect.Uint8 {
1582 if str, ok := expected.(string); ok {
1583 expected = []byte(str)
1584 }
1585 }
1586 } else {
1587 // For unexported fields, use type-specific accessors
1588 switch field.Kind() {
1589 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
1590 val := field.Int()
1591 if val > int64(int(^uint(0)>>1)) || val < int64(-int(^uint(0)>>1)-1) {
1592 t.Errorf("field %s value %d overflows int", fieldName, val)
1593 return
1594 }
1595 got = int(val)
1596 if hasExpectedInt {
1597 expected = expectedInt
1598 }
1599 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
1600 val := field.Uint()
1601 if val > uint64(int(^uint(0)>>1)) {
1602 t.Errorf("field %s value %d overflows int", fieldName, val)
1603 return
1604 }
1605 got = int(val)
1606 if hasExpectedInt {
1607 expected = expectedInt
1608 }
1609 case reflect.Bool:
1610 got = field.Bool()
1611 case reflect.String:
1612 got = field.String()
1613 case reflect.Slice:
1614 // Handle byte slice comparison
1615 if field.Type().Elem().Kind() == reflect.Uint8 {
1616 got = field.Bytes()
1617 if str, ok := expected.(string); ok {
1618 expected = []byte(str)
1619 }
1620 }
1621 default:
1622 t.Errorf("cannot compare unexported field %s of kind %s", fieldName, field.Kind())
1623 return
1624 }
1625 }
1626
1627 if !reflect.DeepEqual(got, expected) {
1628 t.Errorf("%s = %v, want %v", fieldName, got, expected)
1629 }
1630 }