Debian Codegraph @

third_party/rust/tokio/tests/rt_basic.rs

raw
1 #![allow(unknown_lints, unexpected_cfgs)]
2 #![warn(rust_2018_idioms)]
3 #![cfg(feature = "full")]
4
5 use tokio::runtime::Runtime;
6 use tokio::sync::oneshot;
7 use tokio::time::{timeout, Duration};
8 use tokio_test::{assert_err, assert_ok};
9
10 use std::future::Future;
11 use std::pin::Pin;
12 use std::sync::atomic::{AtomicBool, Ordering};
13 use std::task::{Context, Poll};
14 use std::thread;
15
16 mod support {
17 pub(crate) mod mpsc_stream;
18 }
19
20 macro_rules! cfg_metrics {
21 ($($t:tt)*) => {
22 #[cfg(all(tokio_unstable, target_has_atomic = "64"))]
23 {
24 $( $t )*
25 }
26 }
27 }
28
29 #[test]
30 fn spawned_task_does_not_progress_without_block_on() {
31 let (tx, mut rx) = oneshot::channel();
32
33 let rt = rt();
34
35 rt.spawn(async move {
36 assert_ok!(tx.send("hello"));
37 });
38
39 thread::sleep(Duration::from_millis(50));
40
41 assert_err!(rx.try_recv());
42
43 let out = rt.block_on(async { assert_ok!(rx.await) });
44
45 assert_eq!(out, "hello");
46 }
47
48 #[test]
49 fn no_extra_poll() {
50 use pin_project_lite::pin_project;
51 use std::pin::Pin;
52 use std::sync::{
53 atomic::{AtomicUsize, Ordering::SeqCst},
54 Arc,
55 };
56 use std::task::{Context, Poll};
57 use tokio_stream::{Stream, StreamExt};
58
59 pin_project! {
60 struct TrackPolls<S> {
61 npolls: Arc<AtomicUsize>,
62 #[pin]
63 s: S,
64 }
65 }
66
67 impl<S> Stream for TrackPolls<S>
68 where
69 S: Stream,
70 {
71 type Item = S::Item;
72 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
73 let this = self.project();
74 this.npolls.fetch_add(1, SeqCst);
75 this.s.poll_next(cx)
76 }
77 }
78
79 let (tx, rx) = support::mpsc_stream::unbounded_channel_stream::<()>();
80 let rx = TrackPolls {
81 npolls: Arc::new(AtomicUsize::new(0)),
82 s: rx,
83 };
84 let npolls = Arc::clone(&rx.npolls);
85
86 let rt = rt();
87
88 // TODO: could probably avoid this, but why not.
89 let mut rx = Box::pin(rx);
90
91 rt.spawn(async move { while rx.next().await.is_some() {} });
92 rt.block_on(async {
93 tokio::task::yield_now().await;
94 });
95
96 // should have been polled exactly once: the initial poll
97 assert_eq!(npolls.load(SeqCst), 1);
98
99 tx.send(()).unwrap();
100 rt.block_on(async {
101 tokio::task::yield_now().await;
102 });
103
104 // should have been polled twice more: once to yield Some(), then once to yield Pending
105 assert_eq!(npolls.load(SeqCst), 1 + 2);
106
107 drop(tx);
108 rt.block_on(async {
109 tokio::task::yield_now().await;
110 });
111
112 // should have been polled once more: to yield None
113 assert_eq!(npolls.load(SeqCst), 1 + 2 + 1);
114 }
115
116 #[test]
117 fn acquire_mutex_in_drop() {
118 use futures::future::pending;
119 use tokio::task;
120
121 let (tx1, rx1) = oneshot::channel();
122 let (tx2, rx2) = oneshot::channel();
123
124 let rt = rt();
125
126 rt.spawn(async move {
127 let _ = rx2.await;
128 unreachable!();
129 });
130
131 rt.spawn(async move {
132 let _ = rx1.await;
133 tx2.send(()).unwrap();
134 unreachable!();
135 });
136
137 // Spawn a task that will never notify
138 rt.spawn(async move {
139 pending::<()>().await;
140 tx1.send(()).unwrap();
141 });
142
143 // Tick the loop
144 rt.block_on(async {
145 task::yield_now().await;
146 });
147
148 // Drop the rt
149 drop(rt);
150 }
151
152 #[test]
153 fn drop_tasks_in_context() {
154 static SUCCESS: AtomicBool = AtomicBool::new(false);
155
156 struct ContextOnDrop;
157
158 impl Future for ContextOnDrop {
159 type Output = ();
160
161 fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
162 Poll::Pending
163 }
164 }
165
166 impl Drop for ContextOnDrop {
167 fn drop(&mut self) {
168 if tokio::runtime::Handle::try_current().is_ok() {
169 SUCCESS.store(true, Ordering::SeqCst);
170 }
171 }
172 }
173
174 let rt = rt();
175 rt.spawn(ContextOnDrop);
176 drop(rt);
177
178 assert!(SUCCESS.load(Ordering::SeqCst));
179 }
180
181 #[test]
182 #[cfg_attr(target_os = "wasi", ignore = "Wasi does not support panic recovery")]
183 #[should_panic(expected = "boom")]
184 fn wake_in_drop_after_panic() {
185 struct WakeOnDrop(Option<oneshot::Sender<()>>);
186
187 impl Drop for WakeOnDrop {
188 fn drop(&mut self) {
189 let _ = self.0.take().unwrap().send(());
190 }
191 }
192
193 let rt = rt();
194
195 let (tx1, rx1) = oneshot::channel::<()>();
196 let (tx2, rx2) = oneshot::channel::<()>();
197
198 // Spawn two tasks. We don't know the order in which they are dropped, so we
199 // make both tasks identical. When the first task is dropped, we wake up the
200 // second task. This ensures that we trigger a wakeup on a live task while
201 // handling the "boom" panic, no matter the order in which the tasks are
202 // dropped.
203 rt.spawn(async move {
204 let _wake_on_drop = WakeOnDrop(Some(tx2));
205 let _ = rx1.await;
206 unreachable!()
207 });
208
209 rt.spawn(async move {
210 let _wake_on_drop = WakeOnDrop(Some(tx1));
211 let _ = rx2.await;
212 unreachable!()
213 });
214
215 rt.block_on(async {
216 tokio::task::yield_now().await;
217 panic!("boom");
218 });
219 }
220
221 #[test]
222 fn spawn_two() {
223 let rt = rt();
224
225 let out = rt.block_on(async {
226 let (tx, rx) = oneshot::channel();
227
228 tokio::spawn(async move {
229 tokio::spawn(async move {
230 tx.send("ZOMG").unwrap();
231 });
232 });
233
234 assert_ok!(rx.await)
235 });
236
237 assert_eq!(out, "ZOMG");
238
239 cfg_metrics! {
240 let metrics = rt.metrics();
241 drop(rt);
242 assert_eq!(0, metrics.remote_schedule_count());
243
244 let mut local = 0;
245 for i in 0..metrics.num_workers() {
246 local += metrics.worker_local_schedule_count(i);
247 }
248
249 assert_eq!(2, local);
250 }
251 }
252
253 #[cfg_attr(target_os = "wasi", ignore = "WASI: std::thread::spawn not supported")]
254 #[test]
255 fn spawn_remote() {
256 let rt = rt();
257
258 let out = rt.block_on(async {
259 let (tx, rx) = oneshot::channel();
260
261 let handle = tokio::spawn(async move {
262 std::thread::spawn(move || {
263 std::thread::sleep(Duration::from_millis(10));
264 tx.send("ZOMG").unwrap();
265 });
266
267 rx.await.unwrap()
268 });
269
270 handle.await.unwrap()
271 });
272
273 assert_eq!(out, "ZOMG");
274
275 cfg_metrics! {
276 let metrics = rt.metrics();
277 drop(rt);
278 assert_eq!(1, metrics.remote_schedule_count());
279
280 let mut local = 0;
281 for i in 0..metrics.num_workers() {
282 local += metrics.worker_local_schedule_count(i);
283 }
284
285 assert_eq!(1, local);
286 }
287 }
288
289 #[test]
290 #[cfg_attr(target_os = "wasi", ignore = "Wasi does not support panic recovery")]
291 #[should_panic(
292 expected = "A Tokio 1.x context was found, but timers are disabled. Call `enable_time` on the runtime builder to enable timers."
293 )]
294 fn timeout_panics_when_no_time_handle() {
295 let rt = tokio::runtime::Builder::new_current_thread()
296 .build()
297 .unwrap();
298 rt.block_on(async {
299 let (_tx, rx) = oneshot::channel::<()>();
300 let dur = Duration::from_millis(20);
301 let _ = timeout(dur, rx).await;
302 });
303 }
304
305 #[cfg(tokio_unstable)]
306 mod unstable {
307 use tokio::runtime::{Builder, RngSeed, UnhandledPanic};
308
309 #[test]
310 #[should_panic(
311 expected = "a spawned task panicked and the runtime is configured to shut down on unhandled panic"
312 )]
313 fn shutdown_on_panic() {
314 let rt = Builder::new_current_thread()
315 .unhandled_panic(UnhandledPanic::ShutdownRuntime)
316 .build()
317 .unwrap();
318
319 rt.block_on(async {
320 tokio::spawn(async {
321 panic!("boom");
322 });
323
324 futures::future::pending::<()>().await;
325 })
326 }
327
328 #[test]
329 #[cfg_attr(target_os = "wasi", ignore = "Wasi does not support panic recovery")]
330 fn spawns_do_nothing() {
331 use std::sync::Arc;
332
333 let rt = Builder::new_current_thread()
334 .unhandled_panic(UnhandledPanic::ShutdownRuntime)
335 .build()
336 .unwrap();
337
338 let rt1 = Arc::new(rt);
339 let rt2 = rt1.clone();
340
341 let _ = std::thread::spawn(move || {
342 rt2.block_on(async {
343 tokio::spawn(async {
344 panic!("boom");
345 });
346
347 futures::future::pending::<()>().await;
348 })
349 })
350 .join();
351
352 let task = rt1.spawn(async {});
353 let res = futures::executor::block_on(task);
354 assert!(res.is_err());
355 }
356
357 #[test]
358 #[cfg_attr(target_os = "wasi", ignore = "Wasi does not support panic recovery")]
359 fn shutdown_all_concurrent_block_on() {
360 const N: usize = 2;
361 use std::sync::{mpsc, Arc};
362
363 let rt = Builder::new_current_thread()
364 .unhandled_panic(UnhandledPanic::ShutdownRuntime)
365 .build()
366 .unwrap();
367
368 let rt = Arc::new(rt);
369 let mut ths = vec![];
370 let (tx, rx) = mpsc::channel();
371
372 for _ in 0..N {
373 let rt = rt.clone();
374 let tx = tx.clone();
375 ths.push(std::thread::spawn(move || {
376 rt.block_on(async {
377 tx.send(()).unwrap();
378 futures::future::pending::<()>().await;
379 });
380 }));
381 }
382
383 for _ in 0..N {
384 rx.recv().unwrap();
385 }
386
387 rt.spawn(async {
388 panic!("boom");
389 });
390
391 for th in ths {
392 assert!(th.join().is_err());
393 }
394 }
395
396 #[test]
397 fn rng_seed() {
398 let seed = b"bytes used to generate seed";
399 let rt1 = tokio::runtime::Builder::new_current_thread()
400 .rng_seed(RngSeed::from_bytes(seed))
401 .build()
402 .unwrap();
403 let rt1_values = rt1.block_on(async {
404 let rand_1 = tokio::macros::support::thread_rng_n(100);
405 let rand_2 = tokio::macros::support::thread_rng_n(100);
406
407 (rand_1, rand_2)
408 });
409
410 let rt2 = tokio::runtime::Builder::new_current_thread()
411 .rng_seed(RngSeed::from_bytes(seed))
412 .build()
413 .unwrap();
414 let rt2_values = rt2.block_on(async {
415 let rand_1 = tokio::macros::support::thread_rng_n(100);
416 let rand_2 = tokio::macros::support::thread_rng_n(100);
417
418 (rand_1, rand_2)
419 });
420
421 assert_eq!(rt1_values, rt2_values);
422 }
423
424 #[test]
425 fn rng_seed_multi_enter() {
426 let seed = b"bytes used to generate seed";
427
428 fn two_rand_values() -> (u32, u32) {
429 let rand_1 = tokio::macros::support::thread_rng_n(100);
430 let rand_2 = tokio::macros::support::thread_rng_n(100);
431
432 (rand_1, rand_2)
433 }
434
435 let rt1 = tokio::runtime::Builder::new_current_thread()
436 .rng_seed(RngSeed::from_bytes(seed))
437 .build()
438 .unwrap();
439 let rt1_values_1 = rt1.block_on(async { two_rand_values() });
440 let rt1_values_2 = rt1.block_on(async { two_rand_values() });
441
442 let rt2 = tokio::runtime::Builder::new_current_thread()
443 .rng_seed(RngSeed::from_bytes(seed))
444 .build()
445 .unwrap();
446 let rt2_values_1 = rt2.block_on(async { two_rand_values() });
447 let rt2_values_2 = rt2.block_on(async { two_rand_values() });
448
449 assert_eq!(rt1_values_1, rt2_values_1);
450 assert_eq!(rt1_values_2, rt2_values_2);
451 }
452 }
453
454 fn rt() -> Runtime {
455 tokio::runtime::Builder::new_current_thread()
456 .enable_all()
457 .build()
458 .unwrap()
459 }