testkit-postgres 0.1.1

PostgreSQL support for the testkit database testing library
Documentation
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
#![allow(clippy::all, unused_must_use, unused_lifetimes)]
#![cfg(feature = "tokio-postgres")] // This file is specific to tokio-postgres backend

use std::future::Future;
use std::pin::Pin;
use testkit_core::{
    DatabaseBackend, DatabaseConfig, DatabasePool, TestDatabaseInstance, with_boxed_database,
};
use testkit_postgres::{PostgresBackend, PostgresError, postgres_backend_with_config};

// Helper function to create a test config with the correct hostname
#[allow(dead_code)]
fn test_config() -> DatabaseConfig {
    let admin_url = "postgres://postgres:postgres@postgres:5432/postgres?sslmode=disable";
    let user_url = "postgres://postgres:postgres@postgres:5432/postgres?sslmode=disable";
    DatabaseConfig::new(admin_url, user_url)
}

// Helper function to check if an error is a connection error
#[allow(dead_code)]
fn is_connection_error(err: &PostgresError) -> bool {
    let err_str = err.to_string();
    err_str.contains("connection refused")
        || err_str.contains("timeout")
        || err_str.contains("does not exist")
        || err_str.contains("pool timed out")
}

// Helper to create a test backend
#[allow(dead_code)]
async fn test_backend() -> Result<PostgresBackend, PostgresError> {
    let config = test_config();
    postgres_backend_with_config(config).await
}

// Helper function to create a boxed future
#[allow(dead_code)]
fn boxed_future<T, F, Fut>(
    f: F,
) -> impl FnOnce(T) -> Pin<Box<dyn Future<Output = Result<(), PostgresError>> + Send>>
where
    F: FnOnce(T) -> Fut + Send + 'static,
    Fut: Future<Output = Result<(), PostgresError>> + Send + 'static,
    T: Send + 'static,
{
    move |t| Box::pin(f(t))
}

#[tokio::test]
async fn test_postgres_backend() {
    // Use "postgres" as the hostname for the Docker container
    let config = DatabaseConfig::new(
        "postgres://postgres:postgres@postgres:5432/postgres",
        "postgres://postgres:postgres@postgres:5432/postgres",
    );

    let backend = postgres_backend_with_config(config)
        .await
        .expect("Failed to create backend");

    // Test creating a test database
    let ctx = with_boxed_database(backend)
        .execute()
        .await
        .expect("Failed to create database");

    // Confirm we have a database name
    assert!(!ctx.db.db_name.to_string().is_empty());
}

#[tokio::test]
async fn test_setup_database() {
    // Use "postgres" as the hostname for the Docker container
    let config = DatabaseConfig::new(
        "postgres://postgres:postgres@postgres:5432/postgres",
        "postgres://postgres:postgres@postgres:5432/postgres",
    );

    let backend = postgres_backend_with_config(config)
        .await
        .expect("Failed to create backend");

    // Create a database with setup function
    let ctx = with_boxed_database(backend)
        .setup(|conn| {
            Box::pin(async move {
                // Create a table for testing
                conn.client()
                    .execute(
                        "CREATE TABLE test_table (id SERIAL PRIMARY KEY, value TEXT)",
                        &[],
                    )
                    .await?;

                // Verify the table exists with a query
                let result = conn
                    .client()
                    .query(
                        "SELECT EXISTS (
                            SELECT FROM information_schema.tables 
                            WHERE table_name = 'test_table'
                        )",
                        &[],
                    )
                    .await?;

                let exists: bool = result[0].get(0);
                assert!(exists, "Table should exist after creation");

                Ok(())
            })
        })
        .execute()
        .await
        .expect("Failed to setup database");

    // Verify we can get a connection
    let conn = ctx
        .db
        .pool
        .acquire()
        .await
        .expect("Failed to get connection");

    // Verify our table exists
    let result = conn
        .client()
        .query(
            "SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_name = 'test_table'
            )",
            &[],
        )
        .await
        .expect("Failed to query tables");

    let exists: bool = result[0].get(0);
    assert!(exists, "Table should exist");
}

