1
//! Request and file handling, value envelopes and the error payloads a form produces.
2

            
3
use super::*;
4
use crate::envelope::ErrorCode;
5
use nomiscript::Number;
6

            
7
#[tokio::test]
8
1
async fn evaluates_arithmetic_and_returns_value_envelope() {
9
1
    let response = handle_form_smoke("(:id 1 :form (+ 1 2))").await;
10
1
    assert_eq!(response, "(:id 1 :value 3)");
11
1
}
12

            
13
#[tokio::test]
14
1
async fn evaluates_nested_arithmetic() {
15
1
    let response = handle_form_smoke("(:id 5 :form (* (+ 1 2) (- 10 4)))").await;
16
1
    assert_eq!(response, "(:id 5 :value 18)");
17
1
}
18

            
19
#[tokio::test]
20
1
async fn print_in_eval_mode_does_not_panic() {
21
    // Regression: PRINT / DISPLAY / NEWLINE / DEBUG lower to `env.log`,
22
    // which was script-mode-only. In eval mode the missing func index used
23
    // to SIGABRT the compiler (`registry.rs` `HashMap[key]`). The eval-mode
24
    // `log` import + the rpc `env.log` host fn now make it compile + run.
25
1
    let response = handle_form_smoke("(:id 1 :form (print \"hi\"))").await;
26
1
    assert!(response.contains(":id 1"), "got: {response}");
27
1
    assert!(!response.contains(":code"), "must not error: {response}");
28
1
}
29

            
30
#[tokio::test]
31
1
async fn dolist_with_print_in_eval_mode_runs() {
32
    // The exact shape from the Metro script that first surfaced the panic.
33
1
    let response = handle_form_smoke("(:id 2 :form (dolist (x (list 1 2 3)) (print x)))").await;
34
1
    assert!(response.contains(":id 2"), "got: {response}");
35
1
    assert!(!response.contains(":code"), "must not error: {response}");
36
1
}
37

            
38
#[tokio::test]
39
1
async fn handle_request_captures_output_and_value() {
40
    // `(print "hi")` writes "hi" to the per-request buffer (via env.log) and
41
    // its own return value is nil; the structured outcome must carry the
42
    // captured text in `output` AND the value payload — the SLYNK mREPL
43
    // renders these as `:write-string` + `:write-values` respectively.
44
1
    let mut session = Session::new(ScriptCtx::new(uuid::Uuid::nil())).expect("Session::new");
45
1
    let outcome = session.handle_request("(print \"hi\")").await;
46
1
    assert!(
47
1
        outcome.output.contains("hi"),
48
        "captured output should contain the printed text, got: {:?}",
49
        outcome.output
50
    );
51
1
    assert!(
52
1
        matches!(outcome.payload, ResponsePayload::Value(_)),
53
1
        "payload should be a Value, got: {:?}",
54
1
        outcome.payload
55
1
    );
56
1
}
57

            
58
#[tokio::test]
59
1
async fn handle_request_value_only_has_empty_output() {
60
1
    let mut session = Session::new(ScriptCtx::new(uuid::Uuid::nil())).expect("Session::new");
61
1
    let outcome = session.handle_request("(+ 1 2)").await;
62
1
    assert!(outcome.output.is_empty(), "got: {:?}", outcome.output);
63
1
    assert_eq!(
64
1
        outcome.payload,
65
1
        ResponsePayload::Value(Value::Number(Number::Index(3)))
66
1
    );
67
1
}
68

            
69
#[tokio::test]
70
1
async fn handle_request_rejects_plist_shaped_injection() {
71
    // Adversarial review: the source must be parsed as a standalone AST, not
72
    // interpolated into a `(:id 0 :form …)` envelope string — otherwise
73
    // `1 :form (+ 2 3)` would re-read as a plist and eval to `1`. It must
74
    // instead error (more than one top-level form), never silently return 1.
75
1
    let mut session = Session::new(ScriptCtx::new(uuid::Uuid::nil())).expect("Session::new");
76
1
    let outcome = session.handle_request("1 :form (+ 2 3)").await;
77
1
    assert!(
78
1
        matches!(outcome.payload, ResponsePayload::Error { .. }),
79
1
        "plist-shaped input must error, got: {:?}",
80
1
        outcome.payload
81
1
    );
82
1
}
83

            
84
#[tokio::test]
85
1
async fn handle_request_interrupt_latch_aborts_before_eval() {
86
    // An interrupt latched before the request (the SLYNK reader arms it on
87
    // `(:emacs-interrupt)`) must abort the eval at the pre-start check, even
88
    // for a form that would otherwise compile fine.
89
1
    let mut session = Session::new(ScriptCtx::new(uuid::Uuid::nil())).expect("Session::new");
90
1
    session.interrupt_handle().interrupt();
91
1
    let outcome = session.handle_request("(+ 1 2)").await;
92
1
    match outcome.payload {
93
1
        ResponsePayload::Error { code, .. } => {
94
1
            assert_eq!(code.as_symbol(), ErrorCode::INTERRUPTED);
95
1
        }
96
1
        other => panic!("expected interrupted error, got: {other:?}"),
97
1
    }
98
1
}
99

            
100
#[tokio::test]
101
1
async fn handle_file_evaluates_all_forms_and_persists_state() {
102
    // A file with a defun + a call to it: state accumulates across forms,
103
    // and the load returns a summary value (not the last form's value).
104
1
    let dir = std::env::temp_dir();
105
1
    let path = dir.join(format!("nms_load_test_{}.nms", std::process::id()));
106
1
    std::fs::write(&path, "(defun dbl (x) (* x 2))\n(dbl 21)\n").unwrap();
107
1
    let mut session = Session::new(ScriptCtx::new(uuid::Uuid::nil())).expect("Session::new");
108
1
    let outcome = session.handle_file(path.to_str().unwrap()).await;
109
1
    std::fs::remove_file(&path).ok();
110
1
    match outcome.payload {
111
1
        ResponsePayload::Value(Value::String(s)) => {
112
1
            assert!(s.contains("loaded"), "summary: {s}");
113
1
            assert!(s.contains("2 forms"), "summary: {s}");
114
1
        }
115
1
        other => panic!("expected a load summary string, got: {other:?}"),
116
1
    }
117
1
}
118

            
119
#[tokio::test]
120
1
async fn handle_file_missing_path_errors() {
121
1
    let mut session = Session::new(ScriptCtx::new(uuid::Uuid::nil())).expect("Session::new");
122
1
    let outcome = session.handle_file("/no/such/nms/file.nms").await;
123
1
    assert!(
124
1
        matches!(outcome.payload, ResponsePayload::Error { .. }),
125
1
        "got: {:?}",
126
1
        outcome.payload
127
1
    );
128
1
}
129

            
130
#[tokio::test]
131
1
async fn handle_file_aborts_on_a_bad_form() {
132
1
    let dir = std::env::temp_dir();
133
1
    let path = dir.join(format!("nms_load_bad_{}.nms", std::process::id()));
134
1
    std::fs::write(&path, "(+ 1 2)\n(undefined-symbol-here)\n").unwrap();
135
1
    let mut session = Session::new(ScriptCtx::new(uuid::Uuid::nil())).expect("Session::new");
136
1
    let outcome = session.handle_file(path.to_str().unwrap()).await;
137
1
    std::fs::remove_file(&path).ok();
138
1
    assert!(
139
1
        matches!(outcome.payload, ResponsePayload::Error { .. }),
140
1
        "a bad form must abort the load, got: {:?}",
141
1
        outcome.payload
142
1
    );
143
1
}
144

            
145
#[tokio::test]
146
1
async fn handle_file_honours_interrupt_armed_before_load() {
147
    // A `C-g` that lands before/during the synchronous read+parse must abort
148
    // the load (the pre-read latch check), not be ignored until the first
149
    // form reaches the Wasm call.
150
1
    let dir = std::env::temp_dir();
151
1
    let path = dir.join(format!("nms_load_intr_{}.nms", std::process::id()));
152
1
    std::fs::write(&path, "(+ 1 2)\n(+ 3 4)\n").unwrap();
153
1
    let mut session = Session::new(ScriptCtx::new(uuid::Uuid::nil())).expect("Session::new");
154
1
    session.interrupt_handle().interrupt();
155
1
    let outcome = session.handle_file(path.to_str().unwrap()).await;
156
1
    std::fs::remove_file(&path).ok();
157
1
    match outcome.payload {
158
1
        ResponsePayload::Error { code, .. } => {
159
1
            assert_eq!(code.as_symbol(), ErrorCode::INTERRUPTED, "got: {code:?}");
160
1
        }
161
1
        other => panic!("interrupt should abort the load, got: {other:?}"),
162
1
    }
163
1
}
164

            
165
#[tokio::test]
166
1
async fn handle_request_surfaces_error_payload() {
167
1
    let mut session = Session::new(ScriptCtx::new(uuid::Uuid::nil())).expect("Session::new");
168
1
    let outcome = session.handle_request("does-not-exist").await;
169
1
    assert!(
170
1
        matches!(outcome.payload, ResponsePayload::Error { .. }),
171
1
        "payload should be an Error, got: {:?}",
172
1
        outcome.payload
173
1
    );
174
1
}
175

            
176
#[tokio::test]
177
1
async fn handle_request_clears_output_between_calls() {
178
    // The buffer must not leak across requests: a print then a pure value.
179
1
    let mut session = Session::new(ScriptCtx::new(uuid::Uuid::nil())).expect("Session::new");
180
1
    let _ = session.handle_request("(print \"first\")").await;
181
1
    let second = session.handle_request("(+ 1 1)").await;
182
1
    assert!(
183
1
        second.output.is_empty(),
184
1
        "output leaked from prior request: {:?}",
185
1
        second.output
186
1
    );
187
1
}
188

            
189
#[tokio::test]
190
1
async fn returns_value_for_literal_form() {
191
1
    let response = handle_form_smoke("(:id 9 :form 42)").await;
192
1
    assert_eq!(response, "(:id 9 :value 42)");
193
1
}
194

            
195
#[tokio::test]
196
1
async fn returns_value_for_string_literal() {
197
1
    let response = handle_form_smoke("(:id 9 :form \"hello\")").await;
198
1
    assert_eq!(response, "(:id 9 :value \"hello\")");
199
1
}
200

            
201
#[test]
202
1
fn round_trips_bytes_through_eval() {
203
1
    let value = parse_to_value("'#u8(1 2 3)").unwrap();
204
1
    assert_eq!(value, Value::Bytes(vec![1, 2, 3]));
205
1
}
206

            
207
#[tokio::test]
208
1
async fn bad_envelope_emits_envelope_error() {
209
1
    let response = handle_form_smoke("(:form (+ 1 2))").await;
210
1
    assert!(response.contains(":code args"));
211
1
    assert!(response.contains(":id 0"));
212
1
}
213

            
214
#[tokio::test]
215
1
async fn malformed_envelope_emits_parse_error() {
216
1
    let response = handle_form_smoke("(((((").await;
217
1
    assert!(response.contains(":code parse"));
218
1
}
219

            
220
#[tokio::test]
221
1
async fn undefined_symbol_emits_compile_error() {
222
1
    let response = handle_form_smoke("(:id 7 :form does-not-exist)").await;
223
1
    assert!(response.contains(":id 7"));
224
1
    assert!(response.contains(":code compile"));
225
1
}
226

            
227
#[tokio::test]
228
1
async fn user_function_arity_violation_emits_args_error() {
229
1
    let mut session = Session::new(ScriptCtx::new(uuid::Uuid::nil())).expect("Session::new");
230
1
    let _ = session
231
1
        .handle_form("(:id 1 :form (defun id-fn (x) x))")
232
1
        .await;
233
1
    let response = session.handle_form("(:id 2 :form (id-fn))").await;
234
1
    assert!(response.contains(":id 2"));
235
1
    assert!(response.contains(":code args"));
236
1
}