-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathbootstrap_test.go
More file actions
362 lines (306 loc) · 11 KB
/
bootstrap_test.go
File metadata and controls
362 lines (306 loc) · 11 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
package pgengine_test
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"reflect"
"testing"
"time"
"github.com/cybertec-postgresql/pg_timetable/internal/config"
"github.com/cybertec-postgresql/pg_timetable/internal/pgengine"
pgx "github.com/jackc/pgx/v5"
"github.com/pashagolub/pgxmock/v5"
"github.com/stretchr/testify/assert"
)
func anyArgs(i int) []any {
args := make([]any, i)
for j := range i {
args[j] = pgxmock.AnyArg()
}
return args
}
func TestExecuteSchemaScripts(t *testing.T) {
initmockdb(t)
defer mockPool.Close()
mockpge := pgengine.NewDB(mockPool, "pgengine_unit_test")
t.Run("Check schema scripts if error returned for SELECT EXISTS", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
mockPool.ExpectQuery("SELECT EXISTS").WillReturnError(errors.New("expected"))
assert.Error(t, mockpge.ExecuteSchemaScripts(ctx))
})
t.Run("Check schema scripts if error returned", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
mockPool.ExpectQuery("SELECT EXISTS").WillReturnRows(pgxmock.NewRows([]string{"exists"}).AddRow(false))
mockPool.ExpectExec("CREATE SCHEMA timetable").WillReturnError(errors.New("expected"))
mockPool.ExpectExec("DROP SCHEMA IF EXISTS timetable CASCADE").WillReturnError(errors.New("expected"))
assert.Error(t, mockpge.ExecuteSchemaScripts(ctx))
})
t.Run("Check schema scripts if everything fine", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
mockPool.ExpectQuery("SELECT EXISTS").WillReturnRows(pgxmock.NewRows([]string{"exists"}).AddRow(false))
for i := 0; i < 5; i++ {
mockPool.ExpectExec(".*").WillReturnResult(pgxmock.NewResult("EXECUTE", 1))
}
assert.NoError(t, mockpge.ExecuteSchemaScripts(ctx))
})
}
func TestExecuteCustomScripts(t *testing.T) {
initmockdb(t)
defer mockPool.Close()
mockpge := pgengine.NewDB(mockPool, "pgengine_unit_test")
t.Run("Check ExecuteCustomScripts for non-existent file", func(t *testing.T) {
assert.Error(t, mockpge.ExecuteCustomScripts(context.Background(), "foo.bar"))
})
t.Run("Check ExecuteCustomScripts if error returned", func(t *testing.T) {
mockPool.ExpectExec("SELECT timetable.add_job").WillReturnError(errors.New("expected"))
assert.Error(t, mockpge.ExecuteCustomScripts(context.Background(), "../../samples/Basic.sql"))
})
t.Run("Check ExecuteCustomScripts if everything fine", func(t *testing.T) {
mockPool.ExpectExec("SELECT timetable.add_job").WillReturnResult(pgxmock.NewResult("EXECUTE", 1))
mockPool.ExpectExec("INSERT INTO timetable\\.log").WillReturnResult(pgxmock.NewResult("EXECUTE", 1))
assert.NoError(t, mockpge.ExecuteCustomScripts(context.Background(), "../../samples/Basic.sql"))
})
}
func TestFinalizeConnection(t *testing.T) {
initmockdb(t)
mockpge := pgengine.NewDB(mockPool, "pgengine_unit_test")
mockPool.ExpectExec(`DELETE FROM timetable\.active_session`).
WithArgs(mockpge.ClientName).
WillReturnResult(pgxmock.NewResult("EXECUTE", 0))
mockPool.ExpectClose()
mockpge.Finalize()
assert.NoError(t, mockPool.ExpectationsWereMet())
}
type mockpgrow struct {
results []any
}
func (r *mockpgrow) Scan(dest ...any) error {
if len(r.results) > 0 {
if err, ok := r.results[0].(error); ok {
r.results = r.results[1:]
return err
}
destv := reflect.ValueOf(dest[0])
typ := destv.Type()
if typ.Kind() != reflect.Ptr {
return fmt.Errorf("dest must be pointer; got %T", destv)
}
destv.Elem().Set(reflect.ValueOf(r.results[0]))
r.results = r.results[1:]
return nil
}
return errors.New("mockpgrow error")
}
type mockpgconn struct {
r pgx.Row
}
func (m mockpgconn) QueryRow(context.Context, string, ...any) pgx.Row {
return m.r
}
func TestTryLockClientName(t *testing.T) {
pge := pgengine.NewDB(nil, "pgengine_unit_test")
defer func() { pge = nil }()
t.Run("query error", func(t *testing.T) {
r := &mockpgrow{}
m := mockpgconn{r}
assert.Error(t, pge.TryLockClientName(context.Background(), m))
})
t.Run("no schema yet", func(t *testing.T) {
r := &mockpgrow{results: []any{
0, //procoid
}}
m := mockpgconn{r}
assert.NoError(t, pge.TryLockClientName(context.Background(), m))
})
t.Run("locking error", func(t *testing.T) {
r := &mockpgrow{results: []any{
1, //procoid
errors.New("locking error"), //error
}}
m := mockpgconn{r}
assert.Error(t, pge.TryLockClientName(context.Background(), m))
})
t.Run("locking successful", func(t *testing.T) {
r := &mockpgrow{results: []any{
1, //procoid
true, //locked
}}
m := mockpgconn{r}
assert.NoError(t, pge.TryLockClientName(context.Background(), m))
})
}
func TestExecuteFileScript(t *testing.T) {
initmockdb(t)
defer mockPool.Close()
mockpge := pgengine.NewDB(mockPool, "pgengine_unit_test")
// Create temporary directory for test files
tmpDir := t.TempDir()
t.Run("SQL file execution", func(t *testing.T) {
// Create temporary SQL file
sqlFile := filepath.Join(tmpDir, "test.sql")
err := os.WriteFile(sqlFile, []byte("SELECT 1;"), 0644)
assert.NoError(t, err)
// Mock the SQL execution
mockPool.ExpectExec("SELECT 1;").WillReturnResult(pgxmock.NewResult("SELECT", 1))
cmdOpts := config.CmdOptions{}
cmdOpts.Start.File = sqlFile
err = mockpge.ExecuteFileScript(context.Background(), cmdOpts)
assert.NoError(t, err)
})
t.Run("SQL file execution error", func(t *testing.T) {
// Create temporary SQL file
sqlFile := filepath.Join(tmpDir, "test_error.sql")
err := os.WriteFile(sqlFile, []byte("SELECT 1;"), 0644)
assert.NoError(t, err)
// Mock the SQL execution with error
mockPool.ExpectExec("SELECT 1;").WillReturnError(errors.New("SQL execution failed"))
cmdOpts := config.CmdOptions{}
cmdOpts.Start.File = sqlFile
err = mockpge.ExecuteFileScript(context.Background(), cmdOpts)
assert.Error(t, err)
})
t.Run("YAML file validation mode - valid file", func(t *testing.T) {
// Create temporary YAML file
yamlFile := filepath.Join(tmpDir, "test.yaml")
yamlContent := `chains:
- name: test_chain
tasks:
- name: test_task
command: SELECT 1`
err := os.WriteFile(yamlFile, []byte(yamlContent), 0644)
assert.NoError(t, err)
cmdOpts := config.CmdOptions{}
cmdOpts.Start.File = yamlFile
cmdOpts.Start.Validate = true
err = mockpge.ExecuteFileScript(context.Background(), cmdOpts)
assert.NoError(t, err)
})
t.Run("YAML file validation mode - invalid file", func(t *testing.T) {
// Create temporary YAML file with invalid content
yamlFile := filepath.Join(tmpDir, "invalid.yaml")
yamlContent := `chains:
- name: test_chain
invalid_field: value
- malformed yaml`
err := os.WriteFile(yamlFile, []byte(yamlContent), 0644)
assert.NoError(t, err)
cmdOpts := config.CmdOptions{}
cmdOpts.Start.File = yamlFile
cmdOpts.Start.Validate = true
err = mockpge.ExecuteFileScript(context.Background(), cmdOpts)
// Expect error due to invalid YAML structure
assert.Error(t, err)
})
t.Run("YAML file import mode", func(t *testing.T) {
// Create temporary YAML file
yamlFile := filepath.Join(tmpDir, "test_import.yaml")
yamlContent := `chains:
- name: test_chain
tasks:
- name: test_task
command: SELECT 1`
err := os.WriteFile(yamlFile, []byte(yamlContent), 0644)
assert.NoError(t, err)
cmdOpts := config.CmdOptions{}
cmdOpts.Start.File = yamlFile
cmdOpts.Start.Validate = false
cmdOpts.Start.Replace = false
mockPool.ExpectQuery("SELECT EXISTS").
WithArgs("test_chain").
WillReturnRows(pgxmock.NewRows([]string{"exists"}).AddRow(false))
mockPool.ExpectQuery("INSERT INTO timetable\\.chain").
WithArgs(anyArgs(9)...).
WillReturnRows(pgxmock.NewRows([]string{"chain_id"}).AddRow(1))
mockPool.ExpectQuery("INSERT INTO timetable\\.task").
WithArgs(anyArgs(10)...).
WillReturnRows(pgxmock.NewRows([]string{"task_id"}).AddRow(1))
err = mockpge.ExecuteFileScript(context.Background(), cmdOpts)
assert.NoError(t, err)
})
t.Run("YML file extension", func(t *testing.T) {
// Create temporary YML file
ymlFile := filepath.Join(tmpDir, "test.yml")
yamlContent := `chains:
- name: test_chain
tasks:
- name: test_task
command: SELECT 1`
err := os.WriteFile(ymlFile, []byte(yamlContent), 0644)
assert.NoError(t, err)
cmdOpts := config.CmdOptions{}
cmdOpts.Start.File = ymlFile
cmdOpts.Start.Validate = true
err = mockpge.ExecuteFileScript(context.Background(), cmdOpts)
assert.NoError(t, err)
})
t.Run("File without extension", func(t *testing.T) {
// Create file without extension with YAML content
noExtFile := filepath.Join(tmpDir, "test_no_ext")
yamlContent := `chains:
- name: test_chain
tasks:
- name: test_task
command: SELECT 1`
err := os.WriteFile(noExtFile, []byte(yamlContent), 0644)
assert.NoError(t, err)
cmdOpts := config.CmdOptions{}
cmdOpts.Start.File = noExtFile
err = mockpge.ExecuteFileScript(context.Background(), cmdOpts)
assert.Error(t, err)
})
t.Run("File not found error", func(t *testing.T) {
cmdOpts := config.CmdOptions{}
cmdOpts.Start.File = "/nonexistent/file.sql"
err := mockpge.ExecuteFileScript(context.Background(), cmdOpts)
assert.Error(t, err)
})
t.Run("YAML import with replace flag", func(t *testing.T) {
// Create temporary YAML file
yamlFile := filepath.Join(tmpDir, "test_replace.yaml")
yamlContent := `chains:
- name: test_chain_replace
tasks:
- name: test_task
command: SELECT 1`
err := os.WriteFile(yamlFile, []byte(yamlContent), 0644)
assert.NoError(t, err)
cmdOpts := config.CmdOptions{}
cmdOpts.Start.File = yamlFile
cmdOpts.Start.Validate = false
cmdOpts.Start.Replace = true
mockPool.ExpectExec("SELECT timetable\\.delete_job").
WithArgs("test_chain_replace").
WillReturnResult(pgxmock.NewResult("DELETE", 1))
mockPool.ExpectQuery("SELECT EXISTS").
WithArgs("test_chain_replace").
WillReturnRows(pgxmock.NewRows([]string{"exists"}).AddRow(false))
mockPool.ExpectQuery("INSERT INTO timetable\\.chain").
WithArgs(anyArgs(9)...).
WillReturnRows(pgxmock.NewRows([]string{"chain_id"}).AddRow(1))
mockPool.ExpectQuery("INSERT INTO timetable\\.task").
WithArgs(anyArgs(10)...).
WillReturnRows(pgxmock.NewRows([]string{"task_id"}).AddRow(1))
err = mockpge.ExecuteFileScript(context.Background(), cmdOpts)
assert.NoError(t, err)
})
t.Run("SQL file with multiple statements", func(t *testing.T) {
// Create temporary SQL file with multiple statements
sqlFile := filepath.Join(tmpDir, "multi.sql")
sqlContent := `SELECT 1;
SELECT 2;
INSERT INTO test VALUES (1);`
err := os.WriteFile(sqlFile, []byte(sqlContent), 0644)
assert.NoError(t, err)
// Mock the SQL execution - use regex pattern to match the content
mockPool.ExpectExec(`SELECT 1;.*SELECT 2;.*INSERT INTO test VALUES \(1\);`).WillReturnResult(pgxmock.NewResult("SELECT", 1))
cmdOpts := config.CmdOptions{}
cmdOpts.Start.File = sqlFile
err = mockpge.ExecuteFileScript(context.Background(), cmdOpts)
assert.NoError(t, err)
})
}