-
Notifications
You must be signed in to change notification settings - Fork 9
/
run.go
329 lines (301 loc) · 7.48 KB
/
run.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
package gotesplit
import (
"bytes"
"context"
"encoding/xml"
"errors"
"fmt"
"io"
"log"
"math"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"github.com/jstemmer/go-junit-report/v2/gtr"
"github.com/jstemmer/go-junit-report/v2/junit"
parser "github.com/jstemmer/go-junit-report/v2/parser/gotest"
"golang.org/x/sync/errgroup"
)
func run(_ context.Context, total, idx uint, junitDir string, coverprofilesDir string, argv []string, outStream io.Writer, errStream io.Writer) error {
if idx >= total {
return fmt.Errorf("`index` should be the range from 0 to `total`-1, but: %d (total:%d)", idx, total)
}
l := len(argv)
var (
pkgs []string
testOpts []string
)
for i := 0; i < l; i++ {
pkg := argv[i]
if pkg == "--" {
testOpts = argv[i+1:]
break
}
pkgs = append(pkgs, pkg)
}
if junitDir != "" {
verbose := false
for _, opt := range testOpts {
if strings.HasSuffix(opt, "-v") {
verbose = true
}
if strings.HasSuffix(opt, "-json") {
return fmt.Errorf("-json output and -junitDir cannot be specified at the same time")
}
}
if !verbose {
testOpts = append([]string{"-v"}, testOpts...)
}
}
testLists, err := getTestListsFromPkgs(pkgs, detectTags(testOpts), detectRace(testOpts))
if err != nil {
return err
}
testListMap := make(map[string]testList, len(testLists))
for _, tl := range testLists {
testListMap[tl.pkg] = tl
}
const delim = ":::"
var testListStrs []string
for _, v := range testLists {
for _, t := range v.list {
testListStrs = append(testListStrs, v.pkg+delim+t)
}
}
testNum := uint(len(testListStrs))
minMemberPerGroup := testNum / total
mod := testNum % total
getOffset := func(i uint) uint {
return minMemberPerGroup*i + uint(math.Min(float64(i), float64(mod)))
}
from := getOffset(idx)
to := getOffset(idx + 1)
var (
targetTests []testList
allPkgs []string
currList testList
)
addList := func(l testList) {
tl := testListMap[l.pkg]
if len(tl.list) == len(l.list) {
allPkgs = append(allPkgs, l.pkg)
} else {
targetTests = append(targetTests, l)
}
}
for _, v := range testListStrs[from:to] {
stuff := strings.Split(v, delim)
pkg := stuff[0]
test := stuff[1]
if pkg != currList.pkg {
if currList.pkg != "" {
addList(currList)
}
currList = testList{pkg: pkg}
}
currList.list = append(currList.list, test)
}
if len(currList.list) > 0 {
addList(currList)
}
if junitDir != "" {
if err := os.MkdirAll(junitDir, 0755); err != nil {
return err
}
}
// Check if coverprofile flag is set. If so remove it from args and replace it
// later with separate coverprofile files for each `go test` run.
coverprofileFile := ""
for i := range testOpts {
if strings.HasPrefix(testOpts[i], "-coverprofile=") {
coverprofileFile = strings.TrimPrefix(testOpts[i], "-coverprofile=")
if i == len(testOpts)-1 {
testOpts = testOpts[:i]
} else {
testOpts = append(testOpts[:i], testOpts[i+1:]...)
}
break
}
}
if coverprofileFile != "" {
// Make temporary directory to store single coverprofile files in.
if err := os.MkdirAll(coverprofilesDir, 0755); err != nil {
return err
}
}
var testArgsList [][]string
if len(allPkgs) > 0 {
args := append([]string{"test"}, testOpts...)
args = append(args, allPkgs...)
testArgsList = append(testArgsList, args)
}
for _, tl := range targetTests {
args := append([]string{"test"}, testOpts...)
run := "^(?:" + strings.Join(tl.list, "|") + ")$"
args = append(args, "-run", run, tl.pkg)
testArgsList = append(testArgsList, args)
}
for i, args := range testArgsList {
if coverprofileFile != "" {
// Write coverprofiles to temp folder.
args = append(args, fmt.Sprintf("-coverprofile=%s/coverprofile_%d", coverprofilesDir, i))
}
report := goTest(args, outStream, errStream, junitDir)
if err2 := report.err; err2 != nil {
err = err2
}
if report.report != nil {
if report.report.err != nil {
log.Printf("failed to collect test report: %s\n", err)
} else {
fpath := filepath.Join(junitDir, fmt.Sprintf("junit-%d-%d.xml", idx, i))
f, err := os.Create(fpath)
if err != nil {
log.Printf("failed to open file to store test report: %s\n", err)
} else {
defer f.Close()
if err := writeJUnitReportXML(f, report.report.report); err != nil {
log.Printf("failed to store test report: %s\n", err)
}
}
}
}
}
if err != nil {
return err
}
if coverprofileFile != "" {
// Merge single coverprofiles to one file.
err = mergeCoverprofiles(coverprofilesDir, coverprofileFile)
if err != nil {
return err
}
// Remove temp directory.
err = os.RemoveAll(coverprofilesDir)
if err != nil {
return err
}
}
return nil
}
func mergeCoverprofiles(dir string, coverprofileOut string) error {
files, err := os.ReadDir(dir)
if err != nil {
return err
}
modeRegex := regexp.MustCompile(`^mode: [a-zA-Z]+\n`)
mergedContent := []byte{}
for i, file := range files {
content, err := os.ReadFile(dir + "/" + file.Name())
if err != nil {
return fmt.Errorf("failed to read file %s: %w", file.Name(), err)
}
if i != 0 {
// Cover mode is set in first line, remove it from all the following
// files.
content = modeRegex.ReplaceAll(content, []byte{})
}
mergedContent = append(mergedContent, content...)
}
return os.WriteFile(coverprofileOut, mergedContent, 0755)
}
type junitReport struct {
report gtr.Report
err error
}
type testReport struct {
err error
report *junitReport
}
func goTest(args []string, stdout, stderr io.Writer, junitDir string) *testReport {
cmd := exec.Command("go", args...)
log.Printf("running following go test:\n%s", cmd.String())
var (
outCloser io.Closer
errCloser io.Closer
outReader io.Reader
errReader io.Reader
outBuf = bytes.NewBuffer(nil)
eg = &errgroup.Group{}
)
if junitDir == "" {
cmd.Stdout = stdout
cmd.Stderr = stderr
} else {
outPipe, err := cmd.StdoutPipe()
if err != nil {
return &testReport{
err: err,
}
}
defer outPipe.Close()
outCloser = outPipe
outReader = io.TeeReader(outPipe, outBuf)
errPipe, err := cmd.StderrPipe()
if err != nil {
return &testReport{
err: err,
}
}
defer errPipe.Close()
errCloser = errPipe
errReader = io.TeeReader(errPipe, outBuf)
}
if err := cmd.Start(); err != nil {
return &testReport{
err: err,
}
}
if junitDir != "" {
eg.Go(func() error {
defer outCloser.Close()
_, err := io.Copy(stdout, outReader)
if err != nil && errors.Is(err, os.ErrClosed) {
err = nil
}
return err
})
eg.Go(func() error {
defer errCloser.Close()
_, err := io.Copy(stderr, errReader)
if err != nil && errors.Is(err, os.ErrClosed) {
err = nil
}
return err
})
}
eg.Go(cmd.Wait)
err := eg.Wait()
ret := &testReport{
err: err,
}
if junitDir != "" {
report, err := parser.NewParser().Parse(outBuf)
ret.report = &junitReport{
report: report,
err: err,
}
}
return ret
}
// Copied and pasted from
// https://github.com/jstemmer/go-junit-report/blob/v2.0.0/internal/gojunitreport/go-junit-report.go#L73-L93.
// So the license of the following line follows the original one.
func writeJUnitReportXML(w io.Writer, report gtr.Report) error {
testsuites := junit.CreateFromReport(report, "")
if _, err := fmt.Fprintf(w, xml.Header); err != nil {
return err
}
enc := xml.NewEncoder(w)
enc.Indent("", "\t")
if err := enc.Encode(testsuites); err != nil {
return err
}
if err := enc.Flush(); err != nil {
return err
}
_, err := fmt.Fprintf(w, "\n")
return err
}