Lines
90.24 %
Functions
66.67 %
Branches
100 %
use std::collections::HashSet;
use forms::FormValues;
use nomiscript::Reader;
use scripting::runtime::HostCondition;
use sqlx::PgPool;
use uuid::Uuid;
use super::test_edit::detail_text;
use super::test_query_seed::{Fixture, add_tx, fixture};
use super::test_seed::query_text;
use super::test_seed::seed_account;
pub(super) fn values(pairs: &[(&str, &str)]) -> FormValues {
let mut values = FormValues::default();
for (key, value) in pairs {
values.set(key, value);
}
values
/// Reads the result back with the nomiscript reader: (ids, has-more).
fn read_result(text: &str) -> anyhow::Result<(Vec<String>, bool)> {
let program = Reader::parse(text).map_err(|e| anyhow::anyhow!("{e}"))?;
anyhow::ensure!(program.exprs.len() == 1, "{text}");
let ids = text
.split("(:ID \"")
.skip(1)
.filter_map(|chunk| chunk.split('"').next())
.map(str::to_string)
.collect();
Ok((ids, text.contains(":HAS-MORE t :TOTAL ")))
pub(super) async fn query(
f: &Fixture,
pairs: &[(&str, &str)],
) -> anyhow::Result<(Vec<String>, bool)> {
let text = query_text(f.user_id, &values(pairs))
.await
.map_err(|e| anyhow::anyhow!("{e}"))?;
read_result(&text)
fn condition(err: &wasmtime::Error) -> anyhow::Result<&HostCondition> {
err.downcast_ref::<HostCondition>()
.ok_or_else(|| anyhow::anyhow!("not a HostCondition: {err}"))
pub(super) async fn rejected(f: &Fixture, pairs: &[(&str, &str)]) -> anyhow::Result<String> {
let err = query_text(f.user_id, &values(pairs))
.err()
.ok_or_else(|| anyhow::anyhow!("query was accepted"))?;
let cond = condition(&err)?;
anyhow::ensure!(cond.code == "form-invalid", "{cond:?}");
anyhow::ensure!(cond.detail.is_some(), "no detail");
Ok(detail_text(cond))
#[sqlx::test(migrator = "server::db::MIGRATOR")]
async fn equal_dates_page_without_duplicates_or_omissions(pool: PgPool) -> anyhow::Result<()> {
let _guard = server::db::install_test_pool(pool.clone());
let f = fixture(&pool).await?;
let mut created = HashSet::new();
for n in 0..5 {
created.insert(
add_tx(&f, "2024-03-01T10:00:00Z", &format!("n{n}"))
.await?
.to_string(),
);
let mut seen = Vec::new();
for (offset, more) in [("0", true), ("2", true), ("4", false)] {
let (ids, has_more) = query(&f, &[("limit", "2"), ("offset", offset)]).await?;
assert_eq!(has_more, more, "offset {offset}");
seen.extend(ids);
assert_eq!(seen.len(), 5);
assert_eq!(seen.iter().cloned().collect::<HashSet<_>>(), created);
let ids = seen
.iter()
.map(|id| Uuid::parse_str(id))
.collect::<Result<Vec<_>, _>>()?;
assert!(
ids.windows(2).all(|pair| pair[0] > pair[1]),
"equal dates must page in strictly descending id order: {seen:?}"
Ok(())
async fn rows_carry_date_note_and_amount(pool: PgPool) -> anyhow::Result<()> {
let id = add_tx(&f, "2024-03-01T10:00:00.250Z", "lunch \"x\"").await?;
let text = query_text(f.user_id, &values(&[])).await?;
assert_eq!(
text,
format!(
"(:ROWS ((:ID \"{id}\" :DATE \"2024-03-01T10:00:00.250Z\" :DATE-TEXT \"2024-03-01 10:00\" :NOTE \"lunch \\\"x\\\"\" :AMOUNT \"100.00 USD\")) :HAS-MORE nil :TOTAL 1)"
)
Reader::parse(&text).map_err(|e| anyhow::anyhow!("{e}"))?;
async fn date_only_to_includes_the_whole_day(pool: PgPool) -> anyhow::Result<()> {
let late = add_tx(&f, "2024-03-01T23:59:59.500Z", "late").await?;
add_tx(&f, "2024-03-02T00:00:00Z", "next").await?;
add_tx(&f, "2024-02-29T23:59:59Z", "before").await?;
let (ids, more) = query(&f, &[("from", "2024-03-01"), ("to", "2024-03-01")]).await?;
assert_eq!(ids, vec![late.to_string()]);
assert!(!more);
async fn account_filter_takes_a_uuid_only(pool: PgPool) -> anyhow::Result<()> {
let other = seed_account(f.user_id, "Savings").await?;
let id = add_tx(&f, "2024-03-01T10:00:00Z", "a").await?;
let by_uuid = query(&f, &[("account", &f.expenses.to_string())]).await?;
assert_eq!(by_uuid.0, vec![id.to_string()]);
let none = query(&f, &[("account", &other.to_string())]).await?;
assert!(none.0.is_empty());
let foreign = Uuid::new_v4().to_string();
for bad in ["Expenses", "Expenses:Food", "not-a-uuid", foreign.as_str()] {
let detail = rejected(&f, &[("account", bad)]).await?;
detail.starts_with("((:FIELD \"account\" :MESSAGE \"unknown account"),
"{bad}: {detail}"
async fn out_of_range_numbers_name_their_field(pool: PgPool) -> anyhow::Result<()> {
for (key, value) in [
("limit", "0"),
("limit", "201"),
("limit", "many"),
("offset", "-1"),
("offset", "x"),
] {
let detail = rejected(&f, &[(key, value)]).await?;
detail.starts_with(&format!("((:FIELD \"{key}\" :MESSAGE \"")),
"{detail}"
async fn bad_dates_and_unknown_accounts_are_field_errors(pool: PgPool) -> anyhow::Result<()> {
let detail = rejected(
&f,
&[
("from", "yesterday"),
("account", &Uuid::new_v4().to_string()),
],
.await?;
assert!(detail.contains("(:FIELD \"from\" :MESSAGE \""), "{detail}");
detail.contains("(:FIELD \"account\" :MESSAGE \"unknown account"),