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/// The shared middle of a session: what the transport writes and the test reads.
94#[derive(Default)]
95struct Recorder {
96    calls: RefCell<Vec<Call>>,
97    done: RefCell<Option<Value>>,
98    request: RefCell<String>,
99    context: RefCell<Context>,
100}
101
102/// A host that answers from a closure and remembers what it was asked.
103struct Mock {
104    reply: Box<dyn Fn(String, Value) -> Result<Value, Error>>,
105    recorder: Rc<Recorder>,
106}
107
108impl Transport for Mock {
109    /// The closure's answer, wrapped in the envelope a host would have sent and
110    /// then unwrapped by the same code the guest uses.
111    ///
112    /// Going the long way round is deliberate: a test exercises the same reply
113    /// ladder that runs in production, so what it proves about a handler holds
114    /// for the handler as shipped.
115    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
160/// An installed host, for as long as this value is alive.
161///
162/// Dropping it empties the slot, so a session cannot outlive the test that made
163/// it. Hold it in a binding — `let session = ...` or `let _session = ...` — and
164/// not in `let _ = ...`, which drops it immediately.
165pub struct Session {
166    recorder: Rc<Recorder>,
167}
168
169impl Session {
170    /// Everything the code under test asked the host for, in order.
171    ///
172    /// The `__done__` report is not among them; it is [`Session::done`].
173    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    /// The `__done__` document, once [`crate::run`] has reported one.
182    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    /// The payload [`crate::run`] will hand the handler.
191    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    /// The execution context [`crate::run`] will hand the handler.
200    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
215/// Install a host for this thread that answers from `reply`.
216///
217/// `reply` is handed the action name and its parameters, and answers with the
218/// data the host would have produced or an [`Error`] for a host that refused.
219pub 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}