#[tokio::test]
async fn test_transaction() {
    // Use "postgres" as the hostname for the Docker container
    let config = DatabaseConfig::new(
        "postgres://postgres:postgres@postgres:5432/postgres",
        "postgres://postgres:postgres@postgres:5432/postgres",
    );

    let backend = postgres_backend_with_config(config)
        .await
        .expect("Failed to create backend");

    // Create a database with setup and then transaction
    let ctx = with_boxed_database(backend)
        .setup(|conn| {
            Box::pin(async move {
                // Create a table for testing
                conn.client()
                    .execute(
                        "CREATE TABLE test_table (id SERIAL PRIMARY KEY, value TEXT)",
                        &[],
                    )
                    .await?;
                Ok(())
            })
        })
        .with_transaction(|conn| {
            Box::pin(async move {
                // Start a transaction
                conn.client().execute("BEGIN", &[]).await?;

                // Insert data
                conn.client()
                    .execute(
                        "INSERT INTO test_table (value) VALUES ($1)",
                        &[&"test value"],
                    )
                    .await?;

                // Verify data exists in transaction
                let rows = conn.client().query("SELECT * FROM test_table", &[]).await?;
                assert_eq!(rows.len(), 1, "Should have inserted 1 row");

                // Commit the transaction
                conn.client().execute("COMMIT", &[]).await?;

                Ok(())
            })
        })
        .execute()
        .await
        .expect("Failed to execute transaction");

    // Get a connection
    let conn = ctx
        .db
        .pool
        .acquire()
        .await
        .expect("Failed to get connection");

    // Verify data exists after transaction
    let rows = conn
        .client()
        .query("SELECT * FROM test_table", &[])
        .await
        .expect("Failed to query table");

    assert_eq!(rows.len(), 1, "Data should exist after transaction");
}

#[tokio::test]
async fn test_transaction_rollback() {
    // Use "postgres" as the hostname for the Docker container
    let config = DatabaseConfig::new(
        "postgres://postgres:postgres@postgres:5432/postgres",
        "postgres://postgres:postgres@postgres:5432/postgres",
    );

    let backend = postgres_backend_with_config(config)
        .await
        .expect("Failed to create backend");

    // Create a database with setup and then transaction
    let ctx = with_boxed_database(backend)
        .setup(|conn| {
            Box::pin(async move {
                // Create a table for testing
                conn.client()
                    .execute(
                        "CREATE TABLE test_table (id SERIAL PRIMARY KEY, value TEXT)",
                        &[],
                    )
                    .await?;
                Ok(())
            })
        })
        .with_transaction(|conn| {
            Box::pin(async move {
                // Begin transaction
                conn.client().execute("BEGIN", &[]).await?;

                // Insert data
                conn.client()
                    .execute(
                        "INSERT INTO test_table (value) VALUES ($1)",
                        &[&"will be rolled back"],
                    )
                    .await?;

                // Verify data exists in transaction
                let rows = conn.client().query("SELECT * FROM test_table", &[]).await?;
                assert_eq!(rows.len(), 1, "Should have inserted 1 row");

                // Roll back the transaction
                conn.client().execute("ROLLBACK", &[]).await?;

                // Verify data was rolled back
                let rows = conn.client().query("SELECT * FROM test_table", &[]).await?;
                assert_eq!(rows.len(), 0, "Data should be rolled back");

                Ok(())
            })
        })
        .execute()
        .await
        .expect("Failed to execute transaction");

    // Get a connection
    let conn = ctx
        .db
        .pool
        .acquire()
        .await
        .expect("Failed to get connection");

    // Verify data doesn't exist after rollback
    let rows = conn
        .client()
        .query("SELECT * FROM test_table", &[])
        .await
        .expect("Failed to query table");

    assert_eq!(rows.len(), 0, "Data should not exist after rollback");
}

