Lines
97.87 %
Functions
100 %
Branches
//! `get-account` resolves keys exactly as the preflight classifier does.
use server::command::account::CreateAccount;
use server::command::{CmdResult, FinanceEntity};
use sqlx::PgPool;
use uuid::Uuid;
use crate::resolve::Directory;
use crate::resolve::class::Resolution;
use crate::template::render_template;
use crate::{ScriptCtx, Session};
struct Fx {
user: Uuid,
expenses: Uuid,
cafe: Uuid,
bank: Uuid,
fuel: Uuid,
}
async fn seed(user: Uuid, name: &str, parent: Option<Uuid>) -> anyhow::Result<Uuid> {
let mut command = CreateAccount::new().name(name.to_string()).user_id(user);
if let Some(parent) = parent {
command = command.parent(parent);
match command.run().await? {
Some(CmdResult::Entity(FinanceEntity::Account(a))) => Ok(a.id),
other => anyhow::bail!("unexpected CreateAccount result: {other:?}"),
async fn fx(pool: &PgPool) -> anyhow::Result<Fx> {
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, 'Test', 'test@test.com', 'x', false, 'pw', 'user', 'db', NOW())",
)
.bind(user)
.execute(pool)
.await?;
let expenses = seed(user, "Expenses", None).await?;
Ok(Fx {
user,
expenses,
cafe: seed(user, "Cafe", Some(expenses)).await?,
bank: seed(user, "Bank", None).await?,
fuel: seed(user, "Fuel", Some(expenses)).await?,
})
async fn looked_up_id(session: &mut Session, key: &str) -> String {
let form =
format!("(:id 1 :form (let ((a (get-account \"{key}\"))) (if a (account-id a) \"nil\")))");
let resp = session.handle_form(&form).await;
resp.split_once(":value ")
.map(|(_, rest)| {
rest.trim_end_matches(')')
.trim()
.trim_matches('"')
.to_string()
.unwrap_or(resp)
#[sqlx::test(migrator = "server::db::MIGRATOR")]
async fn each_key_form_resolves_to_its_account(pool: PgPool) -> anyhow::Result<()> {
let _guard = server::db::install_test_pool(pool.clone());
let fx = fx(&pool).await?;
let mut session = Session::new(ScriptCtx::new(fx.user))?;
let cases = [
("Expenses:Cafe", fx.cafe.to_string()),
("Bank", fx.bank.to_string()),
("Fuel", fx.fuel.to_string()),
(&fx.expenses.to_string(), fx.expenses.to_string()),
("Expenses:Nothing", "nil".to_string()),
("Nothing", "nil".to_string()),
];
for (key, expected) in cases {
assert_eq!(looked_up_id(&mut session, key).await, expected, "{key}");
Ok(())
async fn a_template_with_a_full_path_drafts_the_nested_account(pool: PgPool) -> anyhow::Result<()> {
let source = "(draft-split (get-account \"Expenses:Cafe\") (get-commodity \"USD\") 5/1)";
seed_usd(fx.user).await?;
let draft = render_template(&ScriptCtx::new(fx.user), source).await?;
assert_eq!(draft.splits.len(), 1);
assert_eq!(draft.splits[0].account_id, fx.cafe.to_string());
async fn seed_usd(user: Uuid) -> anyhow::Result<()> {
server::command::commodity::CreateCommodity::new()
.symbol("USD".to_string())
.name("US Dollar".to_string())
.user_id(user)
.run()
async fn the_classifier_and_the_native_agree(pool: PgPool) -> anyhow::Result<()> {
seed(fx.user, "Dup", Some(fx.expenses)).await?;
seed(fx.user, "Dup", Some(fx.bank)).await?;
let directory = Directory::load("test", fx.user).await?;
let uuid = fx.cafe.to_string();
for key in [
"Expenses:Cafe",
"Expenses",
"Cafe",
&uuid,
"Expenses:No",
"No",
"Dup",
] {
let response = looked_up_id(&mut session, key).await;
let class = directory.classify_account(key);
assert_eq!(
response.contains("ambiguous"),
matches!(class, Resolution::Ambiguous(_)),
"{key}"
);
if !matches!(class, Resolution::Ambiguous(_)) {
assert_eq!(response != "nil", class != Resolution::Unknown, "{key}");
async fn a_uuid_resolves_without_the_directory_and_an_unknown_one_is_nil(
pool: PgPool,
) -> anyhow::Result<()> {
looked_up_id(&mut session, &fx.bank.to_string()).await,
fx.bank.to_string()
looked_up_id(&mut session, &Uuid::new_v4().to_string()).await,
"nil"
async fn the_root_wins_over_a_nested_account_of_the_same_name(pool: PgPool) -> anyhow::Result<()> {
let food = seed(fx.user, "Food", None).await?;
seed(fx.user, "Cafe", Some(food)).await?;
let root_cafe = seed(fx.user, "Cafe", None).await?;
assert_eq!(directory.classify_account("Cafe"), Resolution::Path);
looked_up_id(&mut session, "Cafe").await,
root_cafe.to_string()
async fn an_ambiguous_name_raises_listing_its_candidates(pool: PgPool) -> anyhow::Result<()> {
let nested = seed(fx.user, "Dup", Some(food)).await?;
let other = seed(fx.user, "Dup", Some(fx.bank)).await?;
assert_eq!(directory.classify_account("Dup"), Resolution::Ambiguous(2));
let response = session
.handle_form("(:id 1 :form (get-account \"Dup\"))")
.await;
assert!(response.contains(":error (:code args"), "{response}");
for candidate in [
format!("Food:Dup ({nested})"),
format!("Bank:Dup ({other})"),
assert!(response.contains(&candidate), "{candidate} in {response}");