]> begriffs open source - pg_scribe/blob - tests/test_init.sh
WIP: convert to chain design
[pg_scribe] / tests / test_init.sh
1 #!/usr/bin/env bash
2 #
3 # Test suite for pg_scribe --init command
4 #
5 # This test suite:
6 # - Creates temporary test databases
7 # - Tests various --init scenarios
8 # - Verifies expected outcomes
9 # - Cleans up all resources
10 #
11
12 set -euo pipefail
13
14 # Colors for test output
15 RED='\033[0;31m'
16 GREEN='\033[0;32m'
17 YELLOW='\033[0;33m'
18 BLUE='\033[0;34m'
19 NC='\033[0m' # No Color
20
21 # Test configuration
22 SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
23 PG_SCRIBE="$SCRIPT_DIR/scripts/pg_scribe"
24 TEST_DIR="/tmp/pg_scribe_test_$$"
25 TEST_DB_PREFIX="pg_scribe_test_$$"
26 PGUSER="${PGUSER:-postgres}"
27
28 # Test counters
29 TESTS_RUN=0
30 TESTS_PASSED=0
31 TESTS_FAILED=0
32
33 # Cleanup tracking
34 DATABASES_TO_CLEANUP=()
35
36 #
37 # Logging functions
38 #
39
40 log_test() {
41     echo -e "${BLUE}TEST:${NC} $*"
42 }
43
44 log_pass() {
45     echo -e "${GREEN}PASS:${NC} $*"
46     ((TESTS_PASSED++))
47 }
48
49 log_fail() {
50     echo -e "${RED}FAIL:${NC} $*"
51     ((TESTS_FAILED++))
52 }
53
54 log_info() {
55     echo -e "${YELLOW}INFO:${NC} $*"
56 }
57
58 #
59 # Helper functions
60 #
61
62 run_psql() {
63     local dbname="$1"
64     shift
65     psql -U "$PGUSER" -d "$dbname" -tAq "$@"
66 }
67
68 query_db() {
69     local dbname="$1"
70     local query="$2"
71     run_psql "$dbname" -c "$query" 2>/dev/null || true
72 }
73
74 create_test_db() {
75     local dbname="$1"
76     log_info "Creating test database: $dbname"
77
78     # Drop if exists
79     psql -U "$PGUSER" -d postgres -c "DROP DATABASE IF EXISTS $dbname;" &>/dev/null || true
80
81     # Create database
82     psql -U "$PGUSER" -d postgres -c "CREATE DATABASE $dbname;" &>/dev/null
83
84     DATABASES_TO_CLEANUP+=("$dbname")
85 }
86
87 # shellcheck disable=SC2317  # Function called from cleanup trap handler
88 drop_test_db() {
89     local dbname="$1"
90     log_info "Dropping test database: $dbname"
91
92     # Terminate connections
93     psql -U "$PGUSER" -d postgres -c "
94         SELECT pg_terminate_backend(pid)
95         FROM pg_stat_activity
96         WHERE datname = '$dbname' AND pid <> pg_backend_pid();
97     " &>/dev/null || true
98
99     # Drop database
100     psql -U "$PGUSER" -d postgres -c "DROP DATABASE IF EXISTS $dbname;" &>/dev/null || true
101 }
102
103 # shellcheck disable=SC2317  # Function called from cleanup trap handler
104 drop_replication_slot() {
105     local dbname="$1"
106     local slot="$2"
107     log_info "Dropping replication slot: $slot"
108
109     # Check if slot exists
110     local exists
111     exists=$(query_db "$dbname" "
112         SELECT 1 FROM pg_replication_slots WHERE slot_name = '$slot';
113     ")
114
115     if [[ -n "$exists" ]]; then
116         # Drop slot
117         query_db "$dbname" "SELECT pg_drop_replication_slot('$slot');" || true
118     fi
119 }
120
121 check_slot_exists() {
122     local dbname="$1"
123     local slot="$2"
124     local exists
125     exists=$(query_db "$dbname" "
126         SELECT 1 FROM pg_replication_slots WHERE slot_name = '$slot';
127     ")
128     [[ -n "$exists" ]]
129 }
130
131 check_extension_exists() {
132     local dbname="$1"
133     local extension="$2"
134     local exists
135     exists=$(query_db "$dbname" "
136         SELECT 1 FROM pg_extension WHERE extname = '$extension';
137     ")
138     [[ -n "$exists" ]]
139 }
140
141 create_table_with_pk() {
142     local dbname="$1"
143     local table="$2"
144     query_db "$dbname" "
145         CREATE TABLE $table (
146             id SERIAL PRIMARY KEY,
147             name TEXT,
148             created_at TIMESTAMP DEFAULT now()
149         );
150     "
151 }
152
153 create_table_without_pk() {
154     local dbname="$1"
155     local table="$2"
156     query_db "$dbname" "
157         CREATE TABLE $table (
158             id INTEGER,
159             name TEXT
160         );
161     "
162 }
163
164 #
165 # Test cases
166 #
167
168 test_basic_init_success() {
169     ((TESTS_RUN++))
170     log_test "Basic --init success"
171
172     local dbname="${TEST_DB_PREFIX}_basic"
173     local slot="test_slot_basic"
174     local backup_dir="$TEST_DIR/basic"
175
176     # Setup
177     create_test_db "$dbname"
178     create_table_with_pk "$dbname" "users"
179     mkdir -p "$backup_dir"
180
181     # Run init
182     if "$PG_SCRIBE" --init -d "$dbname" -f "$backup_dir" -S "$slot" -U "$PGUSER" &>/dev/null; then
183         # Verify slot created
184         if ! check_slot_exists "$dbname" "$slot"; then
185             log_fail "Replication slot not created"
186             return 1
187         fi
188
189         # Verify extension installed
190         if ! check_extension_exists "$dbname" "wal2sql"; then
191             log_fail "wal2sql extension not installed"
192             return 1
193         fi
194
195         # Verify chain directory created
196         local chain_dirs=("$backup_dir"/chain-*)
197         if [[ ! -d "${chain_dirs[0]}" ]]; then
198             log_fail "Chain directory not created"
199             return 1
200         fi
201
202         local chain_dir="${chain_dirs[0]}"
203
204         # Verify files in chain directory
205         if [[ ! -f "$chain_dir/base.sql" ]]; then
206             log_fail "Base backup file not created in chain"
207             return 1
208         fi
209
210         if [[ ! -f "$chain_dir/globals.sql" ]]; then
211             log_fail "Globals backup file not created in chain"
212             return 1
213         fi
214
215         if [[ ! -f "$chain_dir/metadata.json" ]]; then
216             log_fail "Metadata file not created in chain"
217             return 1
218         fi
219
220         # Verify pidfile placeholder created
221         if [[ ! -f "$backup_dir/.pg_scribe.pid" ]]; then
222             log_fail "Pidfile placeholder not created"
223             return 1
224         fi
225
226         # Verify metadata content (JSON format)
227         if ! grep -q "\"database\": \"$dbname\"" "$chain_dir/metadata.json"; then
228             log_fail "Metadata missing database name"
229             return 1
230         fi
231
232         if ! grep -q "\"replication_slot\": \"$slot\"" "$chain_dir/metadata.json"; then
233             log_fail "Metadata missing slot name"
234             return 1
235         fi
236
237         log_pass "Basic init successful"
238         return 0
239     else
240         log_fail "Init command failed"
241         return 1
242     fi
243 }
244
245 test_init_validation_failure() {
246     ((TESTS_RUN++))
247     log_test "Init validation failure (table without replica identity)"
248
249     local dbname="${TEST_DB_PREFIX}_nopk"
250     local slot="test_slot_nopk"
251     local backup_dir="$TEST_DIR/nopk"
252
253     # Setup - create table WITHOUT primary key
254     create_test_db "$dbname"
255     create_table_without_pk "$dbname" "bad_table"
256     mkdir -p "$backup_dir"
257
258     # Run init - should fail with exit code 5
259     local exit_code=0
260     "$PG_SCRIBE" --init -d "$dbname" -f "$backup_dir" -S "$slot" -U "$PGUSER" &>/dev/null || exit_code=$?
261
262     if [[ $exit_code -eq 5 ]]; then
263         # Verify slot was NOT created
264         if check_slot_exists "$dbname" "$slot"; then
265             log_fail "Replication slot should not be created on validation failure"
266             return 1
267         fi
268
269         log_pass "Validation failure detected correctly"
270         return 0
271     else
272         log_fail "Expected exit code 5, got $exit_code"
273         return 1
274     fi
275 }
276
277 test_init_force_flag() {
278     ((TESTS_RUN++))
279     log_test "Init with --force flag (bypass validation)"
280
281     local dbname="${TEST_DB_PREFIX}_force"
282     local slot="test_slot_force"
283     local backup_dir="$TEST_DIR/force"
284
285     # Setup - create table WITHOUT primary key
286     create_test_db "$dbname"
287     create_table_without_pk "$dbname" "bad_table"
288     mkdir -p "$backup_dir"
289
290     # Run init with --force - should succeed despite validation failure
291     if "$PG_SCRIBE" --init -d "$dbname" -f "$backup_dir" -S "$slot" -U "$PGUSER" --force &>/dev/null; then
292         # Verify slot was created
293         if ! check_slot_exists "$dbname" "$slot"; then
294             log_fail "Replication slot should be created with --force"
295             return 1
296         fi
297
298         log_pass "Force flag bypassed validation"
299         return 0
300     else
301         log_fail "Init with --force should succeed"
302         return 1
303     fi
304 }
305
306 test_init_non_idempotency() {
307     ((TESTS_RUN++))
308     log_test "Init refuses to run on already-initialized directory"
309
310     local dbname="${TEST_DB_PREFIX}_nonidempotent"
311     local slot="test_slot_nonidempotent"
312     local backup_dir="$TEST_DIR/nonidempotent"
313
314     # Setup
315     create_test_db "$dbname"
316     create_table_with_pk "$dbname" "users"
317     mkdir -p "$backup_dir"
318
319     # Run init first time
320     if ! "$PG_SCRIBE" --init -d "$dbname" -f "$backup_dir" -S "$slot" -U "$PGUSER" &>/dev/null; then
321         log_fail "First init failed"
322         return 1
323     fi
324
325     # Run init second time - should FAIL with validation error
326     local exit_code=0
327     "$PG_SCRIBE" --init -d "$dbname" -f "$backup_dir" -S "$slot" -U "$PGUSER" &>/dev/null || exit_code=$?
328
329     if [[ $exit_code -eq 5 ]]; then
330         # Verify slot still exists from first init
331         if ! check_slot_exists "$dbname" "$slot"; then
332             log_fail "Replication slot should still exist from first init"
333             return 1
334         fi
335
336         # Verify only 1 chain directory (from first init)
337         local chain_count
338         chain_count=$(find "$backup_dir" -maxdepth 1 -type d -name 'chain-*' 2>/dev/null | wc -l)
339         if [[ $chain_count -ne 1 ]]; then
340             log_fail "Expected 1 chain directory, got $chain_count"
341             return 1
342         fi
343
344         log_pass "Init correctly refuses to reinitialize"
345         return 0
346     else
347         log_fail "Expected exit code 5 (validation error), got $exit_code"
348         return 1
349     fi
350 }
351
352 test_init_multiple_tables() {
353     ((TESTS_RUN++))
354     log_test "Init with multiple tables"
355
356     local dbname="${TEST_DB_PREFIX}_multi"
357     local slot="test_slot_multi"
358     local backup_dir="$TEST_DIR/multi"
359
360     # Setup - create multiple tables
361     create_test_db "$dbname"
362     create_table_with_pk "$dbname" "users"
363     create_table_with_pk "$dbname" "orders"
364     create_table_with_pk "$dbname" "products"
365
366     # Insert some data
367     query_db "$dbname" "INSERT INTO users (name) VALUES ('Alice'), ('Bob');"
368     query_db "$dbname" "INSERT INTO orders (name) VALUES ('Order1');"
369     query_db "$dbname" "INSERT INTO products (name) VALUES ('Widget');"
370
371     mkdir -p "$backup_dir"
372
373     # Run init
374     if "$PG_SCRIBE" --init -d "$dbname" -f "$backup_dir" -S "$slot" -U "$PGUSER" &>/dev/null; then
375         # Verify base backup contains all tables
376         local chain_dirs=("$backup_dir"/chain-*)
377         local base_file="${chain_dirs[0]}/base.sql"
378
379         if ! grep -q "CREATE TABLE public.users" "$base_file"; then
380             log_fail "Base backup missing users table"
381             return 1
382         fi
383
384         if ! grep -q "CREATE TABLE public.orders" "$base_file"; then
385             log_fail "Base backup missing orders table"
386             return 1
387         fi
388
389         if ! grep -q "CREATE TABLE public.products" "$base_file"; then
390             log_fail "Base backup missing products table"
391             return 1
392         fi
393
394         log_pass "Multiple tables backed up successfully"
395         return 0
396     else
397         log_fail "Init failed"
398         return 1
399     fi
400 }
401
402 test_init_with_unlogged_table() {
403     ((TESTS_RUN++))
404     log_test "Init with unlogged table (warning but success)"
405
406     local dbname="${TEST_DB_PREFIX}_unlogged"
407     local slot="test_slot_unlogged"
408     local backup_dir="$TEST_DIR/unlogged"
409
410     # Setup
411     create_test_db "$dbname"
412     create_table_with_pk "$dbname" "normal_table"
413     query_db "$dbname" "CREATE UNLOGGED TABLE unlogged_table (id SERIAL PRIMARY KEY, data TEXT);"
414     mkdir -p "$backup_dir"
415
416     # Run init - should succeed with warning (exit code 0 or 10)
417     local output_file="$TEST_DIR/unlogged_output.txt"
418     local exit_code=0
419     "$PG_SCRIBE" --init -d "$dbname" -f "$backup_dir" -S "$slot" -U "$PGUSER" &>"$output_file" || exit_code=$?
420
421     # Exit code 0 (success) or 10 (warning) are both acceptable
422     if [[ $exit_code -eq 0 || $exit_code -eq 10 ]]; then
423         # Check for warning message
424         if ! grep -i "unlogged" "$output_file"; then
425             log_fail "Expected warning about unlogged table"
426             return 1
427         fi
428
429         # Verify backup was created
430         local chain_dirs=("$backup_dir"/chain-*)
431         if [[ ! -f "${chain_dirs[0]}/base.sql" ]]; then
432             log_fail "Base backup file not created"
433             return 1
434         fi
435
436         log_pass "Unlogged table warning shown correctly"
437         return 0
438     else
439         log_fail "Init failed with exit code $exit_code"
440         return 1
441     fi
442 }
443
444 test_backup_content_validity() {
445     ((TESTS_RUN++))
446     log_test "Verify backup SQL is valid"
447
448     local dbname="${TEST_DB_PREFIX}_valid"
449     local slot="test_slot_valid"
450     local backup_dir="$TEST_DIR/valid"
451     local restore_dbname="${TEST_DB_PREFIX}_restored"
452
453     # Setup
454     create_test_db "$dbname"
455     create_table_with_pk "$dbname" "test_data"
456     query_db "$dbname" "INSERT INTO test_data (name) VALUES ('Test Row 1'), ('Test Row 2');"
457     mkdir -p "$backup_dir"
458
459     # Run init
460     if ! "$PG_SCRIBE" --init -d "$dbname" -f "$backup_dir" -S "$slot" -U "$PGUSER" &>/dev/null; then
461         log_fail "Init failed"
462         return 1
463     fi
464
465     # Try to restore the backup to a new database
466     create_test_db "$restore_dbname"
467
468     # Find chain directory
469     local chain_dirs=("$backup_dir"/chain-*)
470     local chain_dir="${chain_dirs[0]}"
471
472     local base_file="$chain_dir/base.sql"
473     local globals_file="$chain_dir/globals.sql"
474
475     # Apply globals (roles, etc.)
476     if ! psql -U "$PGUSER" -d postgres -f "$globals_file" &>/dev/null; then
477         log_fail "Failed to restore globals"
478         return 1
479     fi
480
481     # Apply base backup
482     if ! psql -U "$PGUSER" -d "$restore_dbname" -f "$base_file" &>/dev/null; then
483         log_fail "Failed to restore base backup"
484         return 1
485     fi
486
487     # Verify data
488     local count
489     count=$(query_db "$restore_dbname" "SELECT COUNT(*) FROM test_data;")
490     if [[ "$count" -ne 2 ]]; then
491         log_fail "Expected 2 rows, got $count"
492         return 1
493     fi
494
495     log_pass "Backup SQL is valid and restorable"
496     return 0
497 }
498
499 #
500 # Cleanup
501 #
502
503 # shellcheck disable=SC2317  # Function called via trap handler
504 cleanup() {
505     log_info "Cleaning up test resources..."
506
507     # Drop replication slots
508     for dbname in "${DATABASES_TO_CLEANUP[@]}"; do
509         # Try to drop any slots for this database
510         for slot in test_slot_basic test_slot_nopk test_slot_force test_slot_nonidempotent test_slot_multi test_slot_unlogged test_slot_valid; do
511             drop_replication_slot "$dbname" "$slot" 2>/dev/null || true
512         done
513     done
514
515     # Drop databases
516     for dbname in "${DATABASES_TO_CLEANUP[@]}"; do
517         drop_test_db "$dbname"
518     done
519
520     # Remove test directory
521     if [[ -d "$TEST_DIR" ]]; then
522         rm -rf "$TEST_DIR"
523     fi
524
525     log_info "Cleanup complete"
526 }
527
528 #
529 # Main test runner
530 #
531
532 main() {
533     echo "========================================"
534     echo "pg_scribe --init Test Suite"
535     echo "========================================"
536     echo ""
537
538     # Verify pg_scribe exists
539     if [[ ! -x "$PG_SCRIBE" ]]; then
540         echo "ERROR: pg_scribe not found or not executable: $PG_SCRIBE"
541         exit 1
542     fi
543
544     # Verify PostgreSQL is running
545     if ! psql -U "$PGUSER" -d postgres -c "SELECT 1;" &>/dev/null; then
546         echo "ERROR: Cannot connect to PostgreSQL"
547         exit 1
548     fi
549
550     # Verify wal_level is logical
551     local wal_level
552     wal_level=$(psql -U "$PGUSER" -d postgres -tAq -c "SHOW wal_level;")
553     if [[ "$wal_level" != "logical" ]]; then
554         echo "ERROR: wal_level must be 'logical', currently: $wal_level"
555         echo "Update ~/.pgenv/pgsql/data/postgresql.conf and restart PostgreSQL"
556         exit 1
557     fi
558
559     # Create test directory
560     mkdir -p "$TEST_DIR"
561
562     # Set up cleanup trap
563     trap cleanup EXIT INT TERM
564
565     echo "Running tests..."
566     echo ""
567
568     # Run all tests (use || true to prevent set -e from exiting)
569     test_basic_init_success || true
570     test_init_validation_failure || true
571     test_init_force_flag || true
572     test_init_non_idempotency || true
573     test_init_multiple_tables || true
574     test_init_with_unlogged_table || true
575     test_backup_content_validity || true
576
577     # Summary
578     echo ""
579     echo "========================================"
580     echo "Test Results"
581     echo "========================================"
582     echo "Tests run:    $TESTS_RUN"
583     echo -e "Tests passed: ${GREEN}$TESTS_PASSED${NC}"
584     echo -e "Tests failed: ${RED}$TESTS_FAILED${NC}"
585     echo ""
586
587     if [[ $TESTS_FAILED -eq 0 ]]; then
588         echo -e "${GREEN}All tests passed!${NC}"
589         exit 0
590     else
591         echo -e "${RED}Some tests failed!${NC}"
592         exit 1
593     fi
594 }
595
596 main "$@"