forked from google/skia-buildbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run_unittests.go
562 lines (499 loc) · 16.6 KB
/
run_unittests.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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
package main
/*
This program runs all unit tests in the repository.
*/
import (
"bufio"
"bytes"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"runtime"
"strings"
"sync"
"time"
"go.skia.org/infra/go/common"
"go.skia.org/infra/go/fileutil"
"go.skia.org/infra/go/sklog"
"go.skia.org/infra/go/testutils/unittest"
"go.skia.org/infra/go/timer"
"go.skia.org/infra/go/util"
)
const (
// This gets filled out and printed when a test fails.
TEST_FAILURE = `
============================= TEST FAILURE =============================
Test: %s
Command: %s
Error:
%s
Full output:
------------------------------------------------------------------------
%s
------------------------------------------------------------------------
`
)
var (
// Error message shown when a required executable is not installed.
ERR_NEED_INSTALL = "%s failed to run! Is it installed? Error: %v"
// Directories with these names are skipped when searching for tests.
NO_CRAWL_DIR_NAMES = []string{
".git",
".recipe_deps",
"assets",
"bower_components",
"third_party",
"node_modules",
}
// Directories with these paths, relative to the checkout root, are
// skipped when searching for tests.
NO_CRAWL_REL_PATHS = []string{
"common",
}
POLYMER_PATHS = []string{
"res/imp",
"autoroll/res/imp",
"fuzzer/res/imp",
}
// goTestRegexp is a regular expression used for finding the durations
// of tests.
goTestRegexp = regexp.MustCompile("--- (\\w+):\\s+(\\w+)\\s+\\((.+)\\)")
// Flags.
race = flag.Bool("race", false, "Whether or not to enable the race flag when running go tests. This flag signals to only run go tests.")
// writeTimings is a file in which to write the test timings in JSON
// format.
writeTimings = flag.String("write_timings", "", "JSON file in which to write the test timings.")
// Every call to cmdTest uses a different KARMA_PORT.
nextKarmaPort = 9876
// ignoreGoImportsFailures is a regular expression that determines which files should be ignored
// if their goimports output differs from what is checked in.
ignoreGoImportsFailures = regexp.MustCompile(`^.*.pb.go`)
)
// cmdTest returns a test which runs a command and fails if the command fails.
func cmdTest(cmd []string, cwd, name, testType string) *test {
karmaPort := nextKarmaPort
nextKarmaPort++
return &test{
Name: name,
Cmd: strings.Join(cmd, " "),
run: func() (string, error) {
command := exec.Command(cmd[0], cmd[1:]...)
if cwd != "" {
command.Dir = cwd
}
command.Env = append(os.Environ(), fmt.Sprintf("KARMA_PORT=%d", karmaPort))
output, err := command.CombinedOutput()
if err != nil {
if _, err2 := exec.LookPath(cmd[0]); err2 != nil {
return string(output), fmt.Errorf(ERR_NEED_INSTALL, cmd[0], err)
}
}
return string(output), err
},
Type: testType,
}
}
func polylintTest(cwd, fileName string) *test {
cmd := []string{"polylint", "--no-recursion", "--root", cwd, "--input", fileName}
return &test{
Name: fmt.Sprintf("polylint in %s", filepath.Join(cwd, fileName)),
Cmd: strings.Join(cmd, " "),
run: func() (string, error) {
command := exec.Command(cmd[0], cmd[1:]...)
outputBytes, err := command.Output()
if err != nil {
if _, err2 := exec.LookPath(cmd[0]); err2 != nil {
return string(outputBytes), fmt.Errorf(ERR_NEED_INSTALL, cmd[0], err)
}
return string(outputBytes), err
}
unresolvedProblems := ""
count := 0
for s := bufio.NewScanner(bytes.NewBuffer(outputBytes)); s.Scan(); {
badFileLine := s.Text()
if !s.Scan() {
return string(outputBytes), fmt.Errorf("Unexpected end of polylint output after %q:\n%s", badFileLine, string(outputBytes))
}
problemLine := s.Text()
if !strings.Contains(unresolvedProblems, badFileLine) {
unresolvedProblems = fmt.Sprintf("%s\n%s\n%s", unresolvedProblems, badFileLine, problemLine)
count++
}
}
if unresolvedProblems == "" {
return "", nil
}
return "", fmt.Errorf("%d unresolved polylint problems:\n%s\n", count, unresolvedProblems)
},
Type: unittest.LARGE_TEST,
}
}
// buildPolymerFolder runs the Makefile in the given folder. This sets up the symbolic links so dependencies can be located for polylint.
func buildPolymerFolder(cwd string) error {
cmd := cmdTest([]string{"make", "deps"}, cwd, fmt.Sprintf("Polymer build in %s", cwd), unittest.LARGE_TEST)
return cmd.Run()
}
// polylintTestsForDir builds the folder once and then returns a list of tests for each Polymer file in the directory. If the build fails, a dummy test is returned that prints an error message.
func polylintTestsForDir(cwd string, fileNames ...string) []*test {
if err := buildPolymerFolder(cwd); err != nil {
return []*test{
{
Name: filepath.Join(cwd, "make"),
Cmd: filepath.Join(cwd, "make"),
run: func() (string, error) {
return "", fmt.Errorf("Could not build Polymer files in %s: %s", cwd, err)
},
Type: unittest.LARGE_TEST,
},
}
}
tests := make([]*test, 0, len(fileNames))
for _, name := range fileNames {
tests = append(tests, polylintTest(cwd, name))
}
return tests
}
// findPolymerFiles returns all files that probably contain polymer content
// (i.e. end with sk.html) in a given directory.
func findPolymerFiles(dirPath string) []string {
dir := fileutil.MustOpen(dirPath)
files := make([]string, 0)
for _, info := range fileutil.MustReaddir(dir) {
if n := info.Name(); strings.HasSuffix(info.Name(), "sk.html") {
files = append(files, n)
}
}
return files
}
//polylintTests creates a list of *test from all directories in POLYMER_PATHS
func polylintTests() []*test {
tests := make([]*test, 0)
for _, path := range POLYMER_PATHS {
tests = append(tests, polylintTestsForDir(path, findPolymerFiles(path)...)...)
}
return tests
}
// goTest returns a test which runs `go test` in the given cwd.
func goTest(cwd string, testType string, args ...string) *test {
cmd := []string{"go", "test", "-v", "./go/...", "-p", "1", "-parallel", "1"}
if *race {
cmd = append(cmd, "-race")
}
cmd = append(cmd, args...)
t := cmdTest(cmd, cwd, fmt.Sprintf("go tests (%s) in %s", testType, cwd), testType)
// Go tests print out their own timings. Parse them to obtain individual
// test times.
t.duration = func() map[string]time.Duration {
rv := map[string]time.Duration{}
split := strings.Split(t.output, "\n")
for _, line := range split {
m := goTestRegexp.FindStringSubmatch(line)
if len(m) == 4 {
if m[1] == "PASS" || m[1] == "FAIL" {
d, err := time.ParseDuration(m[3])
if err != nil {
sklog.Errorf("Got invalid test duration: %q", m[3])
continue
}
rv[m[2]] = d
}
}
}
return rv
}
return t
}
// goTestSmall returns a test which runs `go test --small` in the given cwd.
func goTestSmall(cwd string) *test {
return goTest(cwd, unittest.SMALL_TEST, "--small", "--timeout", unittest.TIMEOUT_SMALL)
}
// goTestMedium returns a test which runs `go test --medium` in the given cwd.
func goTestMedium(cwd string) *test {
return goTest(cwd, unittest.MEDIUM_TEST, "--medium", "--timeout", unittest.TIMEOUT_MEDIUM)
}
// goTestLarge returns a test which runs `go test --large` in the given cwd.
func goTestLarge(cwd string) *test {
return goTest(cwd, unittest.LARGE_TEST, "--large", "--timeout", unittest.TIMEOUT_LARGE)
}
// pythonTest returns a test which runs the given Python script and fails if
// the script fails.
func pythonTest(testPath string) *test {
return cmdTest([]string{"python", testPath}, ".", path.Base(testPath), unittest.SMALL_TEST)
}
// Verify that "go generate ./..." produces no diffs.
func goGenerate() *test {
cmd := []string{"go", "generate", "./..."}
return &test{
Name: "go generate",
Cmd: strings.Join(cmd, " "),
run: func() (string, error) {
// Run "git diff" to get a baseline.
diff, err := exec.Command("git", "diff", "--no-ext-diff").CombinedOutput()
if err != nil {
return string(diff), fmt.Errorf("Failed to run git diff: %s", err)
}
// Run "go generate".
command := exec.Command(cmd[0], cmd[1:]...)
outputBytes, err := command.CombinedOutput()
if err != nil {
return string(outputBytes), fmt.Errorf("Failed to run go generate: %s", err)
}
// Run "git diff" again and assert that the diff didn't
// change.
diff2, err := exec.Command("git", "diff", "--no-ext-diff").CombinedOutput()
if err != nil {
return string(diff2), fmt.Errorf("Failed to run git diff: %s", err)
}
if string(diff) != string(diff2) {
return fmt.Sprintf("Diff before:\n%s\n\nDiff after:\n%s", string(diff), string(diff2)), fmt.Errorf("go generate created new diffs!")
}
return "", nil
},
Type: unittest.LARGE_TEST,
}
}
// test is a struct which represents a single test to run.
type test struct {
// Name is the human-friendly name of the test.
Name string
// Cmd is the command to run.
Cmd string
// duration is a function which returns the duration(s) of the test(s).
duration func() map[string]time.Duration
// output contains the output from the command. It is only populated
// after Run() is called.
output string
// run is a function used to run the test. It returns any error and the
// output of the test.
run func() (string, error)
// totalTime is the duration of the test, populated after Run().
totalTime time.Duration
// Type is the small/medium/large categorization of the test.
Type string
}
// Run executes the function for the given test and returns an error if it fails.
func (t *test) Run() error {
if !util.In(t.Type, unittest.TEST_TYPES) {
sklog.Fatalf("Test %q has invalid type %q", t.Name, t.Type)
}
if !unittest.ShouldRun(t.Type) {
sklog.Infof("Not running %s tests; skipping %q", t.Type, t.Name)
return nil
}
started := time.Now()
defer func() {
t.totalTime = time.Now().Sub(started)
}()
output, err := t.run()
if err != nil {
return fmt.Errorf(TEST_FAILURE, t.Name, t.Cmd, err, output)
}
t.output = output
return nil
}
// Duration returns the duration(s) of the test(s) which ran.
func (t *test) Duration() map[string]time.Duration {
if t.duration == nil {
return map[string]time.Duration{t.Name: t.totalTime}
}
return t.duration()
}
// Find and run tests.
func main() {
common.Init()
// Ensure that we're actually going to run something.
ok := false
for _, tt := range unittest.TEST_TYPES {
if unittest.ShouldRun(tt) {
ok = true
}
}
if !ok {
sklog.Errorf("Must provide --small, --medium, and/or --large. This will cause an error in the future.")
}
defer timer.New("Finished").Stop()
_, filename, _, _ := runtime.Caller(0)
rootDir := path.Dir(filename)
if *race {
// Use alternative timeouts when --race is enabled because the tests
// inherently take longer with the extra instrumentation.
unittest.TIMEOUT_SMALL = unittest.TIMEOUT_RACE
unittest.TIMEOUT_MEDIUM = unittest.TIMEOUT_RACE
unittest.TIMEOUT_LARGE = unittest.TIMEOUT_RACE
}
// Gather all of the tests to run.
sklog.Info("Searching for tests.")
tests := []*test{goGenerate()}
gotests := []*test{}
// Search for Python tests and Go dirs to test in the repo.
// These tests are blacklisted from running on our bots because they
// depend on packages (django) which are not included with Python in
// CIPD.
pythonTestBlacklist := map[string]bool{
"csv_comparer_test.py": true,
"json_summary_combiner_test.py": true,
}
if err := filepath.Walk(rootDir, func(p string, info os.FileInfo, err error) error {
basename := path.Base(p)
if info.IsDir() {
// Skip some directories.
for _, skip := range NO_CRAWL_DIR_NAMES {
if basename == skip {
return filepath.SkipDir
}
}
for _, skip := range NO_CRAWL_REL_PATHS {
if p == path.Join(rootDir, skip) {
return filepath.SkipDir
}
}
if basename == "go" {
gotests = append(gotests, goTestSmall(path.Dir(p)))
gotests = append(gotests, goTestMedium(path.Dir(p)))
gotests = append(gotests, goTestLarge(path.Dir(p)))
}
}
if strings.HasSuffix(basename, "_test.py") && !pythonTestBlacklist[basename] {
tests = append(tests, pythonTest(p))
}
return nil
}); err != nil {
sklog.Fatal(err)
}
// Other tests.
tests = append(tests, cmdTest([]string{"go", "vet", "./..."}, ".", "go vet", unittest.SMALL_TEST))
tests = append(tests, cmdTest([]string{"errcheck", "-ignore", ":Close", "go.skia.org/infra/..."}, ".", "errcheck", unittest.MEDIUM_TEST))
tests = append(tests, cmdTest([]string{"go", "run", "prober/go/build_probers_json5/main.go", "--srcdir=.", "--dest=/tmp/allprobers.json5"}, ".", "probers test", unittest.MEDIUM_TEST))
tests = append(tests, cmdTest([]string{"python", "infra/bots/recipes.py", "test", "run"}, ".", "recipes test", unittest.MEDIUM_TEST))
tests = append(tests, cmdTest([]string{"go", "run", "infra/bots/gen_tasks.go", "--test"}, ".", "gen_tasks.go --test", unittest.SMALL_TEST))
tests = append(tests, cmdTest([]string{"python", "go/testutils/unittest/uncategorized_tests.py"}, ".", "uncategorized tests", unittest.SMALL_TEST))
tests = append(tests, cmdTest([]string{"make", "testci"}, "common-sk", "common-sk elements", unittest.MEDIUM_TEST))
tests = append(tests, cmdTest([]string{"make", "testci"}, "named-fiddles", "named-fiddles elements", unittest.MEDIUM_TEST))
tests = append(tests, cmdTest([]string{"make", "test"}, "push", "push elements", unittest.MEDIUM_TEST))
tests = append(tests, cmdTest([]string{"make"}, "licenses", "check go package licenses", unittest.MEDIUM_TEST))
if !*race {
// put this behind a flag because polylintTests trys to build the polymer files
tests = append(tests, polylintTests()...)
}
goimportsCmd := []string{"goimports", "-l", "."}
tests = append(tests, &test{
Name: "goimports",
Cmd: strings.Join(goimportsCmd, " "),
run: func() (string, error) {
command := exec.Command(goimportsCmd[0], goimportsCmd[1:]...)
output, err := command.Output()
outStr := strings.Trim(string(output), "\n")
if err != nil {
if _, err2 := exec.LookPath(goimportsCmd[0]); err2 != nil {
return outStr, fmt.Errorf(ERR_NEED_INSTALL, goimportsCmd[0], err)
}
// Sometimes goimports returns exit code 2, but gives no reason.
if outStr != "" {
return fmt.Sprintf("goimports output: %q", outStr), err
}
}
diffFiles := strings.Split(outStr, "\n")
if len(diffFiles) > 0 && !(len(diffFiles) == 1 && diffFiles[0] == "") {
nonGeneratedFound := false
for _, file := range diffFiles {
if !ignoreGoImportsFailures.Match([]byte(file)) {
nonGeneratedFound = true
break
}
}
if nonGeneratedFound {
return outStr, fmt.Errorf("goimports found diffs in the following files:\n - %s", strings.Join(diffFiles, ",\n - "))
}
}
return "", nil
},
Type: unittest.MEDIUM_TEST,
})
gosimplifyCmd := []string{"gofmt", "-s", "-d", "."}
tests = append(tests, &test{
Name: "go simplify (gofmt -s -w .)",
Cmd: strings.Join(gosimplifyCmd, " "),
run: func() (string, error) {
command := exec.Command(gosimplifyCmd[0], gosimplifyCmd[1:]...)
output, err := command.Output()
outStr := strings.Trim(string(output), "\n")
if err != nil {
if _, err2 := exec.LookPath(gosimplifyCmd[0]); err2 != nil {
return outStr, fmt.Errorf(ERR_NEED_INSTALL, gosimplifyCmd[0], err)
}
}
if outStr != "" {
return outStr, fmt.Errorf(`gofmt -s detects diffs. run "gofmt -s -w ." to apply fixes`)
}
return "", nil
},
Type: unittest.SMALL_TEST,
})
if *race {
tests = gotests
} else {
tests = append(gotests, tests...)
}
// Run the tests.
sklog.Infof("Found %d tests.", len(tests))
errors := map[string]error{}
if *race {
// Do unit tests one at a time, as the -race can fail when done concurrently with a bunch of other stuff.
for _, t := range gotests {
if err := t.Run(); err != nil {
errors[t.Name] = err
}
sklog.Infof("Finished %s", t.Name)
}
} else {
var mutex sync.Mutex
var wg sync.WaitGroup
for _, t := range tests {
wg.Add(1)
go func(t *test) {
defer wg.Done()
sklog.Debugf("Running %s", t.Name)
if err := t.Run(); err != nil {
mutex.Lock()
errors[t.Name] = err
mutex.Unlock()
}
}(t)
}
wg.Wait()
}
// Collect test durations.
durations := map[string]time.Duration{}
for _, t := range tests {
for k, v := range t.Duration() {
if _, ok := durations[k]; ok {
sklog.Errorf("Duplicate test name %q; not keeping timing.", k)
continue
}
durations[k] = v
}
}
if *writeTimings != "" {
b, err := json.MarshalIndent(durations, "", " ")
if err != nil {
errors["encode output"] = err
} else {
if err := ioutil.WriteFile(*writeTimings, b, os.ModePerm); err != nil {
errors["write output"] = err
}
}
}
if len(errors) > 0 {
for _, e := range errors {
sklog.Error(e)
}
os.Exit(1)
}
sklog.Info("All tests succeeded.")
}