summaryrefslogtreecommitdiffhomepage
path: root/cmd/testwrapper/testwrapper_test.go
blob: 46400fd1c0a670d297e5c5b434045894f9eef81f (plain)
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
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause

package main_test

import (
	"bytes"
	"errors"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"runtime"
	"strings"
	"sync"
	"testing"
)

var (
	buildPath string
	buildErr  error
	buildOnce sync.Once
)

func cmdTestwrapper(t *testing.T, args ...string) *exec.Cmd {
	buildOnce.Do(func() {
		buildPath, buildErr = buildTestWrapper()
	})
	if buildErr != nil {
		t.Fatalf("building testwrapper: %s", buildErr)
	}
	return exec.Command(buildPath, args...)
}

func buildTestWrapper() (string, error) {
	dir, err := os.MkdirTemp("", "testwrapper")
	if err != nil {
		return "", fmt.Errorf("making temp dir: %w", err)
	}
	_, err = exec.Command("go", "build", "-o", dir, ".").Output()
	if err != nil {
		return "", fmt.Errorf("go build: %w", err)
	}
	return filepath.Join(dir, "testwrapper"), nil
}

func TestRetry(t *testing.T) {
	t.Parallel()

	testfile := filepath.Join(t.TempDir(), "retry_test.go")
	code := []byte(`package retry_test

import (
	"os"
	"testing"
	"tailscale.com/cmd/testwrapper/flakytest"
)

func TestOK(t *testing.T) {}

func TestFlakeRun(t *testing.T) {
	flakytest.Mark(t, "https://github.com/tailscale/tailscale/issues/0") // random issue
	e := os.Getenv(flakytest.FlakeAttemptEnv)
	if e == "" {
		t.Skip("not running in testwrapper")
	}
	if e == "1" {
		t.Fatal("First run in testwrapper, failing so that test is retried. This is expected.")
	}
}
`)
	if err := os.WriteFile(testfile, code, 0o644); err != nil {
		t.Fatalf("writing package: %s", err)
	}

	out, err := cmdTestwrapper(t, "-v", testfile).CombinedOutput()
	if err != nil {
		t.Fatalf("go run . %s: %s with output:\n%s", testfile, err, out)
	}

	// Replace the unpredictable timestamp with "0.00s".
	out = regexp.MustCompile(`\t\d+\.\d\d\ds\t`).ReplaceAll(out, []byte("\t0.00s\t"))

	want := []byte("ok\t" + testfile + "\t0.00s\t[attempt=2]")
	if !bytes.Contains(out, want) {
		t.Fatalf("wanted output containing %q but got:\n%s", want, out)
	}

	if okRuns := bytes.Count(out, []byte("=== RUN   TestOK")); okRuns != 1 {
		t.Fatalf("expected TestOK to be run once but was run %d times in output:\n%s", okRuns, out)
	}
	if flakeRuns := bytes.Count(out, []byte("=== RUN   TestFlakeRun")); flakeRuns != 2 {
		t.Fatalf("expected TestFlakeRun to be run twice but was run %d times in output:\n%s", flakeRuns, out)
	}

	if testing.Verbose() {
		t.Logf("success - output:\n%s", out)
	}
}

func TestNoRetry(t *testing.T) {
	t.Parallel()

	testfile := filepath.Join(t.TempDir(), "noretry_test.go")
	code := []byte(`package noretry_test

import (
	"testing"
	"tailscale.com/cmd/testwrapper/flakytest"
)

func TestFlakeRun(t *testing.T) {
	flakytest.Mark(t, "https://github.com/tailscale/tailscale/issues/0") // random issue
	t.Error("shouldn't be retried")
}

func TestAlwaysError(t *testing.T) {
	t.Error("error")
}
`)
	if err := os.WriteFile(testfile, code, 0o644); err != nil {
		t.Fatalf("writing package: %s", err)
	}

	out, err := cmdTestwrapper(t, "-v", testfile).Output()
	if err == nil {
		t.Fatalf("go run . %s: expected error but it succeeded with output:\n%s", testfile, out)
	}
	if code, ok := errExitCode(err); ok && code != 1 {
		t.Fatalf("expected exit code 1 but got %d", code)
	}

	want := []byte("Not retrying flaky tests because non-flaky tests failed.")
	if !bytes.Contains(out, want) {
		t.Fatalf("wanted output containing %q but got:\n%s", want, out)
	}

	if flakeRuns := bytes.Count(out, []byte("=== RUN   TestFlakeRun")); flakeRuns != 1 {
		t.Fatalf("expected TestFlakeRun to be run once but was run %d times in output:\n%s", flakeRuns, out)
	}

	if testing.Verbose() {
		t.Logf("success - output:\n%s", out)
	}
}

