0
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-10-30 09:08:00 -04:00

refactor(core): remove run_in_task helper, use tokio::test macro (#19009)

This commit is contained in:
Bartek Iwańczuk 2023-05-06 16:01:05 +02:00 committed by GitHub
parent a6c47ee740
commit b8c9360761
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 72 additions and 71 deletions

View file

@ -1740,6 +1740,7 @@ mod tests {
use crate::RuntimeOptions; use crate::RuntimeOptions;
use crate::Snapshot; use crate::Snapshot;
use deno_ops::op; use deno_ops::op;
use futures::future::poll_fn;
use futures::future::FutureExt; use futures::future::FutureExt;
use parking_lot::Mutex; use parking_lot::Mutex;
use std::fmt; use std::fmt;
@ -1754,12 +1755,6 @@ mod tests {
pub use crate::*; pub use crate::*;
} }
// TODO(ry) Sadly FuturesUnordered requires the current task to be set. So
// even though we are only using poll() in these tests and not Tokio, we must
// nevertheless run it in the tokio executor. Ideally run_in_task can be
// removed in the future.
use crate::runtime::tests::run_in_task;
#[derive(Default)] #[derive(Default)]
struct MockLoader { struct MockLoader {
pub loads: Arc<Mutex<Vec<String>>>, pub loads: Arc<Mutex<Vec<String>>>,
@ -1907,7 +1902,7 @@ import "/a.js";
} }
if inner.url == "file:///slow.js" && inner.counter < 2 { if inner.url == "file:///slow.js" && inner.counter < 2 {
// TODO(ry) Hopefully in the future we can remove current task // TODO(ry) Hopefully in the future we can remove current task
// notification. See comment above run_in_task. // notification.
cx.waker().wake_by_ref(); cx.waker().wake_by_ref();
return Poll::Pending; return Poll::Pending;
} }
@ -2263,8 +2258,8 @@ import "/a.js";
futures::executor::block_on(receiver).unwrap().unwrap(); futures::executor::block_on(receiver).unwrap().unwrap();
} }
#[test] #[tokio::test]
fn dyn_import_err() { async fn dyn_import_err() {
#[derive(Clone, Default)] #[derive(Clone, Default)]
struct DynImportErrLoader { struct DynImportErrLoader {
pub count: Arc<AtomicUsize>, pub count: Arc<AtomicUsize>,
@ -2302,7 +2297,7 @@ import "/a.js";
}); });
// Test an erroneous dynamic import where the specified module isn't found. // Test an erroneous dynamic import where the specified module isn't found.
run_in_task(move |cx| { poll_fn(move |cx| {
runtime runtime
.execute_script_static( .execute_script_static(
"file:///dyn_import2.js", "file:///dyn_import2.js",
@ -2320,7 +2315,9 @@ import "/a.js";
unreachable!(); unreachable!();
} }
assert_eq!(count.load(Ordering::Relaxed), 4); assert_eq!(count.load(Ordering::Relaxed), 4);
Poll::Ready(())
}) })
.await;
} }
#[derive(Clone, Default)] #[derive(Clone, Default)]
@ -2369,8 +2366,8 @@ import "/a.js";
} }
} }
#[test] #[tokio::test]
fn dyn_import_ok() { async fn dyn_import_ok() {
let loader = Rc::new(DynImportOkLoader::default()); let loader = Rc::new(DynImportOkLoader::default());
let prepare_load_count = loader.prepare_load_count.clone(); let prepare_load_count = loader.prepare_load_count.clone();
let resolve_count = loader.resolve_count.clone(); let resolve_count = loader.resolve_count.clone();
@ -2379,7 +2376,7 @@ import "/a.js";
module_loader: Some(loader), module_loader: Some(loader),
..Default::default() ..Default::default()
}); });
run_in_task(move |cx| { poll_fn(move |cx| {
// Dynamically import mod_b // Dynamically import mod_b
runtime runtime
.execute_script_static( .execute_script_static(
@ -2413,11 +2410,13 @@ import "/a.js";
)); ));
assert_eq!(resolve_count.load(Ordering::Relaxed), 7); assert_eq!(resolve_count.load(Ordering::Relaxed), 7);
assert_eq!(load_count.load(Ordering::Relaxed), 1); assert_eq!(load_count.load(Ordering::Relaxed), 1);
Poll::Ready(())
}) })
.await;
} }
#[test] #[tokio::test]
fn dyn_import_borrow_mut_error() { async fn dyn_import_borrow_mut_error() {
// https://github.com/denoland/deno/issues/6054 // https://github.com/denoland/deno/issues/6054
let loader = Rc::new(DynImportOkLoader::default()); let loader = Rc::new(DynImportOkLoader::default());
let prepare_load_count = loader.prepare_load_count.clone(); let prepare_load_count = loader.prepare_load_count.clone();
@ -2426,7 +2425,7 @@ import "/a.js";
..Default::default() ..Default::default()
}); });
run_in_task(move |cx| { poll_fn(move |cx| {
runtime runtime
.execute_script_static( .execute_script_static(
"file:///dyn_import3.js", "file:///dyn_import3.js",
@ -2445,7 +2444,9 @@ import "/a.js";
assert_eq!(prepare_load_count.load(Ordering::Relaxed), 1); assert_eq!(prepare_load_count.load(Ordering::Relaxed), 1);
// Second poll triggers error // Second poll triggers error
let _ = runtime.poll_event_loop(cx, false); let _ = runtime.poll_event_loop(cx, false);
Poll::Ready(())
}) })
.await;
} }
// Regression test for https://github.com/denoland/deno/issues/3736. // Regression test for https://github.com/denoland/deno/issues/3736.
@ -2671,8 +2672,8 @@ import "/a.js";
futures::executor::block_on(fut); futures::executor::block_on(fut);
} }
#[test] #[tokio::test]
fn slow_never_ready_modules() { async fn slow_never_ready_modules() {
let loader = MockLoader::new(); let loader = MockLoader::new();
let loads = loader.loads.clone(); let loads = loader.loads.clone();
let mut runtime = JsRuntime::new(RuntimeOptions { let mut runtime = JsRuntime::new(RuntimeOptions {
@ -2680,7 +2681,7 @@ import "/a.js";
..Default::default() ..Default::default()
}); });
run_in_task(move |cx| { poll_fn(move |cx| {
let spec = resolve_url("file:///main.js").unwrap(); let spec = resolve_url("file:///main.js").unwrap();
let mut recursive_load = let mut recursive_load =
runtime.load_main_module(&spec, None).boxed_local(); runtime.load_main_module(&spec, None).boxed_local();
@ -2694,8 +2695,7 @@ import "/a.js";
// "file:///never_ready.js", // "file:///never_ready.js",
// "file:///slow.js" // "file:///slow.js"
// But due to current task notification in DelayedSourceCodeFuture they // But due to current task notification in DelayedSourceCodeFuture they
// all get loaded in a single poll. Also see the comment above // all get loaded in a single poll.
// run_in_task.
for _ in 0..10 { for _ in 0..10 {
let result = recursive_load.poll_unpin(cx); let result = recursive_load.poll_unpin(cx);
@ -2714,30 +2714,26 @@ import "/a.js";
] ]
); );
} }
Poll::Ready(())
}) })
.await;
} }
#[test] #[tokio::test]
fn loader_disappears_after_error() { async fn loader_disappears_after_error() {
let loader = MockLoader::new(); let loader = MockLoader::new();
let mut runtime = JsRuntime::new(RuntimeOptions { let mut runtime = JsRuntime::new(RuntimeOptions {
module_loader: Some(loader), module_loader: Some(loader),
..Default::default() ..Default::default()
}); });
run_in_task(move |cx| { let spec = resolve_url("file:///bad_import.js").unwrap();
let spec = resolve_url("file:///bad_import.js").unwrap(); let result = runtime.load_main_module(&spec, None).await;
let mut load_fut = runtime.load_main_module(&spec, None).boxed_local(); let err = result.unwrap_err();
let result = load_fut.poll_unpin(cx); assert_eq!(
if let Poll::Ready(Err(err)) = result { err.downcast_ref::<MockError>().unwrap(),
assert_eq!( &MockError::ResolveErr
err.downcast_ref::<MockError>().unwrap(), );
&MockError::ResolveErr
);
} else {
unreachable!();
}
})
} }
#[test] #[test]

