1
use forms::{FormValues, escape_str};
2
use sqlx::PgPool;
3
use uuid::Uuid;
4

            
5
use super::test_seed::{seed_commodity, seed_price, seed_user};
6
use crate::ctx::ScriptCtx;
7
use crate::forms::{Failure, convert};
8
use crate::session::Session;
9

            
10
5
fn values(amount: &str, from: &str, to: &str) -> FormValues {
11
5
    let mut values = FormValues::default();
12
5
    values.set("amount", amount);
13
5
    values.set("from", from);
14
5
    values.set("to", to);
15
5
    values
16
5
}
17

            
18
struct Rates {
19
    user: Uuid,
20
    usd: Uuid,
21
    eur: Uuid,
22
}
23

            
24
6
async fn rates(pool: &PgPool) -> anyhow::Result<Rates> {
25
6
    let user = seed_user(pool).await?;
26
6
    let usd = seed_commodity(user, "USD").await?;
27
6
    let eur = seed_commodity(user, "EUR").await?;
28
6
    Ok(Rates { user, usd, eur })
29
6
}
30

            
31
2
async fn script(session: &mut Session, form: &str) -> String {
32
2
    session.handle_form(&format!("(:id 1 :form {form})")).await
33
2
}
34

            
35
2
async fn invalid_fields(user: Uuid, values: &FormValues) -> anyhow::Result<Vec<String>> {
36
2
    match convert(user, values).await {
37
4
        Err(Failure::Invalid(errors)) => Ok(errors.into_iter().map(|e| e.field).collect()),
38
        other => anyhow::bail!("expected field errors, got {other:?}"),
39
    }
40
2
}
41

            
42
1
async fn refusal(user: Uuid, values: &FormValues) -> anyhow::Result<String> {
43
1
    match convert(user, values).await {
44
1
        Err(Failure::Refused(reason)) => Ok(reason),
45
        other => anyhow::bail!("expected a refusal, got {other:?}"),
46
    }
47
1
}
48

            
49
#[sqlx::test(migrator = "server::db::MIGRATOR")]
50
async fn a_script_receives_the_ratio_as_a_number(pool: PgPool) -> anyhow::Result<()> {
51
    let _guard = server::db::install_test_pool(pool.clone());
52
    let r = rates(&pool).await?;
53
    seed_price(&pool, r.usd, r.eur, (9, 10)).await?;
54
    let mut session = Session::new(ScriptCtx::new(r.user))?;
55
    let payload = format!("(:amount \"1/3\" :from \"{}\" :to \"{}\")", r.usd, r.eur);
56
    let call = format!("(submit-form \"convert\" {})", escape_str(&payload));
57

            
58
    assert_eq!(script(&mut session, &call).await, "(:id 1 :value 3/10)");
59
    assert_eq!(
60
        script(&mut session, &format!("(equal {call} 3/10)")).await,
61
        "(:id 1 :value t)"
62
    );
63
    Ok(())
64
}
65

            
66
#[sqlx::test(migrator = "server::db::MIGRATOR")]
67
async fn the_inverse_price_converts_back(pool: PgPool) -> anyhow::Result<()> {
68
    let _guard = server::db::install_test_pool(pool.clone());
69
    let r = rates(&pool).await?;
70
    seed_price(&pool, r.usd, r.eur, (9, 10)).await?;
71

            
72
    let ratio = convert(r.user, &values("9", &r.eur.to_string(), &r.usd.to_string())).await?;
73

            
74
    assert_eq!((*ratio.numer(), *ratio.denom()), (10, 1));
75
    Ok(())
76
}
77

            
78
#[sqlx::test(migrator = "server::db::MIGRATOR")]
79
async fn the_same_commodity_is_an_error_at_to(pool: PgPool) -> anyhow::Result<()> {
80
    let _guard = server::db::install_test_pool(pool.clone());
81
    let r = rates(&pool).await?;
82
    let usd = r.usd.to_string();
83

            
84
    assert_eq!(
85
        invalid_fields(r.user, &values("1", &usd, &usd)).await?,
86
        ["to"]
87
    );
88
    Ok(())
89
}
90

            
91
#[sqlx::test(migrator = "server::db::MIGRATOR")]
92
async fn bad_fields_are_reported_together(pool: PgPool) -> anyhow::Result<()> {
93
    let _guard = server::db::install_test_pool(pool.clone());
94
    let r = rates(&pool).await?;
95

            
96
    let fields = invalid_fields(r.user, &values("x", &Uuid::new_v4().to_string(), "")).await?;
97

            
98
    assert_eq!(fields, ["amount", "to", "from"]);
99
    Ok(())
100
}
101

            
102
#[sqlx::test(migrator = "server::db::MIGRATOR")]
103
async fn an_overflowing_conversion_is_a_bad_argument(pool: PgPool) -> anyhow::Result<()> {
104
    let _guard = server::db::install_test_pool(pool.clone());
105
    let r = rates(&pool).await?;
106
    seed_price(&pool, r.usd, r.eur, (2, 1)).await?;
107
    let big = i64::MAX.to_string();
108

            
109
    let failure = convert(
110
        r.user,
111
        &values(&big, &r.usd.to_string(), &r.eur.to_string()),
112
    )
113
    .await
114
    .expect_err("overflow");
115

            
116
    assert_eq!(failure.http_status(), 400, "{failure}");
117
    assert!(failure.to_string().contains("overflow"), "{failure}");
118
    Ok(())
119
}
120

            
121
#[sqlx::test(migrator = "server::db::MIGRATOR")]
122
async fn a_missing_price_names_both_commodities(pool: PgPool) -> anyhow::Result<()> {
123
    let _guard = server::db::install_test_pool(pool.clone());
124
    let r = rates(&pool).await?;
125

            
126
    let reason = refusal(r.user, &values("1", &r.usd.to_string(), &r.eur.to_string())).await?;
127

            
128
    assert_eq!(reason, "no exchange rate between USD and EUR");
129
    Ok(())
130
}