func TestBuildError(t *testing.T) {
	t.Parallel()

	// Construct our broken package.
	testfile := filepath.Join(t.TempDir(), "builderror_test.go")
	code := []byte("package builderror_test\n\nderp")
	err := os.WriteFile(testfile, code, 0o644)
	if err != nil {
		t.Fatalf("writing package: %s", err)
	}

	wantErr := "builderror_test.go:3:1: expected declaration, found derp\nFAIL"

	// Confirm `go test` exits with code 1.
	goOut, err := exec.Command("go", "test", testfile).CombinedOutput()
	if code, ok := errExitCode(err); !ok || code != 1 {
		t.Fatalf("go test %s: got exit code %d, want 1 (err: %v)", testfile, code, err)
	}
	if !strings.Contains(string(goOut), wantErr) {
		t.Fatalf("go test %s: got output %q, want output containing %q", testfile, goOut, wantErr)
	}

	// Confirm `testwrapper` exits with code 1.
	twOut, err := cmdTestwrapper(t, testfile).CombinedOutput()
	if code, ok := errExitCode(err); !ok || code != 1 {
		t.Fatalf("testwrapper %s: got exit code %d, want 1 (err: %v)", testfile, code, err)
	}
	if !strings.Contains(string(twOut), wantErr) {
		t.Fatalf("testwrapper %s: got output %q, want output containing %q", testfile, twOut, wantErr)
	}

	if testing.Verbose() {
		t.Logf("success - output:\n%s", twOut)
	}
}

func TestTimeout(t *testing.T) {
	t.Parallel()

	// Construct our broken package.
	testfile := filepath.Join(t.TempDir(), "timeout_test.go")
	code := []byte(`package noretry_test

import (
	"testing"
	"time"
)

func TestTimeout(t *testing.T) {
	time.Sleep(500 * time.Millisecond)
}
`)
	err := os.WriteFile(testfile, code, 0o644)
	if err != nil {
		t.Fatalf("writing package: %s", err)
	}

	out, err := cmdTestwrapper(t, testfile, "-timeout=20ms").CombinedOutput()
	if code, ok := errExitCode(err); !ok || code != 1 {
		t.Fatalf("testwrapper %s: expected error with exit code 0 but got: %v; output was:\n%s", testfile, err, out)
	}
	if want := "panic: test timed out after 20ms"; !bytes.Contains(out, []byte(want)) {
		t.Fatalf("testwrapper %s: expected build error containing %q but got:\n%s", testfile, buildErr, out)
	}

	if testing.Verbose() {
		t.Logf("success - output:\n%s", out)
	}
}

func TestCached(t *testing.T) {
	t.Parallel()

	// Construct our trivial package.
	pkgDir := t.TempDir()
	goVersion := runtime.Version()
	goVersion = strings.TrimPrefix(goVersion, "go")
	goVersion, _, _ = strings.Cut(goVersion, "-X:") // map 1.26.1-X:nogreenteagc to 1.26.1

	goMod := fmt.Sprintf(`module example.com

go %s
`, goVersion)
	test := `package main
import "testing"

func TestCached(t *testing.T) {}
`

	for f, c := range map[string]string{
		"go.mod":         goMod,
		"cached_test.go": test,
	} {
		err := os.WriteFile(filepath.Join(pkgDir, f), []byte(c), 0o644)
		if err != nil {
			t.Fatalf("writing package: %s", err)
		}
	}

	for name, args := range map[string][]string{
		"without_flags":     {"./..."},
		"with_short":        {"./...", "-short"},
		"with_coverprofile": {"./...", "-coverprofile=" + filepath.Join(t.TempDir(), "coverage.out")},
	} {
		t.Run(name, func(t *testing.T) {
			var (
				out []byte
				err error
			)
			for range 2 {
				cmd := cmdTestwrapper(t, args...)
				cmd.Dir = pkgDir
				out, err = cmd.CombinedOutput()
				if err != nil {
					t.Fatalf("testwrapper ./...: expected no error but got: %v; output was:\n%s", err, out)
				}
			}

			want := []byte("ok\texample.com\t(cached)")
			if !bytes.Contains(out, want) {
				t.Fatalf("wanted output containing %q but got:\n%s", want, out)
			}

			if testing.Verbose() {
				t.Logf("success - output:\n%s", out)
			}
		})
	}
}

func errExitCode(err error) (int, bool) {
	if exit, ok := errors.AsType[*exec.ExitError](err); ok {
		return exit.ExitCode(), true
	}
	return 0, false
}