Lines
98.04 %
Functions
100 %
Branches
use forms::{FormValues, REPORT_ACTIVITY, REPORT_BALANCE, REPORT_CATEGORY, Row};
use rpc::{ScriptCtx, Session};
use server::command::account::{CreateAccount, SetAccountTag};
use server::command::commodity::CreateCommodity;
use server::command::{CmdResult, FinanceEntity};
use sqlx::PgPool;
use uuid::Uuid;
use rpc::chart::{ChartFormat, ChartLook};
use rpc::natives::report::run_report_csv;
use super::{ChartRequest, chart, chart_png, csv, csv_call, terminal_chart};
use crate::CommandError;
use crate::eval::Rendered;
use crate::forms::map_references;
use crate::transaction::{create, eval_text};
const SIZE: (u32, u32) = (720, 360);
const FROM: &str = "2026-10-01";
const TO: &str = "2026-10-31";
const FROM_WIRE: &str = "2026-10-01T00:00:00Z";
const TO_WIRE: &str = "2026-10-31T23:59:59.999999Z";
struct Seeded {
session: Session,
food: Uuid,
usd: Uuid,
}
async fn seeded_session(pool: &PgPool) -> anyhow::Result<Session> {
Ok(seeded(pool).await?.session)
async fn seeded(pool: &PgPool) -> anyhow::Result<Seeded> {
let user = Uuid::new_v4();
sqlx::query(
"INSERT INTO users \
(id, user_name, email, photo, verified, user_password, user_role, database_name, created_at) \
VALUES ($1, $2, $3, 'x', false, 'pw', 'user', 'db', NOW())",
)
.bind(user)
.bind(format!("u{user}"))
.bind(format!("{user}@test.com"))
.execute(pool)
.await?;
let Some(CmdResult::String(usd)) = CreateCommodity::new()
.symbol("USD".to_string())
.name("USD".to_string())
.user_id(user)
.run()
.await?
else {
anyhow::bail!("no commodity created");
};
let mut food = Uuid::nil();
for name in ["Cash", "Food"] {
let Some(CmdResult::Entity(FinanceEntity::Account(account))) = CreateAccount::new()
.name(name.to_string())
anyhow::bail!("no account created");
if name == "Food" {
food = account.id;
let mut session = Session::new(ScriptCtx::new(user))?;
let mut spend = FormValues::default();
spend.set("date", "2026-10-15");
spend.set("note", "lunch");
spend.push_row(
"splits",
row(&[
("from", "Cash"),
("to", "Food"),
("from-commodity", "USD"),
("value", "5"),
]),
);
create(&mut session, &spend).await?;
Ok(Seeded {
session,
food,
usd: usd.parse()?,
})
fn row(pairs: &[(&str, &str)]) -> Row {
pairs
.iter()
.map(|(k, v)| ((*k).to_string(), (*v).to_string()))
.collect()
fn values(pairs: &[(&str, &str)]) -> FormValues {
let mut values = FormValues::default();
pairs.iter().for_each(|(k, v)| values.set(k, v));
values
async fn shown(
session: &mut Session,
form: &forms::Form,
given: &FormValues,
) -> Result<Vec<String>, CommandError> {
match terminal_chart(session, form, given, "bar", false, SIZE).await? {
Rendered::Lines(lines) => Ok(lines),
_ => Err(CommandError::Command("expected rendered lines".to_string())),
async fn native(session: &mut Session, form: &str, payload: &str) -> anyhow::Result<Vec<String>> {
let call = format!(
"(report-chart {} {} :format \"text\")",
forms::escape_str(form),
forms::escape_str(payload)
Ok(eval_text(session, &call)
.lines()
.map(str::to_string)
.collect())
fn range() -> String {
format!(r#"(:from "{FROM_WIRE}" :to "{TO_WIRE}")"#)
#[sqlx::test(migrator = "server::db::MIGRATOR")]
async fn balance_matches_the_native(pool: PgPool) -> anyhow::Result<()> {
let _guard = server::db::install_test_pool(pool.clone());
let mut session = seeded_session(&pool).await?;
let expected = native(&mut session, "report-balance", "()").await?;
assert!(expected.iter().any(|l| l.contains("Cash")), "{expected:?}");
for given in [
values(&[]),
values(&[("target", "USD")]),
values(&[("as-of", TO)]),
] {
assert_eq!(
shown(&mut session, &REPORT_BALANCE, &given).await?,
expected
Ok(())
async fn balance_filter_narrows_the_chart(pool: PgPool) -> anyhow::Result<()> {
let all = shown(&mut session, &REPORT_BALANCE, &values(&[])).await?;
let none = values(&[("filter", "(amount> 100)")]);
let filtered = shown(&mut session, &REPORT_BALANCE, &none).await?;
assert_ne!(filtered, all);
async fn activity_matches_the_native(pool: PgPool) -> anyhow::Result<()> {
let expected = native(&mut session, "report-activity", &range()).await?;
let dates = values(&[("from", FROM), ("to", TO)]);
shown(&mut session, &REPORT_ACTIVITY, &dates).await?,
let instants = values(&[("from", FROM_WIRE), ("to", TO_WIRE)]);
shown(&mut session, &REPORT_ACTIVITY, &instants).await?,
let usd = values(&[
("from", FROM),
("to", TO),
("target", "USD"),
("grouping", "none"),
]);
assert_eq!(shown(&mut session, &REPORT_ACTIVITY, &usd).await?, expected);
async fn activity_groups_and_grouping_shape_the_chart(pool: PgPool) -> anyhow::Result<()> {
let mut given = values(&[("from", FROM), ("to", TO), ("grouping", "month")]);
given.push_row(
"groups",
("name", "Spend"),
("filter", "(amount> 0)"),
("flip", "yes"),
let drawn = shown(&mut session, &REPORT_ACTIVITY, &given).await?;
assert!(drawn.iter().any(|l| l.contains("Spend")), "{drawn:?}");
async fn breakdown_matches_the_native(pool: PgPool) -> anyhow::Result<()> {
let expected = native(&mut session, "report-category", &range()).await?;
let given = values(&[("from", FROM), ("to", TO)]);
shown(&mut session, &REPORT_CATEGORY, &given).await?,
let sorted = values(&[
("sort", "name_asc"),
("include-uncategorized", "yes"),
shown(&mut session, &REPORT_CATEGORY, &sorted).await?,
async fn a_bad_filter_is_a_field_error(pool: PgPool) -> anyhow::Result<()> {
let given = values(&[("from", FROM), ("to", TO), ("filter", "(bogus)")]);
match shown(&mut session, &REPORT_ACTIVITY, &given).await {
Err(CommandError::FormInvalid(found)) => {
assert_eq!(found.len(), 1);
assert!(found[0].starts_with("filter:"), "{found:?}");
Err(other) => anyhow::bail!("expected FormInvalid, got {other:?}"),
Ok(_) => anyhow::bail!("expected FormInvalid"),
async fn an_unknown_target_is_an_argument_error(pool: PgPool) -> anyhow::Result<()> {
let outcome = shown(&mut session, &REPORT_BALANCE, &values(&[("target", "XXX")])).await;
assert!(matches!(outcome, Err(CommandError::Argument(_))));
async fn png_is_decoded_to_the_file_bytes(pool: PgPool) -> anyhow::Result<()> {
let png = chart_png(&mut session, &REPORT_BALANCE, &values(&[]), "line", SIZE).await?;
assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"), "{:?}", &png[..8]);
async fn svg_is_the_reply_text(pool: PgPool) -> anyhow::Result<()> {
let request = ChartRequest {
kind: "stacked",
format: ChartFormat::Svg,
size: (300, 200),
look: ChartLook::default(),
let svg = chart(&mut session, &REPORT_BALANCE, &values(&[]), &request).await?;
assert!(svg.starts_with("<svg"), "{svg}");
async fn kitty_output_carries_the_png(pool: PgPool) -> anyhow::Result<()> {
let png = chart_png(&mut session, &REPORT_BALANCE, &values(&[]), "bar", SIZE).await?;
let drawn = terminal_chart(
&mut session,
&REPORT_BALANCE,
&values(&[]),
"bar",
true,
SIZE,
let Rendered::Bytes(bytes) = drawn else {
anyhow::bail!("expected kitty bytes");
assert_eq!(bytes, plotting::kitty::encode_png_apc(&png).into_bytes());
async fn spend_tagged(
date: &str,
value: &str,
tags: &[(&str, &str)],
) -> anyhow::Result<()> {
spend.set("date", date);
spend.set("note", "spend");
("value", value),
for (name, tag_value) in tags {
"split-tags",
("row", "1"),
("name", name),
("value", tag_value),
("side", "to"),
create(session, &spend).await?;
async fn categorized_session(pool: &PgPool) -> anyhow::Result<Seeded> {
let Seeded {
mut session,
usd,
} = seeded(pool).await?;
SetAccountTag::new()
.user_id(session.ctx().user_id)
.account_id(food)
.tag_name("type".to_string())
.tag_value("expense".to_string())
spend_tagged(
"2026-10-20",
"11",
&[("category", "food"), ("venue", "cafe")],
"2026-10-21",
"13",
&[("category", "fun"), ("venue", "club")],
spend_tagged(&mut session, "2026-09-30", "7", &[("category", "food")]).await?;
Ok(Seeded { session, food, usd })
async fn assert_csv_is_native(
native_payload: &str,
) -> anyhow::Result<String> {
let expected = run_report_csv(session.ctx().user_id, native_payload).await?;
let printed = csv(session, &REPORT_CATEGORY, given).await?;
assert_eq!(printed, expected);
assert!(printed.starts_with('\u{feff}'), "{printed:?}");
assert!(printed.ends_with("\r\n"), "{printed:?}");
Ok(printed)
async fn csv_equals_the_native_csv(pool: PgPool) -> anyhow::Result<()> {
let Seeded { mut session, .. } = categorized_session(&pool).await?;
let printed = assert_csv_is_native(
&given,
r#"(:from "2026-10-01" :to "2026-10-31")"#,
assert!(printed.contains("food,USD,11\r\n"), "{printed:?}");
assert!(printed.contains("fun,USD,13\r\n"), "{printed:?}");
assert!(!printed.contains(",7\r\n"), "{printed:?}");
async fn csv_maps_the_target_symbol_to_its_id(pool: PgPool) -> anyhow::Result<()> {
mut session, usd, ..
} = categorized_session(&pool).await?;
let given = values(&[("from", FROM), ("to", TO), ("target", "USD")]);
let mapped = map_references(&mut session, &REPORT_CATEGORY, &given).await?;
let call = csv_call(&REPORT_CATEGORY, &mapped);
assert!(call.contains(&format!(r#":target \"{usd}\""#)), "{call}");
let native = format!(r#"(:from "2026-10-01" :to "2026-10-31" :target "{usd}")"#);
let printed = assert_csv_is_native(&mut session, &given, &native).await?;
async fn csv_groups_by_another_tag(pool: PgPool) -> anyhow::Result<()> {
let given = values(&[("from", FROM), ("to", TO), ("tag", "venue")]);
let native = r#"(:from "2026-10-01" :to "2026-10-31" :tag "venue")"#;
let printed = assert_csv_is_native(&mut session, &given, native).await?;
assert!(printed.contains("cafe,USD,11\r\n"), "{printed:?}");
assert!(!printed.contains("food,"), "{printed:?}");
async fn csv_with_an_invalid_date_is_a_field_error(pool: PgPool) -> anyhow::Result<()> {
let given = values(&[("from", "yesterday")]);
match csv(&mut session, &REPORT_CATEGORY, &given).await {
assert!(found.iter().any(|l| l.starts_with("from:")), "{found:?}");
other => anyhow::bail!("expected FormInvalid, got {other:?}"),
async fn a_size_beyond_the_native_limit_is_refused(pool: PgPool) -> anyhow::Result<()> {
let drawn = chart_png(
(4096, 10),
.await;
assert!(drawn.is_err());