1
use super::{DBError, get_connection, install_test_pool, test_pool_is_set};
2
use sqlx::PgPool;
3
use tokio::sync::OnceCell;
4

            
5
/// Context for keeping environment intact
6
static CONTEXT: OnceCell<()> = OnceCell::const_new();
7

            
8
4
async fn setup() {
9
4
    CONTEXT
10
4
        .get_or_init(|| async {
11
4
            crate::telemetry::init_test_logging();
12
8
        })
13
4
        .await;
14
4
}
15

            
16
#[sqlx::test(migrator = "server::db::MIGRATOR")]
17
async fn migrations_create_schema_without_seed(pool: PgPool) -> sqlx::Result<()> {
18
    setup().await;
19

            
20
    let mut conn = pool.acquire().await?;
21

            
22
    // The migration set is DDL-only: it creates the `config` table but no
23
    // longer seeds it (seeding moved to `bootstrap::seed`). So a freshly
24
    // migrated DB has the table present and empty.
25
    let config_rows: i64 = sqlx::query_scalar("SELECT count(*) FROM config")
26
        .fetch_one(&mut *conn)
27
        .await?;
28
    assert_eq!(config_rows, 0, "migration set must not seed config rows");
29

            
30
    Ok(())
31
}
32

            
33
#[sqlx::test(migrator = "server::db::MIGRATOR")]
34
async fn the_installed_pool_is_an_owned_handle(pool: PgPool) -> anyhow::Result<()> {
35
    setup().await;
36
    let _guard = install_test_pool(pool);
37
    assert!(test_pool_is_set());
38

            
39
    let mut conn = get_connection().await?;
40
    let one: i32 = sqlx::query_scalar("SELECT 1").fetch_one(&mut *conn).await?;
41
    assert_eq!(one, 1);
42

            
43
    Ok(())
44
}
45

            
46
#[sqlx::test(migrator = "server::db::MIGRATOR")]
47
async fn a_closed_installed_pool_reports_pool_closed(pool: PgPool) -> anyhow::Result<()> {
48
    setup().await;
49
    let _guard = install_test_pool(pool.clone());
50
    pool.close().await;
51

            
52
    let outcome = get_connection().await;
53
    assert!(
54
        matches!(outcome, Err(DBError::Sqlx(sqlx::Error::PoolClosed))),
55
        "{outcome:?}"
56
    );
57

            
58
    Ok(())
59
}
60

            
61
#[sqlx::test(migrator = "server::db::MIGRATOR")]
62
async fn dropping_the_guard_clears_the_installed_pool(pool: PgPool) -> anyhow::Result<()> {
63
    setup().await;
64
    let guard = install_test_pool(pool);
65
    assert!(test_pool_is_set());
66

            
67
    drop(guard);
68
    assert!(!test_pool_is_set());
69

            
70
    Ok(())
71
}
72

            
73
#[tokio::test]
74
1
async fn a_missing_test_pool_is_an_error() {
75
1
    let outcome = get_connection().await;
76
1
    assert!(
77
1
        matches!(outcome, Err(DBError::TestPoolUnset)),
78
1
        "{outcome:?}"
79
1
    );
80
1
}