Debian Codegraph @

testutil/testutil.go

raw symbols SCIP
1 // Package testutil provides utilities for unit tests.
2 package testutil
3
4 import (
5 "bufio"
6 "bytes"
7 "encoding/hex"
8 "encoding/json"
9 "fmt"
10 "os"
11 "regexp"
12 "runtime/debug"
13 "slices"
14 "strconv"
15 "strings"
16
17 "github.com/yuin/goldmark"
18 "github.com/yuin/goldmark/parser"
19 "github.com/yuin/goldmark/util"
20 )
21
22 // TestingT is a subset of the functionality provided by testing.T.
23 type TestingT interface {
24 Logf(string, ...any)
25 Skipf(string, ...any)
26 Errorf(string, ...any)
27 FailNow()
28 }
29
30 // MarkdownTestCase represents a test case.
31 type MarkdownTestCase struct {
32 No int
33 Description string
34 Options MarkdownTestCaseOptions
35 Markdown string
36 Expected string
37 }
38
39 func source(t *MarkdownTestCase) string {
40 ret := t.Markdown
41 if t.Options.Trim {
42 ret = strings.TrimSpace(ret)
43 }
44 if t.Options.EnableEscape {
45 return string(applyEscapeSequence([]byte(ret)))
46 }
47 return ret
48 }
49
50 func expected(t *MarkdownTestCase) string {
51 ret := t.Expected
52 if t.Options.Trim {
53 ret = strings.TrimSpace(ret)
54 }
55 if t.Options.EnableEscape {
56 return string(applyEscapeSequence([]byte(ret)))
57 }
58 return ret
59 }
60
61 // MarkdownTestCaseOptions represents options for each test case.
62 type MarkdownTestCaseOptions struct {
63 EnableEscape bool
64 Trim bool
65 }
66
67 const attributeSeparator = "//- - - - - - - - -//"
68 const caseSeparator = "//= = = = = = = = = = = = = = = = = = = = = = = =//"
69
70 var optionsRegexp = regexp.MustCompile(`(?i)\s*options:(.*)`)
71
72 // ParseCliCaseArg parses -case command line args.
73 func ParseCliCaseArg() []int {
74 ret := []int{}
75 for _, a := range os.Args {
76 if strings.HasPrefix(a, "case=") {
77 parts := strings.Split(a, "=")
78 for _, cas := range strings.Split(parts[1], ",") {
79 value, err := strconv.Atoi(strings.TrimSpace(cas))
80 if err == nil {
81 ret = append(ret, value)
82 }
83 }
84 }
85 }
86 return ret
87 }
88
89 // DoTestCaseFile runs test cases in a given file.
90 func DoTestCaseFile(m goldmark.Markdown, filename string, t TestingT, no ...int) {
91 fp, err := os.Open(filename)
92 if err != nil {
93 panic(err)
94 }
95 defer func() {
96 _ = fp.Close()
97 }()
98
99 scanner := bufio.NewScanner(fp)
100 c := MarkdownTestCase{
101 No: -1,
102 Description: "",
103 Options: MarkdownTestCaseOptions{},
104 Markdown: "",
105 Expected: "",
106 }
107 cases := []MarkdownTestCase{}
108 line := 0
109 for scanner.Scan() {
110 line++
111 if util.IsBlank([]byte(scanner.Text())) {
112 continue
113 }
114 header := scanner.Text()
115 c.Description = ""
116 if strings.Contains(header, ":") {
117 parts := strings.Split(header, ":")
118 c.No, err = strconv.Atoi(strings.TrimSpace(parts[0]))
119 c.Description = strings.Join(parts[1:], ":")
120 } else {
121 c.No, err = strconv.Atoi(scanner.Text())
122 }
123 if err != nil {
124 panic(fmt.Sprintf("%s: invalid case No at line %d", filename, line))
125 }
126 if !scanner.Scan() {
127 panic(fmt.Sprintf("%s: invalid case at line %d", filename, line))
128 }
129 line++
130 matches := optionsRegexp.FindAllStringSubmatch(scanner.Text(), -1)
131 if len(matches) != 0 {
132 err = json.Unmarshal([]byte(matches[0][1]), &c.Options)
133 if err != nil {
134 panic(fmt.Sprintf("%s: invalid options at line %d", filename, line))
135 }
136 scanner.Scan()
137 line++
138 }
139 if scanner.Text() != attributeSeparator {
140 panic(fmt.Sprintf("%s: invalid separator '%s' at line %d", filename, scanner.Text(), line))
141 }
142 buf := []string{}
143 for scanner.Scan() {
144 line++
145 text := scanner.Text()
146 if text == attributeSeparator {
147 break
148 }
149 buf = append(buf, text)
150 }
151 c.Markdown = strings.Join(buf, "\n")
152 buf = []string{}
153 for scanner.Scan() {
154 line++
155 text := scanner.Text()
156 if text == caseSeparator {
157 break
158 }
159 buf = append(buf, text)
160 }
161 c.Expected = strings.Join(buf, "\n")
162 if len(c.Expected) != 0 {
163 c.Expected = c.Expected + "\n"
164 }
165 shouldAdd := len(no) == 0
166 if !shouldAdd {
167 shouldAdd = slices.Contains(no, c.No)
168 }
169 if shouldAdd {
170 cases = append(cases, c)
171 }
172 }
173 DoTestCases(m, cases, t)
174 }
175
176 // DoTestCases runs a set of test cases.
177 func DoTestCases(m goldmark.Markdown, cases []MarkdownTestCase, t TestingT, opts ...parser.ParseOption) {
178 for _, testCase := range cases {
179 DoTestCase(m, testCase, t, opts...)
180 }
181 }
182
183 // DoTestCase runs a test case.
184 func DoTestCase(m goldmark.Markdown, testCase MarkdownTestCase, t TestingT, opts ...parser.ParseOption) {
185 var ok bool
186 var out bytes.Buffer
187 defer func() {
188 description := ""
189 if len(testCase.Description) != 0 {
190 description = ": " + testCase.Description
191 }
192 if err := recover(); err != nil {
193 format := `============= case %d%s ================
194 Markdown:
195 -----------
196 %s
197
198 Expected:
199 ----------
200 %s
201
202 Actual
203 ---------
204 %v
205 %s
206 `
207 t.Errorf(format, testCase.No, description, source(&testCase), expected(&testCase), err, debug.Stack())
208 } else if !ok {
209 format := `============= case %d%s ================
210 Markdown:
211 -----------
212 %s
213
214 Expected:
215 ----------
216 %s
217
218 Actual
219 ---------
220 %s
221
222 Diff
223 ---------
224 %s
225 `
226 t.Errorf(format, testCase.No, description, source(&testCase), expected(&testCase), out.Bytes(),
227 DiffPretty([]byte(expected(&testCase)), out.Bytes()))
228 }
229 }()
230
231 if err := m.Convert([]byte(source(&testCase)), &out, opts...); err != nil {
232 panic(err)
233 }
234 ok = bytes.Equal(bytes.TrimSpace(out.Bytes()), bytes.TrimSpace([]byte(expected(&testCase))))
235 }
236
237 type diffType int
238
239 const (
240 diffRemoved diffType = iota
241 diffAdded
242 diffNone
243 )
244
245 type diff struct {
246 Type diffType
247 Lines [][]byte
248 }
249
250 func simpleDiff(v1, v2 []byte) []diff {
251 return simpleDiffAux(
252 bytes.Split(v1, []byte("\n")),
253 bytes.Split(v2, []byte("\n")))
254 }
255
256 func simpleDiffAux(v1lines, v2lines [][]byte) []diff {
257 v1index := map[string][]int{}
258 for i, line := range v1lines {
259 key := util.BytesToReadOnlyString(line)
260 if _, ok := v1index[key]; !ok {
261 v1index[key] = []int{}
262 }
263 v1index[key] = append(v1index[key], i)
264 }
265 overlap := map[int]int{}
266 v1start := 0
267 v2start := 0
268 length := 0
269 for v2pos, line := range v2lines {
270 newOverlap := map[int]int{}
271 key := util.BytesToReadOnlyString(line)
272 if _, ok := v1index[key]; !ok {
273 v1index[key] = []int{}
274 }
275 for _, v1pos := range v1index[key] {
276 value := 0
277 if v1pos != 0 {
278 if v, ok := overlap[v1pos-1]; ok {
279 value = v
280 }
281 }
282 newOverlap[v1pos] = value + 1
283 if newOverlap[v1pos] > length {
284 length = newOverlap[v1pos]
285 v1start = v1pos - length + 1
286 v2start = v2pos - length + 1
287 }
288 }
289 overlap = newOverlap
290 }
291 if length == 0 {
292 diffs := []diff{}
293 if len(v1lines) != 0 {
294 diffs = append(diffs, diff{diffRemoved, v1lines})
295 }
296 if len(v2lines) != 0 {
297 diffs = append(diffs, diff{diffAdded, v2lines})
298 }
299 return diffs
300 }
301 diffs := simpleDiffAux(v1lines[:v1start], v2lines[:v2start])
302 diffs = append(diffs, diff{diffNone, v2lines[v2start : v2start+length]})
303 diffs = append(diffs, simpleDiffAux(v1lines[v1start+length:],
304 v2lines[v2start+length:])...)
305 return diffs
306 }
307
308 // DiffPretty returns pretty formatted diff between given bytes.
309 func DiffPretty(v1, v2 []byte) []byte {
310 var b bytes.Buffer
311 diffs := simpleDiff(v1, v2)
312 for _, diff := range diffs {
313 c := " "
314 switch diff.Type {
315 case diffAdded:
316 c = "+"
317 case diffRemoved:
318 c = "-"
319 case diffNone:
320 c = " "
321 }
322 for _, line := range diff.Lines {
323 if c != " " {
324 fmt.Fprintf(&b, "%s | %s\n", c, util.VisualizeSpaces(line))
325 } else {
326 fmt.Fprintf(&b, "%s | %s\n", c, line)
327 }
328 }
329 }
330 return b.Bytes()
331 }
332
333 func applyEscapeSequence(b []byte) []byte {
334 result := make([]byte, 0, len(b))
335 for i := 0; i < len(b); i++ {
336 if b[i] == '\\' && i != len(b)-1 {
337 switch b[i+1] {
338 case 'a':
339 result = append(result, '\a')
340 i++
341 continue
342 case 'b':
343 result = append(result, '\b')
344 i++
345 continue
346 case 'f':
347 result = append(result, '\f')
348 i++
349 continue
350 case 'n':
351 result = append(result, '\n')
352 i++
353 continue
354 case 'r':
355 result = append(result, '\r')
356 i++
357 continue
358 case 't':
359 result = append(result, '\t')
360 i++
361 continue
362 case 'v':
363 result = append(result, '\v')
364 i++
365 continue
366 case '\\':
367 result = append(result, '\\')
368 i++
369 continue
370 case 'x':
371 if len(b) >= i+3 && util.IsHexDecimal(b[i+2]) && util.IsHexDecimal(b[i+3]) {
372 v, _ := hex.DecodeString(string(b[i+2 : i+4]))
373 result = append(result, v[0])
374 i += 3
375 continue
376 }
377 case 'u', 'U':
378 if len(b) > i+2 {
379 num := []byte{}
380 for j := i + 2; j < len(b); j++ {
381 if util.IsHexDecimal(b[j]) {
382 num = append(num, b[j])
383 continue
384 }
385 break
386 }
387 if len(num) >= 4 && len(num) < 8 {
388 v, _ := strconv.ParseInt(string(num[:4]), 16, 32)
389 result = append(result, []byte(string(rune(v)))...)
390 i += 5
391 continue
392 }
393 if len(num) >= 8 {
394 v, _ := strconv.ParseInt(string(num[:8]), 16, 32)
395 result = append(result, []byte(string(rune(v)))...)
396 i += 9
397 continue
398 }
399 }
400 }
401 }
402 result = append(result, b[i])
403 }
404 return result
405 }