1
use sqlx::PgPool;
2
use supp_macro::local_db_sqlx_test;
3
use tokio::sync::OnceCell;
4
use uuid::Uuid;
5

            
6
use super::ListTemplates;
7
use crate::artifact_mgmt::user::TemplateInfo;
8
use crate::command::CmdResult;
9
use crate::db::install_test_pool;
10
use crate::user::User;
11

            
12
static USER: OnceCell<User> = OnceCell::const_new();
13

            
14
2
async fn setup() {
15
4
    USER.get_or_init(|| async { User { id: Uuid::new_v4() } })
16
2
        .await;
17
2
}
18

            
19
2
async fn user() -> anyhow::Result<&'static User> {
20
2
    let user = USER.get().ok_or_else(|| anyhow::anyhow!("no user"))?;
21
2
    user.commit().await?;
22
2
    Ok(user)
23
2
}
24

            
25
2
async fn listed(user: &User) -> anyhow::Result<Vec<(Uuid, Option<String>)>> {
26
2
    let templates = templates(user).await?;
27
3
    Ok(templates.into_iter().map(|t| (t.id, t.name)).collect())
28
2
}
29

            
30
2
async fn templates(user: &User) -> anyhow::Result<Vec<TemplateInfo>> {
31
2
    match ListTemplates::new().user_id(user.id).run().await? {
32
2
        Some(CmdResult::Templates(listed)) => Ok(listed),
33
        other => anyhow::bail!("unexpected result {other:?}"),
34
    }
35
2
}
36

            
37
#[local_db_sqlx_test]
38
async fn lists_templates_by_name_with_unnamed_last(pool: PgPool) -> anyhow::Result<()> {
39
    let user = user().await?;
40
    let unnamed = user.create_template("(a)".into(), None).await?;
41
    let rent = user
42
        .create_template("(b)".into(), Some("rent".into()))
43
        .await?;
44
    let food = user
45
        .create_template("(c)".into(), Some("food".into()))
46
        .await?;
47

            
48
    assert_eq!(
49
        listed(user).await?,
50
        vec![
51
            (food, Some("food".into())),
52
            (rent, Some("rent".into())),
53
            (unnamed, None),
54
        ]
55
    );
56
}
57

            
58
#[local_db_sqlx_test]
59
async fn lists_nothing_without_templates(pool: PgPool) -> anyhow::Result<()> {
60
    let user = user().await?;
61
    assert!(listed(user).await?.is_empty());
62
}