-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathalt_exit_test.go
More file actions
167 lines (143 loc) · 4.49 KB
/
alt_exit_test.go
File metadata and controls
167 lines (143 loc) · 4.49 KB
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
package logrus_test
import (
"crypto/sha256"
"encoding/hex"
"errors"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"testing"
"github.com/sirupsen/logrus"
)
func TestRegister(t *testing.T) {
if reexecTest(t, "register", func(t *testing.T) {
outfile := os.Args[len(os.Args)-1]
logrus.RegisterExitHandler(func() { appendLine(outfile, "first") })
logrus.RegisterExitHandler(func() { appendLine(outfile, "second") })
logrus.Exit(23)
}) {
return
}
outfile := filepath.Join(t.TempDir(), "out.txt")
cmd := reexecCommand(t, "register", outfile)
out, err := cmd.CombinedOutput()
var ee *exec.ExitError
if !errors.As(err, &ee) {
t.Fatalf("expected *exec.ExitError, got %T: %v (out=%s)", err, err, out)
}
if ee.ExitCode() != 23 {
t.Fatalf("expected exit 23, got %d (out=%s)", ee.ExitCode(), out)
}
want := "first\nsecond\n"
assertFileContent(t, outfile, want, out)
}
func TestDefer(t *testing.T) {
if reexecTest(t, "defer", func(t *testing.T) {
outfile := os.Args[len(os.Args)-1]
logrus.DeferExitHandler(func() { appendLine(outfile, "first") })
logrus.DeferExitHandler(func() { appendLine(outfile, "second") })
logrus.Exit(23)
}) {
return
}
outfile := filepath.Join(t.TempDir(), "out.txt")
cmd := reexecCommand(t, "defer", outfile)
out, err := cmd.CombinedOutput()
var ee *exec.ExitError
if !errors.As(err, &ee) {
t.Fatalf("expected *exec.ExitError, got %T: %v (out=%s)", err, err, out)
}
if ee.ExitCode() != 23 {
t.Fatalf("expected exit 23, got %d (out=%s)", ee.ExitCode(), out)
}
want := "second\nfirst\n"
assertFileContent(t, outfile, want, out)
}
func TestHandler(t *testing.T) {
const payload = "payload"
if reexecTest(t, "handler", func(t *testing.T) {
outfile := os.Args[len(os.Args)-1]
logrus.RegisterExitHandler(func() {
_ = os.WriteFile(outfile, []byte(payload), 0o666)
})
logrus.RegisterExitHandler(func() { panic("bad handler") })
logrus.Exit(23)
}) {
return
}
outfile := filepath.Join(t.TempDir(), "outfile.out")
cmd := reexecCommand(t, "handler", outfile)
out, err := cmd.CombinedOutput()
var ee *exec.ExitError
if !errors.As(err, &ee) {
t.Fatalf("expected *exec.ExitError, got %T: %v (out=%s)", err, err, out)
}
if ee.ExitCode() != 23 {
t.Fatalf("expected exit 23, got %d (out=%s)", ee.ExitCode(), out)
}
want := payload
assertFileContent(t, outfile, want, out)
}
func appendLine(path, s string) {
b, err := os.ReadFile(path)
if err != nil && !os.IsNotExist(err) {
_, _ = os.Stderr.WriteString("appendLine: read " + path + ": " + err.Error() + "\n")
os.Exit(1)
}
b = append(b, []byte(s+"\n")...)
if err := os.WriteFile(path, b, 0o666); err != nil {
_, _ = os.Stderr.WriteString("appendLine: write " + path + ": " + err.Error() + "\n")
os.Exit(1)
}
}
func assertFileContent(t *testing.T, path, want string, childOut []byte) {
t.Helper()
b, err := os.ReadFile(path)
if err != nil {
t.Fatalf("can't read output file: %v (child out=%s)", err, childOut)
}
if got := string(b); got != want {
t.Fatalf("unexpected file content: got %q, want %q (child out=%s)", got, want, childOut)
}
}
const tokenPrefix = "reexectest-"
// argv0Token computes a short deterministic token for (t.Name(), name).
func argv0Token(t *testing.T, name string) string {
sum := sha256.Sum256([]byte(t.Name() + "\x00" + name))
return tokenPrefix + hex.EncodeToString(sum[:8]) // 16 hex chars
}
// reexecTest runs fn if this process is the child (argv0 == token).
// Returns true in the child (caller should return).
func reexecTest(t *testing.T, name string, f func(t *testing.T)) bool {
t.Helper()
if os.Args[0] != argv0Token(t, name) {
return false
}
// Scrub the "-test.run=<pattern>" that was injected by reexecCommand.
origArgs := os.Args
if len(os.Args) > 1 && strings.HasPrefix(os.Args[1], "-test.run=") {
os.Args = append(os.Args[:1], os.Args[2:]...)
defer func() { os.Args = origArgs }()
}
f(t)
return true
}
// reexecCommand builds a command that execs the current test binary (exe)
// with argv0 set to token and "-test.run=<pattern>" so the child runs only
// this test/subtest. extraArgs are appended after that; the parent can pass
// the outfile as extra arg, etc.
func reexecCommand(t *testing.T, name string, args ...string) *exec.Cmd {
t.Helper()
exe, err := os.Executable()
if err != nil {
t.Fatalf("os.Executable(): %v", err)
}
argv0 := argv0Token(t, name)
pattern := "^" + regexp.QuoteMeta(t.Name()) + "$"
cmd := exec.Command(exe)
cmd.Path = exe
cmd.Args = append([]string{argv0, "-test.run=" + pattern}, args...)
return cmd
}