Skip to main content

awa_testing/
setup.rs

1//! Common test setup utilities for Awa integration tests.
2
3use sqlx::postgres::PgPoolOptions;
4use sqlx::PgPool;
5use std::collections::HashMap;
6use std::time::Duration;
7
8/// Default database URL for test runs.
9pub fn database_url() -> String {
10    std::env::var("DATABASE_URL")
11        .unwrap_or_else(|_| "postgres://postgres:test@localhost:15432/awa_test".to_string())
12}
13
14/// Database URL with a custom application_name parameter appended.
15pub fn database_url_with_app_name(app_name: &str) -> String {
16    let mut url = database_url();
17    let sep = if url.contains('?') { '&' } else { '?' };
18    url.push(sep);
19    url.push_str("application_name=");
20    url.push_str(app_name);
21    url
22}
23
24/// Create a connection pool.
25pub async fn pool(max_connections: u32) -> PgPool {
26    PgPoolOptions::new()
27        .max_connections(max_connections)
28        .connect(&database_url())
29        .await
30        .expect("Failed to connect to database")
31}
32
33/// Create a connection pool with a custom database URL.
34pub async fn pool_with_url(url: &str, max_connections: u32) -> PgPool {
35    PgPoolOptions::new()
36        .max_connections(max_connections)
37        .connect(url)
38        .await
39        .expect("Failed to connect to database")
40}
41
42/// Create a pool, run migrations, and return it.
43pub async fn setup(max_connections: u32) -> PgPool {
44    let pool = pool(max_connections).await;
45    awa_model::migrations::run(&pool)
46        .await
47        .expect("Failed to run migrations");
48    reset_runtime_backend(&pool).await;
49    pool
50}
51
52/// Clear any previously-activated runtime backend so legacy integration tests
53/// start from the canonical compatibility surface unless they opt into a
54/// queue-storage runtime explicitly.
55pub async fn reset_runtime_backend(pool: &PgPool) {
56    sqlx::query("DELETE FROM awa.runtime_storage_backends WHERE backend = 'queue_storage'")
57        .execute(pool)
58        .await
59        .expect("Failed to reset active runtime backend for test setup");
60}
61
62/// Delete all jobs, queue metadata, and admin caches for a specific queue.
63///
64/// Explicitly deletes the `queue_state_counts` row to prevent accumulated
65/// cache drift from affecting assertions. The DELETE trigger normally handles
66/// this, but concurrent test runs against a shared DB can cause small delta
67/// errors that compound over time.
68pub async fn clean_queue(pool: &PgPool, queue: &str) {
69    sqlx::query("DELETE FROM awa.jobs WHERE queue = $1")
70        .bind(queue)
71        .execute(pool)
72        .await
73        .expect("Failed to clean queue jobs");
74    sqlx::query("DELETE FROM awa.queue_meta WHERE queue = $1")
75        .bind(queue)
76        .execute(pool)
77        .await
78        .expect("Failed to clean queue meta");
79    sqlx::query("DELETE FROM awa.queue_state_counts WHERE queue = $1")
80        .bind(queue)
81        .execute(pool)
82        .await
83        .expect("Failed to clean queue state counts");
84}
85
86/// Query job state counts for a queue, returning a map of state -> count.
87pub async fn queue_state_counts(pool: &PgPool, queue: &str) -> HashMap<String, i64> {
88    let rows: Vec<(String, i64)> = sqlx::query_as(
89        r#"
90        SELECT state::text, count(*)::bigint
91        FROM awa.jobs
92        WHERE queue = $1
93        GROUP BY state
94        "#,
95    )
96    .bind(queue)
97    .fetch_all(pool)
98    .await
99    .expect("Failed to query state counts");
100
101    rows.into_iter().collect()
102}
103
104/// Extract a count for a given state from a state-counts map.
105pub fn state_count(counts: &HashMap<String, i64>, state: &str) -> i64 {
106    counts.get(state).copied().unwrap_or(0)
107}
108
109/// Poll queue state counts until a predicate is satisfied, or panic on timeout.
110pub async fn wait_for_counts(
111    pool: &PgPool,
112    queue: &str,
113    predicate: impl Fn(&HashMap<String, i64>) -> bool,
114    timeout: Duration,
115) -> HashMap<String, i64> {
116    let start = std::time::Instant::now();
117    loop {
118        let counts = queue_state_counts(pool, queue).await;
119        if predicate(&counts) {
120            return counts;
121        }
122        assert!(
123            start.elapsed() < timeout,
124            "Timed out waiting for queue {queue} counts; last counts: {counts:?}"
125        );
126        tokio::time::sleep(Duration::from_millis(50)).await;
127    }
128}