wasm_bindgen_test/rt/mod.rs
1//! Internal-only runtime module used for the `wasm_bindgen_test` crate.
2//!
3//! No API contained in this module will respect semver, these should all be
4//! considered private APIs.
5
6// # Architecture of `wasm_bindgen_test`
7//
8// This module can seem a bit funky, but it's intended to be the runtime support
9// of the `#[wasm_bindgen_test]` macro and be amenable to executing Wasm test
10// suites. The general idea is that for a Wasm test binary there will be a set
11// of functions tagged `#[wasm_bindgen_test]`. It's the job of the runtime
12// support to execute all of these functions, collecting and collating the
13// results.
14//
15// This runtime support works in tandem with the `wasm-bindgen-test-runner`
16// binary as part of the `wasm-bindgen-cli` package.
17//
18// ## High Level Overview
19//
20// Here's a rough and (semi) high level overview of what happens when this crate
21// runs.
22//
23// * First, the user runs `cargo test --target wasm32-unknown-unknown`
24//
25// * Cargo then compiles all the test suites (aka `tests/*.rs`) as Wasm binaries
26// (the `bin` crate type). These binaries all have entry points that are
27// `main` functions, but it's actually not used. The binaries are also
28// compiled with `--test`, which means they're linked to the standard `test`
29// crate, but this crate doesn't work on Wasm and so we bypass it entirely.
30//
31// * Instead of using `#[test]`, which doesn't work, users wrote tests with
32// `#[wasm_bindgen_test]`. This macro expands to a bunch of `#[no_mangle]`
33// functions with known names (currently named `__wbg_test_*`).
34//
35// * Next up, Cargo was configured via its test runner support to execute the
36// `wasm-bindgen-test-runner` binary. Instead of what Cargo normally does,
37// executing `target/wasm32-unknown-unknown/debug/deps/foo-xxxxx.wasm` (which
38// will fail as we can't actually execute was binaries), Cargo will execute
39// `wasm-bindgen-test-runner target/.../foo-xxxxx.wasm`.
40//
41// * The `wasm-bindgen-test-runner` binary takes over. It runs `wasm-bindgen`
42// over the binary, generating JS bindings and such. It also figures out if
43// we're running in node.js or a browser.
44//
45// * The `wasm-bindgen-test-runner` binary generates a JS entry point. This
46// entry point creates a `Context` below. The runner binary also parses the
47// Wasm file and finds all functions that are named `__wbg_test_*`. The
48// generate file gathers up all these functions into an array and then passes
49// them to `Context` below. Note that these functions are passed as *JS
50// values*.
51//
52// * Somehow, the runner then executes the JS file. This may be with node.js, it
53// may serve up files in a server and wait for the user, or it serves up files
54// in a server and starts headless testing.
55//
56// * Testing starts, it loads all the modules using either ES imports or Node
57// `require` statements. Everything is loaded in JS now.
58//
59// * A `Context` is created. The `Context` is forwarded the CLI arguments of the
60// original `wasm-bindgen-test-runner` in an environment specific fashion.
61// This is used for test filters today.
62//
63// * The `Context::run` function is called. Again, the generated JS has gathered
64// all Wasm tests to be executed into a list, and it's passed in here.
65//
66// * Next, `Context::run` returns a `Promise` representing the eventual
67// execution of all the tests. The Rust `Future` that's returned will work
68// with the tests to ensure that everything's executed by the time the
69// `Promise` resolves.
70//
71// * When a test executes, it's executing an entry point generated by
72// `#[wasm_bindgen_test]`. The test informs the `Context` of its name and
73// other metadata, and then `Context::execute_*` function creates a future
74// representing the execution of the test. This feeds back into the future
75// returned by `Context::run` to finish the test suite.
76//
77// * Finally, after all tests are run, the `Context`'s future resolves, prints
78// out all the result, and finishes in JS.
79//
80// ## Other various notes
81//
82// Phew, that was a lot! Some other various bits and pieces you may want to be
83// aware of are throughout the code. These include things like how printing
84// results is different in node vs a browser, or how we even detect if we're in
85// node or a browser.
86//
87// Overall this is all somewhat in flux as it's pretty new, and feedback is
88// always of course welcome!
89
90use alloc::borrow::ToOwned;
91use alloc::boxed::Box;
92use alloc::format;
93use alloc::rc::Rc;
94use alloc::string::{String, ToString};
95use alloc::vec::Vec;
96use core::cell::{Cell, RefCell};
97use core::fmt::{self, Display};
98use core::future::Future;
99use core::panic::AssertUnwindSafe;
100use core::pin::Pin;
101use core::task::{self, Poll};
102use js_sys::{Array, Function, Promise};
103pub use wasm_bindgen;
104use wasm_bindgen::prelude::*;
105use wasm_bindgen_futures::future_to_promise;
106
107// Maximum number of tests to execute concurrently. Eventually this should be a
108// configuration option specified at runtime or at compile time rather than
109// baked in here.
110//
111// Currently the default is 1 because the DOM has a lot of shared state, and
112// conccurrently doing things by default would likely end up in a bad situation.
113const CONCURRENCY: usize = 1;
114
115pub mod browser;
116
117/// A modified `criterion.rs`, retaining only the basic benchmark capabilities.
118#[cfg_attr(wasm_bindgen_unstable_test_coverage, coverage(off))]
119pub mod criterion;
120pub mod detect;
121pub mod node;
122mod scoped_tls;
123/// Directly depending on wasm-bindgen-test-based libraries should be avoided,
124/// as it creates a circular dependency that breaks their usage within `wasm-bindgen-test`.
125///
126/// Let's copy web-time.
127#[cfg_attr(wasm_bindgen_unstable_test_coverage, coverage(off))]
128pub(crate) mod web_time;
129pub mod worker;
130
131/// Runtime test harness support instantiated in JS.
132///
133/// The node.js entry script instantiates a `Context` here which is used to
134/// drive test execution.
135#[wasm_bindgen(js_name = WasmBindgenTestContext)]
136pub struct Context {
137 state: Rc<State>,
138}
139
140struct State {
141 /// In Benchmark
142 is_bench: bool,
143
144 /// Include ignored tests.
145 include_ignored: Cell<bool>,
146
147 /// Counter of the number of tests that have succeeded.
148 succeeded_count: Cell<usize>,
149
150 /// Number of tests that have been filtered.
151 filtered_count: Cell<usize>,
152
153 /// Number of tests that have been ignored.
154 ignored_count: Cell<usize>,
155
156 /// A list of all tests which have failed.
157 ///
158 /// Each test listed here is paired with a `JsValue` that represents the
159 /// exception thrown which caused the test to fail.
160 failures: RefCell<Vec<(Test, Failure)>>,
161
162 /// Remaining tests to execute, when empty we're just waiting on the
163 /// `Running` tests to finish.
164 remaining: RefCell<Vec<Test>>,
165
166 /// List of currently executing tests. These tests all involve some level
167 /// of asynchronous work, so they're sitting on the running list.
168 running: RefCell<Vec<Test>>,
169
170 /// How to actually format output, either node.js or browser-specific
171 /// implementation.
172 formatter: Box<dyn Formatter>,
173
174 /// Timing the total duration.
175 timer: Option<Timer>,
176}
177
178/// Failure reasons.
179enum Failure {
180 /// Normal failing test.
181 Error(JsValue),
182 /// A test that `should_panic` but didn't.
183 ShouldPanic,
184 /// A test that `should_panic` with a specific message,
185 /// but panicked with a different message.
186 ShouldPanicExpected,
187}
188
189/// Representation of one test that needs to be executed.
190///
191/// Tests are all represented as futures, and tests perform no work until their
192/// future is polled.
193struct Test {
194 name: String,
195 future: Pin<Box<dyn Future<Output = Result<(), JsValue>>>>,
196 output: Rc<RefCell<Output>>,
197 should_panic: Option<Option<&'static str>>,
198}
199
200/// Captured output of each test.
201#[derive(Default)]
202struct Output {
203 debug: String,
204 log: String,
205 info: String,
206 warn: String,
207 error: String,
208 panic: String,
209 should_panic: bool,
210}
211
212enum TestResult {
213 Ok,
214 Err(JsValue),
215 Ignored(Option<String>),
216}
217
218impl From<Result<(), JsValue>> for TestResult {
219 fn from(value: Result<(), JsValue>) -> Self {
220 match value {
221 Ok(()) => Self::Ok,
222 Err(err) => Self::Err(err),
223 }
224 }
225}
226
227impl Display for TestResult {
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 match self {
230 TestResult::Ok => write!(f, "ok"),
231 TestResult::Err(_) => write!(f, "FAIL"),
232 TestResult::Ignored(None) => write!(f, "ignored"),
233 TestResult::Ignored(Some(reason)) => write!(f, "ignored, {}", reason),
234 }
235 }
236}
237
238trait Formatter {
239 /// Writes a line of output, typically status information.
240 fn writeln(&self, line: &str);
241
242 /// Log the result of a test, either passing or failing.
243 fn log_test(&self, is_bench: bool, name: &str, result: &TestResult) {
244 if !is_bench {
245 self.writeln(&format!("test {} ... {}", name, result));
246 }
247 }
248
249 /// Convert a thrown value into a string, using platform-specific apis
250 /// perhaps to turn the error into a string.
251 fn stringify_error(&self, val: &JsValue) -> String;
252}
253
254#[wasm_bindgen]
255extern "C" {
256 #[wasm_bindgen(js_namespace = console, js_name = log)]
257 #[doc(hidden)]
258 pub fn js_console_log(s: &str);
259
260 #[wasm_bindgen(js_namespace = console, js_name = error)]
261 #[doc(hidden)]
262 pub fn js_console_error(s: &str);
263
264 // General-purpose conversion into a `String`.
265 #[wasm_bindgen(js_name = String)]
266 fn stringify(val: &JsValue) -> String;
267
268 type Global;
269
270 #[wasm_bindgen(method, getter)]
271 fn performance(this: &Global) -> JsValue;
272
273 /// Type for the [`Performance` object](https://developer.mozilla.org/en-US/docs/Web/API/Performance).
274 type Performance;
275
276 /// Binding to [`Performance.now()`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now).
277 #[wasm_bindgen(method)]
278 fn now(this: &Performance) -> f64;
279}
280
281/// Internal implementation detail of the `console_log!` macro.
282pub fn console_log(args: &fmt::Arguments) {
283 js_console_log(&args.to_string());
284}
285
286/// Internal implementation detail of the `console_error!` macro.
287pub fn console_error(args: &fmt::Arguments) {
288 js_console_error(&args.to_string());
289}
290
291#[wasm_bindgen(js_class = WasmBindgenTestContext)]
292impl Context {
293 /// Creates a new context ready to run tests.
294 ///
295 /// A `Context` is the main structure through which test execution is
296 /// coordinated, and this will collect output and results for all executed
297 /// tests.
298 #[wasm_bindgen(constructor)]
299 pub fn new(is_bench: bool) -> Context {
300 fn panic_handling(mut message: String) {
301 let should_panic = if !CURRENT_OUTPUT.is_set() {
302 false
303 } else {
304 CURRENT_OUTPUT.with(|output| {
305 let mut output = output.borrow_mut();
306 output.panic.push_str(&message);
307 output.should_panic
308 })
309 };
310
311 // See https://github.com/rustwasm/console_error_panic_hook/blob/4dc30a5448ed3ffcfb961b1ad54d000cca881b84/src/lib.rs#L83-L123.
312 if !should_panic {
313 #[wasm_bindgen]
314 extern "C" {
315 type Error;
316
317 #[wasm_bindgen(constructor)]
318 fn new() -> Error;
319
320 #[wasm_bindgen(method, getter)]
321 fn stack(error: &Error) -> String;
322 }
323
324 message.push_str("\n\nStack:\n\n");
325 let e = Error::new();
326 message.push_str(&e.stack());
327
328 message.push_str("\n\n");
329
330 js_console_error(&message);
331 }
332 }
333 #[cfg(feature = "std")]
334 static SET_HOOK: std::sync::Once = std::sync::Once::new();
335 #[cfg(feature = "std")]
336 SET_HOOK.call_once(|| {
337 std::panic::set_hook(Box::new(|panic_info| {
338 panic_handling(panic_info.to_string());
339 }));
340 });
341 #[cfg(not(feature = "std"))]
342 #[panic_handler]
343 fn panic_handler(panic_info: &core::panic::PanicInfo<'_>) -> ! {
344 panic_handling(panic_info.to_string());
345 unreachable!();
346 }
347
348 let formatter = match detect::detect() {
349 detect::Runtime::Browser => Box::new(browser::Browser::new()) as Box<dyn Formatter>,
350 detect::Runtime::Node => Box::new(node::Node::new()) as Box<dyn Formatter>,
351 detect::Runtime::Worker => Box::new(worker::Worker::new()) as Box<dyn Formatter>,
352 };
353
354 let timer = Timer::new();
355
356 Context {
357 state: Rc::new(State {
358 is_bench,
359 include_ignored: Default::default(),
360 failures: Default::default(),
361 succeeded_count: Default::default(),
362 filtered_count: Default::default(),
363 ignored_count: Default::default(),
364 remaining: Default::default(),
365 running: Default::default(),
366 formatter,
367 timer,
368 }),
369 }
370 }
371
372 /// Handle `--include-ignored` flag.
373 pub fn include_ignored(&mut self, include_ignored: bool) {
374 self.state.include_ignored.set(include_ignored);
375 }
376
377 /// Handle filter argument.
378 pub fn filtered_count(&mut self, filtered: usize) {
379 self.state.filtered_count.set(filtered);
380 }
381
382 /// Executes a list of tests, returning a promise representing their
383 /// eventual completion.
384 ///
385 /// This is the main entry point for executing tests. All the tests passed
386 /// in are the JS `Function` object that was plucked off the
387 /// `WebAssembly.Instance` exports list.
388 ///
389 /// The promise returned resolves to either `true` if all tests passed or
390 /// `false` if at least one test failed.
391 pub fn run(&self, tests: Vec<JsValue>) -> Promise {
392 if !self.state.is_bench {
393 let noun = if tests.len() == 1 { "test" } else { "tests" };
394 self.state
395 .formatter
396 .writeln(&format!("running {} {}", tests.len(), noun));
397 }
398
399 // Execute all our test functions through their Wasm shims (unclear how
400 // to pass native function pointers around here). Each test will
401 // execute one of the `execute_*` tests below which will push a
402 // future onto our `remaining` list, which we'll process later.
403 let cx_arg = (self as *const Context as u32).into();
404 for test in tests {
405 match Function::from(test).call1(&JsValue::null(), &cx_arg) {
406 Ok(_) => {}
407 Err(e) => {
408 panic!(
409 "exception thrown while creating a test: {}",
410 self.state.formatter.stringify_error(&e)
411 );
412 }
413 }
414 }
415
416 // Now that we've collected all our tests we wrap everything up in a
417 // future to actually do all the processing, and pass it out to JS as a
418 // `Promise`.
419 let state = AssertUnwindSafe(self.state.clone());
420 future_to_promise(async {
421 let passed = ExecuteTests(state).await;
422 Ok(JsValue::from(passed))
423 })
424 }
425}
426
427crate::scoped_thread_local!(static CURRENT_OUTPUT: RefCell<Output>);
428
429/// Handler for `console.log` invocations.
430///
431/// If a test is currently running it takes the `args` array and stringifies
432/// it and appends it to the current output of the test. Otherwise it passes
433/// the arguments to the original `console.log` function, psased as
434/// `original`.
435//
436// TODO: how worth is it to actually capture the output here? Due to the nature
437// of futures/js we can't guarantee that all output is captured because JS code
438// could just be executing in the void and we wouldn't know which test to
439// attach it to. The main `test` crate in the rust repo also has issues about
440// how not all output is captured, causing some inconsistencies sometimes.
441#[wasm_bindgen]
442pub fn __wbgtest_console_log(args: &Array) {
443 record(args, |output| &mut output.log)
444}
445
446/// Handler for `console.debug` invocations. See above.
447#[wasm_bindgen]
448pub fn __wbgtest_console_debug(args: &Array) {
449 record(args, |output| &mut output.debug)
450}
451
452/// Handler for `console.info` invocations. See above.
453#[wasm_bindgen]
454pub fn __wbgtest_console_info(args: &Array) {
455 record(args, |output| &mut output.info)
456}
457
458/// Handler for `console.warn` invocations. See above.
459#[wasm_bindgen]
460pub fn __wbgtest_console_warn(args: &Array) {
461 record(args, |output| &mut output.warn)
462}
463
464/// Handler for `console.error` invocations. See above.
465#[wasm_bindgen]
466pub fn __wbgtest_console_error(args: &Array) {
467 record(args, |output| &mut output.error)
468}
469
470fn record(args: &Array, dst: impl FnOnce(&mut Output) -> &mut String) {
471 if !CURRENT_OUTPUT.is_set() {
472 return;
473 }
474
475 CURRENT_OUTPUT.with(|output| {
476 let mut out = output.borrow_mut();
477 let dst = dst(&mut out);
478 args.for_each(&mut |val, idx, _array| {
479 if idx != 0 {
480 dst.push(' ');
481 }
482 dst.push_str(&stringify(&val));
483 });
484 dst.push('\n');
485 });
486}
487
488/// Similar to [`std::process::Termination`], but for wasm-bindgen tests.
489pub trait Termination {
490 /// Convert this into a JS result.
491 fn into_js_result(self) -> Result<(), JsValue>;
492}
493
494impl Termination for () {
495 fn into_js_result(self) -> Result<(), JsValue> {
496 Ok(())
497 }
498}
499
500impl<E: core::fmt::Debug> Termination for Result<(), E> {
501 fn into_js_result(self) -> Result<(), JsValue> {
502 self.map_err(|e| JsError::new(&format!("{:?}", e)).into())
503 }
504}
505
506impl Context {
507 /// Entry point for a synchronous test in wasm. The `#[wasm_bindgen_test]`
508 /// macro generates invocations of this method.
509 pub fn execute_sync<T: Termination>(
510 &self,
511 name: &str,
512 f: impl 'static + FnOnce() -> T,
513 should_panic: Option<Option<&'static str>>,
514 ignore: Option<Option<&'static str>>,
515 ) {
516 self.execute(name, async { f().into_js_result() }, should_panic, ignore);
517 }
518
519 /// Entry point for an asynchronous in wasm. The
520 /// `#[wasm_bindgen_test(async)]` macro generates invocations of this
521 /// method.
522 pub fn execute_async<F>(
523 &self,
524 name: &str,
525 f: impl FnOnce() -> F + 'static,
526 should_panic: Option<Option<&'static str>>,
527 ignore: Option<Option<&'static str>>,
528 ) where
529 F: Future + 'static,
530 F::Output: Termination,
531 {
532 self.execute(
533 name,
534 async { f().await.into_js_result() },
535 should_panic,
536 ignore,
537 )
538 }
539
540 fn execute(
541 &self,
542 name: &str,
543 test: impl Future<Output = Result<(), JsValue>> + 'static,
544 should_panic: Option<Option<&'static str>>,
545 ignore: Option<Option<&'static str>>,
546 ) {
547 // Remove the crate name to mimic libtest more closely.
548 // This also removes our `__wbgt_` or `__wbgb_` prefix and the `ignored` and `should_panic` modifiers.
549 let name = name.split_once("::").unwrap().1;
550
551 if let Some(ignore) = ignore {
552 if !self.state.include_ignored.get() {
553 self.state.formatter.log_test(
554 self.state.is_bench,
555 name,
556 &TestResult::Ignored(ignore.map(str::to_owned)),
557 );
558 let ignored = self.state.ignored_count.get();
559 self.state.ignored_count.set(ignored + 1);
560 return;
561 }
562 }
563
564 // Looks like we've got a test that needs to be executed! Push it onto
565 // the list of remaining tests.
566 let output = Output {
567 should_panic: should_panic.is_some(),
568 ..Default::default()
569 };
570 let output = Rc::new(RefCell::new(output));
571 let future = TestFuture {
572 output: output.clone(),
573 test,
574 };
575 self.state.remaining.borrow_mut().push(Test {
576 name: name.to_string(),
577 future: Pin::from(Box::new(future)),
578 output,
579 should_panic,
580 });
581 }
582}
583
584struct ExecuteTests(AssertUnwindSafe<Rc<State>>);
585
586impl Future for ExecuteTests {
587 type Output = bool;
588
589 fn poll(self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<bool> {
590 let mut running = self.0.running.borrow_mut();
591 let mut remaining = self.0.remaining.borrow_mut();
592
593 // First up, try to make progress on all active tests. Remove any
594 // finished tests.
595 for i in (0..running.len()).rev() {
596 let result = match running[i].future.as_mut().poll(cx) {
597 Poll::Ready(result) => result,
598 Poll::Pending => continue,
599 };
600 let test = running.remove(i);
601 self.0.log_test_result(test, result.into());
602 }
603
604 // Next up, try to schedule as many tests as we can. Once we get a test
605 // we `poll` it once to ensure we'll receive notifications. We only
606 // want to schedule up to a maximum amount of work though, so this may
607 // not schedule all tests.
608 while running.len() < CONCURRENCY {
609 let mut test = match remaining.pop() {
610 Some(test) => test,
611 None => break,
612 };
613 let result = match test.future.as_mut().poll(cx) {
614 Poll::Ready(result) => result,
615 Poll::Pending => {
616 running.push(test);
617 continue;
618 }
619 };
620 self.0.log_test_result(test, result.into());
621 }
622
623 // Tests are still executing, we're registered to get a notification,
624 // keep going.
625 if !running.is_empty() {
626 return Poll::Pending;
627 }
628
629 // If there are no tests running then we must have finished everything,
630 // so we shouldn't have any more remaining tests either.
631 assert_eq!(remaining.len(), 0);
632
633 self.0.print_results();
634 let all_passed = self.0.failures.borrow().is_empty();
635 Poll::Ready(all_passed)
636 }
637}
638
639impl State {
640 fn log_test_result(&self, test: Test, result: TestResult) {
641 // Save off the test for later processing when we print the final
642 // results.
643 if let Some(should_panic) = test.should_panic {
644 if let TestResult::Err(_e) = result {
645 if let Some(expected) = should_panic {
646 if !test.output.borrow().panic.contains(expected) {
647 self.formatter.log_test(
648 self.is_bench,
649 &test.name,
650 &TestResult::Err(JsValue::NULL),
651 );
652 self.failures
653 .borrow_mut()
654 .push((test, Failure::ShouldPanicExpected));
655 return;
656 }
657 }
658
659 self.formatter
660 .log_test(self.is_bench, &test.name, &TestResult::Ok);
661 self.succeeded_count.set(self.succeeded_count.get() + 1);
662 } else {
663 self.formatter
664 .log_test(self.is_bench, &test.name, &TestResult::Err(JsValue::NULL));
665 self.failures
666 .borrow_mut()
667 .push((test, Failure::ShouldPanic));
668 }
669 } else {
670 self.formatter.log_test(self.is_bench, &test.name, &result);
671
672 match result {
673 TestResult::Ok => self.succeeded_count.set(self.succeeded_count.get() + 1),
674 TestResult::Err(e) => self.failures.borrow_mut().push((test, Failure::Error(e))),
675 _ => (),
676 }
677 }
678 }
679
680 fn print_results(&self) {
681 let failures = self.failures.borrow();
682 if !failures.is_empty() {
683 self.formatter.writeln("\nfailures:\n");
684 for (test, failure) in failures.iter() {
685 self.print_failure(test, failure);
686 }
687 self.formatter.writeln("failures:\n");
688 for (test, _) in failures.iter() {
689 self.formatter.writeln(&format!(" {}", test.name));
690 }
691 }
692 let finished_in = if let Some(timer) = &self.timer {
693 format!("; finished in {:.2?}s", timer.elapsed())
694 } else {
695 String::new()
696 };
697 self.formatter.writeln("");
698 self.formatter.writeln(&format!(
699 "test result: {}. \
700 {} passed; \
701 {} failed; \
702 {} ignored; \
703 {} filtered out\
704 {}\n",
705 if failures.is_empty() { "ok" } else { "FAILED" },
706 self.succeeded_count.get(),
707 failures.len(),
708 self.ignored_count.get(),
709 self.filtered_count.get(),
710 finished_in,
711 ));
712 }
713
714 fn accumulate_console_output(&self, logs: &mut String, which: &str, output: &str) {
715 if output.is_empty() {
716 return;
717 }
718 logs.push_str(which);
719 logs.push_str(" output:\n");
720 logs.push_str(&tab(output));
721 logs.push('\n');
722 }
723
724 fn print_failure(&self, test: &Test, failure: &Failure) {
725 let mut logs = String::new();
726 let output = test.output.borrow();
727
728 match failure {
729 Failure::ShouldPanic => {
730 logs.push_str(&format!(
731 "note: {} did not panic as expected\n\n",
732 test.name
733 ));
734 }
735 Failure::ShouldPanicExpected => {
736 logs.push_str("note: panic did not contain expected string\n");
737 logs.push_str(&format!(" panic message: `\"{}\"`,\n", output.panic));
738 logs.push_str(&format!(
739 " expected substring: `\"{}\"`\n\n",
740 test.should_panic.unwrap().unwrap()
741 ));
742 }
743 _ => (),
744 }
745
746 self.accumulate_console_output(&mut logs, "debug", &output.debug);
747 self.accumulate_console_output(&mut logs, "log", &output.log);
748 self.accumulate_console_output(&mut logs, "info", &output.info);
749 self.accumulate_console_output(&mut logs, "warn", &output.warn);
750 self.accumulate_console_output(&mut logs, "error", &output.error);
751
752 if let Failure::Error(error) = failure {
753 logs.push_str("JS exception that was thrown:\n");
754 let error_string = self.formatter.stringify_error(error);
755 logs.push_str(&tab(&error_string));
756 }
757
758 let msg = format!("---- {} output ----\n{}", test.name, tab(&logs));
759 self.formatter.writeln(&msg);
760 }
761}
762
763/// A wrapper future around each test
764///
765/// This future is what's actually executed for each test and is what's stored
766/// inside of a `Test`. This wrapper future performs two critical functions:
767///
768/// * First, every time when polled, it configures the `CURRENT_OUTPUT` tls
769/// variable to capture output for the current test. That way at least when
770/// we've got Rust code running we'll be able to capture output.
771///
772/// * Next, this "catches panics". Right now all Wasm code is configured as
773/// panic=abort, but it's more like an exception in JS. It's pretty sketchy
774/// to actually continue executing Rust code after an "abort", but we don't
775/// have much of a choice for now.
776///
777/// Panics are caught here by using a shim function that is annotated with
778/// `catch` so we can capture JS exceptions (which Rust panics become). This
779/// way if any Rust code along the execution of a test panics we'll hopefully
780/// capture it.
781///
782/// Note that both of the above aspects of this future are really just best
783/// effort. This is all a bit of a hack right now when it comes down to it and
784/// it definitely won't work in some situations. Hopefully as those situations
785/// arise though we can handle them!
786///
787/// The good news is that everything should work flawlessly in the case where
788/// tests have no output and execute successfully. And everyone always writes
789/// perfect code on the first try, right? *sobs*
790struct TestFuture<F> {
791 output: Rc<RefCell<Output>>,
792 test: F,
793}
794
795#[wasm_bindgen]
796extern "C" {
797 #[wasm_bindgen(catch)]
798 fn __wbg_test_invoke(f: &mut dyn FnMut()) -> Result<(), JsValue>;
799}
800
801impl<F: Future<Output = Result<(), JsValue>>> Future for TestFuture<F> {
802 type Output = F::Output;
803
804 fn poll(self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<Self::Output> {
805 let output = self.output.clone();
806 // Use `new_unchecked` here to project our own pin, and we never
807 // move `test` so this should be safe
808 let test = unsafe { Pin::map_unchecked_mut(self, |me| &mut me.test) };
809 let mut future_output = None;
810 let result = CURRENT_OUTPUT.set(&output, || {
811 let mut test = Some(test);
812 __wbg_test_invoke(&mut || {
813 let test = test.take().unwrap_throw();
814 future_output = Some(test.poll(cx))
815 })
816 });
817 match (result, future_output) {
818 (_, Some(Poll::Ready(result))) => Poll::Ready(result),
819 (_, Some(Poll::Pending)) => Poll::Pending,
820 (Err(e), _) => Poll::Ready(Err(e)),
821 (Ok(_), None) => wasm_bindgen::throw_str("invalid poll state"),
822 }
823 }
824}
825
826fn tab(s: &str) -> String {
827 let mut result = String::new();
828 for line in s.lines() {
829 result.push_str(" ");
830 result.push_str(line);
831 result.push('\n');
832 }
833 result
834}
835
836struct Timer {
837 performance: Performance,
838 started: f64,
839}
840
841impl Timer {
842 fn new() -> Option<Self> {
843 let global: Global = js_sys::global().unchecked_into();
844 let performance = global.performance();
845 (!performance.is_undefined()).then(|| {
846 let performance: Performance = performance.unchecked_into();
847 let started = performance.now();
848 Self {
849 performance,
850 started,
851 }
852 })
853 }
854
855 fn elapsed(&self) -> f64 {
856 (self.performance.now() - self.started) / 1000.
857 }
858}