#[tokio::test]
async fn test_multiple_databases() {
    // Use "postgres" as the hostname for the Docker container
    let config = DatabaseConfig::new(
        "postgres://postgres:postgres@postgres:5432/postgres",
        "postgres://postgres:postgres@postgres:5432/postgres",
    );

    // Create two backends
    let backend1 = postgres_backend_with_config(config.clone())
        .await
        .expect("Failed to create first backend");

    let backend2 = postgres_backend_with_config(config)
        .await
        .expect("Failed to create second backend");

    // Create first database with a table
    let ctx1 = with_boxed_database(backend1)
        .setup(|conn| {
            Box::pin(async move {
                conn.client()
                    .execute(
                        "CREATE TABLE db1_table (id SERIAL PRIMARY KEY, value TEXT)",
                        &[],
                    )
                    .await?;
                Ok(())
            })
        })
        .execute()
        .await
        .expect("Failed to create first database");

    // Create second database with a different table
    let ctx2 = with_boxed_database(backend2)
        .setup(|conn| {
            Box::pin(async move {
                conn.client()
                    .execute(
                        "CREATE TABLE db2_table (id SERIAL PRIMARY KEY, value TEXT)",
                        &[],
                    )
                    .await?;
                Ok(())
            })
        })
        .execute()
        .await
        .expect("Failed to create second database");

    // Verify databases are separate
    let conn1 = ctx1
        .db
        .pool
        .acquire()
        .await
        .expect("Failed to connect to db1");
    let conn2 = ctx2
        .db
        .pool
        .acquire()
        .await
        .expect("Failed to connect to db2");

    // db1 should have db1_table but not db2_table
    let result = conn1
        .client()
        .query(
            "SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_name = 'db1_table'
            )",
            &[],
        )
        .await
        .expect("Failed to query db1");

    let db1_has_db1_table: bool = result[0].get(0);
    assert!(db1_has_db1_table, "db1 should have db1_table");

    let result = conn1
        .client()
        .query(
            "SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_name = 'db2_table'
            )",
            &[],
        )
        .await
        .expect("Failed to query db1");

    let db1_has_db2_table: bool = result[0].get(0);
    assert!(!db1_has_db2_table, "db1 should not have db2_table");

    // db2 should have db2_table but not db1_table
    let result = conn2
        .client()
        .query(
            "SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_name = 'db2_table'
            )",
            &[],
        )
        .await
        .expect("Failed to query db2");

    let db2_has_db2_table: bool = result[0].get(0);
    assert!(db2_has_db2_table, "db2 should have db2_table");

    let result = conn2
        .client()
        .query(
            "SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_name = 'db1_table'
            )",
            &[],
        )
        .await
        .expect("Failed to query db2");

    let db2_has_db1_table: bool = result[0].get(0);
    assert!(!db2_has_db1_table, "db2 should not have db1_table");
}

#[tokio::test]
async fn test_boxed_database_api() {
    // Use "postgres" as the hostname for the Docker container
    let config = DatabaseConfig::new(
        "postgres://postgres:postgres@postgres:5432/postgres",
        "postgres://postgres:postgres@postgres:5432/postgres",
    );

    let backend = postgres_backend_with_config(config)
        .await
        .expect("Failed to create backend");

    // Create a local variable to capture in the setup closure
    let table_name = String::from("test_table");
    let table_name_clone = table_name.clone(); // Clone the value to avoid move

    // Create a database using the boxed API to handle the captured variable
    let ctx = with_boxed_database(backend)
        .setup(|conn| {
            Box::pin(async move {
                // Create a table using our captured variable
                let create_query = format!(
                    "CREATE TABLE {} (id SERIAL PRIMARY KEY, value TEXT)",
                    table_name_clone
                );
                conn.client().execute(&create_query, &[]).await?;

                // Insert some test data
                let insert_query = format!("INSERT INTO {} (value) VALUES ($1)", table_name_clone);
                conn.client()
                    .execute(&insert_query, &[&"test value"])
                    .await?;

                Ok(())
            })
        })
        .execute()
        .await
        .expect("Failed to create context with test database");

    // Verify the table exists with the expected name
    let conn = ctx
        .db
        .pool
        .acquire()
        .await
        .expect("Failed to get connection");

    // Verify the table exists
    let query = format!(
        "SELECT EXISTS (
            SELECT FROM information_schema.tables 
            WHERE table_name = '{}'
        )",
        table_name
    );

    let result = conn
        .client()
        .query(&query, &[])
        .await
        .expect("Failed to query tables");

    let exists: bool = result[0].get(0);
    assert!(exists, "Table should exist");

    // Now check if our data is there
    let query = format!("SELECT * FROM {}", table_name);
    let rows = conn
        .client()
        .query(&query, &[])
        .await
        .expect("Failed to query table");

    assert_eq!(rows.len(), 1, "Should have one row");
    assert_eq!(rows[0].get::<&str, String>("value"), "test value");
}

#[tokio::test]
async fn test_basic_connection() {
    // Create the backend with our test config
    let backend = match postgres_backend_with_config(test_config()).await {
        Ok(b) => b,
        Err(e) => {
            if is_connection_error(&e) {
                println!("Skipping test: PostgreSQL appears to be unavailable");
                return;
            }
            panic!("Failed to create backend: {:?}", e);
        }
    };

    // Create a test database instance with the backend and config
    let db = match TestDatabaseInstance::new(backend.clone(), test_config()).await {
        Ok(db) => db,
        Err(e) => {
            if is_connection_error(&e) {
                println!("Skipping test: PostgreSQL appears to be unavailable");
                return;
            }
            panic!("Failed to create test database: {:?}", e);
        }
    };

    // Get a connection from the pool
    let conn = match db.pool.acquire().await {
        Ok(conn) => conn,
        Err(e) => panic!("Failed to acquire connection: {:?}", e),
    };

    // Create a test table
    match conn
        .client()
        .execute(
            "CREATE TABLE test_table (id SERIAL PRIMARY KEY, value TEXT)",
            &[],
        )
        .await
    {
        Ok(_) => {}
        Err(e) => panic!("Failed to create table: {:?}", e),
    }

    // Insert some test data
    match conn
        .client()
        .execute(
            "INSERT INTO test_table (value) VALUES ($1)",
            &[&"test value"],
        )
        .await
    {
        Ok(_) => {}
        Err(e) => panic!("Failed to insert data: {:?}", e),
    }

    // Query the data
    let rows = match conn
        .client()
        .query("SELECT value FROM test_table", &[])
        .await
    {
        Ok(rows) => rows,
        Err(e) => panic!("Failed to query data: {:?}", e),
    };

    assert_eq!(rows.len(), 1, "Should have one row");
    assert_eq!(rows[0].get::<&str, String>("value"), "test value");
}

