1 #![allow(unknown_lints, unexpected_cfgs)]
2 #![warn(rust_2018_idioms)]
3 #![cfg(all(feature = "full", tokio_unstable))]
4 
5 use tokio::runtime::LocalOptions;
6 use tokio::task::spawn_local;
7 
8 #[test]
test_spawn_local_in_runtime()9 fn test_spawn_local_in_runtime() {
10     let rt = rt();
11 
12     let res = rt.block_on(async move {
13         let (tx, rx) = tokio::sync::oneshot::channel();
14 
15         spawn_local(async {
16             tokio::task::yield_now().await;
17             tx.send(5).unwrap();
18         });
19 
20         rx.await.unwrap()
21     });
22 
23     assert_eq!(res, 5);
24 }
25 
26 #[test]
test_spawn_from_handle()27 fn test_spawn_from_handle() {
28     let rt = rt();
29 
30     let (tx, rx) = tokio::sync::oneshot::channel();
31 
32     rt.handle().spawn(async {
33         tokio::task::yield_now().await;
34         tx.send(5).unwrap();
35     });
36 
37     let res = rt.block_on(async move { rx.await.unwrap() });
38 
39     assert_eq!(res, 5);
40 }
41 
42 #[test]
test_spawn_local_on_runtime_object()43 fn test_spawn_local_on_runtime_object() {
44     let rt = rt();
45 
46     let (tx, rx) = tokio::sync::oneshot::channel();
47 
48     rt.spawn_local(async {
49         tokio::task::yield_now().await;
50         tx.send(5).unwrap();
51     });
52 
53     let res = rt.block_on(async move { rx.await.unwrap() });
54 
55     assert_eq!(res, 5);
56 }
57 
58 #[test]
test_spawn_local_from_guard()59 fn test_spawn_local_from_guard() {
60     let rt = rt();
61 
62     let (tx, rx) = tokio::sync::oneshot::channel();
63 
64     let _guard = rt.enter();
65 
66     spawn_local(async {
67         tokio::task::yield_now().await;
68         tx.send(5).unwrap();
69     });
70 
71     let res = rt.block_on(async move { rx.await.unwrap() });
72 
73     assert_eq!(res, 5);
74 }
75 
76 #[test]
77 #[should_panic]
test_spawn_local_from_guard_other_thread()78 fn test_spawn_local_from_guard_other_thread() {
79     let (tx, rx) = std::sync::mpsc::channel();
80 
81     std::thread::spawn(move || {
82         let rt = rt();
83         let handle = rt.handle().clone();
84 
85         tx.send(handle).unwrap();
86     });
87 
88     let handle = rx.recv().unwrap();
89 
90     let _guard = handle.enter();
91 
92     spawn_local(async {});
93 }
94 
rt() -> tokio::runtime::LocalRuntime95 fn rt() -> tokio::runtime::LocalRuntime {
96     tokio::runtime::Builder::new_current_thread()
97         .enable_all()
98         .build_local(&LocalOptions::default())
99         .unwrap()
100 }
101