-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathmysql_test.go
More file actions
403 lines (332 loc) · 11.2 KB
/
Copy pathmysql_test.go
File metadata and controls
403 lines (332 loc) · 11.2 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
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
package mysql
import (
"context"
"database/sql"
"fmt"
"strings"
"testing"
"github.com/cschleiden/go-workflows/backend"
"github.com/cschleiden/go-workflows/backend/history"
"github.com/cschleiden/go-workflows/backend/test"
"github.com/google/uuid"
)
const testUser = "root"
const testPassword = "root"
// Creating and dropping databases is terribly inefficient, but easiest for complete test isolation. For
// the future consider nested transactions, or manually TRUNCATE-ing the tables in-between tests.
func Test_MysqlBackend(t *testing.T) {
if testing.Short() {
t.Skip()
}
var dbName string
test.BackendTest(t, func(options ...backend.BackendOption) test.TestBackend {
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@/?parseTime=true&interpolateParams=true", testUser, testPassword))
if err != nil {
panic(err)
}
dbName = "test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
if _, err := db.Exec("CREATE DATABASE " + dbName); err != nil {
panic(fmt.Errorf("creating database: %w", err))
}
if err := db.Close(); err != nil {
panic(err)
}
options = append(options, backend.WithStickyTimeout(0))
return NewMysqlBackend("localhost", 3306, testUser, testPassword, dbName, WithBackendOptions(options...))
}, func(b test.TestBackend) {
if err := b.(*mysqlBackend).db.Close(); err != nil {
panic(err)
}
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@/?parseTime=true&interpolateParams=true", testUser, testPassword))
if err != nil {
panic(err)
}
if _, err := db.Exec("DROP DATABASE IF EXISTS " + dbName); err != nil {
panic(fmt.Errorf("dropping database: %w", err))
}
if err := db.Close(); err != nil {
panic(err)
}
})
}
func TestMySqlBackendE2E(t *testing.T) {
if testing.Short() {
t.Skip()
}
var dbName string
test.EndToEndBackendTest(t, func(options ...backend.BackendOption) test.TestBackend {
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@/?parseTime=true&interpolateParams=true", testUser, testPassword))
if err != nil {
panic(err)
}
dbName = "test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
if _, err := db.Exec("CREATE DATABASE " + dbName); err != nil {
panic(fmt.Errorf("creating database: %w", err))
}
if err := db.Close(); err != nil {
panic(err)
}
options = append(options, backend.WithStickyTimeout(0))
return NewMysqlBackend("localhost", 3306, testUser, testPassword, dbName, WithBackendOptions(options...))
}, func(b test.TestBackend) {
if err := b.(*mysqlBackend).db.Close(); err != nil {
panic(err)
}
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@/?parseTime=true&interpolateParams=true", testUser, testPassword))
if err != nil {
panic(err)
}
if _, err := db.Exec("DROP DATABASE IF EXISTS " + dbName); err != nil {
panic(fmt.Errorf("dropping database: %w", err))
}
if err := db.Close(); err != nil {
panic(err)
}
})
}
func Test_MysqlBackendWithCustomMigrationsTable(t *testing.T) {
if testing.Short() {
t.Skip()
}
adminDB, err := sql.Open("mysql", fmt.Sprintf("%s:%s@/?parseTime=true&interpolateParams=true", testUser, testPassword))
if err != nil {
t.Fatal(err)
}
dbName := "test_migration_table_" + strings.ReplaceAll(uuid.NewString(), "-", "")
if _, err := adminDB.Exec("CREATE DATABASE " + dbName); err != nil {
t.Fatal(err)
}
defer func() {
adminDB.Exec("DROP DATABASE IF EXISTS " + dbName)
adminDB.Close()
}()
dsn := fmt.Sprintf("%s:%s@tcp(localhost:3306)/%s?parseTime=true&interpolateParams=true", testUser, testPassword, dbName)
db, err := sql.Open("mysql", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
if _, err := db.Exec("CREATE TABLE schema_migrations (version bigint not null primary key, dirty boolean not null)"); err != nil {
t.Fatal(err)
}
if _, err := db.Exec("INSERT INTO schema_migrations (version, dirty) VALUES (10, false)"); err != nil {
t.Fatal(err)
}
backend := NewMysqlBackendWithDB(
db,
WithApplyMigrations(true),
WithMigrationDSN(dsn+"&multiStatements=true"),
WithMigrationsTable("go_workflows_schema_migrations"),
)
defer backend.Close()
if _, err := db.Exec("SELECT 1 FROM instances LIMIT 1"); err != nil {
t.Fatalf("table should exist after migrations: %v", err)
}
var defaultVersion int
if err := db.QueryRow("SELECT version FROM schema_migrations").Scan(&defaultVersion); err != nil {
t.Fatal(err)
}
if defaultVersion != 10 {
t.Fatalf("expected default migration table version 10, got %d", defaultVersion)
}
var workflowsVersion int
if err := db.QueryRow("SELECT version FROM go_workflows_schema_migrations").Scan(&workflowsVersion); err != nil {
t.Fatal(err)
}
if workflowsVersion != 4 {
t.Fatalf("expected workflows migration table version 4, got %d", workflowsVersion)
}
}
var _ test.TestBackend = (*mysqlBackend)(nil)
func (mb *mysqlBackend) GetFutureEvents(ctx context.Context) ([]*history.Event, error) {
tx, err := mb.db.BeginTx(ctx, nil)
if err != nil {
return nil, err
}
defer tx.Rollback()
// There is no index on `visible_at`, but this is okay for test only usage.
futureEvents, err := tx.QueryContext(
ctx,
"SELECT pe.id, pe.sequence_id, pe.instance_id, pe.execution_id, pe.event_type, pe.timestamp, pe.schedule_event_id, pe.visible_at, a.data FROM `pending_events` pe JOIN `attributes` a ON a.id = pe.id AND a.instance_id = pe.instance_id AND a.execution_id = pe.execution_id WHERE pe.visible_at IS NOT NULL",
)
if err != nil {
return nil, fmt.Errorf("getting history: %w", err)
}
defer futureEvents.Close()
f := make([]*history.Event, 0)
for futureEvents.Next() {
var instanceID string
var attributes []byte
fe := &history.Event{}
if err := futureEvents.Scan(
&fe.ID,
&fe.SequenceID,
&instanceID,
&fe.Type,
&fe.Timestamp,
&fe.ScheduleEventID,
&attributes,
&fe.VisibleAt,
); err != nil {
return nil, fmt.Errorf("scanning event: %w", err)
}
a, err := history.DeserializeAttributes(fe.Type, attributes)
if err != nil {
return nil, fmt.Errorf("deserializing attributes: %w", err)
}
fe.Attributes = a
f = append(f, fe)
}
if futureEvents.Err() != nil {
return nil, futureEvents.Err()
}
return f, nil
}
func Test_MysqlBackend_WorkerName(t *testing.T) {
if testing.Short() {
t.Skip()
}
t.Run("DefaultWorkerName", func(t *testing.T) {
// Create a backend without specifying worker name
// Since we can't connect to MySQL without it being available, we'll test the getWorkerName function directly
options := &options{
Options: backend.ApplyOptions(),
}
workerName := getWorkerName(options)
// The default worker name should be in the format "worker-<uuid>"
if !strings.Contains(workerName, "worker-") {
t.Errorf("Expected worker name to contain 'worker-', got: %s", workerName)
}
if len(workerName) != 43 { // "worker-" (7) + UUID (36)
t.Errorf("Expected worker name length to be 43, got: %d", len(workerName))
}
})
t.Run("CustomWorkerName", func(t *testing.T) {
customWorkerName := "test-worker-123"
options := &options{
Options: backend.ApplyOptions(backend.WithWorkerName(customWorkerName)),
}
workerName := getWorkerName(options)
if workerName != customWorkerName {
t.Errorf("Expected worker name to be '%s', got: %s", customWorkerName, workerName)
}
})
t.Run("EmptyWorkerNameUsesDefault", func(t *testing.T) {
options := &options{
Options: backend.ApplyOptions(backend.WithWorkerName("")),
}
workerName := getWorkerName(options)
// Empty worker name should fall back to UUID generation
if !strings.Contains(workerName, "worker-") {
t.Errorf("Expected worker name to contain 'worker-', got: %s", workerName)
}
if len(workerName) != 43 { // "worker-" (7) + UUID (36)
t.Errorf("Expected worker name length to be 43, got: %d", len(workerName))
}
})
}
func Test_MysqlBackendWithDB(t *testing.T) {
if testing.Short() {
t.Skip()
}
t.Run("UsesProvidedConnection", func(t *testing.T) {
// Create database for test
adminDB, err := sql.Open("mysql", fmt.Sprintf("%s:%s@/?parseTime=true&interpolateParams=true", testUser, testPassword))
if err != nil {
t.Fatal(err)
}
dbName := "test_withdb_" + strings.ReplaceAll(uuid.NewString(), "-", "")
if _, err := adminDB.Exec("CREATE DATABASE " + dbName); err != nil {
t.Fatal(err)
}
defer func() {
adminDB.Exec("DROP DATABASE IF EXISTS " + dbName)
adminDB.Close()
}()
// Create our own connection to the test database
dsn := fmt.Sprintf("%s:%s@tcp(localhost:3306)/%s?parseTime=true&interpolateParams=true", testUser, testPassword, dbName)
db, err := sql.Open("mysql", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
// Create backend with existing connection and migration DSN
migrationDSN := dsn + "&multiStatements=true"
backend := NewMysqlBackendWithDB(db,
WithApplyMigrations(true),
WithMigrationDSN(migrationDSN),
)
// Verify the backend uses our connection
if backend.db != db {
t.Error("Backend should use provided db connection")
}
if backend.ownsConnection {
t.Error("Backend should not own the connection")
}
// Close backend - should NOT close our connection
if err := backend.Close(); err != nil {
t.Fatal(err)
}
// Verify our connection is still usable
if err := db.Ping(); err != nil {
t.Errorf("Connection should still be open after backend.Close(): %v", err)
}
})
t.Run("MigrationsDisabledByDefault", func(t *testing.T) {
// Create database for test
adminDB, err := sql.Open("mysql", fmt.Sprintf("%s:%s@/?parseTime=true&interpolateParams=true", testUser, testPassword))
if err != nil {
t.Fatal(err)
}
dbName := "test_withdb2_" + strings.ReplaceAll(uuid.NewString(), "-", "")
if _, err := adminDB.Exec("CREATE DATABASE " + dbName); err != nil {
t.Fatal(err)
}
defer func() {
adminDB.Exec("DROP DATABASE IF EXISTS " + dbName)
adminDB.Close()
}()
dsn := fmt.Sprintf("%s:%s@tcp(localhost:3306)/%s?parseTime=true&interpolateParams=true", testUser, testPassword, dbName)
db, err := sql.Open("mysql", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
// Create backend without enabling migrations
backend := NewMysqlBackendWithDB(db)
defer backend.Close()
// Tables should not exist since migrations weren't applied
_, err = db.Exec("SELECT 1 FROM instances LIMIT 1")
if err == nil {
t.Error("Expected error because table should not exist")
}
})
t.Run("MigrationFailsWithoutDSN", func(t *testing.T) {
// Create database for test
adminDB, err := sql.Open("mysql", fmt.Sprintf("%s:%s@/?parseTime=true&interpolateParams=true", testUser, testPassword))
if err != nil {
t.Fatal(err)
}
dbName := "test_withdb3_" + strings.ReplaceAll(uuid.NewString(), "-", "")
if _, err := adminDB.Exec("CREATE DATABASE " + dbName); err != nil {
t.Fatal(err)
}
defer func() {
adminDB.Exec("DROP DATABASE IF EXISTS " + dbName)
adminDB.Close()
}()
dsn := fmt.Sprintf("%s:%s@tcp(localhost:3306)/%s?parseTime=true&interpolateParams=true", testUser, testPassword, dbName)
db, err := sql.Open("mysql", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
// Create backend without migration DSN - should panic when trying to migrate
defer func() {
if r := recover(); r == nil {
t.Error("Expected panic when ApplyMigrations=true without MigrationDSN")
}
}()
NewMysqlBackendWithDB(db, WithApplyMigrations(true))
})
}