-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgo-test-sift.go
338 lines (300 loc) · 9.74 KB
/
go-test-sift.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/*
go-test-sift: A utility to process Go unit test logs and provide summary information or extract individual test outputs.
Feature: Reconstructing Parallel Unit Test Output
This program attempts to group interleaved log lines into the correct
test context, even for parallel or nested subtests. While Go's
parallel test execution can sometimes produce interleaved logs that
make attribution challenging (where subtests or parent tests are
running in parallel), the program does its best to maintain logical
groupings. Also note, output not associated with `t.Log`, `t.Error`,
or similar Go testing functions) might not always be attributed
correctly. Debug output (`-d`) can help troubleshoot such scenarios.
Options:
-l Print a summary of failed tests, including their names,
statuses, and durations.
-L Print a summary of failed tests (like -l) but also include the
full output for each failed test. Useful for debugging failures
directly in the console.
-d Enable debug output. Provides detailed information about how the
program processes the input, including line-by-line analysis and
test context switching.
-w Write each test's output to individual files, organised by test
name. Files are created in a directory structure that matches
the test hierarchy.
-F Force directory creation when used with -w. If directories
already exist, they are overwritten instead of causing the
program to exit.
-o Base directory for writing output files (default: current
directory). Used in conjunction with -w to specify where the
test outputs should be saved.
-t Regular expression to filter test names for summary output. By
default, all tests are included (".*"). You can use this option
to restrict the output to specific tests.
*/
package main
import (
"bufio"
"flag"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
)
type TestSummary struct {
Status string
Name string
Time string
Level int
}
const (
FailMarker = "FAIL"
PassMarker = "PASS"
)
func main() {
listFailures := flag.Bool("l", false, "Print summary of failures (list test names with failures)")
listFailuresWithOutput := flag.Bool("L", false, "Print summary of failures and include the full output for each failure")
forceFlag := flag.Bool("F", false, "Force directory creation even if directories exist")
debugFlag := flag.Bool("d", false, "Enable debug output")
writeFiles := flag.Bool("w", false, "Write each test's output to individual files")
outputDir := flag.String("o", ".", "Base directory to write output files (default current directory)")
testPattern := flag.String("t", ".*", "Regular expression to filter test names for summary output")
flag.Parse()
reTest, err := regexp.Compile(*testPattern)
if err != nil {
fmt.Fprintf(os.Stderr, "Invalid regular expression for -t: %v\n", err)
os.Exit(1)
}
args := flag.Args()
runRegex := regexp.MustCompile(`^=== RUN\s+(.*)`)
nameRegex := regexp.MustCompile(`^=== NAME\s+(.*)`)
contRegex := regexp.MustCompile(`^=== CONT\s+(.*)`)
testBuffers := make(map[string][]string)
var summaryRecords []TestSummary
processReader := func(reader io.Reader) {
scanner := bufio.NewScanner(reader)
var currentTest string
var lastName string
started := false
inSummary := false
lineNumber := 0
stopParsing := false
for scanner.Scan() {
if stopParsing {
break
}
lineNumber++
line := scanner.Text()
if *debugFlag {
fmt.Printf("[DEBUG] Reading line %d: %s\n", lineNumber, line)
}
// Skip lines until the first '=== RUN' marker.
if !started {
if runRegex.MatchString(line) {
started = true
if *debugFlag {
fmt.Println("[DEBUG] Found first '=== RUN' marker, starting parsing.")
}
} else {
continue
}
}
// Switch to summary mode when encountering a summary line.
if !inSummary && strings.HasPrefix(strings.TrimSpace(line), "---") {
inSummary = true
if *debugFlag {
fmt.Printf("[DEBUG] Encountered first summary line at line %d, switching to summary mode.\n", lineNumber)
}
}
if inSummary {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "---") {
fields := strings.Fields(trimmed)
// Expecting format: --- STATUS: TestName (Time).
if len(fields) >= 3 {
statusWithColon := fields[1]
status := strings.TrimSuffix(statusWithColon, ":")
testName := fields[2]
timeStr := ""
if len(fields) >= 4 {
timeStr = strings.Trim(fields[3], "()")
}
indent := len(line) - len(strings.TrimLeft(line, " "))
level := indent / 4
newSummary := TestSummary{
Status: status,
Name: testName,
Time: timeStr,
Level: level,
}
summaryRecords = append(summaryRecords, newSummary)
if *debugFlag {
fmt.Printf("[DEBUG] Added summary record at line %d: %+v\n", lineNumber, newSummary)
}
}
}
if trimmed == FailMarker || trimmed == PassMarker {
stopParsing = true
if *debugFlag {
fmt.Printf("[DEBUG] Encountered %s terminator at line %d; parsing now stopped\n", trimmed, lineNumber)
}
}
continue
}
switch {
case strings.HasPrefix(strings.TrimSpace(line), "=== PAUSE"):
if *debugFlag {
fmt.Printf("[DEBUG] Encountered PAUSE for test context at line %d\n", lineNumber)
}
case contRegex.MatchString(line):
match := contRegex.FindStringSubmatch(line)
currentTest = match[1]
lastName = currentTest
if *debugFlag {
fmt.Printf("[DEBUG] Resuming test context: %s at line %d\n", currentTest, lineNumber)
}
case nameRegex.MatchString(line):
match := nameRegex.FindStringSubmatch(line)
newName := match[1]
if lastName != "" && strings.HasPrefix(lastName, newName+"/") {
currentTest = lastName
if *debugFlag {
fmt.Printf("[DEBUG] Continuing context for subtest: %s at line %d\n", currentTest, lineNumber)
}
} else {
currentTest = newName
lastName = newName
if *debugFlag {
fmt.Printf("[DEBUG] Switching context to test: %s at line %d\n", currentTest, lineNumber)
}
}
case runRegex.MatchString(line):
match := runRegex.FindStringSubmatch(line)
currentTest = match[1]
if _, exists := testBuffers[currentTest]; !exists {
testBuffers[currentTest] = []string{}
if *debugFlag {
fmt.Printf("[DEBUG] New test started at line %d: %s\n", lineNumber, currentTest)
}
}
default:
if currentTest != "" {
testBuffers[currentTest] = append(testBuffers[currentTest], line)
if *debugFlag {
fmt.Printf("[DEBUG] Collected meaningful line %d for test %s\n", lineNumber, currentTest)
}
} else {
fmt.Println(line)
}
}
}
if err := scanner.Err(); err != nil {
fmt.Fprintf(os.Stderr, "Error reading input: %v\n", err)
}
}
if len(args) == 0 {
if *debugFlag {
fmt.Println("[DEBUG] No arguments provided, reading from stdin.")
}
processReader(os.Stdin)
} else {
for _, input := range args {
var reader io.Reader
if u, err := url.ParseRequestURI(input); err == nil && (u.Scheme == "http" || u.Scheme == "https") {
if *debugFlag {
fmt.Printf("[DEBUG] Fetching URL: %s\n", input)
}
resp, err := http.Get(input)
if err != nil {
fmt.Fprintf(os.Stderr, "Error fetching URL %s: %v\n", input, err)
continue
}
defer resp.Body.Close()
reader = resp.Body
} else {
if *debugFlag {
fmt.Printf("[DEBUG] Opening file: %s\n", input)
}
file, err := os.Open(input)
if err != nil {
fmt.Fprintf(os.Stderr, "Error opening file %s: %v\n", input, err)
continue
}
defer file.Close()
reader = file
}
processReader(reader)
}
}
if *writeFiles {
matchingTests := make(map[string][]string)
for testName, lines := range testBuffers {
if reTest.MatchString(testName) {
matchingTests[testName] = lines
}
}
// Create directories only for matching tests.
for testName := range matchingTests {
dirPath := filepath.Join(*outputDir, testName)
if !*forceFlag {
if _, err := os.Stat(dirPath); err == nil {
fmt.Fprintf(os.Stderr, "Error: directory '%s' already exists.\n", dirPath)
os.Exit(1)
}
}
if err := os.MkdirAll(dirPath, 0755); err != nil {
fmt.Fprintf(os.Stderr, "Error creating directory %s: %v\n", dirPath, err)
os.Exit(1)
}
if *debugFlag {
fmt.Printf("[DEBUG] Created directory: %s\n", dirPath)
}
filePath := filepath.Join(dirPath, "output.log")
file, err := os.Create(filePath)
if err != nil {
fmt.Fprintf(os.Stderr, "Error creating file %s: %v\n", filePath, err)
continue
}
if *debugFlag {
fmt.Printf("[DEBUG] Writing to file: %s\n", filePath)
}
for _, line := range matchingTests[testName] {
_, _ = file.WriteString(line + "\n")
}
file.Close()
}
return
}
if *listFailures || *listFailuresWithOutput {
for _, summary := range summaryRecords {
if summary.Status == FailMarker && reTest.MatchString(summary.Name) {
indent := strings.Repeat(" ", summary.Level)
fmt.Printf("%s--- %s: %s (%s)\n", indent, summary.Status, summary.Name, summary.Time)
if *listFailuresWithOutput {
if lines, exists := testBuffers[summary.Name]; exists {
for _, line := range lines {
fmt.Printf("%s %s\n", indent, line)
}
}
}
}
}
return
}
// Default behavior: regroup test output.
for _, summary := range summaryRecords {
if !reTest.MatchString(summary.Name) {
continue
}
indent := strings.Repeat(" ", summary.Level)
fmt.Printf("%s--- %s: %s (%s)\n", indent, summary.Status, summary.Name, summary.Time)
if lines, exists := testBuffers[summary.Name]; exists {
for _, line := range lines {
fmt.Printf("%s %s\n", indent, line)
}
}
}
}