Lines
89.29 %
Functions
97.37 %
Branches
100 %
//! The lossless fixture through the TUI edit form: a no-op and a note-only
//! edit submit the loaded payload byte for byte, and the store is unchanged.
use cli_core::transaction::submit_call;
use forms::{FormValues, TRANSACTION_EDIT, escape_str, write_payload};
use nomiscript::Value;
use rpc::{ResponsePayload, ScriptCtx, Session};
use server::lossless::{
EDITED_NOTE, NOTE, first_row_tag, kept_only, seed, snapshot, split_tag_facts, tag_facts,
without_note,
};
use sqlx::PgPool;
use crate::app::App;
use crate::modal::Modal;
use crate::route::{FormOptionsSource, Route, RouteCtx};
use crate::view::ViewId;
use crate::widgets::splits::{COL_FROM, COL_FROM_COMM, COL_TO, COL_TO_COMM, COL_VALUE};
use crate::widgets::{FocusedSubWidget, SplitsWidget, Widget};
async fn reply(session: &mut Session, form: &str) -> String {
session.handle_form(&format!("(:id 1 :form {form})")).await
}
fn value(wire: &str) -> anyhow::Result<String> {
match rpc::parse_response(wire).map(|response| response.payload) {
Ok(ResponsePayload::Value(Value::String(text))) => Ok(text),
other => anyhow::bail!("expected a string value, got {other:?}"),
/// The edit form opened from a real `load-form` reply with real options.
async fn open(session: &mut Session, id: &str) -> anyhow::Result<(App, String)> {
let wire = reply(
session,
&format!("(load-form \"transaction-edit\" \"{id}\")"),
)
.await;
let mut app = crate::test_support::app();
app.form_options_seq.advance();
app.deliver_transaction_edit_reply(
Some(app.window_of(crate::view::ViewId::Transactions)),
&wire,
);
for (target, source, form) in [
(
ViewId::Accounts,
FormOptionsSource::FormAccounts,
r#"(form-options "accounts")"#,
),
ViewId::Commodities,
FormOptionsSource::FormCommodities,
r#"(form-options "commodities")"#,
] {
let ctx = RouteCtx::FormOptions { seq: 1, source };
app.deliver_reply(
Route {
target: Some(app.window_of(target)),
ctx,
},
&reply(session, form).await,
Ok((app, value(&wire)?))
/// The values the open form submits, after `change` edits it.
fn submitted(
mut app: App,
change: impl FnOnce(&mut crate::form::Form),
) -> anyhow::Result<FormValues> {
let Some(Modal::Form(mut form)) = app.overlays.pop() else {
anyhow::bail!("the edit form is not open: {}", app.status);
change(&mut form);
Ok(form.values())
fn widget_mut<'a>(form: &'a mut crate::form::Form, key: &str) -> Option<&'a mut Widget> {
form.fields
.iter_mut()
.find(|field| field.key == Some(key))
.map(|field| &mut field.widget)
async fn submit(session: &mut Session, values: &FormValues) -> anyhow::Result<()> {
let wire = reply(session, &submit_call(&TRANSACTION_EDIT, values)).await;
value(&wire).map(|_| ())
fn without_revision(text: &str) -> String {
let (head, rest) = text.split_once(" :revision \"").unwrap_or((text, "\""));
let tail = rest.split_once('"').map_or("", |(_, tail)| tail);
format!("{head}{tail}")
/// The form leaves an empty cell out of its payload; the server reads it the same.
fn without_empty_to_commodity(text: &str) -> String {
text.replace(" :to-commodity \"\"", "")
#[sqlx::test(migrator = "server::db::MIGRATOR")]
async fn noop_and_note_only_edits_are_lossless(pool: PgPool) -> anyhow::Result<()> {
let _guard = server::db::install_test_pool(pool.clone());
let fixture = seed(&pool).await?;
let id = fixture.transaction.to_string();
let mut session = Session::new(ScriptCtx::new(fixture.user))?;
let stored = snapshot(&pool, fixture.transaction).await?;
let (app, loaded) = open(&mut session, &id).await?;
assert!(loaded.contains(":description \"client forms\""), "{loaded}");
assert!(
loaded.contains(":description \"split memo\\nsecond line\")"),
"{loaded}"
let values = submitted(app, |_| ())?;
assert_eq!(
write_payload(&TRANSACTION_EDIT, &values),
without_empty_to_commodity(&loaded)
submit(&mut session, &values).await?;
assert_eq!(snapshot(&pool, fixture.transaction).await?, stored);
let (app, reloaded) = open(&mut session, &id).await?;
assert_eq!(without_revision(&reloaded), without_revision(&loaded));
let values = submitted(app, |form| {
if let Some(note) = widget_mut(form, "note") {
note.set_text(EDITED_NOTE);
})?;
let expected = reloaded.replace(&escape_str(NOTE), &escape_str(EDITED_NOTE));
without_empty_to_commodity(&expected)
let (_, after) = open(&mut session, &id).await?;
assert_eq!(without_revision(&after), without_revision(&expected));
let now = snapshot(&pool, fixture.transaction).await?;
assert_eq!(without_note(&now), without_note(&stored));
now.contains(&format!("tag note {EDITED_NOTE} -")),
"{now:?}"
Ok(())
/// Pick the option matching `text` in the select at `col` of the focused row.
fn pick(sw: &mut SplitsWidget, col: usize, text: &str) {
sw.col_focus = col;
if let Some(FocusedSubWidget::Select(select)) = sw.focused_subwidget_mut() {
text.chars().for_each(|c| select.filter_push(c));
select.confirm();
/// Drop row `r2` and append two rows from Cash to Food of 1 and 2 USD.
fn drop_r2_and_add_two(sw: &mut SplitsWidget) {
if let Some(index) = sw.rows().iter().position(|row| row.text("key") == "r2") {
sw.row_focus = index;
sw.remove_row();
for value in ["1", "2"] {
sw.row_focus = sw.rows().len() - 1;
sw.add_row();
pick(sw, COL_FROM, "Cash");
pick(sw, COL_TO, "Food");
pick(sw, COL_FROM_COMM, "USD");
pick(sw, COL_TO_COMM, "USD");
sw.col_focus = COL_VALUE;
if let Some(FocusedSubWidget::Amount(amount)) = sw.focused_subwidget_mut() {
value.chars().for_each(|c| amount.insert_char(c));
async fn two_new_keyless_rows_and_a_removed_row_keep_the_other_tags(
pool: PgPool,
) -> anyhow::Result<()> {
let name = first_row_tag(&loaded).ok_or_else(|| anyhow::anyhow!("no r1 tag"))?;
let kept = split_tag_facts(&snapshot(&pool, fixture.transaction).await?, name);
if let Some(Widget::Splits(sw)) = widget_mut(form, "splits") {
drop_r2_and_add_two(sw);
assert_eq!(values.rows("splits").map(<[_]>::len), Some(3));
assert!(kept_only(&now, &kept), "{kept:?}: {now:?}");
fn type_into_tags(form: &mut crate::form::Form, text: &str) {
if let Some(Widget::Rows(rw)) = widget_mut(form, "tags")
&& let Some(editor) = rw.focused_editor_mut()
{
text.chars().for_each(|c| editor.insert_char(c));
async fn a_tag_is_added_changed_and_cleared_through_the_session(
let before = tag_facts(&snapshot(&pool, fixture.transaction).await?);
let (app, _) = open(&mut session, &id).await?;
if let Some(Widget::Rows(rw)) = widget_mut(form, "tags") {
rw.add_row();
type_into_tags(form, "shop");
rw.advance_cell();
type_into_tags(form, "x");
let added = tag_facts(&snapshot(&pool, fixture.transaction).await?);
assert_eq!(added.len(), before.len() + 1, "{added:?}");
assert!(added.contains(&"tag shop x -".to_string()), "{added:?}");
let shop = (0..rw.values().map_or(0, |rows| rows.len())).find(|&row| {
rw.focus_cell(row, "name");
rw.focused_editor_mut()
.is_some_and(|e| e.buffer() == "shop")
});
if let Some(row) = shop {
rw.focus_cell(row, "description");
if let Some(editor) = rw.focused_editor_mut() {
"bought".chars().for_each(|c| editor.insert_char(c));
let changed = tag_facts(&snapshot(&pool, fixture.transaction).await?);
changed.contains(&"tag shop x bought".to_string()),
"{changed:?}"
let count = rw.values().map_or(0, |rows| rows.len());
(0..count).for_each(|_| rw.remove_row());
assert!(tag_facts(&snapshot(&pool, fixture.transaction).await?).is_empty());