1
//! The lossless fixture through the Emacs edit buffer against a real server:
2
//! `emacs_lossless.el` (ERT) edits the server's load reply, this test submits
3
//! what Emacs wrote and compares the stored transaction.
4

            
5
#![cfg(feature = "db")]
6

            
7
use std::path::{Path, PathBuf};
8
use std::process::Command;
9

            
10
use cli_core::eval::escape_str;
11
use nomiscript::Value;
12
use rpc::{ResponsePayload, ScriptCtx, Session, parse_response};
13
use server::db::install_test_pool;
14
use server::lossless::{
15
    EDITED_NOTE, NOTE, first_row_tag, seed, snapshot, split_tag_facts, without_note,
16
};
17
use sqlx::PgPool;
18
use uuid::Uuid;
19

            
20
/// The directory shared with Emacs, removed however the test ends.
21
struct Exchange(PathBuf);
22

            
23
impl Exchange {
24
3
    fn create() -> std::io::Result<Self> {
25
3
        let dir = std::env::temp_dir().join(format!("nomisync-lossless-{}", Uuid::new_v4()));
26
3
        std::fs::create_dir(&dir)?;
27
3
        Ok(Self(dir))
28
3
    }
29
}
30

            
31
impl Drop for Exchange {
32
3
    fn drop(&mut self) {
33
3
        let _ = std::fs::remove_dir_all(&self.0);
34
3
    }
35
}
36

            
37
4
fn repo_root() -> PathBuf {
38
4
    Path::new(env!("CARGO_MANIFEST_DIR")).join("..")
39
4
}
40

            
41
18
async fn reply(session: &mut Session, form: &str) -> String {
42
18
    session.handle_form(&format!("(:id 1 :form {form})")).await
43
18
}
44

            
45
9
fn value(wire: &str) -> anyhow::Result<String> {
46
9
    match parse_response(wire).map(|response| response.payload) {
47
9
        Ok(ResponsePayload::Value(Value::String(text))) => Ok(text),
48
        other => anyhow::bail!("expected a string value, got {other:?}"),
49
    }
50
9
}
51

            
52
/// The load reply text after writing it for Emacs.
53
5
async fn load(session: &mut Session, dir: &Path, id: &str) -> anyhow::Result<String> {
54
5
    let wire = reply(
55
5
        session,
56
5
        &format!("(load-form \"transaction-edit\" \"{id}\")"),
57
5
    )
58
5
    .await;
59
5
    std::fs::write(dir.join("load.wire"), &wire)?;
60
5
    value(&wire)
61
5
}
62

            
63
const NOTE_ENV: &str = "NOMISYNC_LOSSLESS_NOTE";
64
const ROWS_ENV: &str = "NOMISYNC_LOSSLESS_ROWS";
65

            
66
/// Run the ERT edit, configured by the `edit` variables, over the stored
67
/// load reply; the payload Emacs submits.
68
4
fn emacs_edit(dir: &Path, id: &str, edit: &[(&str, &str)]) -> anyhow::Result<String> {
69
4
    let root = repo_root();
70
4
    let mut command = Command::new("emacs");
71
4
    command
72
4
        .current_dir(&root)
73
4
        .env("NOMISYNC_LOSSLESS_DIR", dir)
74
4
        .env("NOMISYNC_LOSSLESS_ID", id)
75
4
        .env_remove(NOTE_ENV)
76
4
        .env_remove(ROWS_ENV)
77
4
        .envs(edit.iter().copied())
78
4
        .args(["-Q", "-batch", "-L", "emacs", "-l", "ert"])
79
4
        .args(["--eval", "(setq load-prefer-newer t)"])
80
4
        .arg("-l")
81
4
        .arg(root.join("tests-integration/tests/emacs_lossless.el"))
82
4
        .args(["-f", "ert-run-tests-batch-and-exit"]);
83
4
    let output = command
84
4
        .output()
85
        .map_err(|e| anyhow::anyhow!("cannot run emacs (it must be installed): {e}"))?;
86
4
    anyhow::ensure!(
87
4
        output.status.success(),
88
        "ERT failed ({}):\n{}\n{}",
89
        output.status,
90
        String::from_utf8_lossy(&output.stdout),
91
        String::from_utf8_lossy(&output.stderr)
92
    );
93
4
    Ok(std::fs::read_to_string(dir.join("payload.sexp"))?)
94
4
}
95

            
96
4
async fn submit(session: &mut Session, payload: &str) -> anyhow::Result<()> {
97
4
    let form = format!("(submit-form \"transaction-edit\" {})", escape_str(payload));
98
4
    value(&reply(session, &form).await).map(|_| ())
99
4
}
100

            
101
4
fn without_revision(text: &str) -> String {
102
4
    let (head, rest) = text.split_once(" :revision \"").unwrap_or((text, "\""));
103
4
    let tail = rest.split_once('"').map_or("", |(_, tail)| tail);
104
4
    format!("{head}{tail}")
105
4
}
106

            
107
/// The exchange directory holding the server's descriptors and option lists.
108
3
async fn exchange(session: &mut Session) -> anyhow::Result<Exchange> {
109
3
    let exchange = Exchange::create()?;
110
3
    let descriptors = reply(session, "(form-descriptor \"\")").await;
111
3
    std::fs::write(exchange.0.join("descriptors.wire"), descriptors)?;
112
3
    for source in ["accounts", "commodities"] {
113
6
        let options = reply(session, &format!("(form-options \"{source}\")")).await;
114
6
        std::fs::write(exchange.0.join(format!("options-{source}.wire")), options)?;
115
    }
116
3
    Ok(exchange)
117
3
}
118

            
119
#[sqlx::test(migrator = "server::db::MIGRATOR")]
120
async fn emacs_noop_and_note_only_edits_are_lossless(pool: PgPool) -> anyhow::Result<()> {
121
    let _guard = install_test_pool(pool.clone());
122
    let fixture = seed(&pool).await?;
123
    let id = fixture.transaction.to_string();
124
    let mut session = Session::new(ScriptCtx::new(fixture.user))?;
125
    let stored = snapshot(&pool, fixture.transaction).await?;
126
    let exchange = exchange(&mut session).await?;
127
    let dir = exchange.0.as_path();
128

            
129
    let loaded = load(&mut session, dir, &id).await?;
130
    assert!(loaded.contains(":description \"client forms\""), "{loaded}");
131
    assert!(
132
        loaded.contains(":description \"split memo\\nsecond line\")"),
133
        "{loaded}"
134
    );
135
    let payload = emacs_edit(dir, &id, &[])?;
136
    // An empty tags-table cell cannot tell a stored "" description from none,
137
    // nor an empty to-commodity from a missing one; the server stores both
138
    // alike, which the snapshot check below proves.
139
    assert_eq!(without_empty_cells(&payload), without_empty_cells(&loaded));
140
    submit(&mut session, &payload).await?;
141
    assert_eq!(snapshot(&pool, fixture.transaction).await?, stored);
142

            
143
    let reloaded = load(&mut session, dir, &id).await?;
144
    assert_eq!(without_revision(&reloaded), without_revision(&loaded));
145
    let payload = emacs_edit(dir, &id, &[(NOTE_ENV, EDITED_NOTE)])?;
146
    let expected = reloaded.replace(&escape_str(NOTE), &escape_str(EDITED_NOTE));
147
    assert_eq!(
148
        without_empty_cells(&payload),
149
        without_empty_cells(&expected)
150
    );
151
    submit(&mut session, &payload).await?;
152
    let after = load(&mut session, dir, &id).await?;
153
    assert_eq!(without_revision(&after), without_revision(&expected));
154
    let now = snapshot(&pool, fixture.transaction).await?;
155
    assert_eq!(without_note(&now), without_note(&stored));
156
    assert!(
157
        now.contains(&format!("tag note {EDITED_NOTE} -")),
158
        "{now:?}"
159
    );
160
    Ok(())
161
}
162

            
163
4
fn without_empty_cells(wire: &str) -> String {
164
4
    wire.replace(" :description \"\"", "")
165
4
        .replace(" :to-commodity \"\"", "")
166
4
}
167

            
168
2
fn count(snapshot: &[String], kind: &str) -> usize {
169
2
    let prefix = format!("{kind} ");
170
2
    snapshot
171
2
        .iter()
172
32
        .filter(|fact| fact.starts_with(&prefix))
173
        .count()
174
2
}
175

            
176
/// Each row is two splits; a removed row takes its split tags along.
177
2
async fn keeps_other_tags_after_rows_edit(
178
2
    pool: PgPool,
179
2
    rows: &str,
180
2
    splits: usize,
181
2
) -> anyhow::Result<()> {
182
2
    let _guard = install_test_pool(pool.clone());
183
2
    let fixture = seed(&pool).await?;
184
2
    let id = fixture.transaction.to_string();
185
2
    let mut session = Session::new(ScriptCtx::new(fixture.user))?;
186
2
    let exchange = exchange(&mut session).await?;
187
2
    let dir = exchange.0.as_path();
188
2
    let loaded = load(&mut session, dir, &id).await?;
189
2
    let name = first_row_tag(&loaded).ok_or_else(|| anyhow::anyhow!("no r1 tag"))?;
190
2
    let kept = split_tag_facts(&snapshot(&pool, fixture.transaction).await?, name);
191
2
    let payload = emacs_edit(dir, &id, &[(ROWS_ENV, rows)])?;
192
2
    submit(&mut session, &payload).await?;
193
2
    let now = snapshot(&pool, fixture.transaction).await?;
194
2
    assert_eq!(count(&now, "split"), splits, "{now:?}");
195
2
    assert!(
196
4
        kept.iter().all(|fact| now.contains(fact)),
197
        "{kept:?}: {now:?}"
198
    );
199
2
    Ok(())
200
2
}
201

            
202
#[sqlx::test(migrator = "server::db::MIGRATOR")]
203
async fn emacs_new_keyless_rows_keep_the_other_tags(pool: PgPool) -> anyhow::Result<()> {
204
    keeps_other_tags_after_rows_edit(pool, "add", 8).await
205
}
206

            
207
#[sqlx::test(migrator = "server::db::MIGRATOR")]
208
async fn emacs_a_removed_row_keeps_the_other_tags(pool: PgPool) -> anyhow::Result<()> {
209
    keeps_other_tags_after_rows_edit(pool, "remove", 2).await
210
}