Debian Codegraph @

internal/testutil/datatest/helpers.go

raw symbols SCIP
1 // Copyright 2025 The go-yaml Project Contributors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Helper functions for test data processing.
5 // Includes hex decoding, struct unmarshaling, and test case normalization.
6
7 package datatest
8
9 import (
10 "encoding/hex"
11 "fmt"
12 "reflect"
13 "strings"
14 "testing"
15 )
16
17 // HexToBytes converts a hex string to bytes.
18 // This is useful for test data that needs to specify binary data.
19 func HexToBytes(t *testing.T, s string) []byte {
20 t.Helper()
21 b, err := hex.DecodeString(s)
22 if err != nil {
23 t.Fatalf("invalid hex string: %s: %v", s, err)
24 }
25 return b
26 }
27
28 // GetField uses reflection to get a field value from a struct or pointer to struct.
29 // This is useful for test assertions that need to check internal field values.
30 func GetField(t *testing.T, obj any, fieldName string) any {
31 t.Helper()
32 v := reflect.ValueOf(obj)
33 if v.Kind() == reflect.Ptr {
34 v = v.Elem()
35 }
36 field := v.FieldByName(fieldName)
37 if !field.IsValid() {
38 t.Fatalf("field %s not found in %T", fieldName, obj)
39 }
40 return field.Interface()
41 }
42
43 // CallMethod calls a method on an object using reflection.
44 // This is useful for test cases that need to call methods dynamically.
45 // Returns the slice of return values from the method call as [reflect.Value] wrappers.
46 // Callers must extract the actual values using methods like .Interface(), .Int(), .String(), etc.
47 func CallMethod(t *testing.T, obj any, methodName string, args []any) []reflect.Value {
48 t.Helper()
49 v := reflect.ValueOf(obj)
50 method := v.MethodByName(methodName)
51 if !method.IsValid() {
52 t.Fatalf("method %s not found on %T", methodName, obj)
53 }
54
55 var argValues []reflect.Value
56 for _, arg := range args {
57 argValues = append(argValues, reflect.ValueOf(arg))
58 }
59
60 return method.Call(argValues)
61 }
62
63 // WantBool extracts a bool value from a test case's Want field.
64 // If Want is nil, returns the defaultVal.
65 // This is useful for test cases where the expected result is a boolean.
66 func WantBool(t *testing.T, want any, defaultVal bool) bool {
67 t.Helper()
68 if want == nil {
69 return defaultVal
70 }
71 boolVal, ok := want.(bool)
72 if !ok {
73 t.Fatalf("Want should be bool, got %T", want)
74 }
75 return boolVal
76 }
77
78 // WantString extracts a string value from a test case's Want field.
79 // If Want is nil, returns the defaultVal.
80 func WantString(t *testing.T, want any, defaultVal string) string {
81 t.Helper()
82 if want == nil {
83 return defaultVal
84 }
85 strVal, ok := want.(string)
86 if !ok {
87 t.Fatalf("Want should be string, got %T", want)
88 }
89 return strVal
90 }
91
92 // WantInt extracts an int value from a test case's Want field.
93 // If Want is nil, returns the defaultVal.
94 func WantInt(t *testing.T, want any, defaultVal int) int {
95 t.Helper()
96 if want == nil {
97 return defaultVal
98 }
99 intVal, ok := want.(int)
100 if !ok {
101 t.Fatalf("Want should be int, got %T", want)
102 }
103 return intVal
104 }
105
106 // WantSlice extracts a slice value from a test case's Want field.
107 // If Want is nil, returns nil.
108 func WantSlice(t *testing.T, want any) []any {
109 t.Helper()
110 if want == nil {
111 return nil
112 }
113 sliceVal, ok := want.([]any)
114 if !ok {
115 t.Fatalf("Want should be []interface{}, got %T", want)
116 }
117 return sliceVal
118 }
119
120 // SetFieldValue sets a field value on a struct using reflection.
121 // This is useful for test setup that needs to configure objects dynamically.
122 func SetFieldValue(t *testing.T, obj any, fieldName string, value any) {
123 t.Helper()
124 v := reflect.ValueOf(obj)
125 if v.Kind() == reflect.Ptr {
126 v = v.Elem()
127 }
128 field := v.FieldByName(fieldName)
129 if !field.IsValid() {
130 t.Fatalf("field %s not found in %T", fieldName, obj)
131 }
132 if !field.CanSet() {
133 t.Fatalf("field %s cannot be set (unexported?)", fieldName)
134 }
135 field.Set(reflect.ValueOf(value))
136 }
137
138 // TrimTrailingNewline removes a trailing newline character from a string if present.
139 // This is useful for YAML literal blocks which add a trailing newline.
140 func TrimTrailingNewline(s string) string {
141 if len(s) > 0 && s[len(s)-1] == '\n' {
142 return s[:len(s)-1]
143 }
144 return s
145 }
146
147 // GenerateData generates test data from a generator specification.
148 // Supports simple loops, concatenation of parts (join), and nested loops.
149 //
150 // Format:
151 //
152 // Simple loop: {loop: ["value", count]}
153 // Join parts: {join: [{text: "..."}, {loop: ["...", count]}]}
154 // Nested: {join: [...], loop: count}
155 func GenerateData(spec any) ([]byte, error) {
156 specMap, ok := spec.(map[string]any)
157 if !ok {
158 // If it's just a string, return it as-is
159 if str, ok := spec.(string); ok {
160 return []byte(str), nil
161 }
162 return nil, fmt.Errorf("data spec must be map or string, got %T", spec)
163 }
164
165 // Check for simple loop: {loop: ["value", count]}
166 if loopVal, hasLoop := specMap["loop"]; hasLoop {
167 if _, hasJoin := specMap["join"]; !hasJoin {
168 return generateSimpleLoop(loopVal)
169 }
170 }
171
172 // Check for join: {join: [{text: "..."}, {loop: ["...", count]}]}
173 if joinVal, hasJoin := specMap["join"]; hasJoin {
174 result, err := generateJoin(joinVal)
175 if err != nil {
176 return nil, err
177 }
178
179 // Check for loop: repeat the entire join N times
180 if loopVal, hasLoop := specMap["loop"]; hasLoop {
181 count, ok := loopVal.(int)
182 if !ok {
183 return nil, fmt.Errorf("loop count must be int, got %T", loopVal)
184 }
185 return []byte(strings.Repeat(string(result), count)), nil
186 }
187
188 return result, nil
189 }
190
191 return nil, fmt.Errorf("data spec must have 'loop' or 'join' field")
192 }
193
194 // generateSimpleLoop generates test data by repeating a string value n times.
195 func generateSimpleLoop(loopVal any) ([]byte, error) {
196 loopArr, ok := loopVal.([]any)
197 if !ok {
198 return nil, fmt.Errorf("loop must be array [value, count], got %T", loopVal)
199 }
200
201 if len(loopArr) != 2 {
202 return nil, fmt.Errorf("loop must have 2 elements [value, count], got %d", len(loopArr))
203 }
204
205 value, ok := loopArr[0].(string)
206 if !ok {
207 return nil, fmt.Errorf("loop value must be string, got %T", loopArr[0])
208 }
209
210 count, ok := loopArr[1].(int)
211 if !ok {
212 return nil, fmt.Errorf("loop count must be int, got %T", loopArr[1])
213 }
214
215 return []byte(strings.Repeat(value, count)), nil
216 }
217
218 // generateJoin generates test data by joining multiple strings.
219 func generateJoin(joinVal any) ([]byte, error) {
220 joinList, ok := joinVal.([]any)
221 if !ok {
222 return nil, fmt.Errorf("join must be array, got %T", joinVal)
223 }
224
225 var result strings.Builder
226 for i, item := range joinList {
227 itemMap, ok := item.(map[string]any)
228 if !ok {
229 return nil, fmt.Errorf("join item %d must be map, got %T", i, item)
230 }
231
232 // Check for text field
233 if text, hasText := itemMap["text"]; hasText {
234 textStr, ok := text.(string)
235 if !ok {
236 return nil, fmt.Errorf("join item %d text must be string, got %T", i, text)
237 }
238 result.WriteString(textStr)
239 continue
240 }
241
242 // Check for loop field
243 if loopVal, hasLoop := itemMap["loop"]; hasLoop {
244 loopData, err := generateSimpleLoop(loopVal)
245 if err != nil {
246 return nil, fmt.Errorf("join item %d: %w", i, err)
247 }
248 result.Write(loopData)
249 continue
250 }
251
252 return nil, fmt.Errorf("join item %d must have 'text' or 'loop' field", i)
253 }
254
255 return []byte(result.String()), nil
256 }