Skip to main content

sk_runtime/
testing.rs

1//! The JS runtime for tests: one per process, on one thread. JSC boots once per process, and
2//! `JsRuntime` is thread-affine, so a test that needs JS runs its body on one long-lived thread
3//! ([`on_js_thread`]). Bodies share that thread's global object and thread-locals, so a test sets up
4//! what it reads; a panic in a body fails only that test.
5
6use std::panic::{self, AssertUnwindSafe};
7use std::sync::mpsc;
8use std::sync::{Mutex, OnceLock};
9
10use crate::JsRuntime;
11
12type Job = Box<dyn FnOnce() + Send>;
13
14static JS_THREAD: OnceLock<Mutex<mpsc::Sender<Job>>> = OnceLock::new();
15
16pub fn on_js_thread<R, F>(f: F) -> R
17where
18    F: FnOnce() -> R + Send + 'static,
19    R: Send + 'static,
20{
21    let jobs = JS_THREAD.get_or_init(|| {
22        let (tx, rx) = mpsc::channel::<Job>();
23        std::thread::Builder::new()
24            .name("sk-runtime test JS thread".into())
25            .spawn(move || {
26                JsRuntime::init();
27                for job in rx {
28                    job();
29                }
30            })
31            .expect("could not start the JS test thread");
32        Mutex::new(tx)
33    });
34    let (done, result) = mpsc::sync_channel(1);
35    let job: Job = Box::new(move || {
36        let _ = done.send(panic::catch_unwind(AssertUnwindSafe(f)));
37    });
38    jobs.lock()
39        .unwrap_or_else(|poisoned| poisoned.into_inner())
40        .send(job)
41        .expect("the JS test thread has exited");
42    match result
43        .recv()
44        .expect("the JS test thread exited while running a test body")
45    {
46        Ok(value) => value,
47        Err(payload) => panic::resume_unwind(payload),
48    }
49}