1
use std::collections::HashSet;
2

            
3
use forms::FormValues;
4
use nomiscript::Reader;
5
use scripting::runtime::HostCondition;
6
use sqlx::PgPool;
7
use uuid::Uuid;
8

            
9
use super::test_edit::detail_text;
10
use super::test_query_seed::{Fixture, add_tx, fixture};
11
use super::test_seed::query_text;
12
use super::test_seed::seed_account;
13

            
14
29
pub(super) fn values(pairs: &[(&str, &str)]) -> FormValues {
15
29
    let mut values = FormValues::default();
16
29
    for (key, value) in pairs {
17
40
        values.set(key, value);
18
    }
19
29
    values
20
29
}
21

            
22
/// Reads the result back with the nomiscript reader: (ids, has-more).
23
10
fn read_result(text: &str) -> anyhow::Result<(Vec<String>, bool)> {
24
10
    let program = Reader::parse(text).map_err(|e| anyhow::anyhow!("{e}"))?;
25
10
    anyhow::ensure!(program.exprs.len() == 1, "{text}");
26
10
    let ids = text
27
10
        .split("(:ID \"")
28
10
        .skip(1)
29
15
        .filter_map(|chunk| chunk.split('"').next())
30
10
        .map(str::to_string)
31
        .collect();
32
10
    Ok((ids, text.contains(":HAS-MORE t :TOTAL ")))
33
10
}
34

            
35
10
pub(super) async fn query(
36
10
    f: &Fixture,
37
10
    pairs: &[(&str, &str)],
38
10
) -> anyhow::Result<(Vec<String>, bool)> {
39
10
    let text = query_text(f.user_id, &values(pairs))
40
10
        .await
41
        .map_err(|e| anyhow::anyhow!("{e}"))?;
42
10
    read_result(&text)
43
10
}
44

            
45
13
fn condition(err: &wasmtime::Error) -> anyhow::Result<&HostCondition> {
46
13
    err.downcast_ref::<HostCondition>()
47
        .ok_or_else(|| anyhow::anyhow!("not a HostCondition: {err}"))
48
13
}
49

            
50
13
pub(super) async fn rejected(f: &Fixture, pairs: &[(&str, &str)]) -> anyhow::Result<String> {
51
13
    let err = query_text(f.user_id, &values(pairs))
52
13
        .await
53
        .err()
54
        .ok_or_else(|| anyhow::anyhow!("query was accepted"))?;
55
13
    let cond = condition(&err)?;
56
13
    anyhow::ensure!(cond.code == "form-invalid", "{cond:?}");
57
13
    anyhow::ensure!(cond.detail.is_some(), "no detail");
58
13
    Ok(detail_text(cond))
59
13
}
60

            
61
#[sqlx::test(migrator = "server::db::MIGRATOR")]
62
async fn equal_dates_page_without_duplicates_or_omissions(pool: PgPool) -> anyhow::Result<()> {
63
    let _guard = server::db::install_test_pool(pool.clone());
64
    let f = fixture(&pool).await?;
65
    let mut created = HashSet::new();
66
    for n in 0..5 {
67
        created.insert(
68
            add_tx(&f, "2024-03-01T10:00:00Z", &format!("n{n}"))
69
                .await?
70
                .to_string(),
71
        );
72
    }
73
    let mut seen = Vec::new();
74
    for (offset, more) in [("0", true), ("2", true), ("4", false)] {
75
        let (ids, has_more) = query(&f, &[("limit", "2"), ("offset", offset)]).await?;
76
        assert_eq!(has_more, more, "offset {offset}");
77
        seen.extend(ids);
78
    }
79
    assert_eq!(seen.len(), 5);
80
    assert_eq!(seen.iter().cloned().collect::<HashSet<_>>(), created);
81
    let ids = seen
82
        .iter()
83
5
        .map(|id| Uuid::parse_str(id))
84
        .collect::<Result<Vec<_>, _>>()?;
85
    assert!(
86
4
        ids.windows(2).all(|pair| pair[0] > pair[1]),
87
        "equal dates must page in strictly descending id order: {seen:?}"
88
    );
89
    Ok(())
90
}
91

            
92
#[sqlx::test(migrator = "server::db::MIGRATOR")]
93
async fn rows_carry_date_note_and_amount(pool: PgPool) -> anyhow::Result<()> {
94
    let _guard = server::db::install_test_pool(pool.clone());
95
    let f = fixture(&pool).await?;
96
    let id = add_tx(&f, "2024-03-01T10:00:00.250Z", "lunch \"x\"").await?;
97
    let text = query_text(f.user_id, &values(&[])).await?;
98
    assert_eq!(
99
        text,
100
        format!(
101
            "(:ROWS ((:ID \"{id}\" :DATE \"2024-03-01T10:00:00.250Z\" :DATE-TEXT \"2024-03-01 10:00\" :NOTE \"lunch \\\"x\\\"\" :AMOUNT \"100.00 USD\")) :HAS-MORE nil :TOTAL 1)"
102
        )
103
    );
104
    Reader::parse(&text).map_err(|e| anyhow::anyhow!("{e}"))?;
105
    Ok(())
106
}
107

            
108
#[sqlx::test(migrator = "server::db::MIGRATOR")]
109
async fn date_only_to_includes_the_whole_day(pool: PgPool) -> anyhow::Result<()> {
110
    let _guard = server::db::install_test_pool(pool.clone());
111
    let f = fixture(&pool).await?;
112
    let late = add_tx(&f, "2024-03-01T23:59:59.500Z", "late").await?;
113
    add_tx(&f, "2024-03-02T00:00:00Z", "next").await?;
114
    add_tx(&f, "2024-02-29T23:59:59Z", "before").await?;
115
    let (ids, more) = query(&f, &[("from", "2024-03-01"), ("to", "2024-03-01")]).await?;
116
    assert_eq!(ids, vec![late.to_string()]);
117
    assert!(!more);
118
    Ok(())
119
}
120

            
121
#[sqlx::test(migrator = "server::db::MIGRATOR")]
122
async fn account_filter_takes_a_uuid_only(pool: PgPool) -> anyhow::Result<()> {
123
    let _guard = server::db::install_test_pool(pool.clone());
124
    let f = fixture(&pool).await?;
125
    let other = seed_account(f.user_id, "Savings").await?;
126
    let id = add_tx(&f, "2024-03-01T10:00:00Z", "a").await?;
127
    let by_uuid = query(&f, &[("account", &f.expenses.to_string())]).await?;
128
    assert_eq!(by_uuid.0, vec![id.to_string()]);
129
    let none = query(&f, &[("account", &other.to_string())]).await?;
130
    assert!(none.0.is_empty());
131

            
132
    let foreign = Uuid::new_v4().to_string();
133
    for bad in ["Expenses", "Expenses:Food", "not-a-uuid", foreign.as_str()] {
134
        let detail = rejected(&f, &[("account", bad)]).await?;
135
        assert!(
136
            detail.starts_with("((:FIELD \"account\" :MESSAGE \"unknown account"),
137
            "{bad}: {detail}"
138
        );
139
    }
140
    Ok(())
141
}
142

            
143
#[sqlx::test(migrator = "server::db::MIGRATOR")]
144
async fn out_of_range_numbers_name_their_field(pool: PgPool) -> anyhow::Result<()> {
145
    let _guard = server::db::install_test_pool(pool.clone());
146
    let f = fixture(&pool).await?;
147
    for (key, value) in [
148
        ("limit", "0"),
149
        ("limit", "201"),
150
        ("limit", "many"),
151
        ("offset", "-1"),
152
        ("offset", "x"),
153
    ] {
154
        let detail = rejected(&f, &[(key, value)]).await?;
155
        assert!(
156
            detail.starts_with(&format!("((:FIELD \"{key}\" :MESSAGE \"")),
157
            "{detail}"
158
        );
159
    }
160
    Ok(())
161
}
162

            
163
#[sqlx::test(migrator = "server::db::MIGRATOR")]
164
async fn bad_dates_and_unknown_accounts_are_field_errors(pool: PgPool) -> anyhow::Result<()> {
165
    let _guard = server::db::install_test_pool(pool.clone());
166
    let f = fixture(&pool).await?;
167
    let detail = rejected(
168
        &f,
169
        &[
170
            ("from", "yesterday"),
171
            ("account", &Uuid::new_v4().to_string()),
172
        ],
173
    )
174
    .await?;
175
    assert!(detail.contains("(:FIELD \"from\" :MESSAGE \""), "{detail}");
176
    assert!(
177
        detail.contains("(:FIELD \"account\" :MESSAGE \"unknown account"),
178
        "{detail}"
179
    );
180
    Ok(())
181
}