#[tokio::test]
async fn test_with_connection() {
    // Create a backend
    let backend = match test_backend().await {
        Ok(backend) => backend,
        Err(e) => {
            if is_connection_error(&e) {
                println!("Skipping test: PostgreSQL appears to be unavailable");
                return;
            }
            panic!("Failed to create backend: {:?}", e);
        }
    };

    // Create a database with a test table
    let ctx = match with_boxed_database(backend)
        .setup(|conn| {
            Box::pin(async move {
                // Create a test table and insert data
                conn.client()
                    .execute(
                        "CREATE TABLE one_off_test (id SERIAL PRIMARY KEY, value TEXT)",
                        &[],
                    )
                    .await?;

                conn.client()
                    .execute(
                        "INSERT INTO one_off_test (value) VALUES ($1)",
                        &[&"test_value"],
                    )
                    .await?;

                Ok(())
            })
        })
        .execute()
        .await
    {
        Ok(ctx) => ctx,
        Err(e) => {
            if is_connection_error(&e) {
                println!("Skipping test: PostgreSQL appears to be unavailable");
                return;
            }
            panic!("Failed to create database: {:?}", e);
        }
    };

    // Test with_connection functionality
    let conn_string = ctx.db.backend().connection_string(ctx.db.name());
    println!("Debug: Using connection string: {}", conn_string);

    // Use one-off connection to verify data
    let result = testkit_postgres::with_postgres_connection(conn_string, |conn| {
        Box::pin(async move {
            let rows = conn
                .client()
                .query("SELECT * FROM one_off_test", &[])
                .await
                .map_err(|e| PostgresError::QueryError(e.to_string()))?;

            assert_eq!(rows.len(), 1, "Expected 1 row");
            Ok::<_, PostgresError>(())
        })
    })
    .await;

    assert!(result.is_ok(), "with_postgres_connection should succeed");
}

#[tokio::test]
async fn test_postgres_with_connection() {
    // Create a backend
    let backend = match test_backend().await {
        Ok(backend) => backend,
        Err(e) => {
            if is_connection_error(&e) {
                println!("Skipping test: PostgreSQL appears to be unavailable");
                return;
            }
            panic!("Failed to create backend: {:?}", e);
        }
    };

    // Create a database with a test table
    let ctx = match with_boxed_database(backend)
        .setup(|conn| {
            Box::pin(async move {
                // Create a test table and insert data
                conn.client()
                    .execute(
                        "CREATE TABLE one_off_test (id SERIAL PRIMARY KEY, value TEXT)",
                        &[],
                    )
                    .await?;

                conn.client()
                    .execute(
                        "INSERT INTO one_off_test (value) VALUES ($1)",
                        &[&"test_value"],
                    )
                    .await?;

                Ok(())
            })
        })
        .execute()
        .await
    {
        Ok(ctx) => ctx,
        Err(e) => {
            if is_connection_error(&e) {
                println!("Skipping test: PostgreSQL appears to be unavailable");
                return;
            }
            panic!("Failed to create database: {:?}", e);
        }
    };

    // Test with_connection functionality
    let conn_string = ctx.db.backend().connection_string(ctx.db.name());
    println!("Debug: Using connection string: {}", conn_string);

    // Use one-off connection to verify data
    let result = testkit_postgres::with_postgres_connection(conn_string, |conn| {
        Box::pin(async move {
            let rows = conn
                .client()
                .query("SELECT * FROM one_off_test", &[])
                .await
                .map_err(|e| PostgresError::QueryError(e.to_string()))?;

            assert_eq!(rows.len(), 1, "Expected 1 row");
            Ok::<_, PostgresError>(())
        })
    })
    .await;

    assert!(result.is_ok(), "with_postgres_connection should succeed");
}