Lines
98.22 %
Functions
100 %
Branches
use clap::Parser;
use sqlx::PgPool;
use super::*;
use crate::{AccountCmd, Cli, Command, CommodityCmd, ConfigCmd, TagCmd};
fn parse(args: &[&str]) -> Result<Command, clap::Error> {
let user = Uuid::new_v4().to_string();
let argv = ["nomisync", "--userid", &user]
.into_iter()
.chain(args.iter().copied());
Cli::try_parse_from(argv).map(|cli| cli.cmd)
}
fn call(args: &[&str]) -> anyhow::Result<FormCall> {
match parse(args)? {
Command::Account(AccountCmd::Forms(AccountForms(call)))
| Command::Commodity(CommodityCmd::Forms(CommodityForms(call)))
| Command::Tag(TagCmd::Forms(TagForms(call)))
| Command::Config(ConfigCmd::Forms(ConfigForms(call))) => Ok(call),
other => anyhow::bail!("not a form command: {other:?}"),
#[test]
fn account_create_takes_the_descriptor_fields() -> anyhow::Result<()> {
let call = call(&["account", "create", "--name", "Cash", "--parent", "Assets"])?;
assert_eq!(call.form.name, "account-create");
assert_eq!(call.id, None);
assert_eq!(call.values.text("name"), Some("Cash"));
assert_eq!(call.values.text("parent"), Some("Assets"));
Ok(())
fn a_missing_required_field_is_left_for_the_server() -> anyhow::Result<()> {
assert_eq!(call(&["account", "create"])?.values.text("name"), None);
fn account_edit_takes_an_id_and_tag_rows() -> anyhow::Result<()> {
let id = Uuid::new_v4();
let call = call(&[
"account",
"edit",
&id.to_string(),
"--name",
"Wallet",
"--tag",
"name=kind,value=cash",
])?;
assert_eq!(call.form.name, "account-edit");
assert_eq!(call.id, Some(id));
assert_eq!(call.values.rows("tags").map(<[_]>::len), Some(1));
fn edit_without_an_id_is_a_usage_error() {
assert!(parse(&["commodity", "edit", "--symbol", "X"]).is_err());
fn commodity_create_edit_and_convert_parse() -> anyhow::Result<()> {
let created = call(&["commodity", "create", "--symbol", "USD", "--name", "Dollar"])?;
assert_eq!(created.values.text("symbol"), Some("USD"));
let edited = call(&["commodity", "edit", &id.to_string(), "--clear-tags"])?;
assert_eq!(edited.values.rows("tags"), Some(&[][..]));
let converted = call(&[
"commodity",
"convert",
"--amount",
"10",
"--from",
"USD",
"--to",
"EUR",
assert_eq!(converted.form.name, "convert");
assert_eq!(converted.values.text("to"), Some("EUR"));
fn config_set_uses_the_descriptor_keys() -> anyhow::Result<()> {
let call = call(&["config", "set", "--key", "theme", "--value", "dark"])?;
assert_eq!(call.form.name, "config-set");
assert_eq!(call.values.text("key"), Some("theme"));
assert!(parse(&["config", "set", "--name", "theme"]).is_err());
fn config_get_stays_on_name() -> anyhow::Result<()> {
assert!(matches!(
parse(&["config", "get", "--name", "theme"])?,
Command::Config(ConfigCmd::Get { .. })
));
fn every_entry_builds_a_command() {
for entry in ACCOUNT_FORMS
.iter()
.chain(&COMMODITY_FORMS)
.chain(&TAG_FORMS)
.chain(&CONFIG_FORMS)
{
entry_command(entry).debug_assert();
fn replies_print_as_the_clients_do() {
let mut values = FormValues::default();
["amount", "from", "to"]
.zip(["10", "USD", "EUR"])
.for_each(|(key, text)| values.set(key, text));
assert_eq!(
printed(&values, &Reply::Entity("abc".to_string())),
Some("abc".to_string())
);
assert_eq!(printed(&values, &Reply::Done), None);
printed(&values, &Reply::Value("9".to_string())),
Some("10 USD = 9 EUR".to_string())
fn tag_create_and_edit_take_the_descriptor_fields() -> anyhow::Result<()> {
let created = call(&[
"tag",
"create",
"kind",
"--value",
"fiat",
"--description",
"money",
assert_eq!(created.form.name, "tag-create");
assert_eq!(created.id, None);
assert_eq!(created.values.text("description"), Some("money"));
let edited = call(&["tag", "edit", &id.to_string(), "--value", "crypto"])?;
assert_eq!(edited.form.name, "tag-edit");
assert_eq!(edited.id, Some(id));
assert_eq!(edited.values.text("value"), Some("crypto"));
assert_eq!(edited.values.text("name"), None);
fn tag_delete_and_list_parse() -> anyhow::Result<()> {
parse(&["tag", "delete", &id.to_string()])?,
Command::Tag(TagCmd::Delete { id: parsed, yes: false }) if parsed == id
parse(&["tag", "delete", &id.to_string(), "--yes"])?,
Command::Tag(TagCmd::Delete { yes: true, .. })
parse(&["tag", "list"])?,
Command::Tag(TagCmd::List)
assert!(parse(&["tag", "delete"]).is_err());
assert!(parse(&["tag", "edit", "--value", "x"]).is_err());
pub(crate) async fn seed_user(pool: &PgPool) -> anyhow::Result<Uuid> {
let user_id = 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_id)
.bind(format!("u{user_id}"))
.bind(format!("{user_id}@test.com"))
.execute(pool)
.await?;
Ok(user_id)
fn values(pairs: &[(&str, &str)]) -> FormValues {
pairs.iter().for_each(|(k, v)| values.set(k, v));
values
async fn seeded_tag(pool: &PgPool) -> anyhow::Result<(Session, Uuid)> {
let user = seed_user(pool).await?;
let mut session = Session::new(rpc::ScriptCtx::new(user))?;
let made = cli_core::flat::submit(
&mut session,
&forms::TAG_CREATE,
&values(&[("name", "kind"), ("value", "fiat")]),
match made.reply {
cli_core::flat::Reply::Entity(id) => Ok((session, Uuid::parse_str(&id)?)),
other => anyhow::bail!("expected an entity, got {other:?}"),
async fn tag_count(session: &mut Session) -> anyhow::Result<usize> {
match cli_core::eval::eval_form(session, "(list-tags)", RenderMode::TagList).await? {
cli_core::eval::Rendered::Lines(lines) => Ok(lines.len()),
other => anyhow::bail!("expected lines, got {other:?}"),
#[sqlx::test(migrator = "server::db::MIGRATOR")]
async fn a_declined_tag_delete_keeps_the_tag(pool: PgPool) -> anyhow::Result<()> {
let _guard = server::db::install_test_pool(pool.clone());
let (mut session, id) = seeded_tag(&pool).await?;
let deleted = delete_tag_confirmed(&mut session, id, false, true, "n\n".as_bytes()).await?;
assert!(!deleted);
assert_eq!(tag_count(&mut session).await?, 1);
async fn a_confirmed_tag_delete_removes_the_tag(pool: PgPool) -> anyhow::Result<()> {
let deleted = delete_tag_confirmed(&mut session, id, false, true, "y\n".as_bytes()).await?;
assert!(deleted);
assert_eq!(tag_count(&mut session).await?, 0);
async fn tag_delete_with_yes_needs_no_input(pool: PgPool) -> anyhow::Result<()> {
let deleted = delete_tag_confirmed(&mut session, id, true, false, "".as_bytes()).await?;
async fn tag_delete_without_a_terminal_or_yes_is_refused(pool: PgPool) -> anyhow::Result<()> {
let refused = delete_tag_confirmed(&mut session, id, false, false, "y\n".as_bytes()).await;
assert!(
matches!(refused, Err(CommandError::Argument(_))),
"{refused:?}"