1
use scripting::runtime::EvalValue;
2
use server::user::User;
3
use sqlx::PgPool;
4
use uuid::Uuid;
5

            
6
use super::test_edit::{Fx, fx};
7
use super::tests_transaction_tags::{TRIP, tagged};
8
use crate::compile_script;
9
use crate::ctx::ScriptCtx;
10
use crate::natives::script_store::run_run_script;
11
use crate::session::Session;
12

            
13
const TAG_SYNC: &str = include_str!("../../../../doc/scripts/tag-sync.nms");
14

            
15
const BOOM_ON_TRIP: &str = r#"
16
(do ((i 0 (+ i 1)))
17
    ((>= i (entity-count)))
18
    (when (and (= (entity-type i) +entity-tag+)
19
               (string= (tag-name i) "trip"))
20
        (error 'boom "no")))
21
"#;
22

            
23
3
async fn stored(fx: &Fx, source: &str) -> anyhow::Result<Uuid> {
24
3
    let user = User { id: fx.user };
25
3
    Ok(user
26
3
        .create_script(compile_script(source)?, Some("run".to_string()))
27
3
        .await?)
28
3
}
29

            
30
2
fn plist(items: Vec<EvalValue>) -> EvalValue {
31
2
    EvalValue::List(items)
32
2
}
33

            
34
3
fn symbol(name: &str) -> EvalValue {
35
3
    EvalValue::Symbol(format!(":{name}"))
36
3
}
37

            
38
2
async fn run(fx: &Fx, script: Uuid) -> wasmtime::Result<EvalValue> {
39
2
    run_run_script(fx.user, Some(script.to_string()), Some(fx.cash.to_string())).await
40
2
}
41

            
42
#[sqlx::test(migrator = "server::db::MIGRATOR")]
43
async fn tag_sync_reports_what_ran_and_what_changed(pool: PgPool) -> anyhow::Result<()> {
44
    let _guard = server::db::install_test_pool(pool.clone());
45
    let fx = fx(&pool).await?;
46
    tagged(&fx, &[TRIP]).await?;
47
    tagged(&fx, &[]).await?;
48
    let script = stored(&fx, TAG_SYNC).await?;
49

            
50
    let report = run(&fx, script).await?;
51

            
52
    assert_eq!(
53
        report,
54
        plist(vec![
55
            symbol("RAN"),
56
            EvalValue::I32(2),
57
            symbol("COMMITTED"),
58
            EvalValue::I32(1),
59
            symbol("FAILURES"),
60
            plist(Vec::new()),
61
        ])
62
    );
63
    Ok(())
64
}
65

            
66
#[sqlx::test(migrator = "server::db::MIGRATOR")]
67
async fn a_script_failure_is_reported_and_nothing_is_committed(pool: PgPool) -> anyhow::Result<()> {
68
    let _guard = server::db::install_test_pool(pool.clone());
69
    let fx = fx(&pool).await?;
70
    let boom = tagged(&fx, &[TRIP]).await?;
71
    tagged(&fx, &[]).await?;
72
    let script = stored(&fx, BOOM_ON_TRIP).await?;
73

            
74
    let EvalValue::List(report) = run(&fx, script).await? else {
75
        anyhow::bail!("expected a plist");
76
    };
77

            
78
    assert_eq!(report[3], EvalValue::I32(0));
79
    let EvalValue::List(failures) = &report[5] else {
80
        anyhow::bail!("expected failures, got {:?}", report[5]);
81
    };
82
    assert_eq!(failures.len(), 1);
83
    let EvalValue::List(failure) = &failures[0] else {
84
        anyhow::bail!("expected a failure plist");
85
    };
86
    assert_eq!(failure[1], EvalValue::String(boom.to_string()));
87
    assert_eq!(failure[3], EvalValue::String(script.to_string()));
88
    Ok(())
89
}
90

            
91
#[sqlx::test(migrator = "server::db::MIGRATOR")]
92
async fn a_missing_script_is_not_found_and_a_bad_id_is_args(pool: PgPool) -> anyhow::Result<()> {
93
    let _guard = server::db::install_test_pool(pool.clone());
94
    let fx = fx(&pool).await?;
95
    let mut session = Session::new(ScriptCtx::new(fx.user))?;
96
    let missing = format!(
97
        "(:id 1 :form (run-script \"{}\" \"{}\"))",
98
        Uuid::new_v4(),
99
        fx.cash
100
    );
101

            
102
    let not_found = session.handle_form(&missing).await;
103
    let malformed = session
104
        .handle_form(&format!(
105
            "(:id 2 :form (run-script \"nope\" \"{}\"))",
106
            fx.cash
107
        ))
108
        .await;
109

            
110
    assert!(not_found.contains(":code not-found"), "got: {not_found}");
111
    assert!(malformed.contains(":code args"), "got: {malformed}");
112
    Ok(())
113
}
114

            
115
#[sqlx::test(migrator = "server::db::MIGRATOR")]
116
async fn the_session_answers_the_plist_on_the_wire(pool: PgPool) -> anyhow::Result<()> {
117
    let _guard = server::db::install_test_pool(pool.clone());
118
    let fx = fx(&pool).await?;
119
    tagged(&fx, &[TRIP]).await?;
120
    let script = stored(&fx, TAG_SYNC).await?;
121
    let mut session = Session::new(ScriptCtx::new(fx.user))?;
122

            
123
    let response = session
124
        .handle_form(&format!(
125
            "(:id 1 :form (run-script \"{script}\" \"{}\"))",
126
            fx.cash
127
        ))
128
        .await;
129

            
130
    assert!(
131
        response.contains("(:RAN 1 :COMMITTED 1 :FAILURES nil)"),
132
        "got: {response}"
133
    );
134
    Ok(())
135
}