1
use axum::{
2
    Router,
3
    body::Body,
4
    http::{Request, StatusCode},
5
    routing::{get, post},
6
};
7
use serde_json::Value;
8
use sqlx::types::Uuid;
9
use tower::ServiceExt;
10
use web::pages::{account, commodity, forms, tag};
11

            
12
use crate::common::tenant::provision_tenant;
13
use crate::common::{create_mock_jwt_auth, create_mock_user, create_test_app_state};
14

            
15
5
async fn app(user: web::model::User) -> Router {
16
5
    let app_state = create_test_app_state().await;
17
5
    let jwt_auth = create_mock_jwt_auth(user);
18
5
    Router::new()
19
5
        .route("/tag/edit/{id}", get(tag::edit::tag_edit_page))
20
5
        .route("/tag/edit/submit", post(tag::edit::tag_edit_submit))
21
5
        .route(
22
5
            "/forms/suggestions/{source}",
23
5
            get(forms::suggestions::form_suggestions),
24
5
        )
25
5
        .route("/commodity/list", get(commodity::list::commodity_table))
26
5
        .route(
27
5
            "/commodity/convert",
28
5
            get(commodity::convert::commodity_convert),
29
5
        )
30
5
        .route(
31
5
            "/commodity/create",
32
5
            post(commodity::create::commodity_create_submit),
33
5
        )
34
5
        .route("/account/info", get(account::list::account_info))
35
5
        .route("/account/list", get(account::list::account_table))
36
5
        .route(
37
5
            "/account/{account_id}/script/{script_id}",
38
5
            post(account::script::run_account_script),
39
5
        )
40
5
        .layer(axum::middleware::from_fn(
41
13
            move |mut req: Request<Body>, next: axum::middleware::Next| {
42
13
                let jwt_auth = jwt_auth.clone();
43
13
                async move {
44
13
                    req.extensions_mut().insert(jwt_auth);
45
13
                    next.run(req).await
46
13
                }
47
13
            },
48
        ))
49
5
        .with_state(app_state)
50
5
}
51

            
52
13
async fn send(
53
13
    app: &Router,
54
13
    method: &str,
55
13
    uri: &str,
56
13
    form: Option<(&str, String)>,
57
13
) -> (StatusCode, String) {
58
13
    let mut builder = Request::builder().method(method).uri(uri);
59
13
    let body = match form {
60
        Some((content_type, body)) => {
61
4
            builder = builder.header("content-type", content_type);
62
4
            Body::from(body)
63
        }
64
9
        None => Body::empty(),
65
    };
66
13
    let response = app
67
13
        .clone()
68
13
        .oneshot(builder.body(body).expect("request"))
69
13
        .await
70
13
        .expect("response");
71
13
    let status = response.status();
72
13
    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
73
13
        .await
74
13
        .expect("body");
75
13
    (status, String::from_utf8_lossy(&bytes).into_owned())
76
13
}
77

            
78
2
async fn tag_edit(
79
2
    user: &web::model::User,
80
2
    id: Uuid,
81
2
    value: &str,
82
2
) -> Option<(&'static str, String)> {
83
2
    let loaded = rpc::forms::load(user.id, &::forms::TAG_EDIT, &id.to_string())
84
2
        .await
85
2
        .expect("load");
86
2
    let revision = loaded.text("revision").unwrap_or_default();
87
2
    let id = id.to_string();
88
2
    let pairs = [
89
2
        ("id", id.as_str()),
90
2
        ("revision", revision),
91
2
        ("name", "trip"),
92
2
        ("value", value),
93
2
    ];
94
2
    let body = serde_urlencoded::to_string(pairs).expect("urlencoded");
95
2
    Some(("application/x-www-form-urlencoded", body))
96
2
}
97

            
98
10
fn error_message(body: &str) -> String {
99
10
    let value: Value = serde_json::from_str(body).expect("error json");
100
10
    assert_eq!(value["status"], "error");
101
10
    value["message"].as_str().expect("message").to_string()
102
10
}
103

            
104
#[supp_macro::shared_runtime_test]
105
1
async fn an_unreachable_tenant_is_a_503() {
106
1
    let app = app(create_mock_user()).await;
107
1
    let uuid = Uuid::new_v4();
108
    let calls = [
109
1
        send(&app, "GET", "/commodity/list", None).await,
110
1
        send(&app, "GET", "/commodity/convert", None).await,
111
1
        send(&app, "GET", "/account/list", None).await,
112
1
        send(&app, "GET", &format!("/account/info?account={uuid}"), None).await,
113
1
        send(
114
1
            &app,
115
1
            "GET",
116
1
            "/forms/suggestions/transaction-tag-names",
117
1
            None,
118
1
        )
119
1
        .await,
120
    ];
121
1
    for (status, body) in calls {
122
5
        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE, "{body}");
123
5
        assert_eq!(
124
5
            error_message(&body),
125
5
            "The service is temporarily unavailable"
126
        );
127
    }
