Skip to content

Commit

Permalink
Add some tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
futursolo committed Aug 21, 2022
1 parent fa3e4f6 commit 2523651
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 0 deletions.
47 changes: 47 additions & 0 deletions packages/yew/src/platform/rt_tokio/local_worker.rs
Expand Up @@ -141,3 +141,50 @@ impl LocalHandle {
});
}
}

#[cfg(test)]
mod tests {
use futures::channel::oneshot;
use tokio::test;
use yew::platform::Runtime;

use super::*;

#[test]
async fn test_local_handle_exists() {
assert!(LocalHandle::try_current().is_none());

let runtime = Runtime::default();
let (tx, rx) = oneshot::channel();

runtime.spawn_pinned(move || async move {
tx.send(LocalHandle::try_current().is_some())
.expect("failed to send");
});

assert!(rx.await.expect("failed to receive"));
}

#[test]
async fn test_local_handle_spawns_on_same_worker() {
assert!(LocalHandle::try_current().is_none());

let runtime = Runtime::default();
let (tx1, rx1) = oneshot::channel();
let (tx2, rx2) = oneshot::channel();

runtime.spawn_pinned(move || async move {
let handle = LocalHandle::current();

tx1.send(std::thread::current().id())
.expect("failed to send");

handle.spawn_local(async move {
tx2.send(std::thread::current().id())
.expect("failed to send");
})
});

assert_eq!(rx1.await, rx2.await);
}
}
50 changes: 50 additions & 0 deletions packages/yew/src/platform/rt_tokio/mod.rs
Expand Up @@ -105,3 +105,53 @@ impl Runtime {
worker.spawn_pinned(create_task);
}
}

#[cfg(test)]
mod tests {
use futures::channel::oneshot;
use tokio::test;

use super::*;

#[test]
async fn test_spawn_pinned_least_busy() {
let runtime = Runtime::new(2).expect("failed to create runtime.");

let (tx1, rx1) = oneshot::channel();
let (tx2, rx2) = oneshot::channel();

runtime.spawn_pinned(move || async move {
tx1.send(std::thread::current().id())
.expect("failed to send!");
});

runtime.spawn_pinned(move || async move {
tx2.send(std::thread::current().id())
.expect("failed to send!");
});

// first task and second task are not on the same thread.
assert_ne!(rx1.await, rx2.await);
}

#[test]
async fn test_spawn_local_within_send() {
let runtime = Runtime::new(1).expect("failed to create runtime.");

let (tx, rx) = oneshot::channel();

runtime.spawn_pinned(move || async move {
tokio::task::spawn(async move {
// tokio::task::spawn_local cannot spawn within a Send task.
//
// yew::platform::spawn_local can spawn within a Send task as long as runnting under
// a Yew Runtime.
spawn_local(async move {
tx.send(()).expect("failed to send!");
})
});
});

assert_eq!(rx.await, Ok(()));
}
}

0 comments on commit 2523651

Please sign in to comment.