aboutsummaryrefslogtreecommitdiffstats
path: root/src/document/testing.rs
blob: b34d85fb0f1f33afbbb8d0a31a7a628e079f10dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//! For tests: writing to documents the way the node does, one change at a time, so
//! that tests don't depend on how the engine groups writes into changes.

use super::Document;

/// The writes `f` makes to `doc`, as one change; what `f` returns.
pub(crate) fn change<T>(doc: &mut Document, f: impl FnOnce(&mut Document) -> T) -> T {
    let out = f(doc);
    doc.commit();
    out
}

/// The writes `f` makes to `doc`, as one change if it succeeds, dropped if not; what
/// `f` returns. Committed at time 0: the same writes make the same change.
pub(crate) fn try_change<T, E>(
    doc: &mut Document,
    f: impl FnOnce(&mut Document) -> Result<T, E>,
) -> Result<T, E> {
    let out = f(doc);
    match &out {
        Ok(_) => {
            doc.commit_with(automerge::transaction::CommitOptions::default().with_time(0));
        }
        Err(_) => {
            doc.rollback();
        }
    }
    out
}