Lines
95.15 %
Functions
91.3 %
Branches
100 %
//! The lossless fixture through the Emacs edit buffer against a real server:
//! `emacs_lossless.el` (ERT) edits the server's load reply, this test submits
//! what Emacs wrote and compares the stored transaction.
#![cfg(feature = "db")]
use std::path::{Path, PathBuf};
use std::process::Command;
use cli_core::eval::escape_str;
use nomiscript::Value;
use rpc::{ResponsePayload, ScriptCtx, Session, parse_response};
use server::db::install_test_pool;
use server::lossless::{
EDITED_NOTE, NOTE, first_row_tag, seed, snapshot, split_tag_facts, without_note,
};
use sqlx::PgPool;
use uuid::Uuid;
/// The directory shared with Emacs, removed however the test ends.
struct Exchange(PathBuf);
impl Exchange {
fn create() -> std::io::Result<Self> {
let dir = std::env::temp_dir().join(format!("nomisync-lossless-{}", Uuid::new_v4()));
std::fs::create_dir(&dir)?;
Ok(Self(dir))
}
impl Drop for Exchange {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
fn repo_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("..")
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 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 load reply text after writing it for Emacs.
async fn load(session: &mut Session, dir: &Path, id: &str) -> anyhow::Result<String> {
let wire = reply(
session,
&format!("(load-form \"transaction-edit\" \"{id}\")"),
)
.await;
std::fs::write(dir.join("load.wire"), &wire)?;
value(&wire)
const NOTE_ENV: &str = "NOMISYNC_LOSSLESS_NOTE";
const ROWS_ENV: &str = "NOMISYNC_LOSSLESS_ROWS";
/// Run the ERT edit, configured by the `edit` variables, over the stored
/// load reply; the payload Emacs submits.
fn emacs_edit(dir: &Path, id: &str, edit: &[(&str, &str)]) -> anyhow::Result<String> {
let root = repo_root();
let mut command = Command::new("emacs");
command
.current_dir(&root)
.env("NOMISYNC_LOSSLESS_DIR", dir)
.env("NOMISYNC_LOSSLESS_ID", id)
.env_remove(NOTE_ENV)
.env_remove(ROWS_ENV)
.envs(edit.iter().copied())
.args(["-Q", "-batch", "-L", "emacs", "-l", "ert"])
.args(["--eval", "(setq load-prefer-newer t)"])
.arg("-l")
.arg(root.join("tests-integration/tests/emacs_lossless.el"))
.args(["-f", "ert-run-tests-batch-and-exit"]);
let output = command
.output()
.map_err(|e| anyhow::anyhow!("cannot run emacs (it must be installed): {e}"))?;
anyhow::ensure!(
output.status.success(),
"ERT failed ({}):\n{}\n{}",
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
Ok(std::fs::read_to_string(dir.join("payload.sexp"))?)
async fn submit(session: &mut Session, payload: &str) -> anyhow::Result<()> {
let form = format!("(submit-form \"transaction-edit\" {})", escape_str(payload));
value(&reply(session, &form).await).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 exchange directory holding the server's descriptors and option lists.
async fn exchange(session: &mut Session) -> anyhow::Result<Exchange> {
let exchange = Exchange::create()?;
let descriptors = reply(session, "(form-descriptor \"\")").await;
std::fs::write(exchange.0.join("descriptors.wire"), descriptors)?;
for source in ["accounts", "commodities"] {
let options = reply(session, &format!("(form-options \"{source}\")")).await;
std::fs::write(exchange.0.join(format!("options-{source}.wire")), options)?;
Ok(exchange)
#[sqlx::test(migrator = "server::db::MIGRATOR")]
async fn emacs_noop_and_note_only_edits_are_lossless(pool: PgPool) -> anyhow::Result<()> {
let _guard = 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 exchange = exchange(&mut session).await?;
let dir = exchange.0.as_path();
let loaded = load(&mut session, dir, &id).await?;
assert!(loaded.contains(":description \"client forms\""), "{loaded}");
assert!(
loaded.contains(":description \"split memo\\nsecond line\")"),
"{loaded}"
let payload = emacs_edit(dir, &id, &[])?;
// An empty tags-table cell cannot tell a stored "" description from none,
// nor an empty to-commodity from a missing one; the server stores both
// alike, which the snapshot check below proves.
assert_eq!(without_empty_cells(&payload), without_empty_cells(&loaded));
submit(&mut session, &payload).await?;
assert_eq!(snapshot(&pool, fixture.transaction).await?, stored);
let reloaded = load(&mut session, dir, &id).await?;
assert_eq!(without_revision(&reloaded), without_revision(&loaded));
let payload = emacs_edit(dir, &id, &[(NOTE_ENV, EDITED_NOTE)])?;
let expected = reloaded.replace(&escape_str(NOTE), &escape_str(EDITED_NOTE));
assert_eq!(
without_empty_cells(&payload),
without_empty_cells(&expected)
let after = load(&mut session, dir, &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(())
fn without_empty_cells(wire: &str) -> String {
wire.replace(" :description \"\"", "")
.replace(" :to-commodity \"\"", "")
fn count(snapshot: &[String], kind: &str) -> usize {
let prefix = format!("{kind} ");
snapshot
.iter()
.filter(|fact| fact.starts_with(&prefix))
.count()
/// Each row is two splits; a removed row takes its split tags along.
async fn keeps_other_tags_after_rows_edit(
pool: PgPool,
rows: &str,
splits: usize,
) -> 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);
let payload = emacs_edit(dir, &id, &[(ROWS_ENV, rows)])?;
assert_eq!(count(&now, "split"), splits, "{now:?}");
kept.iter().all(|fact| now.contains(fact)),
"{kept:?}: {now:?}"
async fn emacs_new_keyless_rows_keep_the_other_tags(pool: PgPool) -> anyhow::Result<()> {
keeps_other_tags_after_rows_edit(pool, "add", 8).await
async fn emacs_a_removed_row_keeps_the_other_tags(pool: PgPool) -> anyhow::Result<()> {
keeps_other_tags_after_rows_edit(pool, "remove", 2).await