128
}
129

            
130
#[supp_macro::shared_runtime_test]
131
1
async fn missing_rows_are_404_and_bad_input_is_a_clear_4xx() {
132
1
    let user = create_mock_user();
133
1
    provision_tenant(user.id).await;
134
1
    let app = app(user.clone()).await;
135
1
    let missing = Uuid::new_v4();
136
    let responses = [
137
1
        send(&app, "GET", &format!("/tag/edit/{missing}"), None).await,
138
1
        send(
139
1
            &app,
140
1
            "GET",
141
1
            &format!("/account/info?account={missing}"),
142
1
            None,
143
1
        )
144
1
        .await,
145
1
        send(
146
1
            &app,
147
1
            "POST",
148
1
            &format!("/account/{missing}/script/{missing}"),
149
1
            None,
150
1
        )
151
1
        .await,
152
    ];
153

            
154
1
    let expected = [
155
1
        (StatusCode::NOT_FOUND, "Tag not found"),
156
1
        (StatusCode::NOT_FOUND, "Account not found"),
157
1
        (StatusCode::NOT_FOUND, "Script not found"),
158
1
    ];
159
1
    for ((status, body), (want_status, want_message)) in responses.iter().zip(expected) {
160
3
        assert_eq!(*status, want_status, "{body}");
161
3
        let message = error_message(body);
162
3
        assert!(message.contains(want_message), "{message}");
163
3
        assert!(!message.is_empty());
164
    }
165
}
166

            
167
#[supp_macro::shared_runtime_test]
168
1
async fn conversion_without_a_price_path_is_an_unprocessable_request() {
169
1
    let user = create_mock_user();
170
1
    provision_tenant(user.id).await;
171
1
    let app = app(user.clone()).await;
172
2
    let create = |symbol: &'static str, name: &'static str| {
173
2
        let app = app.clone();
174
2
        async move {
175
2
            let (_, reply) = send(
176
2
                &app,
177
2
                "POST",
178
2
                "/commodity/create",
179
2
                Some((
180
2
                    "application/x-www-form-urlencoded",
181
2
                    format!("symbol={symbol}&name={name}"),
182
2
                )),
183
2
            )
184
2
            .await;
185
2
            reply.rsplit(' ').next().unwrap_or_default().to_string()
186
2
        }
187
2
    };
188
1
    let first = create("AAA", "Alpha").await;
189
1
    let second = create("BBB", "Beta").await;
190
1
    let convert = send(
191
1
        &app,
192
1
        "GET",
193
1
        &format!("/commodity/convert?amount=5&from={first}&to={second}"),
194
1
        None,
195
1
    )
196
1
    .await;
197

            
198
1
    assert_eq!(convert.0, StatusCode::UNPROCESSABLE_ENTITY, "{}", convert.1);
199
1
    assert!(
200
1
        convert.1.contains("no exchange rate between AAA and BBB"),
201
        "{}",
202
        convert.1
203
    );
204
}
205

            
206
#[supp_macro::shared_runtime_test]
207
1
async fn renaming_a_tag_onto_another_tags_key_is_a_clear_clash() {
208
1
    let user = create_mock_user();
209
1
    provision_tenant(user.id).await;
210
1
    let app = app(user.clone()).await;
211
1
    let server_user = server::user::User { id: user.id };
212
1
    let taken = server_user
213
1
        .create_tag("trip".to_string(), "rome".to_string(), None)
214
1
        .await;
215
1
    let other = server_user
216
1
        .create_tag("trip".to_string(), "oslo".to_string(), None)
217
1
        .await;
218
1
    let (status, body) = match (taken, other) {
219
        (Ok(_), Ok(other)) => {
220
1
            send(
221
1
                &app,
222
1
                "POST",
223
1
                "/tag/edit/submit",
224
1
                tag_edit(&user, other, "rome").await,
225
            )
226
1
            .await
227
        }
228
        created => (StatusCode::INTERNAL_SERVER_ERROR, format!("{created:?}")),
229
    };
230
1
    assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{body}");
231
1
    assert_eq!(error_message(&body), "Another tag trip=rome already exists");
232
}
233

            
234
#[supp_macro::shared_runtime_test]
235
1
async fn a_tag_locked_by_a_stalled_writer_is_a_409_busy() {
236
    use sqlx::Connection;
237

            
238
1
    let user = create_mock_user();
239
1
    provision_tenant(user.id).await;
240
1
    let app = app(user.clone()).await;
241
1
    let server_user = server::user::User { id: user.id };
242
1
    let tag = server_user
243
1
        .create_tag("trip".to_string(), "rome".to_string(), None)
244
1
        .await
245
1
        .expect("tag");
246
1
    let mut holder_conn = crate::common::tenant::tenant_connection(user.id).await;
247
1
    let mut holder = holder_conn.begin().await.expect("holder");
248
1
    sqlx::query("SELECT id FROM tags WHERE id = $1 FOR UPDATE")
249
1
        .bind(tag)
250
1
        .fetch_one(&mut *holder)
251
1
        .await
252
1
        .expect("hold the row");
253

            
254
1
    let (status, body) = send(
255
1
        &app,
256
1
        "POST",
257
1
        "/tag/edit/submit",
258
1
        tag_edit(&user, tag, "oslo").await,
259
    )
260
1
    .await;
261
1
    holder.rollback().await.expect("release");
262
1
    drop(holder_conn);
263

            
264
1
    assert_eq!(status, StatusCode::CONFLICT, "{body}");
265
1
    assert_eq!(
266
1
        error_message(&body),
267
1
        "The data changed while saving; try again"
268
    );
269
}