Source file
src/testing/example.go
1
2
3
4
5 package testing
6
7 import (
8 "fmt"
9 "runtime"
10 "slices"
11 "strings"
12 "time"
13 )
14
15 type InternalExample struct {
16 Name string
17 F func()
18 Output string
19 Unordered bool
20 }
21
22
23
24 func RunExamples(matchString func(pat, str string) (bool, error), examples []InternalExample) (ok bool) {
25 _, ok = runExamples(matchString, examples)
26 return ok
27 }
28
29 func runExamples(matchString func(pat, str string) (bool, error), examples []InternalExample) (ran, ok bool) {
30 ok = true
31
32 m := newMatcher(matchString, *match, "-test.run", *skip)
33
34 var eg InternalExample
35 for _, eg = range examples {
36 _, matched, _ := m.fullName(nil, eg.Name)
37 if !matched {
38 continue
39 }
40 ran = true
41 if !runExample(eg) {
42 ok = false
43 }
44 }
45
46 return ran, ok
47 }
48
49 func sortLines(output string) string {
50 lines := strings.Split(output, "\n")
51 slices.Sort(lines)
52 return strings.Join(lines, "\n")
53 }
54
55
56
57
58
59
60
61
62
63
64 func (eg *InternalExample) processRunResult(stdout string, timeSpent time.Duration, finished bool, recovered any) (passed bool) {
65 passed = true
66 dstr := fmtDuration(timeSpent)
67 var fail string
68 got := strings.TrimSpace(stdout)
69 want := strings.TrimSpace(eg.Output)
70 if runtime.GOOS == "windows" {
71 got = strings.ReplaceAll(got, "\r\n", "\n")
72 want = strings.ReplaceAll(want, "\r\n", "\n")
73 }
74 if eg.Unordered {
75 if sortLines(got) != sortLines(want) && recovered == nil {
76 fail = fmt.Sprintf("got:\n%s\nwant (unordered):\n%s\n", stdout, eg.Output)
77 }
78 } else {
79 if got != want && recovered == nil {
80 fail = fmt.Sprintf("got:\n%s\nwant:\n%s\n", got, want)
81 }
82 }
83 if fail != "" || !finished || recovered != nil {
84 fmt.Printf("%s--- FAIL: %s (%s)\n%s", chatty.prefix(), eg.Name, dstr, fail)
85 passed = false
86 } else if chatty.on {
87 fmt.Printf("%s--- PASS: %s (%s)\n", chatty.prefix(), eg.Name, dstr)
88 }
89
90 if chatty.on && chatty.json {
91 fmt.Printf("%s=== NAME %s\n", chatty.prefix(), "")
92 }
93
94 if recovered != nil {
95
96 panic(recovered)
97 } else if !finished {
98 panic(errNilPanicOrGoexit)
99 }
100
101 return
102 }
103
View as plain text