Lines
99.53 %
Functions
100 %
Branches
use axum::{
Router,
body::Body,
http::{Request, StatusCode},
routing::{get, post},
};
use serde_json::Value;
use sqlx::types::Uuid;
use tower::ServiceExt;
use web::pages::{account, commodity, forms, tag};
use crate::common::tenant::provision_tenant;
use crate::common::{create_mock_jwt_auth, create_mock_user, create_test_app_state};
async fn app(user: web::model::User) -> Router {
let app_state = create_test_app_state().await;
let jwt_auth = create_mock_jwt_auth(user);
Router::new()
.route("/tag/edit/{id}", get(tag::edit::tag_edit_page))
.route("/tag/edit/submit", post(tag::edit::tag_edit_submit))
.route(
"/forms/suggestions/{source}",
get(forms::suggestions::form_suggestions),
)
.route("/commodity/list", get(commodity::list::commodity_table))
"/commodity/convert",
get(commodity::convert::commodity_convert),
"/commodity/create",
post(commodity::create::commodity_create_submit),
.route("/account/info", get(account::list::account_info))
.route("/account/list", get(account::list::account_table))
"/account/{account_id}/script/{script_id}",
post(account::script::run_account_script),
.layer(axum::middleware::from_fn(
move |mut req: Request<Body>, next: axum::middleware::Next| {
let jwt_auth = jwt_auth.clone();
async move {
req.extensions_mut().insert(jwt_auth);
next.run(req).await
}
},
))
.with_state(app_state)
async fn send(
app: &Router,
method: &str,
uri: &str,
form: Option<(&str, String)>,
) -> (StatusCode, String) {
let mut builder = Request::builder().method(method).uri(uri);
let body = match form {
Some((content_type, body)) => {
builder = builder.header("content-type", content_type);
Body::from(body)
None => Body::empty(),
let response = app
.clone()
.oneshot(builder.body(body).expect("request"))
.await
.expect("response");
let status = response.status();
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.expect("body");
(status, String::from_utf8_lossy(&bytes).into_owned())
async fn tag_edit(
user: &web::model::User,
id: Uuid,
value: &str,
) -> Option<(&'static str, String)> {
let loaded = rpc::forms::load(user.id, &::forms::TAG_EDIT, &id.to_string())
.expect("load");
let revision = loaded.text("revision").unwrap_or_default();
let id = id.to_string();
let pairs = [
("id", id.as_str()),
("revision", revision),
("name", "trip"),
("value", value),
];
let body = serde_urlencoded::to_string(pairs).expect("urlencoded");
Some(("application/x-www-form-urlencoded", body))
fn error_message(body: &str) -> String {
let value: Value = serde_json::from_str(body).expect("error json");
assert_eq!(value["status"], "error");
value["message"].as_str().expect("message").to_string()
#[supp_macro::shared_runtime_test]
async fn an_unreachable_tenant_is_a_503() {
let app = app(create_mock_user()).await;
let uuid = Uuid::new_v4();
let calls = [
send(&app, "GET", "/commodity/list", None).await,
send(&app, "GET", "/commodity/convert", None).await,
send(&app, "GET", "/account/list", None).await,
send(&app, "GET", &format!("/account/info?account={uuid}"), None).await,
send(
&app,
"GET",
"/forms/suggestions/transaction-tag-names",
None,
.await,
for (status, body) in calls {
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE, "{body}");
assert_eq!(
error_message(&body),
"The service is temporarily unavailable"
);
async fn missing_rows_are_404_and_bad_input_is_a_clear_4xx() {
let user = create_mock_user();
provision_tenant(user.id).await;
let app = app(user.clone()).await;
let missing = Uuid::new_v4();
let responses = [
send(&app, "GET", &format!("/tag/edit/{missing}"), None).await,
&format!("/account/info?account={missing}"),
"POST",
&format!("/account/{missing}/script/{missing}"),
let expected = [
(StatusCode::NOT_FOUND, "Tag not found"),
(StatusCode::NOT_FOUND, "Account not found"),
(StatusCode::NOT_FOUND, "Script not found"),
for ((status, body), (want_status, want_message)) in responses.iter().zip(expected) {
assert_eq!(*status, want_status, "{body}");
let message = error_message(body);
assert!(message.contains(want_message), "{message}");
assert!(!message.is_empty());
async fn conversion_without_a_price_path_is_an_unprocessable_request() {
let create = |symbol: &'static str, name: &'static str| {
let app = app.clone();
let (_, reply) = send(
Some((
"application/x-www-form-urlencoded",
format!("symbol={symbol}&name={name}"),
)),
.await;
reply.rsplit(' ').next().unwrap_or_default().to_string()
let first = create("AAA", "Alpha").await;
let second = create("BBB", "Beta").await;
let convert = send(
&format!("/commodity/convert?amount=5&from={first}&to={second}"),
assert_eq!(convert.0, StatusCode::UNPROCESSABLE_ENTITY, "{}", convert.1);
assert!(
convert.1.contains("no exchange rate between AAA and BBB"),
"{}",
convert.1
async fn renaming_a_tag_onto_another_tags_key_is_a_clear_clash() {
let server_user = server::user::User { id: user.id };
let taken = server_user
.create_tag("trip".to_string(), "rome".to_string(), None)
let other = server_user
.create_tag("trip".to_string(), "oslo".to_string(), None)
let (status, body) = match (taken, other) {
(Ok(_), Ok(other)) => {
"/tag/edit/submit",
tag_edit(&user, other, "rome").await,
created => (StatusCode::INTERNAL_SERVER_ERROR, format!("{created:?}")),
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{body}");
assert_eq!(error_message(&body), "Another tag trip=rome already exists");
async fn a_tag_locked_by_a_stalled_writer_is_a_409_busy() {
use sqlx::Connection;
let tag = server_user
.expect("tag");
let mut holder_conn = crate::common::tenant::tenant_connection(user.id).await;
let mut holder = holder_conn.begin().await.expect("holder");
sqlx::query("SELECT id FROM tags WHERE id = $1 FOR UPDATE")
.bind(tag)
.fetch_one(&mut *holder)
.expect("hold the row");
let (status, body) = send(
tag_edit(&user, tag, "oslo").await,
holder.rollback().await.expect("release");
drop(holder_conn);
assert_eq!(status, StatusCode::CONFLICT, "{body}");
"The data changed while saving; try again"