View file

@ -2610,8 +2610,6 @@ pub mod tests {
use crate::modules::SymbolicModule; use crate::modules::SymbolicModule;
use crate::ZeroCopyBuf; use crate::ZeroCopyBuf;
use deno_ops::op; use deno_ops::op;
use futures::future::lazy;
use std::ops::FnOnce;
use std::pin::Pin; use std::pin::Pin;
use std::rc::Rc; use std::rc::Rc;
use std::sync::atomic::AtomicUsize; use std::sync::atomic::AtomicUsize;
@ -2623,13 +2621,6 @@ pub mod tests {
pub use crate::*; pub use crate::*;
} }
pub fn run_in_task<F>(f: F)
where
F: FnOnce(&mut Context) + 'static,
{
futures::executor::block_on(lazy(move |cx| f(cx)));
}
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub enum Mode { pub enum Mode {
Async, Async,
@ -2864,7 +2855,7 @@ pub mod tests {
#[tokio::test] #[tokio::test]
async fn test_poll_value() { async fn test_poll_value() {
let mut runtime = JsRuntime::new(Default::default()); let mut runtime = JsRuntime::new(Default::default());
run_in_task(move |cx| { poll_fn(move |cx| {
let value_global = runtime let value_global = runtime
.execute_script_static("a.js", "Promise.resolve(1 + 2)") .execute_script_static("a.js", "Promise.resolve(1 + 2)")
.unwrap(); .unwrap();
@ -2903,7 +2894,8 @@ pub mod tests {
.unwrap(); .unwrap();
let v = runtime.poll_value(&value_global, cx); let v = runtime.poll_value(&value_global, cx);
matches!(v, Poll::Ready(Err(e)) if e.to_string() == "Promise resolution is still pending but the event loop has already resolved."); matches!(v, Poll::Ready(Err(e)) if e.to_string() == "Promise resolution is still pending but the event loop has already resolved.");
}); Poll::Ready(())
}).await;
} }
#[tokio::test] #[tokio::test]
@ -3061,10 +3053,10 @@ pub mod tests {
assert_eq!(frame.column_number, Some(12)); assert_eq!(frame.column_number, Some(12));
} }
#[test] #[tokio::test]
fn test_encode_decode() { async fn test_encode_decode() {
let (mut runtime, _dispatch_count) = setup(Mode::Async); let (mut runtime, _dispatch_count) = setup(Mode::Async);
run_in_task(move |cx| { poll_fn(move |cx| {
runtime runtime
.execute_script( .execute_script(
"encode_decode_test.js", "encode_decode_test.js",
@ -3075,13 +3067,15 @@ pub mod tests {
if let Poll::Ready(Err(_)) = runtime.poll_event_loop(cx, false) { if let Poll::Ready(Err(_)) = runtime.poll_event_loop(cx, false) {
unreachable!(); unreachable!();
} }
}); Poll::Ready(())
})
.await;
} }
#[test] #[tokio::test]
fn test_serialize_deserialize() { async fn test_serialize_deserialize() {
let (mut runtime, _dispatch_count) = setup(Mode::Async); let (mut runtime, _dispatch_count) = setup(Mode::Async);
run_in_task(move |cx| { poll_fn(move |cx| {
runtime runtime
.execute_script( .execute_script(
"serialize_deserialize_test.js", "serialize_deserialize_test.js",
@ -3091,11 +3085,13 @@ pub mod tests {
if let Poll::Ready(Err(_)) = runtime.poll_event_loop(cx, false) { if let Poll::Ready(Err(_)) = runtime.poll_event_loop(cx, false) {
unreachable!(); unreachable!();
} }
}); Poll::Ready(())
})
.await;
} }
#[test] #[tokio::test]
fn test_error_builder() { async fn test_error_builder() {
#[op] #[op]
fn op_err() -> Result<(), Error> { fn op_err() -> Result<(), Error> {
Err(custom_error("DOMExceptionOperationError", "abc")) Err(custom_error("DOMExceptionOperationError", "abc"))
@ -3111,7 +3107,7 @@ pub mod tests {
get_error_class_fn: Some(&get_error_class_name), get_error_class_fn: Some(&get_error_class_name),
..Default::default() ..Default::default()
}); });
run_in_task(move |cx| { poll_fn(move |cx| {
runtime runtime
.execute_script_static( .execute_script_static(
"error_builder_test.js", "error_builder_test.js",
@ -3121,7 +3117,9 @@ pub mod tests {
if let Poll::Ready(Err(_)) = runtime.poll_event_loop(cx, false) { if let Poll::Ready(Err(_)) = runtime.poll_event_loop(cx, false) {
unreachable!(); unreachable!();
} }
}); Poll::Ready(())
})
.await;
} }
#[test] #[test]
@ -3646,10 +3644,10 @@ main();
assert_eq!(result.unwrap_err().to_string(), expected_error); assert_eq!(result.unwrap_err().to_string(), expected_error);
} }
#[test] #[tokio::test]
fn test_error_async_stack() { async fn test_error_async_stack() {
let mut runtime = JsRuntime::new(RuntimeOptions::default()); let mut runtime = JsRuntime::new(RuntimeOptions::default());
run_in_task(move |cx| { poll_fn(move |cx| {
runtime runtime
.execute_script_static( .execute_script_static(
"error_async_stack.js", "error_async_stack.js",
@ -3680,11 +3678,13 @@ main();
} }
_ => panic!(), _ => panic!(),
}; };
Poll::Ready(())
}) })
.await;
} }
#[test] #[tokio::test]
fn test_error_context() { async fn test_error_context() {
use anyhow::anyhow; use anyhow::anyhow;
#[op] #[op]
@ -3703,7 +3703,7 @@ main();
..Default::default() ..Default::default()
}); });
run_in_task(move |cx| { poll_fn(move |cx| {
runtime runtime
.execute_script_static( .execute_script_static(
"test_error_context_sync.js", "test_error_context_sync.js",
@ -3746,13 +3746,14 @@ if (errMessage !== "higher-level sync error: original sync error") {
Poll::Ready(Err(err)) => panic!("{err:?}"), Poll::Ready(Err(err)) => panic!("{err:?}"),
_ => panic!(), _ => panic!(),
} }
}) Poll::Ready(())
}).await;
} }
#[test] #[tokio::test]
fn test_pump_message_loop() { async fn test_pump_message_loop() {
let mut runtime = JsRuntime::new(RuntimeOptions::default()); let mut runtime = JsRuntime::new(RuntimeOptions::default());
run_in_task(move |cx| { poll_fn(move |cx| {
runtime runtime
.execute_script_static( .execute_script_static(
"pump_message_loop.js", "pump_message_loop.js",
@ -3797,7 +3798,9 @@ assertEquals(1, notify_return_value);
r#"assertEquals(globalThis.resolved, true);"#, r#"assertEquals(globalThis.resolved, true);"#,
) )
.unwrap(); .unwrap();
Poll::Ready(())
}) })
.await;
} }
#[test] #[test]
@ -4695,7 +4698,7 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
..Default::default() ..Default::default()
}); });
run_in_task(move |cx| { poll_fn(move |cx| {
let main_realm = runtime.global_realm(); let main_realm = runtime.global_realm();
let other_realm = runtime.create_realm().unwrap(); let other_realm = runtime.create_realm().unwrap();
@ -4747,7 +4750,9 @@ Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
runtime.poll_event_loop(cx, false), runtime.poll_event_loop(cx, false),
Poll::Ready(Ok(())) Poll::Ready(Ok(()))
)); ));
}); Poll::Ready(())
})
.await;
} }
#[test] #[test]