simpleplatform_sdk/
testing.rs1use std::cell::RefCell;
76use std::rc::Rc;
77
78use serde_json::{json, Value};
79
80use crate::error::Error;
81use crate::host::{self, Transport, DONE};
82use crate::run::Context;
83
84#[derive(Clone, Debug)]
86pub struct Call {
87 pub name: String,
89 pub params: Value,
91}
92
93#[derive(Default)]
95struct Recorder {
96 calls: RefCell<Vec<Call>>,
97 done: RefCell<Option<Value>>,
98 request: RefCell<String>,
99 context: RefCell<Context>,
100}
101
102struct Mock {
104 reply: Box<dyn Fn(String, Value) -> Result<Value, Error>>,
105 recorder: Rc<Recorder>,
106}
107
108impl Transport for Mock {
109 fn call(&self, name: String, params: Value) -> Result<Value, Error> {
116 if let Ok(mut calls) = self.recorder.calls.try_borrow_mut() {
117 calls.push(Call {
118 name: name.clone(),
119 params: params.clone(),
120 });
121 }
122
123 let reply = match (self.reply)(name.clone(), params) {
124 Ok(data) => json!({ "ok": true, "data": data }),
125 Err(refusal) => json!({ "ok": false, "error": { "message": refusal.message() } }),
126 };
127
128 host::unwrap_reply(&name, reply)
129 }
130
131 fn cast(&self, name: String, params: Value) {
132 if name == DONE {
133 if let Ok(mut done) = self.recorder.done.try_borrow_mut() {
134 *done = Some(params);
135 }
136
137 return;
138 }
139
140 if let Ok(mut calls) = self.recorder.calls.try_borrow_mut() {
141 calls.push(Call { name, params });
142 }
143 }
144
145 fn context(&self) -> Option<String> {
146 let request = self.recorder.request.try_borrow().ok()?.clone();
147 let context = self.recorder.context.try_borrow().ok()?.clone();
148
149 Some(
150 json!({
151 "context": context,
152 "data": request,
153 "headers": {},
154 })
155 .to_string(),
156 )
157 }
158}
159
160pub struct Session {
166 recorder: Rc<Recorder>,
167}
168
169impl Session {
170 pub fn calls(&self) -> Vec<Call> {
174 self.recorder
175 .calls
176 .try_borrow()
177 .map(|calls| calls.clone())
178 .unwrap_or_default()
179 }
180
181 pub fn done(&self) -> Option<Value> {
183 self.recorder
184 .done
185 .try_borrow()
186 .ok()
187 .and_then(|done| done.clone())
188 }
189
190 pub fn with_request(self, data: Value) -> Session {
192 if let Ok(mut request) = self.recorder.request.try_borrow_mut() {
193 *request = data.to_string();
194 }
195
196 self
197 }
198
199 pub fn with_context(self, context: Context) -> Session {
201 if let Ok(mut slot) = self.recorder.context.try_borrow_mut() {
202 *slot = context;
203 }
204
205 self
206 }
207}
208
209impl Drop for Session {
210 fn drop(&mut self) {
211 host::set(None);
212 }
213}
214
215pub fn install<F>(reply: F) -> Session
220where
221 F: Fn(String, Value) -> Result<Value, Error> + 'static,
222{
223 let recorder = Rc::new(Recorder {
224 request: RefCell::new("null".to_string()),
225 ..Recorder::default()
226 });
227
228 host::set(Some(Rc::new(Mock {
229 reply: Box::new(reply),
230 recorder: Rc::clone(&recorder),
231 })));
232
233 Session { recorder }
234}
235
236#[cfg(test)]
237mod tests {
238 use super::*;
239 use crate::run::Request;
240
241 #[test]
242 fn a_session_records_what_it_was_asked() {
243 let session = install(|_name, _params| Ok(json!({ "rows": [] })));
244
245 let _: Value = crate::graphql::query("query Q { rows { a } }", json!({ "x": 1 })).unwrap();
246
247 let calls = session.calls();
248
249 assert_eq!(calls.len(), 1);
250 assert_eq!(calls[0].name, "action:db/execute");
251 assert_eq!(calls[0].params["variables"], json!({ "x": 1 }));
252 }
253
254 #[test]
255 fn a_refusing_host_reaches_the_caller_as_an_error() {
256 let _session = install(|_name, _params| Err(Error::denied("nope")));
257
258 let error = crate::graphql::query::<Value>("query Q { a }", json!({})).unwrap_err();
259
260 assert!(error.message().contains("nope"));
261 }
262
263 #[test]
264 fn the_slot_is_empty_once_the_session_is_dropped() {
265 {
266 let _session = install(|_name, _params| Ok(json!(null)));
267 assert!(host::transport().is_ok());
268 }
269
270 assert!(host::transport().is_err());
271 }
272
273 #[test]
274 fn run_reports_a_success_envelope() {
275 let session = install(|_name, _params| Ok(json!(null))).with_request(json!({ "a": 1 }));
276
277 crate::run(|request: Request<Value>| Ok(json!({ "seen": request.data })));
278
279 assert_eq!(
280 session.done().unwrap(),
281 json!({ "data": { "seen": { "a": 1 } }, "errors": [], "ok": true })
282 );
283 }
284
285 #[test]
286 fn run_reports_a_failure_envelope_and_still_says_ok() {
287 let session = install(|_name, _params| Ok(json!(null))).with_request(json!({}));
288
289 crate::run(|_request: Request<Value>| {
290 Err::<Value, Error>(Error::invalid("no id").hint("Send an id."))
291 });
292
293 let done = session.done().unwrap();
294
295 assert_eq!(done["ok"], json!(true));
296 assert_eq!(
297 done["data"]["error"]["extensions"]["code"],
298 json!("INVALID_TOOL_INPUT")
299 );
300 assert_eq!(
301 done["data"]["error"]["extensions"]["retryable"],
302 json!(false)
303 );
304 assert_eq!(
305 done["data"]["error"]["extensions"]["hint"],
306 json!("Send an id.")
307 );
308 }
309
310 #[test]
311 fn run_reports_exactly_once_even_when_the_handler_panics() {
312 let session = install(|_name, _params| Ok(json!(null))).with_request(json!({}));
313
314 crate::run(|_request: Request<Value>| -> Result<Value, Error> {
315 panic!("the action fell over")
316 });
317
318 let done = session.done().unwrap();
319
320 assert!(done["data"]["error"]["message"]
321 .as_str()
322 .unwrap()
323 .contains("the action fell over"));
324 }
325
326 #[test]
327 fn a_payload_that_does_not_match_never_reaches_the_handler() {
328 let session = install(|_name, _params| Ok(json!(null))).with_request(json!({ "a": 1 }));
329
330 #[derive(Debug, serde::Deserialize)]
331 struct Needs {
332 #[allow(dead_code)]
333 required: String,
334 }
335
336 crate::run(|_request: Request<Needs>| -> Result<Value, Error> {
337 panic!("the handler must not run")
338 });
339
340 assert_eq!(
341 session.done().unwrap()["data"]["error"]["extensions"]["code"],
342 json!("INVALID_TOOL_INPUT")
343 );
344 }
345
346 #[test]
347 fn the_context_the_session_was_given_reaches_the_handler() {
348 let mut context = Context::default();
349 context.logic.execution_id = "EXEC9".to_string();
350 context.tenant.name = "acme".to_string();
351
352 let session = install(|_name, _params| Ok(json!(null)))
353 .with_request(json!({}))
354 .with_context(context);
355
356 crate::run(|request: Request<Value>| {
357 Ok(json!({
358 "execution": request.context.logic.execution_id,
359 "tenant": request.context.tenant.name,
360 }))
361 });
362
363 assert_eq!(
364 session.done().unwrap()["data"],
365 json!({ "execution": "EXEC9", "tenant": "acme" })
366 );
367 }
368}