-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathpostgres_test.go
More file actions
383 lines (322 loc) · 11.3 KB
/
Copy pathpostgres_test.go
File metadata and controls
383 lines (322 loc) · 11.3 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
package postgres
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"
_ "github.com/jackc/pgx/v5/stdlib"
)
const testUser = "root"
const testPassword = "root"
// Creating and dropping databases is inefficient but gives full isolation for tests.
// For future optimization consider: transactional tests (pgx + rollback),
// or TRUNCATE between tests within a single database
func Test_PostgresBackend(t *testing.T) {
if testing.Short() {
t.Skip()
}
var dbName string
test.BackendTest(t, func(options ...backend.BackendOption) test.TestBackend {
// Connect to default "postgres" database to create a new one
adminDB, err := sql.Open("pgx", fmt.Sprintf("host=localhost port=5432 user=%s password=%s dbname=postgres sslmode=disable", testUser, testPassword))
if err != nil {
panic(err)
}
defer adminDB.Close()
dbName = "test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
if _, err := adminDB.Exec("CREATE DATABASE " + dbName); err != nil {
panic(fmt.Errorf("creating database: %w", err))
}
options = append(options, backend.WithStickyTimeout(0))
// Create backend pointing to the newly created database
return NewPostgresBackend("localhost", 5432, testUser, testPassword, dbName, WithBackendOptions(options...))
}, func(b test.TestBackend) {
// Close backend DB first
if err := b.(*postgresBackend).db.Close(); err != nil {
panic(err)
}
adminDB, err := sql.Open("pgx", fmt.Sprintf("host=localhost port=5432 user=%s password=%s dbname=postgres sslmode=disable", testUser, testPassword))
if err != nil {
panic(err)
}
defer adminDB.Close()
if _, err := adminDB.Exec("DROP DATABASE IF EXISTS " + dbName + " WITH (FORCE)"); err != nil {
panic(fmt.Errorf("dropping database: %w", err))
}
})
}
func TestPostgresBackendE2E(t *testing.T) {
if testing.Short() {
t.Skip()
}
var dbName string
test.EndToEndBackendTest(t, func(options ...backend.BackendOption) test.TestBackend {
adminDB, err := sql.Open("pgx", fmt.Sprintf("host=localhost port=5432 user=%s password=%s dbname=postgres sslmode=disable", testUser, testPassword))
if err != nil {
panic(err)
}
defer adminDB.Close()
dbName = "test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
if _, err := adminDB.Exec("CREATE DATABASE " + dbName); err != nil {
panic(fmt.Errorf("creating database: %w", err))
}
options = append(options, backend.WithStickyTimeout(0))
return NewPostgresBackend("localhost", 5432, testUser, testPassword, dbName, WithBackendOptions(options...))
}, func(b test.TestBackend) {
if err := b.(*postgresBackend).db.Close(); err != nil {
panic(err)
}
adminDB, err := sql.Open("pgx", fmt.Sprintf("host=localhost port=5432 user=%s password=%s dbname=postgres sslmode=disable", testUser, testPassword))
if err != nil {
panic(err)
}
defer adminDB.Close()
if _, err := adminDB.Exec("DROP DATABASE IF EXISTS " + dbName + " WITH (FORCE)"); err != nil {
panic(fmt.Errorf("dropping database: %w", err))
}
})
}
var _ test.TestBackend = (*postgresBackend)(nil)
// GetFutureEvents returns all pending events that have a non-null visible_at (timers / scheduled future events).
func (pb *postgresBackend) GetFutureEvents(ctx context.Context) ([]*history.Event, error) {
tx, err := pb.db.BeginTx(ctx, nil)
if err != nil {
return nil, err
}
defer tx.Rollback()
// attributes now lives in the separate attributes table (joined by event_id + instance_id + execution_id)
rows, err := tx.QueryContext(ctx,
`SELECT
pe.event_id,
pe.sequence_id,
pe.event_type,
pe.timestamp,
pe.schedule_event_id,
a.data,
pe.visible_at
FROM pending_events pe
JOIN attributes a
ON a.event_id = pe.event_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("querying future events: %w", err)
}
defer rows.Close()
var future []*history.Event
for rows.Next() {
var raw []byte
e := &history.Event{}
if err := rows.Scan(
&e.ID,
&e.SequenceID,
&e.Type,
&e.Timestamp,
&e.ScheduleEventID,
&raw,
&e.VisibleAt,
); err != nil {
return nil, fmt.Errorf("scanning future event: %w", err)
}
attr, err := history.DeserializeAttributes(e.Type, raw)
if err != nil {
return nil, fmt.Errorf("deserializing attributes: %w", err)
}
e.Attributes = attr
future = append(future, e)
}
if err := rows.Err(); err != nil {
return nil, err
}
if err := tx.Commit(); err != nil {
return nil, err
}
return future, nil
}
func Test_PostgresBackend_WorkerName(t *testing.T) {
if testing.Short() {
t.Skip()
}
t.Run("DefaultWorkerName", func(t *testing.T) {
options := &options{
Options: backend.ApplyOptions(),
}
workerName := getWorkerName(options)
if !strings.HasPrefix(workerName, "worker-") {
t.Errorf("Expected worker name to start with 'worker-', got: %s", workerName)
}
if len(workerName) != 43 { // 7 + 36
t.Errorf("Expected worker name length 43, got: %d", len(workerName))
}
})
t.Run("CustomWorkerName", func(t *testing.T) {
custom := "test-worker-123"
options := &options{
Options: backend.ApplyOptions(backend.WithWorkerName(custom)),
}
if got := getWorkerName(options); got != custom {
t.Errorf("Expected '%s', got '%s'", custom, got)
}
})
t.Run("EmptyWorkerNameUsesDefault", func(t *testing.T) {
options := &options{
Options: backend.ApplyOptions(backend.WithWorkerName("")),
}
workerName := getWorkerName(options)
if !strings.HasPrefix(workerName, "worker-") {
t.Errorf("Expected worker name to start with 'worker-', got: %s", workerName)
}
if len(workerName) != 43 {
t.Errorf("Expected worker name length 43, got: %d", len(workerName))
}
})
}
func Test_PostgresBackend_SSLMode(t *testing.T) {
t.Run("DefaultSSLMode", func(t *testing.T) {
// sql.Open doesn't actually connect, so this works without a real database
b := NewPostgresBackend("localhost", 5432, "user", "pass", "db", WithApplyMigrations(false))
defer b.Close()
expected := "host=localhost port=5432 user=user password=pass dbname=db sslmode=disable"
if b.dsn != expected {
t.Errorf("Expected DSN %q, got %q", expected, b.dsn)
}
})
t.Run("CustomSSLMode", func(t *testing.T) {
b := NewPostgresBackend("localhost", 5432, "user", "pass", "db", WithApplyMigrations(false), WithSSLMode("require"))
defer b.Close()
expected := "host=localhost port=5432 user=user password=pass dbname=db sslmode=require"
if b.dsn != expected {
t.Errorf("Expected DSN %q, got %q", expected, b.dsn)
}
})
t.Run("VerifyFullSSLMode", func(t *testing.T) {
b := NewPostgresBackend("localhost", 5432, "user", "pass", "db", WithApplyMigrations(false), WithSSLMode("verify-full"))
defer b.Close()
expected := "host=localhost port=5432 user=user password=pass dbname=db sslmode=verify-full"
if b.dsn != expected {
t.Errorf("Expected DSN %q, got %q", expected, b.dsn)
}
})
t.Run("EmptySSLModeDefaultsToDisable", func(t *testing.T) {
b := NewPostgresBackend("localhost", 5432, "user", "pass", "db", WithApplyMigrations(false), WithSSLMode(""))
defer b.Close()
expected := "host=localhost port=5432 user=user password=pass dbname=db sslmode=disable"
if b.dsn != expected {
t.Errorf("Expected DSN %q, got %q", expected, b.dsn)
}
})
t.Run("WithSSLModeOption", func(t *testing.T) {
opts := &options{
Options: backend.ApplyOptions(),
}
WithSSLMode("verify-ca")(opts)
if opts.SSLMode != "verify-ca" {
t.Errorf("Expected SSLMode 'verify-ca', got %q", opts.SSLMode)
}
})
}
func Test_PostgresBackendWithDB(t *testing.T) {
if testing.Short() {
t.Skip()
}
t.Run("UsesProvidedConnection", func(t *testing.T) {
// Create database for test
adminDB, err := sql.Open("pgx", fmt.Sprintf("host=localhost port=5432 user=%s password=%s dbname=postgres sslmode=disable", 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 + " WITH (FORCE)")
adminDB.Close()
}()
// Create our own connection to the test database
db, err := sql.Open("pgx", fmt.Sprintf("host=localhost port=5432 user=%s password=%s dbname=%s sslmode=disable", testUser, testPassword, dbName))
if err != nil {
t.Fatal(err)
}
defer db.Close()
// Create backend with existing connection and apply migrations
backend := NewPostgresBackendWithDB(db, WithApplyMigrations(true))
// 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("pgx", fmt.Sprintf("host=localhost port=5432 user=%s password=%s dbname=postgres sslmode=disable", 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 + " WITH (FORCE)")
adminDB.Close()
}()
db, err := sql.Open("pgx", fmt.Sprintf("host=localhost port=5432 user=%s password=%s dbname=%s sslmode=disable", testUser, testPassword, dbName))
if err != nil {
t.Fatal(err)
}
defer db.Close()
// Create backend without enabling migrations
backend := NewPostgresBackendWithDB(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("MigrationsCanBeEnabled", func(t *testing.T) {
// Create database for test
adminDB, err := sql.Open("pgx", fmt.Sprintf("host=localhost port=5432 user=%s password=%s dbname=postgres sslmode=disable", 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 + " WITH (FORCE)")
adminDB.Close()
}()
db, err := sql.Open("pgx", fmt.Sprintf("host=localhost port=5432 user=%s password=%s dbname=%s sslmode=disable", testUser, testPassword, dbName))
if err != nil {
t.Fatal(err)
}
defer db.Close()
// Create backend with migrations enabled
backend := NewPostgresBackendWithDB(db, WithApplyMigrations(true))
defer backend.Close()
// Tables should exist
_, err = db.Exec("SELECT 1 FROM instances LIMIT 1")
if err != nil {
t.Errorf("Table should exist after migrations: %v", err)
}
})
}