1
use std::cell::RefCell;
2
use std::future::Future;
3

            
4
use server::user::TenantConnection;
5
use sqlx::types::Uuid;
6
use tests_integration::tenant_guard::TestTenant;
7

            
8
tokio::task_local! {
9
    static HELD: RefCell<Vec<TestTenant>>;
10
}
11

            
12
/// Runs a test body so that every tenant it provisions is removed when the body
13
/// ends, whether it returns, fails an assertion or panics.
14
330
pub async fn scoped<F: Future>(body: F) -> F::Output {
15
330
    let ended = async {
16
330
        let output = body.await;
17
330
        remove_held();
18
330
        output
19
330
    };
20
330
    HELD.scope(RefCell::new(Vec::new()), ended).await
21
330
}
22

            
23
/// On a normal end, so that a failed cleanup fails the test.
24
330
fn remove_held() {
25
330
    let held = HELD.with(|held| held.take());
26
330
    for tenant in held {
27
212
        drop(tenant);
28
    }
29
330
}
30

            
31
213
pub async fn provision_tenant(user_id: Uuid) {
32
213
    hold(TestTenant::provisioned(user_id));
33
213
    let database_name = server::provision::create_user_database(user_id)
34
213
        .await
35
213
        .expect("provision tenant");
36
213
    let mut conn = server::db::get_connection().await.expect("connection");
37
213
    sqlx::query(
38
213
        "INSERT INTO users (id, user_name, email, user_password, database_name, \
39
213
         jwt_public_key, verified) VALUES ($1, $2, $3, 'unused', $4, $5, TRUE)",
40
213
    )
41
213
    .bind(user_id)
42
213
    .bind(format!("probe-{}", user_id.simple()))
43
213
    .bind(format!("tags-{}@example.test", user_id.simple()))
44
213
    .bind(database_name)
45
213
    .bind(crate::common::TEST_PUBLIC_KEY_B64)
46
213
    .execute(&mut *conn)
47
213
    .await
48
213
    .expect("seed directory row");
49
213
}
50

            
51
213
fn hold(tenant: TestTenant) {
52
213
    HELD.try_with(|held| held.borrow_mut().push(tenant))
53
213
        .expect("tenants are provisioned inside a shared_runtime_test body");
54
213
}
55

            
56
/// Removes a tenant before the body ends, for tests that need it gone.
57
1
pub fn release_tenant(user_id: Uuid) {
58
1
    let released = HELD
59
1
        .try_with(|held| {
60
1
            let mut held = held.borrow_mut();
61
1
            let index = held
62
1
                .iter()
63
1
                .position(|tenant| tenant.user() == Some(user_id));
64
1
            index.map(|index| held.remove(index))
65
1
        })
66
1
        .expect("tenants are released inside a shared_runtime_test body");
67
1
    drop(released);
68
1
}
69

            
70
82
pub async fn tenant_connection(user_id: Uuid) -> TenantConnection {
71
82
    server::user::User { id: user_id }
72
82
        .get_connection()
73
82
        .await
74
82
        .expect("tenant connection")
75
82
}