1
use super::*;
2
use crate::forms::Failure;
3
use crate::natives::forms::native_failure;
4
use crate::status::error_status;
5
use finance::error::ReportError;
6
use server::db::DBError;
7
use server::error::ServerError;
8

            
9
2
fn write_conflict() -> CmdError {
10
2
    CmdError::Server(ServerError::DB(DBError::WriteConflict))
11
2
}
12

            
13
5
fn condition(err: &wasmtime::Error) -> Option<&HostCondition> {
14
5
    err.chain()
15
5
        .find_map(|cause| cause.downcast_ref::<HostCondition>())
16
5
}
17

            
18
#[test]
19
1
fn a_write_conflict_is_the_busy_condition_not_a_host_failure() {
20
1
    let err = cmd_failure("set-account-tag", write_conflict());
21
1
    assert!(!is_host_failure(&err), "{err}");
22
1
    assert_eq!(
23
1
        condition(&err),
24
1
        Some(&HostCondition {
25
1
            code: ErrorCode::BUSY.to_string(),
26
1
            message: DBError::WriteConflict.to_string(),
27
1
            detail: None,
28
1
        })
29
    );
30
1
}
31

            
32
#[test]
33
1
fn an_unreachable_database_is_the_unavailable_condition_not_a_host_failure() {
34
1
    let causes = [
35
1
        DBError::PoolBudgetExhausted,
36
1
        DBError::TenantQuarantined,
37
1
        DBError::TenantDisabled,
38
1
        DBError::UnknownTenant,
39
1
        DBError::Sqlx(sqlx::Error::PoolTimedOut),
40
1
    ];
41
1
    for cause in causes {
42
5
        let message = cause.to_string();
43
5
        let err = cmd_failure("get-commodity", CmdError::from(cause));
44
5
        assert!(!is_host_failure(&err), "{err}");
45
5
        assert_eq!(
46
5
            condition_code(&err),
47
5
            Some(ErrorCode::UNAVAILABLE),
48
            "{message}"
49
        );
50
5
        assert_eq!(error_status(&err), 503, "{message}");
51
    }
52
1
}
53

            
54
#[test]
55
1
fn a_missing_url_stays_a_host_failure() {
56
1
    let err = cmd_failure("x", CmdError::from(DBError::MissingUrl));
57
1
    assert!(is_host_failure(&err));
58
1
    assert_eq!(condition_code(&err), None);
59
1
}
60

            
61
#[test]
62
1
fn a_missing_price_is_the_no_conversion_condition() {
63
1
    let (from, to) = (uuid::Uuid::new_v4(), uuid::Uuid::new_v4());
64
1
    let err = cmd_failure("convert-commodity", CmdError::NoPrice { from, to });
65
1
    assert!(!is_host_failure(&err), "{err}");
66
1
    assert_eq!(
67
1
        condition(&err),
68
1
        Some(&HostCondition {
69
1
            code: ErrorCode::NO_CONVERSION.to_string(),
70
1
            message: CmdError::NoPrice { from, to }.to_string(),
71
1
            detail: None,
72
1
        })
73
    );
74
1
}
75

            
76
#[test]
77
1
fn a_missing_entity_is_the_not_found_condition() {
78
1
    let err = cmd_failure("x", CmdError::NotFound("Commodity not found".into()));
79
1
    assert!(!is_host_failure(&err), "{err}");
80
1
    assert_eq!(
81
1
        condition(&err),
82
1
        Some(&HostCondition {
83
1
            code: ErrorCode::NOT_FOUND.to_string(),
84
1
            message: CmdError::NotFound("Commodity not found".into()).to_string(),
85
1
            detail: Some(EvalValue::String("x".to_string())),
86
1
        })
87
    );
88
1
}
89

            
90
#[test]
91
1
fn other_server_failures_stay_host_failures() {
92
1
    let err = cmd_failure("x", CmdError::Server(ServerError::Lock));
93
1
    assert!(is_host_failure(&err));
94
1
    assert_eq!(condition_code(&err), None);
95
1
}
96

            
97
#[test]
98
1
fn a_form_native_meeting_a_write_conflict_raises_busy() {
99
1
    let err = native_failure(Failure::Internal(cmd_failure(
100
1
        "submit-form",
101
1
        write_conflict(),
102
1
    )));
103
1
    assert_eq!(
104
1
        condition(&err).map(|c| c.code.as_str()),
105
1
        Some(ErrorCode::BUSY)
106
    );
107
1
}
108

            
109
#[test]
110
1
fn a_missing_price_names_both_commodities() {
111
1
    let missing = ReportError::MissingConversion {
112
1
        from_commodity: "JPY".to_owned(),
113
1
        to_commodity: "USD".to_owned(),
114
1
    };
115
1
    let err = cmd_failure("balance-report", CmdError::Finance(missing.into()));
116
1
    let message = err.to_string();
117
1
    assert!(
118
1
        message.contains("JPY") && message.contains("USD"),
119
        "{message}"
120
    );
121
1
    assert!(!is_host_failure(&err));
122
1
}
123

            
124
#[sqlx::test(migrator = "server::db::MIGRATOR")]
125
async fn a_lock_timeout_is_the_busy_condition_too(pool: sqlx::PgPool) -> anyhow::Result<()> {
126
    use server::command::account::{CreateAccount, SetAccountTag};
127
    use server::command::{CmdResult, FinanceEntity};
128
    use sqlx::Connection;
129

            
130
    let _guard = server::db::install_test_pool(pool.clone());
131
    let user = uuid::Uuid::new_v4();
132
    sqlx::query(
133
        "INSERT INTO users \
134
         (id, user_name, email, photo, verified, user_password, user_role, database_name, created_at) \
135
         VALUES ($1, 'Test', 'test@test.com', 'x', false, 'pw', 'user', 'db', NOW())",
136
    )
137
    .bind(user)
138
    .execute(&pool)
139
    .await?;
140
    let Some(CmdResult::Entity(FinanceEntity::Account(account))) = CreateAccount::new()
141
        .name("Bank".to_string())
142
        .user_id(user)
143
        .run()
144
        .await?
145
    else {
146
        anyhow::bail!("account");
147
    };
148
2
    let set = |value: &str| {
149
2
        SetAccountTag::new()
150
2
            .user_id(user)
151
2
            .account_id(account.id)
152
2
            .tag_name("type".to_string())
153
2
            .tag_value(value.to_string())
154
2
            .run()
155
2
    };
156
    set("asset").await?;
157

            
158
    let mut conn = pool.acquire().await?;
159
    let mut holder = conn.begin().await?;
160
    sqlx::query("SELECT id FROM tags WHERE tag_name = 'type' AND tag_value = 'asset' FOR UPDATE")
161
        .fetch_one(&mut *holder)
162
        .await?;
163
    let stalled = set("expense").await;
164
    holder.rollback().await?;
165

            
166
    let Err(cmd_err) = stalled else {
167
        anyhow::bail!("the set should have timed out");
168
    };
169
    let err = cmd_failure("set-account-tag", cmd_err);
170
    assert!(!is_host_failure(&err), "{err}");
171
    assert_eq!(condition_code(&err), Some(ErrorCode::BUSY));
172
    Ok(())
173
}
174

            
175
#[sqlx::test(migrator = "server::db::MIGRATOR")]
176
async fn a_missing_split_is_a_script_error_not_a_host_failure(
177
    pool: sqlx::PgPool,
178
) -> anyhow::Result<()> {
179
    use server::command::split::SetSplitTag;
180

            
181
    let _guard = server::db::install_test_pool(pool.clone());
182
    let user = uuid::Uuid::new_v4();
183
    sqlx::query(
184
        "INSERT INTO users \
185
         (id, user_name, email, photo, verified, user_password, user_role, database_name, created_at) \
186
         VALUES ($1, 'Test', 'test@test.com', 'x', false, 'pw', 'user', 'db', NOW())",
187
    )
188
    .bind(user)
189
    .execute(&pool)
190
    .await?;
191
    let Err(cmd_err) = SetSplitTag::new()
192
        .user_id(user)
193
        .split_id(uuid::Uuid::new_v4())
194
        .tag_name("memo".to_string())
195
        .tag_value("m".to_string())
196
        .run()
197
        .await
198
    else {
199
        anyhow::bail!("a missing split must not be tagged");
200
    };
201
    assert!(matches!(cmd_err, CmdError::NotFound(_)), "{cmd_err:?}");
202
    let err = cmd_failure("set-split-tag", cmd_err);
203
    assert!(!is_host_failure(&err), "{err}");
204
    Ok(())
205
}
206

            
207
#[test]
208
1
fn a_command_argument_failure_is_the_args_condition() {
209
1
    let err = cmd_failure("set-account-tag", CmdError::Args("bad".into()));
210
1
    assert!(!is_host_failure(&err), "{err}");
211
1
    assert_eq!(
212
1
        condition(&err),
213
1
        Some(&HostCondition {
214
1
            code: ErrorCode::ARGS.to_string(),
215
1
            message: "bad".to_string(),
216
1
            detail: None,
217
1
        })
218
    );
219
1
}
220

            
221
#[test]
222
1
fn a_refusal_an_unkeepable_edit_and_a_gone_parent_are_the_args_condition() {
223
1
    let parent = uuid::Uuid::new_v4();
224
1
    let causes = [
225
1
        (CmdError::Refused("no".into()), "no".to_string()),
226
1
        (CmdError::Unkeepable("odd".into()), "odd".to_string()),
227
1
        (
228
1
            CmdError::ParentGone(parent),
229
1
            CmdError::ParentGone(parent).to_string(),
230
1
        ),
231
1
    ];
232
1
    for (cause, message) in causes {
233
3
        let err = cmd_failure("x", cause);
234
3
        assert!(!is_host_failure(&err), "{err}");
235
3
        assert_eq!(condition_code(&err), Some(ErrorCode::ARGS));
236
3
        assert_eq!(condition_text(&err), Some(message));
237
    }
238
1
}
239

            
240
#[test]
241
1
fn a_disabled_account_is_not_a_host_failure() {
242
1
    let err = cmd_failure("ssh-key-add", CmdError::Disabled);
243
1
    assert!(!is_host_failure(&err), "{err}");
244
1
    assert_eq!(err.to_string(), "ssh-key-add: This account is disabled");
245
1
    assert_eq!(crate::status::error_status(&err), 403);
246
1
}
247

            
248
#[test]
249
1
fn a_database_failure_is_a_host_failure() {
250
1
    let err = cmd_failure("x", CmdError::DB(sqlx::Error::Protocol("x".into())));
251
1
    assert!(is_host_failure(&err), "{err}");
252
1
}
253

            
254
#[test]
255
1
fn a_command_failure_reads_once_on_the_wire() {
256
    use scripting::runtime::{EngineError, classify_runtime_error};
257

            
258
1
    let finance = CmdError::Finance(finance::error::FinanceError::Internal("x".into()));
259
1
    let expected = format!("ssh-key-add: {finance}");
260
1
    let causes = [
261
1
        (
262
1
            CmdError::Disabled,
263
1
            "ssh-key-add: This account is disabled".to_string(),
264
1
        ),
265
1
        (finance, expected),
266
1
    ];
267
1
    for (cause, text) in causes {
268
2
        let err = cmd_failure("ssh-key-add", cause);
269
2
        assert!(
270
2
            matches!(classify_runtime_error(&err), EngineError::Trap(ref message) if *message == text),
271
            "{err}"
272
        );
273
    }
274
1
}
275

            
276
#[test]
277
1
fn a_plain_native_and_the_form_path_classify_every_command_failure_alike() {
278
    use crate::forms::tests_status::every_command_failure;
279

            
280
1
    for (plain, form) in every_command_failure()
281
1
        .into_iter()
282
1
        .zip(every_command_failure())
283
    {
284
21
        let label = plain.to_string();
285
21
        let plain = cmd_failure("ctx", plain);
286
21
        let form = native_failure(Failure::from_command("ctx", form));
287
21
        assert_eq!(condition_code(&plain), condition_code(&form), "{label}");
288
21
        assert_eq!(condition_text(&plain), condition_text(&form), "{label}");
289
21
        assert_eq!(is_host_failure(&plain), is_host_failure(&form), "{label}");
290
    }
291
1
}
292

            
293
#[test]
294
1
fn a_domain_rule_violation_is_args_for_a_plain_native() {
295
    use finance::error::TransactionError;
296

            
297
1
    let rule = [
298
1
        CmdError::Finance(TransactionError::ZeroSum.into()),
299
1
        CmdError::Server(ServerError::Creation),
300
1
        CmdError::Server(ServerError::TagClash {
301
1
            name: "n".into(),
302
1
            value: "v".into(),
303
1
        }),
304
1
        CmdError::Server(ServerError::Finance(TransactionError::ZeroSum.into())),
305
1
    ];
306
1
    for err in rule {
307
4
        let label = err.to_string();
308
4
        let err = cmd_failure("create-transaction", err);
309
4
        assert_eq!(condition_code(&err), Some(ErrorCode::ARGS), "{label}");
310
4
        assert!(!is_host_failure(&err), "{label}");
311
    }
312
1
}
313

            
314
#[test]
315
1
fn a_report_missing_price_is_no_conversion_like_a_missing_price_row() {
316
    let missing = || ReportError::MissingConversion {
317
2
        from_commodity: "JPY".to_owned(),
318
2
        to_commodity: "USD".to_owned(),
319
2
    };
320
1
    let err = cmd_failure("balance-report", CmdError::Finance(missing().into()));
321
1
    assert_eq!(condition_code(&err), Some(ErrorCode::NO_CONVERSION));
322
1
    assert_eq!(condition_text(&err), Some(missing().to_string()));
323
1
}
324

            
325
#[test]
326
1
fn an_unclassified_connect_fault_is_left_to_the_edge_that_answers() {
327
1
    let captured = server::log_capture::Captured::default();
328
1
    let _logs = tracing::subscriber::set_default(captured.subscriber());
329

            
330
1
    let err = cmd_failure("list-accounts", DBError::MissingUrl.into());
331

            
332
1
    assert!(is_host_failure(&err), "{err}");
333
1
    assert_eq!(captured.error_lines(), 0);
334
1
}