Skip to main content

simpleplatform_sdk/
testing.rs

1//! Running an action on your own machine, with no host and no wasm.
2//!
3//! # Why this is in the SDK and not in your action
4//!
5//! A handler reaches its host through one seam, so the stand-in for that host
6//! belongs beside it. Shipping it here means a test drives the same seam
7//! production drives, and every action gets the same one — kept in step with the
8//! wire format by the crate that defines the wire format.
9//!
10//! # The whole of it
11//!
12//! ```
13//! use simpleplatform_sdk::prelude::*;
14//! use simpleplatform_sdk::testing;
15//!
16//! #[derive(Deserialize)]
17//! struct Input {
18//!     id: String,
19//! }
20//!
21//! fn handler(request: Request<Input>) -> Result<Value, Error> {
22//!     let answer: Value = simple::graphql::query(
23//!         "query One($id: ID!) { thing: app__thing(where: {id: {_eq: $id}}) { id } }",
24//!         json!({ "id": request.data.id }),
25//!     )?;
26//!
27//!     Ok(answer)
28//! }
29//!
30//! let session = testing::install(|name, params| {
31//!     assert_eq!(name, "action:db/execute");
32//!     assert_eq!(params["variables"]["id"], json!("T1"));
33//!
34//!     Ok(json!({ "thing": [{ "id": "T1" }] }))
35//! });
36//!
37//! let answer = handler(Request::new(Input { id: "T1".into() })).unwrap();
38//!
39//! assert_eq!(answer, json!({ "thing": [{ "id": "T1" }] }));
40//! assert_eq!(session.calls().len(), 1);
41//! ```
42//!
43//! The closure answers in *results*, not envelopes: return the data the host
44//! would have produced, or an [`Error`] for a host that refused. Wrapping it in
45//! `{ ok, data }` is this module's job, exactly as unwrapping it is the SDK's
46//! job in production.
47//!
48//! # Testing the envelope as well as the answer
49//!
50//! [`crate::run`] works here too. Give the session a request payload and it will
51//! drive the whole path — parse, handle, report — and keep the `__done__`
52//! document for you to assert on:
53//!
54//! ```
55//! use simpleplatform_sdk::prelude::*;
56//! use simpleplatform_sdk::testing;
57//!
58//! let session = testing::install(|_name, _params| Ok(json!(null)))
59//!     .with_request(json!({ "id": "T1" }));
60//!
61//! simple::run(|request: Request<Value>| Ok(json!({ "echoed": request.data })));
62//!
63//! assert_eq!(
64//!     session.done().unwrap(),
65//!     json!({ "data": { "echoed": { "id": "T1" } }, "errors": [], "ok": true })
66//! );
67//! ```
68//!
69//! # One session per thread
70//!
71//! The slot is thread-local, so tests run in parallel without seeing each
72//! other's hosts. Installing twice on one thread replaces the first; dropping
73//! the session empties the slot.
74
75use 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/// One thing the code under test asked its host for.
85#[derive(Clone, Debug)]
86pub struct Call {
87    /// The action name.
88    pub name: String,
89    /// The parameters, exactly as they were sent.
90    pub params: Value,
91}
92
93/// How a test answers a call whose reply is a run of bytes.
94type BytesReply = Box<dyn Fn(String, Value) -> Result<Vec<u8>, Error>>;
95
96/// The shared middle of a session: what the transport writes and the test reads.
97#[derive(Default)]
98struct Recorder {
99    calls: RefCell<Vec<Call>>,
100    done: RefCell<Option<Value>>,
101    request: RefCell<String>,
102    context: RefCell<Context>,
103    bytes: RefCell<Option<BytesReply>>,
104}
105
106/// A host that answers from a closure and remembers what it was asked.
107struct Mock {
108    reply: Box<dyn Fn(String, Value) -> Result<Value, Error>>,
109    recorder: Rc<Recorder>,
110}
111
112impl Transport for Mock {
113    /// The closure's answer, wrapped in the envelope a host would have sent and
114    /// then unwrapped by the same code the guest uses.
115    ///
116    /// Going the long way round is deliberate: a test exercises the same reply
117    /// ladder that runs in production, so what it proves about a handler holds
118    /// for the handler as shipped.
119    fn call(&self, name: String, params: Value) -> Result<Value, Error> {
120        if let Ok(mut calls) = self.recorder.calls.try_borrow_mut() {
121            calls.push(Call {
122                name: name.clone(),
123                params: params.clone(),
124            });
125        }
126
127        let reply = match (self.reply)(name.clone(), params) {
128            Ok(data) => json!({ "ok": true, "data": data }),
129            Err(refusal) => json!({ "ok": false, "error": { "message": refusal.message() } }),
130        };
131
132        host::unwrap_reply(&name, reply)
133    }
134
135    /// The bytes closure's answer, appended as the real transport appends them.
136    /// A refusal takes the same envelope ladder as [`Mock::call`], so a test
137    /// sees the error production would have raised.
138    fn call_bytes(&self, name: String, params: Value, into: &mut Vec<u8>) -> Result<usize, Error> {
139        if let Ok(mut calls) = self.recorder.calls.try_borrow_mut() {
140            calls.push(Call {
141                name: name.clone(),
142                params: params.clone(),
143            });
144        }
145
146        let answer = match self.recorder.bytes.try_borrow() {
147            Ok(reply) => match reply.as_ref() {
148                Some(reply) => reply(name.clone(), params),
149                None => {
150                    return Err(Error::failed(format!(
151                        "{name} answers with bytes, and this session was given no way to."
152                    ))
153                    .hint("Answer it with Session::with_bytes."))
154                }
155            },
156            Err(_busy) => {
157                return Err(Error::failed(format!(
158                    "{name} was called from inside the session's own reply."
159                )))
160            }
161        };
162
163        match answer {
164            Ok(bytes) => {
165                into.extend_from_slice(&bytes);
166                Ok(bytes.len())
167            }
168            Err(refusal) => host::unwrap_reply(
169                &name,
170                json!({ "ok": false, "error": { "message": refusal.message() } }),
171            )
172            .map(|_never| 0),
173        }
174    }
175
176    fn cast(&self, name: String, params: Value) {
177        if name == DONE {
178            if let Ok(mut done) = self.recorder.done.try_borrow_mut() {
179                *done = Some(params);
180            }
181
182            return;
183        }
184
185        if let Ok(mut calls) = self.recorder.calls.try_borrow_mut() {
186            calls.push(Call { name, params });
187        }
188    }
189
190    fn context(&self) -> Option<String> {
191        let request = self.recorder.request.try_borrow().ok()?.clone();
192        let context = self.recorder.context.try_borrow().ok()?.clone();
193
194        Some(
195            json!({
196                "context": context,
197                "data": request,
198                "headers": {},
199            })
200            .to_string(),
201        )
202    }
203}
204
205/// An installed host, for as long as this value is alive.
206///
207/// Dropping it empties the slot, so a session cannot outlive the test that made
208/// it. Hold it in a binding — `let session = ...` or `let _session = ...` — and
209/// not in `let _ = ...`, which drops it immediately.
210pub struct Session {
211    recorder: Rc<Recorder>,
212}
213
214impl Session {
215    /// Everything the code under test asked the host for, in order.
216    ///
217    /// The `__done__` report is not among them; it is [`Session::done`].
218    pub fn calls(&self) -> Vec<Call> {
219        self.recorder
220            .calls
221            .try_borrow()
222            .map(|calls| calls.clone())
223            .unwrap_or_default()
224    }
225
226    /// The `__done__` document, once [`crate::run`] has reported one.
227    pub fn done(&self) -> Option<Value> {
228        self.recorder
229            .done
230            .try_borrow()
231            .ok()
232            .and_then(|done| done.clone())
233    }
234
235    /// The payload [`crate::run`] will hand the handler.
236    pub fn with_request(self, data: Value) -> Session {
237        if let Ok(mut request) = self.recorder.request.try_borrow_mut() {
238            *request = data.to_string();
239        }
240
241        self
242    }
243
244    /// Answer the calls whose reply is a run of bytes, such as a read of a
245    /// stored file's range, from `reply`.
246    ///
247    /// `reply` is handed the action name and its parameters, and answers with
248    /// the bytes the host would have written or an [`Error`] for a host that
249    /// refused. Every other call is still answered by the closure the session
250    /// was installed with.
251    pub fn with_bytes<F>(self, reply: F) -> Session
252    where
253        F: Fn(String, Value) -> Result<Vec<u8>, Error> + 'static,
254    {
255        if let Ok(mut slot) = self.recorder.bytes.try_borrow_mut() {
256            *slot = Some(Box::new(reply));
257        }
258
259        self
260    }
261
262    /// The execution context [`crate::run`] will hand the handler.
263    pub fn with_context(self, context: Context) -> Session {
264        if let Ok(mut slot) = self.recorder.context.try_borrow_mut() {
265            *slot = context;
266        }
267
268        self
269    }
270}
271
272impl Drop for Session {
273    fn drop(&mut self) {
274        host::set(None);
275    }
276}
277
278/// Install a host for this thread that answers from `reply`.
279///
280/// `reply` is handed the action name and its parameters, and answers with the
281/// data the host would have produced or an [`Error`] for a host that refused.
282pub fn install<F>(reply: F) -> Session
283where
284    F: Fn(String, Value) -> Result<Value, Error> + 'static,
285{
286    let recorder = Rc::new(Recorder {
287        request: RefCell::new("null".to_string()),
288        ..Recorder::default()
289    });
290
291    host::set(Some(Rc::new(Mock {
292        reply: Box::new(reply),
293        recorder: Rc::clone(&recorder),
294    })));
295
296    Session { recorder }
297}
298
299#[cfg(test)]
300mod tests {
301    use super::*;
302    use crate::run::Request;
303
304    #[test]
305    fn a_session_records_what_it_was_asked() {
306        let session = install(|_name, _params| Ok(json!({ "rows": [] })));
307
308        let _: Value = crate::graphql::query("query Q { rows { a } }", json!({ "x": 1 })).unwrap();
309
310        let calls = session.calls();
311
312        assert_eq!(calls.len(), 1);
313        assert_eq!(calls[0].name, "action:db/execute");
314        assert_eq!(calls[0].params["variables"], json!({ "x": 1 }));
315    }
316
317    #[test]
318    fn a_refusing_host_reaches_the_caller_as_an_error() {
319        let _session = install(|_name, _params| Err(Error::denied("nope")));
320
321        let error = crate::graphql::query::<Value>("query Q { a }", json!({})).unwrap_err();
322
323        assert!(error.message().contains("nope"));
324    }
325
326    #[test]
327    fn the_slot_is_empty_once_the_session_is_dropped() {
328        {
329            let _session = install(|_name, _params| Ok(json!(null)));
330            assert!(host::transport().is_ok());
331        }
332
333        assert!(host::transport().is_err());
334    }
335
336    #[test]
337    fn run_reports_a_success_envelope() {
338        let session = install(|_name, _params| Ok(json!(null))).with_request(json!({ "a": 1 }));
339
340        crate::run(|request: Request<Value>| Ok(json!({ "seen": request.data })));
341
342        assert_eq!(
343            session.done().unwrap(),
344            json!({ "data": { "seen": { "a": 1 } }, "errors": [], "ok": true })
345        );
346    }
347
348    #[test]
349    fn run_reports_a_failure_envelope_and_still_says_ok() {
350        let session = install(|_name, _params| Ok(json!(null))).with_request(json!({}));
351
352        crate::run(|_request: Request<Value>| {
353            Err::<Value, Error>(Error::invalid("no id").hint("Send an id."))
354        });
355
356        let done = session.done().unwrap();
357
358        assert_eq!(done["ok"], json!(true));
359        assert_eq!(
360            done["data"]["error"]["extensions"]["code"],
361            json!("INVALID_TOOL_INPUT")
362        );
363        assert_eq!(
364            done["data"]["error"]["extensions"]["retryable"],
365            json!(false)
366        );
367        assert_eq!(
368            done["data"]["error"]["extensions"]["hint"],
369            json!("Send an id.")
370        );
371    }
372
373    #[test]
374    fn run_reports_exactly_once_even_when_the_handler_panics() {
375        let session = install(|_name, _params| Ok(json!(null))).with_request(json!({}));
376
377        crate::run(|_request: Request<Value>| -> Result<Value, Error> {
378            panic!("the action fell over")
379        });
380
381        let done = session.done().unwrap();
382
383        assert!(done["data"]["error"]["message"]
384            .as_str()
385            .unwrap()
386            .contains("the action fell over"));
387    }
388
389    #[test]
390    fn a_payload_that_does_not_match_never_reaches_the_handler() {
391        let session = install(|_name, _params| Ok(json!(null))).with_request(json!({ "a": 1 }));
392
393        #[derive(Debug, serde::Deserialize)]
394        struct Needs {
395            #[allow(dead_code)]
396            required: String,
397        }
398
399        crate::run(|_request: Request<Needs>| -> Result<Value, Error> {
400            panic!("the handler must not run")
401        });
402
403        assert_eq!(
404            session.done().unwrap()["data"]["error"]["extensions"]["code"],
405            json!("INVALID_TOOL_INPUT")
406        );
407    }
408
409    #[test]
410    fn the_context_the_session_was_given_reaches_the_handler() {
411        let mut context = Context::default();
412        context.logic.execution_id = "EXEC9".to_string();
413        context.tenant.name = "acme".to_string();
414
415        let session = install(|_name, _params| Ok(json!(null)))
416            .with_request(json!({}))
417            .with_context(context);
418
419        crate::run(|request: Request<Value>| {
420            Ok(json!({
421                "execution": request.context.logic.execution_id,
422                "tenant": request.context.tenant.name,
423            }))
424        });
425
426        assert_eq!(
427            session.done().unwrap()["data"],
428            json!({ "execution": "EXEC9", "tenant": "acme" })
429        );
430    }
431}