-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.go
More file actions
275 lines (242 loc) · 6.09 KB
/
Copy pathmain_test.go
File metadata and controls
275 lines (242 loc) · 6.09 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
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
package main
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"net"
"os"
osexec "os/exec"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/rogpeppe/go-internal/testscript"
"github.com/artefactual-labs/migrate/internal/ssmock"
"github.com/artefactual-labs/migrate/internal/testutil"
)
func TestMain(m *testing.M) {
testscript.Main(m, map[string]func(){
"migrate": main,
})
}
func TestScripts(t *testing.T) {
testscript.Run(t, testscript.Params{
Dir: "testdata",
Cmds: map[string]func(ts *testscript.TestScript, neg bool, args []string){
"temporal": temporalCmd,
"worker": workerCmd,
"ssmock": ssmock.TestScriptCmd,
},
})
}
func workerCmd(ts *testscript.TestScript, neg bool, args []string) {
if neg {
ts.Fatalf("worker: negation not supported")
}
// Parse flags
fs := flag.NewFlagSet("worker", flag.ContinueOnError)
fs.SetOutput(io.Discard)
updateConfigFlag := fs.Bool("update-config", false, "update migrate config.json before starting worker")
if err := fs.Parse(args); err != nil {
ts.Fatalf("worker: %v", err)
}
// Optionally update the config file with Temporal address
if *updateConfigFlag {
temporalAddr := ts.Getenv("TEMPORAL_ADDRESS")
if temporalAddr == "" {
ts.Fatalf("worker: TEMPORAL_ADDRESS not set, start temporal server first")
}
if err := updateConfig(ts, temporalAddr); err != nil {
ts.Fatalf("worker: unable to update config: %v", err)
}
}
// Create a cancellable context
ctx, cancel := context.WithCancel(context.Background())
// Prepare to call exec with the "worker" subcommand
workerArgs := []string{"worker"}
if len(fs.Args()) > 0 {
workerArgs = append(workerArgs, fs.Args()...)
}
// Run the worker in a goroutine
errCh := make(chan error, 1)
go func() {
var stdout, stderr bytes.Buffer
err := exec(ctx, workerArgs, os.Stdin, &stdout, &stderr)
if stdout.Len() > 0 {
_, _ = fmt.Fprint(ts.Stdout(), stdout.String())
}
if stderr.Len() > 0 {
_, _ = fmt.Fprint(ts.Stderr(), stderr.String())
}
errCh <- err
}()
// Set up cleanup
var errConsumed bool
ts.Defer(func() {
if errConsumed {
return
}
cancel()
select {
case err := <-errCh:
errConsumed = true
if err != nil && ctx.Err() == nil {
ts.Logf("worker: exit error: %v", err)
}
case <-time.After(2 * time.Second):
errConsumed = true
ts.Logf("worker: shutdown timeout")
}
})
// Give the worker a moment to start
time.Sleep(500 * time.Millisecond)
// Check if it crashed immediately
select {
case err := <-errCh:
errConsumed = true
if err != nil {
ts.Fatalf("worker: failed to start: %v", err)
}
ts.Fatalf("worker: exited unexpectedly")
default:
ts.Logf("worker: started")
}
}
func temporalCmd(ts *testscript.TestScript, _ bool, args []string) {
port, err := testutil.FreePort()
if err != nil {
ts.Fatalf("temporal: get free port: %v", err)
}
addr := fmt.Sprintf("127.0.0.1:%d", port)
ts.Setenv("TEMPORAL_ADDRESS", addr)
if len(args) > 0 && args[0] == "--update-config" {
if err := updateConfig(ts, addr); err != nil {
ts.Fatalf("temporal: unable to update config: %v", err)
}
}
stdout := &safeBuffer{}
stderr := &safeBuffer{}
cmd := osexec.Command("go", []string{
"tool",
"bine",
"run",
"--",
"temporal",
"server",
"start-dev",
"--headless",
"--port",
strconv.Itoa(port),
}...)
cmd.Stdout = stdout
cmd.Stderr = stderr
if err := cmd.Start(); err != nil {
ts.Fatalf("temporal: start: %v", err)
}
waitCh := make(chan error, 1)
var waitConsumed bool
go func() {
waitCh <- cmd.Wait()
}()
ts.Defer(func() {
if waitConsumed {
return
}
_ = cmd.Process.Signal(os.Interrupt)
select {
case err := <-waitCh:
waitConsumed = true
if err != nil {
ts.Logf("temporal: exit error: %v", err)
logTemporalOutput(ts, stdout, stderr)
}
case <-time.After(2 * time.Second):
_ = cmd.Process.Kill()
err := <-waitCh
waitConsumed = true
if err != nil {
ts.Logf("temporal: exit error after kill: %v", err)
logTemporalOutput(ts, stdout, stderr)
}
}
})
deadline := time.Now().Add(600 * time.Second)
for {
select {
case err := <-waitCh:
waitConsumed = true
if err != nil {
ts.Logf("temporal: exited before ready: %v", err)
logTemporalOutput(ts, stdout, stderr)
ts.Fatalf("temporal: exited before ready: %v", err)
}
ts.Fatalf("temporal: exited before ready")
default:
}
conn, err := net.DialTimeout("tcp", addr, 250*time.Millisecond)
if err == nil {
_ = conn.Close()
break
}
if time.Now().After(deadline) {
ts.Logf("temporal: server not ready: %v", err)
logTemporalOutput(ts, stdout, stderr)
ts.Fatalf("temporal: server not ready: %v", err)
}
time.Sleep(100 * time.Millisecond)
}
ts.Logf("temporal dev server listening on %s", addr)
}
func updateConfig(ts *testscript.TestScript, temporalAddr string) error {
configPath := ts.MkAbs("config.json")
data, err := os.ReadFile(configPath)
if err != nil {
return err
}
var config map[string]any
if err := json.Unmarshal(data, &config); err != nil {
return err
}
if config["temporal"] == nil {
config["temporal"] = make(map[string]any)
}
temporalConfig, ok := config["temporal"].(map[string]any)
if !ok {
// Handle case where "temporal" exists but is not a map.
// For this implementation, we'll overwrite it.
temporalConfig = make(map[string]any)
config["temporal"] = temporalConfig
}
temporalConfig["address"] = temporalAddr
updatedData, err := json.MarshalIndent(config, "", " ")
if err != nil {
return err
}
return os.WriteFile(configPath, updatedData, 0o644)
}
func logTemporalOutput(ts *testscript.TestScript, stdout, stderr *safeBuffer) {
if out := strings.TrimSpace(stdout.String()); out != "" {
ts.Logf("temporal stdout:\n%s", out)
}
if errOut := strings.TrimSpace(stderr.String()); errOut != "" {
ts.Logf("temporal stderr:\n%s", errOut)
}
}
type safeBuffer struct {
mu sync.Mutex
buf bytes.Buffer
}
func (sb *safeBuffer) Write(p []byte) (int, error) {
sb.mu.Lock()
defer sb.mu.Unlock()
return sb.buf.Write(p)
}
func (sb *safeBuffer) String() string {
sb.mu.Lock()
defer sb.mu.Unlock()
return sb.buf.String()
}