...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package proftest
18
19 import (
20 "encoding/json"
21 "flag"
22 "fmt"
23 "io"
24 "os"
25 "os/exec"
26 "regexp"
27 "testing"
28
29 _ "embed"
30 )
31
32 var flagLargeProfile = flag.String("large_profile", "", "The name of a file that contains a profile to use in benchmarks. If empty, a profile of a synthetic program is used.")
33
34
35
36
37 func Diff(b1, b2 []byte) (data []byte, err error) {
38 f1, err := os.CreateTemp("", "proto_test")
39 if err != nil {
40 return nil, err
41 }
42 defer os.Remove(f1.Name())
43 defer f1.Close()
44
45 f2, err := os.CreateTemp("", "proto_test")
46 if err != nil {
47 return nil, err
48 }
49 defer os.Remove(f2.Name())
50 defer f2.Close()
51
52 f1.Write(b1)
53 f2.Write(b2)
54
55 data, err = exec.Command("diff", "-u", f1.Name(), f2.Name()).CombinedOutput()
56 if len(data) > 0 {
57
58
59 err = nil
60 }
61 if err != nil {
62 data = []byte(fmt.Sprintf("diff failed: %v\nb1: %q\nb2: %q\n", err, b1, b2))
63 err = nil
64 }
65 return
66 }
67
68
69
70 func EncodeJSON(x interface{}) []byte {
71 data, err := json.MarshalIndent(x, "", " ")
72 if err != nil {
73 panic(err)
74 }
75 data = append(data, '\n')
76 return data
77 }
78
79
80
81
82
83 type TestUI struct {
84 T testing.TB
85 Ignore int
86 AllowRx string
87 NumAllowRxMatches int
88 Input []string
89 index int
90 }
91
92
93 func (ui *TestUI) ReadLine(_ string) (string, error) {
94 if ui.index >= len(ui.Input) {
95 return "", io.EOF
96 }
97 input := ui.Input[ui.index]
98 ui.index++
99 if input == "**error**" {
100 return "", fmt.Errorf("error: %s", input)
101 }
102 return input, nil
103 }
104
105
106 func (ui *TestUI) Print(args ...interface{}) {
107 }
108
109
110
111 func (ui *TestUI) PrintErr(args ...interface{}) {
112 if ui.AllowRx != "" {
113 if matched, err := regexp.MatchString(ui.AllowRx, fmt.Sprint(args...)); matched || err != nil {
114 if err != nil {
115 ui.T.Errorf("failed to match against regex %q: %v", ui.AllowRx, err)
116 }
117 ui.NumAllowRxMatches++
118 return
119 }
120 }
121 if ui.Ignore > 0 {
122 ui.Ignore--
123 return
124 }
125
126
127
128
129 ui.T.Error("unexpected error: " + fmt.Sprint(args...))
130 }
131
132
133 func (ui *TestUI) IsTerminal() bool {
134 return false
135 }
136
137
138 func (ui *TestUI) WantBrowser() bool {
139 return false
140 }
141
142
143 func (ui *TestUI) SetAutoComplete(_ func(string) string) {
144 }
145
146
147
148
149
150
151 func LargeProfile(tb testing.TB) []byte {
152 tb.Helper()
153 if f := *flagLargeProfile; f != "" {
154
155 data, err := os.ReadFile(f)
156 if err != nil {
157 tb.Fatalf("custom profile file: %v\n", err)
158 }
159 return data
160 }
161
162 return largeProfileData
163 }
164
165
166 var largeProfileData []byte
167
View as plain text