1
//! The script create, edit and toggle flows through the real key dispatch.
2

            
3
use crate::tabs::nms_eval::double::Sent;
4
use crate::test_support::{ctrl, key, press};
5
use forms::{FormValues, SCRIPT_EDIT, write_payload};
6

            
7
use super::edit::{top_form, wire_of};
8
use super::scripts::{OLD, SYNC, load, load_states, pending, scripts_app};
9
use super::template_forms::{pending_request, rejected};
10
use crate::app::App;
11
use crate::event::{Intent, apply};
12
use crate::form::FormKind;
13
use crate::route::ScriptRoute;
14
use ratatui::crossterm::event::KeyCode;
15

            
16
const SOURCE: &str = "(+ 1 2)";
17

            
18
3
fn type_text(app: &mut App, text: &str) {
19
16
    text.chars().for_each(|c| apply(app, Intent::InsertChar(c)));
20
3
}
21

            
22
6
fn edit_values(id: &str, enabled: &str) -> FormValues {
23
6
    let mut values = FormValues::default();
24
6
    values.set("id", id);
25
6
    values.set("revision", "rev-1");
26
6
    values.set("name", "sync");
27
6
    values.set("source", SOURCE);
28
6
    values.set("enabled", enabled);
29
6
    values
30
6
}
31

            
32
6
fn edit_wire(values: &FormValues, notice: Option<&str>) -> String {
33
6
    let mut wire = wire_of(&write_payload(&SCRIPT_EDIT, values));
34
6
    if let Some(notice) = notice {
35
1
        wire.truncate(wire.len() - 1);
36
1
        wire.push_str(&format!(r#" :notices ("{notice}"))"#));
37
5
    }
38
6
    wire
39
6
}
40

            
41
4
fn created_wire(request: i64, id: &str) -> String {
42
4
    format!(r#"(:id {request} :value "{id}")"#)
43
4
}
44

            
45
6
async fn echoed(app: &mut App, sent: &Sent) -> String {
46
6
    tokio::task::yield_now().await;
47
6
    app.drain_eval();
48
6
    sent.frames().join("\n")
49
6
}
50

            
51
#[tokio::test]
52
1
async fn c_opens_the_create_form_and_a_saved_script_is_selected() -> anyhow::Result<()> {
53
1
    let (mut app, sent) = scripts_app();
54
1
    load(&mut app, &[(SYNC, "sync")])?;
55

            
56
1
    press(&mut app, key(KeyCode::Char('c')));
57
1
    assert_eq!(top_form(&app).kind, FormKind::ScriptCreate);
58
1
    type_text(&mut app, "tags");
59
1
    apply(&mut app, Intent::NextField);
60
1
    type_text(&mut app, SOURCE);
61
1
    press(&mut app, ctrl(KeyCode::Char('s')));
62
1
    let request = pending_request(&app)?;
63
1
    let echoed = echoed(&mut app, &sent).await;
64
1
    assert!(
65
1
        echoed.contains(r#"(submit-form "script-create""#),
66
        "{echoed}"
67
    );
68

            
69
1
    app.route_reply(request, &created_wire(request, OLD));
70
1
    assert!(app.pending_form.is_none());
71
1
    load(&mut app, &[(SYNC, "sync"), (OLD, "tags")])?;
72
1
    assert_eq!(app.scripts().selected_key(), Some(OLD));
73
2
    Ok(())
74
1
}
75

            
76
#[tokio::test]
77
1
async fn a_source_that_does_not_compile_shows_at_the_source_field() -> anyhow::Result<()> {
78
1
    let (mut app, _) = scripts_app();
79
1
    load(&mut app, &[])?;
80
1
    press(&mut app, key(KeyCode::Char('c')));
81
1
    apply(&mut app, Intent::NextField);
82
1
    type_text(&mut app, "(oops");
83
1
    press(&mut app, ctrl(KeyCode::Char('s')));
84
1
    let request = pending_request(&app)?;
85

            
86
1
    let message = "unexpected end\\n(oops\\n     ^";
87
1
    app.route_reply(request, &rejected(request, "source", message));
88

            
89
1
    assert_eq!(top_form(&app).kind, FormKind::ScriptCreate);
90
1
    assert_eq!(
91
1
        top_form(&app).errors,
92
1
        ["Source: unexpected end\n(oops\n     ^"]
93
    );
94
1
    assert_eq!(top_form(&app).values().text("source"), Some("(oops"));
95
2
    Ok(())
96
1
}
97

            
98
#[tokio::test]
99
1
async fn e_loads_the_script_with_its_notice_and_submits_it_with_its_revision() -> anyhow::Result<()>
100
1
{
101
1
    let (mut app, sent) = scripts_app();
102
1
    load(&mut app, &[(SYNC, "sync")])?;
103

            
104
1
    press(&mut app, key(KeyCode::Char('e')));
105
1
    assert!(pending(&app, |r| matches!(r, ScriptRoute::Edit)).is_some());
106
1
    let text = echoed(&mut app, &sent).await;
107
1
    assert!(
108
1
        text.contains(&format!(r#"(load-form "script-edit" "{SYNC}")"#)),
109
        "{text}"
110
    );
111

            
112
1
    let notice = "uploaded as bytecode and has no source";
113
1
    app.deliver_script_edit_reply(
114
1
        Some(app.window_of(crate::view::ViewId::Scripts)),
115
1
        &edit_wire(&edit_values(SYNC, "true"), Some(notice)),
116
1
    );
117
1
    assert_eq!(top_form(&app).kind, FormKind::ScriptEdit);
118
1
    assert_eq!(top_form(&app).notices, [notice]);
119
1
    assert_eq!(top_form(&app).hidden[1], ("revision", "rev-1".to_string()));
120
1
    assert_eq!(top_form(&app).values().text("source"), Some(SOURCE));
121

            
122
1
    apply(&mut app, Intent::Submit);
123
1
    assert!(app.pending_form.is_some());
124
1
    let text = echoed(&mut app, &sent).await;
125
1
    assert!(
126
1
        text.contains(r#"(submit-form "script-edit" "(:id "#),
127
        "{text}"
128
    );
129
1
    assert!(text.contains(r#":revision \"rev-1\""#), "{text}");
130
2
    Ok(())
131
1
}
132

            
133
#[tokio::test]
134
1
async fn a_saved_edit_refreshes_the_list() -> anyhow::Result<()> {
135
1
    let (mut app, _) = scripts_app();
136
1
    load(&mut app, &[(SYNC, "sync")])?;
137
1
    app.deliver_script_edit_reply(
138
1
        Some(app.window_of(crate::view::ViewId::Scripts)),
139
1
        &edit_wire(&edit_values(SYNC, "true"), None),
140
1
    );
141
1
    apply(&mut app, Intent::Submit);
142
1
    let request = pending_request(&app)?;
143

            
144
1
    app.route_reply(request, &created_wire(request, SYNC));
145

            
146
1
    assert!(app.pending_form.is_none());
147
1
    assert!(app.scripts().any_loading());
148
2
    Ok(())
149
1
}
150

            
151
#[tokio::test]
152
1
async fn a_stale_revision_keeps_the_form_and_shows_the_reload_hint() -> anyhow::Result<()> {
153
1
    let (mut app, _) = scripts_app();
154
1
    load(&mut app, &[(SYNC, "sync")])?;
155
1
    app.deliver_script_edit_reply(
156
1
        Some(app.window_of(crate::view::ViewId::Scripts)),
157
1
        &edit_wire(&edit_values(SYNC, "true"), None),
158
1
    );
159
1
    apply(&mut app, Intent::Submit);
160
1
    let request = pending_request(&app)?;
161

            
162
1
    let message = "the script changed since it was loaded; reload it";
163
1
    app.route_reply(request, &rejected(request, "revision", message));
164

            
165
1
    assert_eq!(top_form(&app).errors, [message]);
166
1
    assert!(
167
1
        app.status
168
1
            .ends_with("(close the form and open it again to reload)"),
169
        "{}",
170
        app.status
171
    );
172
1
    assert_eq!(top_form(&app).values().text("name"), Some("sync"));
173
2
    Ok(())
174
1
}
175

            
176
#[tokio::test]
177
1
async fn a_script_that_vanished_shows_not_found_instead_of_the_form() {
178
1
    let (mut app, _) = scripts_app();
179
1
    app.deliver_script_edit_reply(
180
1
        Some(app.window_of(crate::view::ViewId::Scripts)),
181
1
        r#"(:id 1 :error (:code not-found :message "no such script"))"#,
182
1
    );
183
1
    assert!(
184
1
        app.status.starts_with("can't edit this script"),
185
        "{}",
186
        app.status
187
    );
188
1
    assert!(app.overlays.is_empty());
189
1
}
190

            
191
#[tokio::test]
192
1
async fn t_loads_the_script_then_saves_it_with_the_other_state() -> anyhow::Result<()> {
193
1
    let (mut app, sent) = scripts_app();
194
1
    load(&mut app, &[(SYNC, "sync")])?;
195

            
196
1
    press(&mut app, key(KeyCode::Char('t')));
197
1
    let loading = pending(&app, |r| matches!(r, ScriptRoute::Toggle { .. }))
198
        .ok_or_else(|| anyhow::anyhow!("load not sent"))?;
199
1
    let text = echoed(&mut app, &sent).await;
200
1
    assert!(
201
1
        text.contains(&format!(r#"(load-form "script-edit" "{SYNC}")"#)),
202
        "{text}"
203
    );
204

            
205
1
    app.route_reply(loading, &edit_wire(&edit_values(SYNC, "true"), None));
206
1
    let saving = pending(&app, |r| matches!(r, ScriptRoute::Toggled { .. }))
207
        .ok_or_else(|| anyhow::anyhow!("save not sent"))?;
208
1
    let text = echoed(&mut app, &sent).await;
209
1
    assert!(
210
1
        text.contains(r#"(submit-form "script-edit" "(:id "#),
211
        "{text}"
212
    );
213
1
    assert!(text.contains(r#":revision \"rev-1\""#), "{text}");
214
1
    assert!(text.contains(r#":enabled \"false\""#), "{text}");
215

            
216
1
    app.route_reply(saving, &created_wire(saving, SYNC));
217
1
    assert_eq!(app.status, "sync disabled");
218
1
    assert!(app.scripts().any_loading());
219
2
    Ok(())
220
1
}
221

            
222
#[tokio::test]
223
1
async fn t_on_a_disabled_script_switches_it_on() -> anyhow::Result<()> {
224
1
    let (mut app, sent) = scripts_app();
225
1
    load_states(&mut app, &[(SYNC, "sync", false, true)])?;
226
1
    press(&mut app, key(KeyCode::Char('t')));
227
1
    let loading = pending(&app, |r| matches!(r, ScriptRoute::Toggle { .. }))
228
        .ok_or_else(|| anyhow::anyhow!("load not sent"))?;
229

            
230
1
    app.route_reply(loading, &edit_wire(&edit_values(SYNC, "false"), None));
231

            
232
1
    let saving = pending(&app, |r| matches!(r, ScriptRoute::Toggled { .. }))
233
        .ok_or_else(|| anyhow::anyhow!("save not sent"))?;
234
1
    let text = echoed(&mut app, &sent).await;
235
1
    assert!(text.contains(r#":enabled \"true\""#), "{text}");
236
1
    app.route_reply(saving, &created_wire(saving, SYNC));
237
1
    assert_eq!(app.status, "sync enabled");
238
2
    Ok(())
239
1
}
240

            
241
#[tokio::test]
242
1
async fn a_stale_toggle_shows_the_servers_refusal() -> anyhow::Result<()> {
243
1
    let (mut app, _) = scripts_app();
244
1
    load(&mut app, &[(SYNC, "sync")])?;
245
1
    press(&mut app, key(KeyCode::Char('t')));
246
1
    let loading = pending(&app, |r| matches!(r, ScriptRoute::Toggle { .. }))
247
        .ok_or_else(|| anyhow::anyhow!("load not sent"))?;
248
1
    app.route_reply(loading, &edit_wire(&edit_values(SYNC, "true"), None));
249
1
    let saving = pending(&app, |r| matches!(r, ScriptRoute::Toggled { .. }))
250
        .ok_or_else(|| anyhow::anyhow!("save not sent"))?;
251

            
252
1
    let message = "the script changed since it was loaded; reload it";
253
1
    app.route_reply(saving, &rejected(saving, "revision", message));
254

            
255
1
    assert_eq!(
256
1
        app.status,
257
1
        format!("can't switch sync: revision: {message}")
258
    );
259
1
    assert!(!app.scripts().any_loading());
260
2
    Ok(())
261
1
}
262

            
263
#[tokio::test]
264
1
async fn a_toggle_whose_load_fails_says_so() -> anyhow::Result<()> {
265
1
    let (mut app, _) = scripts_app();
266
1
    load(&mut app, &[(SYNC, "sync")])?;
267
1
    press(&mut app, key(KeyCode::Char('t')));
268
1
    let loading = pending(&app, |r| matches!(r, ScriptRoute::Toggle { .. }))
269
        .ok_or_else(|| anyhow::anyhow!("load not sent"))?;
270

            
271
1
    app.route_reply(
272
1
        loading,
273
1
        &format!(r#"(:id {loading} :error (:code not-found :message "no such script"))"#),
274
1
    );
275

            
276
1
    assert!(
277
1
        app.status.starts_with("can't switch sync: no such script"),
278
        "{}",
279
        app.status
280
    );
281
1
    assert!(pending(&app, |r| matches!(r, ScriptRoute::Toggled { .. })).is_none());
282
2
    Ok(())
283
1
}