1
use clap::Parser;
2
use sqlx::PgPool;
3

            
4
use super::*;
5
use crate::{AccountCmd, Cli, Command, CommodityCmd, ConfigCmd, TagCmd};
6

            
7
17
fn parse(args: &[&str]) -> Result<Command, clap::Error> {
8
17
    let user = Uuid::new_v4().to_string();
9
17
    let argv = ["nomisync", "--userid", &user]
10
17
        .into_iter()
11
17
        .chain(args.iter().copied());
12
17
    Cli::try_parse_from(argv).map(|cli| cli.cmd)
13
17
}
14

            
15
9
fn call(args: &[&str]) -> anyhow::Result<FormCall> {
16
9
    match parse(args)? {
17
        Command::Account(AccountCmd::Forms(AccountForms(call)))
18
        | Command::Commodity(CommodityCmd::Forms(CommodityForms(call)))
19
        | Command::Tag(TagCmd::Forms(TagForms(call)))
20
9
        | Command::Config(ConfigCmd::Forms(ConfigForms(call))) => Ok(call),
21
        other => anyhow::bail!("not a form command: {other:?}"),
22
    }
23
9
}
24

            
25
#[test]
26
1
fn account_create_takes_the_descriptor_fields() -> anyhow::Result<()> {
27
1
    let call = call(&["account", "create", "--name", "Cash", "--parent", "Assets"])?;
28
1
    assert_eq!(call.form.name, "account-create");
29
1
    assert_eq!(call.id, None);
30
1
    assert_eq!(call.values.text("name"), Some("Cash"));
31
1
    assert_eq!(call.values.text("parent"), Some("Assets"));
32
1
    Ok(())
33
1
}
34

            
35
#[test]
36
1
fn a_missing_required_field_is_left_for_the_server() -> anyhow::Result<()> {
37
1
    assert_eq!(call(&["account", "create"])?.values.text("name"), None);
38
1
    Ok(())
39
1
}
40

            
41
#[test]
42
1
fn account_edit_takes_an_id_and_tag_rows() -> anyhow::Result<()> {
43
1
    let id = Uuid::new_v4();
44
1
    let call = call(&[
45
1
        "account",
46
1
        "edit",
47
1
        &id.to_string(),
48
1
        "--name",
49
1
        "Wallet",
50
1
        "--tag",
51
1
        "name=kind,value=cash",
52
1
    ])?;
53
1
    assert_eq!(call.form.name, "account-edit");
54
1
    assert_eq!(call.id, Some(id));
55
1
    assert_eq!(call.values.rows("tags").map(<[_]>::len), Some(1));
56
1
    Ok(())
57
1
}
58

            
59
#[test]
60
1
fn edit_without_an_id_is_a_usage_error() {
61
1
    assert!(parse(&["commodity", "edit", "--symbol", "X"]).is_err());
62
1
}
63

            
64
#[test]
65
1
fn commodity_create_edit_and_convert_parse() -> anyhow::Result<()> {
66
1
    let created = call(&["commodity", "create", "--symbol", "USD", "--name", "Dollar"])?;
67
1
    assert_eq!(created.values.text("symbol"), Some("USD"));
68
1
    let id = Uuid::new_v4();
69
1
    let edited = call(&["commodity", "edit", &id.to_string(), "--clear-tags"])?;
70
1
    assert_eq!(edited.values.rows("tags"), Some(&[][..]));
71
1
    let converted = call(&[
72
1
        "commodity",
73
1
        "convert",
74
1
        "--amount",
75
1
        "10",
76
1
        "--from",
77
1
        "USD",
78
1
        "--to",
79
1
        "EUR",
80
1
    ])?;
81
1
    assert_eq!(converted.form.name, "convert");
82
1
    assert_eq!(converted.values.text("to"), Some("EUR"));
83
1
    Ok(())
84
1
}
85

            
86
#[test]
87
1
fn config_set_uses_the_descriptor_keys() -> anyhow::Result<()> {
88
1
    let call = call(&["config", "set", "--key", "theme", "--value", "dark"])?;
89
1
    assert_eq!(call.form.name, "config-set");
90
1
    assert_eq!(call.values.text("key"), Some("theme"));
91
1
    assert!(parse(&["config", "set", "--name", "theme"]).is_err());
92
1
    Ok(())
93
1
}
94

            
95
#[test]
96
1
fn config_get_stays_on_name() -> anyhow::Result<()> {
97
1
    assert!(matches!(
98
1
        parse(&["config", "get", "--name", "theme"])?,
99
        Command::Config(ConfigCmd::Get { .. })
100
    ));
101
1
    Ok(())
102
1
}
103

            
104
#[test]
105
1
fn every_entry_builds_a_command() {
106
1
    for entry in ACCOUNT_FORMS
107
1
        .iter()
108
1
        .chain(&COMMODITY_FORMS)
109
1
        .chain(&TAG_FORMS)
110
1
        .chain(&CONFIG_FORMS)
111
    {
112
8
        entry_command(entry).debug_assert();
113
    }
114
1
}
115

            
116
#[test]
117
1
fn replies_print_as_the_clients_do() {
118
1
    let mut values = FormValues::default();
119
1
    ["amount", "from", "to"]
120
1
        .into_iter()
121
1
        .zip(["10", "USD", "EUR"])
122
3
        .for_each(|(key, text)| values.set(key, text));
123
1
    assert_eq!(
124
1
        printed(&values, &Reply::Entity("abc".to_string())),
125
1
        Some("abc".to_string())
126
    );
127
1
    assert_eq!(printed(&values, &Reply::Done), None);
128
1
    assert_eq!(
129
1
        printed(&values, &Reply::Value("9".to_string())),
130
1
        Some("10 USD = 9 EUR".to_string())
131
    );
132
1
}
133

            
134
#[test]
135
1
fn tag_create_and_edit_take_the_descriptor_fields() -> anyhow::Result<()> {
136
1
    let created = call(&[
137
1
        "tag",
138
1
        "create",
139
1
        "--name",
140
1
        "kind",
141
1
        "--value",
142
1
        "fiat",
143
1
        "--description",
144
1
        "money",
145
1
    ])?;
146
1
    assert_eq!(created.form.name, "tag-create");
147
1
    assert_eq!(created.id, None);
148
1
    assert_eq!(created.values.text("description"), Some("money"));
149
1
    let id = Uuid::new_v4();
150
1
    let edited = call(&["tag", "edit", &id.to_string(), "--value", "crypto"])?;
151
1
    assert_eq!(edited.form.name, "tag-edit");
152
1
    assert_eq!(edited.id, Some(id));
153
1
    assert_eq!(edited.values.text("value"), Some("crypto"));
154
1
    assert_eq!(edited.values.text("name"), None);
155
1
    Ok(())
156
1
}
157

            
158
#[test]
159
1
fn tag_delete_and_list_parse() -> anyhow::Result<()> {
160
1
    let id = Uuid::new_v4();
161
1
    assert!(matches!(
162
1
        parse(&["tag", "delete", &id.to_string()])?,
163
1
        Command::Tag(TagCmd::Delete { id: parsed, yes: false }) if parsed == id
164
    ));
165
1
    assert!(matches!(
166
1
        parse(&["tag", "delete", &id.to_string(), "--yes"])?,
167
        Command::Tag(TagCmd::Delete { yes: true, .. })
168
    ));
169
1
    assert!(matches!(
170
1
        parse(&["tag", "list"])?,
171
        Command::Tag(TagCmd::List)
172
    ));
173
1
    assert!(parse(&["tag", "delete"]).is_err());
174
1
    assert!(parse(&["tag", "edit", "--value", "x"]).is_err());
175
1
    Ok(())
176
1
}
177

            
178
18
pub(crate) async fn seed_user(pool: &PgPool) -> anyhow::Result<Uuid> {
179
18
    let user_id = Uuid::new_v4();
180
18
    sqlx::query(
181
18
        "INSERT INTO users \
182
18
         (id, user_name, email, photo, verified, user_password, user_role, database_name, created_at) \
183
18
         VALUES ($1, $2, $3, 'x', false, 'pw', 'user', 'db', NOW())",
184
18
    )
185
18
    .bind(user_id)
186
18
    .bind(format!("u{user_id}"))
187
18
    .bind(format!("{user_id}@test.com"))
188
18
    .execute(pool)
189
18
    .await?;
190
18
    Ok(user_id)
191
18
}
192

            
193
4
fn values(pairs: &[(&str, &str)]) -> FormValues {
194
4
    let mut values = FormValues::default();
195
8
    pairs.iter().for_each(|(k, v)| values.set(k, v));
196
4
    values
197
4
}
198

            
199
4
async fn seeded_tag(pool: &PgPool) -> anyhow::Result<(Session, Uuid)> {
200
4
    let user = seed_user(pool).await?;
201
4
    let mut session = Session::new(rpc::ScriptCtx::new(user))?;
202
4
    let made = cli_core::flat::submit(
203
4
        &mut session,
204
4
        &forms::TAG_CREATE,
205
4
        &values(&[("name", "kind"), ("value", "fiat")]),
206
4
    )
207
4
    .await?;
208
4
    match made.reply {
209
4
        cli_core::flat::Reply::Entity(id) => Ok((session, Uuid::parse_str(&id)?)),
210
        other => anyhow::bail!("expected an entity, got {other:?}"),
211
    }
212
4
}
213

            
214
4
async fn tag_count(session: &mut Session) -> anyhow::Result<usize> {
215
4
    match cli_core::eval::eval_form(session, "(list-tags)", RenderMode::TagList).await? {
216
4
        cli_core::eval::Rendered::Lines(lines) => Ok(lines.len()),
217
        other => anyhow::bail!("expected lines, got {other:?}"),
218
    }
219
4
}
220

            
221
#[sqlx::test(migrator = "server::db::MIGRATOR")]
222
async fn a_declined_tag_delete_keeps_the_tag(pool: PgPool) -> anyhow::Result<()> {
223
    let _guard = server::db::install_test_pool(pool.clone());
224
    let (mut session, id) = seeded_tag(&pool).await?;
225

            
226
    let deleted = delete_tag_confirmed(&mut session, id, false, true, "n\n".as_bytes()).await?;
227

            
228
    assert!(!deleted);
229
    assert_eq!(tag_count(&mut session).await?, 1);
230
    Ok(())
231
}
232

            
233
#[sqlx::test(migrator = "server::db::MIGRATOR")]
234
async fn a_confirmed_tag_delete_removes_the_tag(pool: PgPool) -> anyhow::Result<()> {
235
    let _guard = server::db::install_test_pool(pool.clone());
236
    let (mut session, id) = seeded_tag(&pool).await?;
237

            
238
    let deleted = delete_tag_confirmed(&mut session, id, false, true, "y\n".as_bytes()).await?;
239

            
240
    assert!(deleted);
241
    assert_eq!(tag_count(&mut session).await?, 0);
242
    Ok(())
243
}
244

            
245
#[sqlx::test(migrator = "server::db::MIGRATOR")]
246
async fn tag_delete_with_yes_needs_no_input(pool: PgPool) -> anyhow::Result<()> {
247
    let _guard = server::db::install_test_pool(pool.clone());
248
    let (mut session, id) = seeded_tag(&pool).await?;
249

            
250
    let deleted = delete_tag_confirmed(&mut session, id, true, false, "".as_bytes()).await?;
251

            
252
    assert!(deleted);
253
    assert_eq!(tag_count(&mut session).await?, 0);
254
    Ok(())
255
}
256

            
257
#[sqlx::test(migrator = "server::db::MIGRATOR")]
258
async fn tag_delete_without_a_terminal_or_yes_is_refused(pool: PgPool) -> anyhow::Result<()> {
259
    let _guard = server::db::install_test_pool(pool.clone());
260
    let (mut session, id) = seeded_tag(&pool).await?;
261

            
262
    let refused = delete_tag_confirmed(&mut session, id, false, false, "y\n".as_bytes()).await;
263

            
264
    assert!(
265
        matches!(refused, Err(CommandError::Argument(_))),
266
        "{refused:?}"
267
    );
268
    assert_eq!(tag_count(&mut session).await?, 1);
269
    Ok(())
270
}