-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathall_tests.go
67 lines (59 loc) · 1.85 KB
/
all_tests.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
package main
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"os/exec"
"strings"
"time"
)
// TestResult represents the structure of a test result
type TestEvent struct {
Time time.Time `json:"time"`
Action string `json:"action"`
Package string `json:"package"`
Test string `json:"test"`
Elapsed *float64 `json:"elapsed,omitempty"`
Output *string `json:"output,omitempty"`
}
// collectTestResults runs `go test -json` and parses the output
func collectTestResults(pkgDir string) ([]TestEvent, error) {
cmd := exec.Command("go", "test", pkgDir, "-json", "-coverprofile=coverage.out")
output, _ := cmd.Output()
tests, err := parseTestOutput(output)
if err != nil {
return nil, fmt.Errorf("failed to parse test output: %w", err)
}
var results []TestEvent
for _, test := range tests {
if test.Test == "" || (test.Action != "pass" && test.Action != "fail") {
continue
}
results = append(results, test)
}
return results, nil
}
func parseTestOutput(output []byte) ([]TestEvent, error) {
var result []TestEvent
list := "[" + strings.ReplaceAll(string(output[:len(output)-1]), "\n", ",") + "]"
err := json.Unmarshal([]byte(list), &result)
if err != nil {
return nil, err
}
return result, nil
}
func populateTestResults(ctx context.Context, db *sql.DB, pkgDir string) ([]TestEvent, error) {
testResults, err := collectTestResults(pkgDir)
if err != nil {
return nil, fmt.Errorf("failed to collect test results: %w", err)
}
for _, test := range testResults {
insertSQL := "INSERT INTO all_tests (\"time\", \"action\", package, test, elapsed, \"output\") VALUES (?, ?, ?, ?, ?, ?);"
_, err = db.ExecContext(ctx, insertSQL, test.Time, test.Action, test.Package, test.Test, test.Elapsed, test.Output)
if err != nil {
return nil, fmt.Errorf("failed to insert test results: %w", err)
}
}
return testResults, nil
}