Debian Codegraph @

internal/testutil/datatest/loader.go

raw symbols SCIP
1 // Copyright 2025 The go-yaml Project Contributors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Package datatest provides utilities for data-driven testing with YAML test
5 // files.
6 // It extracts and generalizes the testing infrastructure originally from
7 // internal/libyaml.
8 package datatest
9
10 import (
11 "fmt"
12 "os"
13 "reflect"
14 "strings"
15 )
16
17 // LoadYAMLFunc is a function type for loading YAML data.
18 // Different packages can provide their own YAML loading implementation.
19 type LoadYAMLFunc func([]byte) (any, error)
20
21 // LoadTestCasesFromFile loads and normalizes test cases from a YAML file.
22 // It reads the file, parses it with the provided loadYAML function, and normalizes
23 // the type-as-key format to standard format.
24 func LoadTestCasesFromFile(filename string, loadYAML LoadYAMLFunc) ([]map[string]any, error) {
25 data, err := os.ReadFile(filename)
26 if err != nil {
27 return nil, err
28 }
29
30 rawData, err := loadYAML(data)
31 if err != nil {
32 return nil, err
33 }
34
35 rawCases, ok := rawData.([]any)
36 if !ok {
37 return nil, fmt.Errorf("expected []interface{}, got %T", rawData)
38 }
39
40 result := make([]map[string]any, 0, len(rawCases))
41 for _, item := range rawCases {
42 rawCase, ok := item.(map[string]any)
43 if !ok {
44 continue
45 }
46
47 // Normalize type-as-key format: {test-type: {...}} -> {type: test-type, ...}
48 normalized := NormalizeTypeAsKey(rawCase)
49 result = append(result, normalized)
50 }
51
52 return result, nil
53 }
54
55 // UnmarshalStruct populates a struct from a map using reflection and yaml tags.
56 // This function is exported so it can be used by other packages for data-driven testing.
57 //
58 // Example:
59 //
60 // type TestCase struct {
61 // Name string `yaml:"name"`
62 // Data string `yaml:"data"`
63 // }
64 // var tc TestCase
65 // err := datatest.UnmarshalStruct(&tc, map[string]interface{}{
66 // "name": "test1",
67 // "data": "hello",
68 // })
69 func UnmarshalStruct(target any, data map[string]any) error {
70 v := reflect.ValueOf(target)
71 if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct {
72 return fmt.Errorf("target must be pointer to struct, got %T", target)
73 }
74
75 v = v.Elem()
76 t := v.Type()
77
78 // Build map of yaml tag names to field indices (support multiple fields per tag)
79 fieldMap := make(map[string][]int)
80 for i := 0; i < t.NumField(); i++ {
81 field := t.Field(i)
82 yamlTag := field.Tag.Get("yaml")
83 if yamlTag != "" && yamlTag != "-" {
84 // Remove options like ",omitempty"
85 if idx := strings.Index(yamlTag, ","); idx != -1 {
86 yamlTag = yamlTag[:idx]
87 }
88 fieldMap[yamlTag] = append(fieldMap[yamlTag], i)
89 }
90 }
91
92 // Populate fields from map
93 for key, value := range data {
94 fieldIndices, ok := fieldMap[key]
95 if !ok {
96 // Skip unknown fields
97 continue
98 }
99
100 // Try each field with this tag until one succeeds
101 var lastErr error
102 for _, fieldIdx := range fieldIndices {
103 field := v.Field(fieldIdx)
104 if !field.CanSet() {
105 continue
106 }
107
108 if err := setField(field, value); err != nil {
109 lastErr = err
110 continue
111 }
112 // Success, move to next key
113 lastErr = nil
114 break
115 }
116
117 // If all fields failed, return the last error
118 if lastErr != nil {
119 return fmt.Errorf("field %s: %w", key, lastErr)
120 }
121 }
122
123 return nil
124 }
125
126 // setField sets a [reflect.Value] from an interface{} value
127 func setField(field reflect.Value, value any) error {
128 if !field.CanSet() {
129 return fmt.Errorf("field cannot be set")
130 }
131
132 if value == nil {
133 // Set zero value
134 field.Set(reflect.Zero(field.Type()))
135 return nil
136 }
137
138 fieldType := field.Type()
139
140 // Handle custom types with FromValue method (IntOrStr, ByteInput, Args)
141 if field.CanAddr() {
142 addr := field.Addr()
143 if converter, ok := addr.Interface().(interface{ FromValue(any) error }); ok {
144 if err := converter.FromValue(value); err != nil {
145 return err
146 }
147 return nil
148 }
149 }
150
151 // Handle basic types
152 valueRefl := reflect.ValueOf(value)
153 valueType := valueRefl.Type()
154
155 // Direct assignment if types match
156 if valueType.AssignableTo(fieldType) {
157 field.Set(valueRefl)
158 return nil
159 }
160
161 // Check if conversion is possible for compatible types
162 if valueType.ConvertibleTo(fieldType) && valueRefl.CanConvert(fieldType) {
163 field.Set(valueRefl.Convert(fieldType))
164 return nil
165 }
166
167 // Handle conversions
168 switch fieldType.Kind() {
169 case reflect.String:
170 if str, ok := value.(string); ok {
171 field.SetString(str)
172 return nil
173 }
174 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
175 if !field.CanInt() {
176 return fmt.Errorf("field cannot store int values")
177 }
178 if !valueRefl.CanInt() {
179 return fmt.Errorf("field type %v expects an integer value, but got %T", fieldType, value)
180 }
181 i64 := valueRefl.Int()
182 if field.OverflowInt(i64) {
183 return fmt.Errorf("value %v overflows %v", value, fieldType)
184 }
185 field.SetInt(i64)
186 return nil
187 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
188 if !field.CanUint() {
189 return fmt.Errorf("field cannot store uint values")
190 }
191 // Check for negative integers first (most specific error case)
192 if valueRefl.CanInt() && valueRefl.Int() < 0 {
193 return fmt.Errorf("field type %v expects an unsigned integer, but got negative value %v of type %T", fieldType, value, value)
194 }
195 // Then check if value can be converted to uint
196 if !valueRefl.CanUint() {
197 return fmt.Errorf("field type %v expects an unsigned integer value, but got %T", fieldType, value)
198 }
199 u64 := valueRefl.Uint()
200 if field.OverflowUint(u64) {
201 return fmt.Errorf("value %v overflows %v", value, fieldType)
202 }
203 field.SetUint(u64)
204 return nil
205 case reflect.Bool:
206 if valueRefl.Kind() != reflect.Bool {
207 // Check if value can be converted to bool
208 if valueRefl.Type().ConvertibleTo(fieldType) {
209 field.Set(valueRefl.Convert(fieldType))
210 return nil
211 }
212 return fmt.Errorf("field type %v expects a boolean value, but got %T", fieldType, value)
213 }
214 field.SetBool(valueRefl.Bool())
215 return nil
216 case reflect.Float32, reflect.Float64:
217 if !field.CanFloat() {
218 return fmt.Errorf("field cannot store float values")
219 }
220 if !valueRefl.CanFloat() {
221 return fmt.Errorf("field type %v expects a floating-point value, but got %T", fieldType, value)
222 }
223 f64 := valueRefl.Float()
224 if field.OverflowFloat(f64) {
225 return fmt.Errorf("value %f overflows %v", f64, fieldType)
226 }
227 field.SetFloat(f64)
228 return nil
229 case reflect.Slice:
230 return setSliceField(field, value)
231 case reflect.Map:
232 return setMapField(field, value)
233 case reflect.Struct:
234 // Recursively unmarshal nested structs
235 if m, ok := value.(map[string]any); ok {
236 if !field.CanAddr() {
237 return fmt.Errorf("cannot take address of field for nested struct unmarshaling")
238 }
239 return UnmarshalStruct(field.Addr().Interface(), m)
240 }
241 case reflect.Interface:
242 // Just set the value directly
243 field.Set(valueRefl)
244 return nil
245 case reflect.Ptr:
246 // Handle pointer types
247 if fieldType.Elem().Kind() == reflect.Struct {
248 m, ok := value.(map[string]any)
249 if !ok {
250 return fmt.Errorf("expected map for struct pointer, got %T", value)
251 }
252 newStruct := reflect.New(fieldType.Elem())
253 if err := UnmarshalStruct(newStruct.Interface(), m); err != nil {
254 return err
255 }
256 field.Set(newStruct)
257 return nil
258 } else {
259 // Handle pointer to basic types (like *bool, *int, *string)
260 ptr := reflect.New(fieldType.Elem())
261 if err := setField(ptr.Elem(), value); err != nil {
262 return err
263 }
264 field.Set(ptr)
265 return nil
266 }
267 }
268
269 return fmt.Errorf("cannot convert %T to %v", value, fieldType)
270 }
271
272 // NormalizeTypeAsKey converts maps with type as key to standard format.
273 // Example: {"SCALAR_TOKEN": {"value": "x"}} -> {"type": "SCALAR_TOKEN", "value": "x"}
274 // This function is exported so it can be used by test code that needs to normalize
275 // YAML test data with type-as-key format.
276 func NormalizeTypeAsKey(itemMap map[string]any) map[string]any {
277 // Check if map has exactly one key and no "type" field
278 if len(itemMap) == 1 {
279 _, hasType := itemMap["type"]
280 if !hasType {
281 // Get the single key
282 for key, value := range itemMap {
283 // Check if key looks like a type constant (all uppercase with underscores)
284 if IsTypeConstant(key) {
285 // Check if value is a map
286 if subMap, ok := value.(map[string]any); ok {
287 // Create new map with "type" field for test type
288 newMap := map[string]any{"type": key}
289 // Merge in the sub-map fields, but preserve sub-map's "type" as "output_type" if it exists
290 for k, v := range subMap {
291 if k == "type" {
292 // Sub-map has its own "type" field - preserve it as "output_type"
293 newMap["output_type"] = v
294 } else {
295 newMap[k] = v
296 }
297 }
298 return newMap
299 }
300 }
301 }
302 }
303 }
304 return itemMap
305 }
306
307 // IsTypeConstant checks if a string looks like a type constant.
308 // Accepts: UPPERCASE_WITH_UNDERSCORES or lowercase-with-hyphens
309 // This function is exported for use in test infrastructure.
310 func IsTypeConstant(s string) bool {
311 if s == "" {
312 return false
313 }
314 hasUpper := false
315 hasLower := false
316 for _, c := range s {
317 if c >= 'A' && c <= 'Z' {
318 hasUpper = true
319 } else if c >= 'a' && c <= 'z' {
320 hasLower = true
321 } else if !(c == '_' || c == '-' || c >= '0' && c <= '9') {
322 return false
323 }
324 }
325 // Either all uppercase (EVENT_TYPE) or has lowercase (test-type)
326 return hasUpper || hasLower
327 }
328
329 // setSliceField sets a slice field from a value
330 func setSliceField(field reflect.Value, value any) error {
331 sliceVal, ok := value.([]any)
332 if !ok {
333 return fmt.Errorf("expected []interface{} for slice, got %T", value)
334 }
335
336 elemType := field.Type().Elem()
337 newSlice := reflect.MakeSlice(field.Type(), len(sliceVal), len(sliceVal))
338
339 for i, item := range sliceVal {
340 elem := newSlice.Index(i)
341
342 // Handle struct elements
343 if elemType.Kind() == reflect.Struct {
344 var m map[string]any
345
346 // Check if item is a scalar string (simplified format)
347 if strVal, ok := item.(string); ok {
348 // Convert scalar to map with type field
349 m = map[string]any{"type": strVal}
350 } else {
351 m, ok = item.(map[string]any)
352 if !ok {
353 return fmt.Errorf("slice element %d: expected map for struct, got %T", i, item)
354 }
355 // Normalize type-as-key format
356 m = NormalizeTypeAsKey(m)
357 }
358
359 if !elem.CanAddr() {
360 return fmt.Errorf("slice element %d: cannot take address for struct unmarshaling", i)
361 }
362 if err := UnmarshalStruct(elem.Addr().Interface(), m); err != nil {
363 return fmt.Errorf("slice element %d: %w", i, err)
364 }
365 continue
366 }
367
368 // Handle other types
369 if err := setField(elem, item); err != nil {
370 return fmt.Errorf("slice element %d: %w", i, err)
371 }
372 }
373
374 field.Set(newSlice)
375 return nil
376 }
377
378 // setMapField sets a map field from a value
379 func setMapField(field reflect.Value, value any) error {
380 mapVal, ok := value.(map[string]any)
381 if !ok {
382 return fmt.Errorf("expected map[string]interface{}, got %T", value)
383 }
384
385 mapType := field.Type()
386 if mapType.Key().Kind() != reflect.String {
387 return fmt.Errorf("only string keys supported for maps")
388 }
389
390 newMap := reflect.MakeMap(mapType)
391 valueType := mapType.Elem()
392
393 for k, v := range mapVal {
394 keyRefl := reflect.ValueOf(k)
395 valueRefl := reflect.New(valueType).Elem()
396
397 // Handle struct values
398 if valueType.Kind() == reflect.Struct {
399 m, ok := v.(map[string]any)
400 if !ok {
401 return fmt.Errorf("map value for key %s: expected map for struct, got %T", k, v)
402 }
403 if !valueRefl.CanAddr() {
404 return fmt.Errorf("map value for key %s: cannot take address for struct unmarshaling", k)
405 }
406 if err := UnmarshalStruct(valueRefl.Addr().Interface(), m); err != nil {
407 return fmt.Errorf("map value for key %s: %w", k, err)
408 }
409 } else {
410 if err := setField(valueRefl, v); err != nil {
411 return fmt.Errorf("map value for key %s: %w", k, err)
412 }
413 }
414
415 newMap.SetMapIndex(keyRefl, valueRefl)
416 }
417
418 field.Set(newMap)
419 return nil
420 }
421
422 // LoadTestCasesFunc is a function type for loading test cases from a file.
423 // Each package can provide its own implementation that uses its preferred YAML loader.
424 type LoadTestCasesFunc func(filename string) ([]map[string]any, error)