1
use super::tag::{CreateTag, DeleteTag, EditTag, ListTags};
2
use super::{CmdError, CmdResult, FinanceEntity};
3
use crate::db::install_test_pool;
4
use crate::error::ServerError;
5
use crate::tag_state::{STALE_TAG, tag_revision};
6
use crate::user::User;
7
use sqlx::PgPool;
8
use supp_macro::local_db_sqlx_test;
9
use tokio::sync::OnceCell;
10
use uuid::Uuid;
11

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

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

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

            
25
7
async fn create(user: &User, name: &str, value: &str) -> anyhow::Result<Uuid> {
26
7
    match CreateTag::new()
27
7
        .user_id(user.id)
28
7
        .name(name.to_string())
29
7
        .value(value.to_string())
30
7
        .run()
31
7
        .await?
32
    {
33
7
        Some(CmdResult::Uuid(id)) => Ok(id),
34
        other => anyhow::bail!("unexpected CreateTag result {other:?}"),
35
    }
36
7
}
37

            
38
6
async fn edit(
39
6
    user: &User,
40
6
    tag: Uuid,
41
6
    revision: &str,
42
6
    description: Option<&str>,
43
6
) -> Result<Option<CmdResult>, CmdError> {
44
6
    let mut command = EditTag::new()
45
6
        .user_id(user.id)
46
6
        .tag_id(tag)
47
6
        .name("kind".to_string())
48
6
        .value("fiat".to_string())
49
6
        .revision(revision.to_string());
50
6
    if let Some(text) = description {
51
4
        command = command.description(text.to_string());
52
2
    }
53
6
    command.run().await
54
6
}
55

            
56
#[local_db_sqlx_test]
57
async fn test_edit_with_the_loaded_revision_applies(pool: PgPool) -> Result<(), anyhow::Error> {
58
    let user = user().await?;
59
    let tag = create(user, "kind", "fiat").await?;
60
    let revision = tag_revision(&user.stored_tag(tag).await?);
61

            
62
    edit(user, tag, &revision, Some("note")).await?;
63

            
64
    assert_eq!(
65
        user.stored_tag(tag).await?.description.as_deref(),
66
        Some("note")
67
    );
68
}
69

            
70
#[local_db_sqlx_test]
71
async fn test_edit_with_an_old_revision_is_stale(pool: PgPool) -> Result<(), anyhow::Error> {
72
    let user = user().await?;
73
    let tag = create(user, "kind", "fiat").await?;
74
    let revision = tag_revision(&user.stored_tag(tag).await?);
75
    edit(user, tag, &revision, Some("first")).await?;
76

            
77
    let result = edit(user, tag, &revision, Some("second")).await;
78

            
79
    assert!(
80
        matches!(&result, Err(CmdError::Args(m)) if m == STALE_TAG),
81
        "{result:?}"
82
    );
83
    assert_eq!(
84
        user.stored_tag(tag).await?.description.as_deref(),
85
        Some("first")
86
    );
87
}
88

            
89
#[local_db_sqlx_test]
90
async fn test_edit_onto_another_tag_is_a_clash(pool: PgPool) -> Result<(), anyhow::Error> {
91
    let user = user().await?;
92
    let tag = create(user, "kind", "coin").await?;
93
    create(user, "kind", "fiat").await?;
94
    let revision = tag_revision(&user.stored_tag(tag).await?);
95

            
96
    let result = edit(user, tag, &revision, None).await;
97

            
98
    assert!(
99
        matches!(&result, Err(CmdError::Server(ServerError::TagClash { .. }))),
100
        "{result:?}"
101
    );
102
}
103

            
104
#[local_db_sqlx_test]
105
async fn test_edit_of_a_deleted_tag_is_not_found(pool: PgPool) -> Result<(), anyhow::Error> {
106
    let user = user().await?;
107
    let tag = create(user, "kind", "fiat").await?;
108
    let revision = tag_revision(&user.stored_tag(tag).await?);
109
    user.delete_tag(tag).await?;
110

            
111
    let edited = edit(user, tag, &revision, None).await;
112
    let updated = user
113
        .rename_tag(tag, "kind".into(), "fiat".into(), None)
114
        .await;
115

            
116
    assert!(
117
        matches!(&edited, Err(err) if err.is_missing_row()),
118
        "{edited:?}"
119
    );
120
    assert!(
121
        matches!(&updated, Err(err) if err.is_missing_row()),
122
        "{updated:?}"
123
    );
124
}
125

            
126
#[local_db_sqlx_test]
127
async fn test_delete_removes_the_tag_and_a_second_delete_is_not_found(
128
    pool: PgPool,
129
) -> Result<(), anyhow::Error> {
130
    let user = user().await?;
131
    let tag = create(user, "kind", "fiat").await?;
132
2
    let delete = || DeleteTag::new().user_id(user.id).tag_id(tag).run();
133

            
134
    let first = delete().await?;
135
    let second = delete().await;
136

            
137
    assert!(matches!(first, Some(CmdResult::Bool(true))), "{first:?}");
138
    assert!(user.find_tag(tag).await?.is_none());
139
    assert!(matches!(second, Err(CmdError::NotFound(_))), "{second:?}");
140
}
141

            
142
#[local_db_sqlx_test]
143
async fn test_list_returns_the_users_tags_with_descriptions(
144
    pool: PgPool,
145
) -> Result<(), anyhow::Error> {
146
    let user = user().await?;
147
    let tag = create(user, "kind", "fiat").await?;
148
    let revision = tag_revision(&user.stored_tag(tag).await?);
149
    edit(user, tag, &revision, Some("note")).await?;
150

            
151
    let listed = ListTags::new().user_id(user.id).run().await?;
152

            
153
    let Some(CmdResult::Entities(entities)) = listed else {
154
        anyhow::bail!("unexpected ListTags result {listed:?}");
155
    };
156
    let [FinanceEntity::Tag(found)] = entities.as_slice() else {
157
        anyhow::bail!("expected one tag, got {entities:?}");
158
    };
159
    assert_eq!(found.id, tag);
160
    assert_eq!(found.description.as_deref(), Some("note"));
161
}
162

            
163
#[local_db_sqlx_test]
164
async fn test_list_is_empty_for_a_user_without_tags(pool: PgPool) -> Result<(), anyhow::Error> {
165
    let user = user().await?;
166

            
167
    let listed = ListTags::new().user_id(user.id).run().await?;
168

            
169
    assert!(
170
        matches!(&listed, Some(CmdResult::Entities(entities)) if entities.is_empty()),
171
        "{listed:?}"
172
    );
173
}