Debian Codegraph @

debian/missing-sources/futures-channel/tests/mpsc.rs

raw
1 use futures::channel::{mpsc, oneshot};
2 use futures::executor::{block_on, block_on_stream};
3 use futures::future::{poll_fn, FutureExt};
4 use futures::pin_mut;
5 use futures::sink::{Sink, SinkExt};
6 use futures::stream::{Stream, StreamExt};
7 use futures::task::{Context, Poll};
8 use futures_test::task::{new_count_waker, noop_context};
9 use std::sync::atomic::{AtomicUsize, Ordering};
10 use std::sync::{Arc, Mutex};
11 use std::thread;
12
13 #[allow(dead_code)]
14 trait AssertSend: Send {}
15 impl AssertSend for mpsc::Sender<i32> {}
16 impl AssertSend for mpsc::Receiver<i32> {}
17
18 #[test]
19 fn send_recv() {
20 let (mut tx, rx) = mpsc::channel::<i32>(16);
21
22 block_on(tx.send(1)).unwrap();
23 drop(tx);
24 let v: Vec<_> = block_on(rx.collect());
25 assert_eq!(v, vec![1]);
26 }
27
28 #[test]
29 fn send_recv_no_buffer() {
30 // Run on a task context
31 block_on(poll_fn(move |cx| {
32 let (tx, rx) = mpsc::channel::<i32>(0);
33 pin_mut!(tx, rx);
34
35 assert!(tx.as_mut().poll_flush(cx).is_ready());
36 assert!(tx.as_mut().poll_ready(cx).is_ready());
37
38 // Send first message
39 assert!(tx.as_mut().start_send(1).is_ok());
40 assert!(tx.as_mut().poll_ready(cx).is_pending());
41
42 // poll_ready said Pending, so no room in buffer, therefore new sends
43 // should get rejected with is_full.
44 assert!(tx.as_mut().start_send(0).unwrap_err().is_full());
45 assert!(tx.as_mut().poll_ready(cx).is_pending());
46
47 // Take the value
48 assert_eq!(rx.as_mut().poll_next(cx), Poll::Ready(Some(1)));
49 assert!(tx.as_mut().poll_ready(cx).is_ready());
50
51 // Send second message
52 assert!(tx.as_mut().poll_ready(cx).is_ready());
53 assert!(tx.as_mut().start_send(2).is_ok());
54 assert!(tx.as_mut().poll_ready(cx).is_pending());
55
56 // Take the value
57 assert_eq!(rx.as_mut().poll_next(cx), Poll::Ready(Some(2)));
58 assert!(tx.as_mut().poll_ready(cx).is_ready());
59
60 Poll::Ready(())
61 }));
62 }
63
64 #[test]
65 fn send_shared_recv() {
66 let (mut tx1, rx) = mpsc::channel::<i32>(16);
67 let mut rx = block_on_stream(rx);
68 let mut tx2 = tx1.clone();
69
70 block_on(tx1.send(1)).unwrap();
71 assert_eq!(rx.next(), Some(1));
72
73 block_on(tx2.send(2)).unwrap();
74 assert_eq!(rx.next(), Some(2));
75 }
76
77 #[test]
78 fn send_recv_threads() {
79 let (mut tx, rx) = mpsc::channel::<i32>(16);
80
81 let t = thread::spawn(move || {
82 block_on(tx.send(1)).unwrap();
83 });
84
85 let v: Vec<_> = block_on(rx.take(1).collect());
86 assert_eq!(v, vec![1]);
87
88 t.join().unwrap();
89 }
90
91 #[test]
92 fn send_recv_threads_no_capacity() {
93 let (mut tx, rx) = mpsc::channel::<i32>(0);
94
95 let t = thread::spawn(move || {
96 block_on(tx.send(1)).unwrap();
97 block_on(tx.send(2)).unwrap();
98 });
99
100 let v: Vec<_> = block_on(rx.collect());
101 assert_eq!(v, vec![1, 2]);
102
103 t.join().unwrap();
104 }
105
106 #[test]
107 fn recv_close_gets_none() {
108 let (mut tx, mut rx) = mpsc::channel::<i32>(10);
109
110 // Run on a task context
111 block_on(poll_fn(move |cx| {
112 rx.close();
113
114 assert_eq!(rx.poll_next_unpin(cx), Poll::Ready(None));
115 match tx.poll_ready(cx) {
116 Poll::Pending | Poll::Ready(Ok(_)) => panic!(),
117 Poll::Ready(Err(e)) => assert!(e.is_disconnected()),
118 };
119
120 Poll::Ready(())
121 }));
122 }
123
124 #[test]
125 fn tx_close_gets_none() {
126 let (_, mut rx) = mpsc::channel::<i32>(10);
127
128 // Run on a task context
129 block_on(poll_fn(move |cx| {
130 assert_eq!(rx.poll_next_unpin(cx), Poll::Ready(None));
131 Poll::Ready(())
132 }));
133 }
134
135 // #[test]
136 // fn spawn_sends_items() {
137 // let core = local_executor::Core::new();
138 // let stream = unfold(0, |i| Some(ok::<_,u8>((i, i + 1))));
139 // let rx = mpsc::spawn(stream, &core, 1);
140 // assert_eq!(core.run(rx.take(4).collect()).unwrap(),
141 // [0, 1, 2, 3]);
142 // }
143
144 // #[test]
145 // fn spawn_kill_dead_stream() {
146 // use std::thread;
147 // use std::time::Duration;
148 // use futures::future::Either;
149 // use futures::sync::oneshot;
150 //
151 // // a stream which never returns anything (maybe a remote end isn't
152 // // responding), but dropping it leads to observable side effects
153 // // (like closing connections, releasing limited resources, ...)
154 // #[derive(Debug)]
155 // struct Dead {
156 // // when dropped you should get Err(oneshot::Canceled) on the
157 // // receiving end
158 // done: oneshot::Sender<()>,
159 // }
160 // impl Stream for Dead {
161 // type Item = ();
162 // type Error = ();
163 //
164 // fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
165 // Ok(Poll::Pending)
166 // }
167 // }
168 //
169 // // need to implement a timeout for the test, as it would hang
170 // // forever right now
171 // let (timeout_tx, timeout_rx) = oneshot::channel();
172 // thread::spawn(move || {
173 // thread::sleep(Duration::from_millis(1000));
174 // let _ = timeout_tx.send(());
175 // });
176 //
177 // let core = local_executor::Core::new();
178 // let (done_tx, done_rx) = oneshot::channel();
179 // let stream = Dead{done: done_tx};
180 // let rx = mpsc::spawn(stream, &core, 1);
181 // let res = core.run(
182 // Ok::<_, ()>(())
183 // .into_future()
184 // .then(move |_| {
185 // // now drop the spawned stream: maybe some timeout exceeded,
186 // // or some connection on this end was closed by the remote
187 // // end.
188 // drop(rx);
189 // // and wait for the spawned stream to release its resources
190 // done_rx
191 // })
192 // .select2(timeout_rx)
193 // );
194 // match res {
195 // Err(Either::A((oneshot::Canceled, _))) => (),
196 // _ => {
197 // panic!("dead stream wasn't canceled");
198 // },
199 // }
200 // }
201
202 #[test]
203 fn stress_shared_unbounded() {
204 const AMT: u32 = if cfg!(miri) { 100 } else { 10000 };
205 const NTHREADS: u32 = 8;
206 let (tx, rx) = mpsc::unbounded::<i32>();
207
208 let t = thread::spawn(move || {
209 let result: Vec<_> = block_on(rx.collect());
210 assert_eq!(result.len(), (AMT * NTHREADS) as usize);
211 for item in result {
212 assert_eq!(item, 1);
213 }
214 });
215
216 for _ in 0..NTHREADS {
217 let tx = tx.clone();
218
219 thread::spawn(move || {
220 for _ in 0..AMT {
221 tx.unbounded_send(1).unwrap();
222 }
223 });
224 }
225
226 drop(tx);
227
228 t.join().ok().unwrap();
229 }
230
231 #[test]
232 fn stress_shared_bounded_hard() {
233 const AMT: u32 = if cfg!(miri) { 100 } else { 10000 };
234 const NTHREADS: u32 = 8;
235 let (tx, rx) = mpsc::channel::<i32>(0);
236
237 let t = thread::spawn(move || {
238 let result: Vec<_> = block_on(rx.collect());
239 assert_eq!(result.len(), (AMT * NTHREADS) as usize);
240 for item in result {
241 assert_eq!(item, 1);
242 }
243 });
244
245 for _ in 0..NTHREADS {
246 let mut tx = tx.clone();
247
248 thread::spawn(move || {
249 for _ in 0..AMT {
250 block_on(tx.send(1)).unwrap();
251 }
252 });
253 }
254
255 drop(tx);
256
257 t.join().unwrap();
258 }
259
260 #[allow(clippy::same_item_push)]
261 #[test]
262 fn stress_receiver_multi_task_bounded_hard() {
263 const AMT: usize = if cfg!(miri) { 100 } else { 10_000 };
264 const NTHREADS: u32 = 2;
265
266 let (mut tx, rx) = mpsc::channel::<usize>(0);
267 let rx = Arc::new(Mutex::new(Some(rx)));
268 let n = Arc::new(AtomicUsize::new(0));
269
270 let mut th = vec![];
271
272 for _ in 0..NTHREADS {
273 let rx = rx.clone();
274 let n = n.clone();
275
276 let t = thread::spawn(move || {
277 let mut i = 0;
278
279 loop {
280 i += 1;
281 let mut rx_opt = rx.lock().unwrap();
282 if let Some(rx) = &mut *rx_opt {
283 if i % 5 == 0 {
284 let item = block_on(rx.next());
285
286 if item.is_none() {
287 *rx_opt = None;
288 break;
289 }
290
291 n.fetch_add(1, Ordering::Relaxed);
292 } else {
293 // Just poll
294 let n = n.clone();
295 match rx.poll_next_unpin(&mut noop_context()) {
296 Poll::Ready(Some(_)) => {
297 n.fetch_add(1, Ordering::Relaxed);
298 }
299 Poll::Ready(None) => {
300 *rx_opt = None;
301 break;
302 }
303 Poll::Pending => {}
304 }
305 }
306 } else {
307 break;
308 }
309 }
310 });
311
312 th.push(t);
313 }
314
315 for i in 0..AMT {
316 block_on(tx.send(i)).unwrap();
317 }
318 drop(tx);
319
320 for t in th {
321 t.join().unwrap();
322 }
323
324 assert_eq!(AMT, n.load(Ordering::Relaxed));
325 }
326
327 /// Stress test that receiver properly receives all the messages
328 /// after sender dropped.
329 #[test]
330 fn stress_drop_sender() {
331 const ITER: usize = if cfg!(miri) { 100 } else { 10000 };
332
333 fn list() -> impl Stream<Item = i32> {
334 let (tx, rx) = mpsc::channel(1);
335 thread::spawn(move || {
336 block_on(send_one_two_three(tx));
337 });
338 rx
339 }
340
341 for _ in 0..ITER {
342 let v: Vec<_> = block_on(list().collect());
343 assert_eq!(v, vec![1, 2, 3]);
344 }
345 }
346
347 async fn send_one_two_three(mut tx: mpsc::Sender<i32>) {
348 for i in 1..=3 {
349 tx.send(i).await.unwrap();
350 }
351 }
352
353 /// Stress test that after receiver dropped,
354 /// no messages are lost.
355 fn stress_close_receiver_iter() {
356 let (tx, rx) = mpsc::unbounded();
357 let mut rx = block_on_stream(rx);
358 let (unwritten_tx, unwritten_rx) = std::sync::mpsc::channel();
359 let th = thread::spawn(move || {
360 for i in 1.. {
361 if tx.unbounded_send(i).is_err() {
362 unwritten_tx.send(i).expect("unwritten_tx");
363 return;
364 }
365 }
366 });
367
368 // Read one message to make sure thread effectively started
369 assert_eq!(Some(1), rx.next());
370
371 rx.close();
372
373 for i in 2.. {
374 match rx.next() {
375 Some(r) => assert!(i == r),
376 None => {
377 let unwritten = unwritten_rx.recv().expect("unwritten_rx");
378 assert_eq!(unwritten, i);
379 th.join().unwrap();
380 return;
381 }
382 }
383 }
384 }
385
386 #[test]
387 fn stress_close_receiver() {
388 const ITER: usize = if cfg!(miri) { 50 } else { 10000 };
389
390 for _ in 0..ITER {
391 stress_close_receiver_iter();
392 }
393 }
394
395 async fn stress_poll_ready_sender(mut sender: mpsc::Sender<u32>, count: u32) {
396 for i in (1..=count).rev() {
397 sender.send(i).await.unwrap();
398 }
399 }
400
401 /// Tests that after `poll_ready` indicates capacity a channel can always send without waiting.
402 #[allow(clippy::same_item_push)]
403 #[test]
404 fn stress_poll_ready() {
405 const AMT: u32 = if cfg!(miri) { 100 } else { 1000 };
406 const NTHREADS: u32 = 8;
407
408 /// Run a stress test using the specified channel capacity.
409 fn stress(capacity: usize) {
410 let (tx, rx) = mpsc::channel(capacity);
411 let mut threads = Vec::new();
412 for _ in 0..NTHREADS {
413 let sender = tx.clone();
414 threads.push(thread::spawn(move || block_on(stress_poll_ready_sender(sender, AMT))));
415 }
416 drop(tx);
417
418 let result: Vec<_> = block_on(rx.collect());
419 assert_eq!(result.len() as u32, AMT * NTHREADS);
420
421 for thread in threads {
422 thread.join().unwrap();
423 }
424 }
425
426 stress(0);
427 stress(1);
428 stress(8);
429 stress(16);
430 }
431
432 #[test]
433 fn try_send_1() {
434 const N: usize = if cfg!(miri) { 100 } else { 3000 };
435 let (mut tx, rx) = mpsc::channel(0);
436
437 let t = thread::spawn(move || {
438 for i in 0..N {
439 loop {
440 if tx.try_send(i).is_ok() {
441 break;
442 }
443 }
444 }
445 });
446
447 let result: Vec<_> = block_on(rx.collect());
448 for (i, j) in result.into_iter().enumerate() {
449 assert_eq!(i, j);
450 }
451
452 t.join().unwrap();
453 }
454
455 #[test]
456 fn try_send_2() {
457 let (mut tx, rx) = mpsc::channel(0);
458 let mut rx = block_on_stream(rx);
459
460 tx.try_send("hello").unwrap();
461
462 let (readytx, readyrx) = oneshot::channel::<()>();
463
464 let th = thread::spawn(move || {
465 block_on(poll_fn(|cx| {
466 assert!(tx.poll_ready(cx).is_pending());
467 Poll::Ready(())
468 }));
469
470 drop(readytx);
471 block_on(tx.send("goodbye")).unwrap();
472 });
473
474 let _ = block_on(readyrx);
475 assert_eq!(rx.next(), Some("hello"));
476 assert_eq!(rx.next(), Some("goodbye"));
477 assert_eq!(rx.next(), None);
478
479 th.join().unwrap();
480 }
481
482 #[test]
483 fn try_send_fail() {
484 let (mut tx, rx) = mpsc::channel(0);
485 let mut rx = block_on_stream(rx);
486
487 tx.try_send("hello").unwrap();
488
489 // This should fail
490 assert!(tx.try_send("fail").is_err());
491
492 assert_eq!(rx.next(), Some("hello"));
493
494 tx.try_send("goodbye").unwrap();
495 drop(tx);
496
497 assert_eq!(rx.next(), Some("goodbye"));
498 assert_eq!(rx.next(), None);
499 }
500
501 #[test]
502 fn try_send_recv() {
503 let (mut tx, mut rx) = mpsc::channel(1);
504 tx.try_send("hello").unwrap();
505 tx.try_send("hello").unwrap();
506 tx.try_send("hello").unwrap_err(); // should be full
507 rx.try_next().unwrap();
508 rx.try_next().unwrap();
509 rx.try_next().unwrap_err(); // should be empty
510 tx.try_send("hello").unwrap();
511 rx.try_next().unwrap();
512 rx.try_next().unwrap_err(); // should be empty
513 }
514
515 #[test]
516 fn same_receiver() {
517 let (mut txa1, _) = mpsc::channel::<i32>(1);
518 let txa2 = txa1.clone();
519
520 let (mut txb1, _) = mpsc::channel::<i32>(1);
521 let txb2 = txb1.clone();
522
523 assert!(txa1.same_receiver(&txa2));
524 assert!(txb1.same_receiver(&txb2));
525 assert!(!txa1.same_receiver(&txb1));
526
527 txa1.disconnect();
528 txb1.close_channel();
529
530 assert!(!txa1.same_receiver(&txa2));
531 assert!(txb1.same_receiver(&txb2));
532 }
533
534 #[test]
535 fn is_connected_to() {
536 let (txa, rxa) = mpsc::channel::<i32>(1);
537 let (txb, rxb) = mpsc::channel::<i32>(1);
538
539 assert!(txa.is_connected_to(&rxa));
540 assert!(txb.is_connected_to(&rxb));
541 assert!(!txa.is_connected_to(&rxb));
542 assert!(!txb.is_connected_to(&rxa));
543 }
544
545 #[test]
546 fn hash_receiver() {
547 use std::collections::hash_map::DefaultHasher;
548 use std::hash::Hasher;
549
550 let mut hasher_a1 = DefaultHasher::new();
551 let mut hasher_a2 = DefaultHasher::new();
552 let mut hasher_b1 = DefaultHasher::new();
553 let mut hasher_b2 = DefaultHasher::new();
554 let (mut txa1, _) = mpsc::channel::<i32>(1);
555 let txa2 = txa1.clone();
556
557 let (mut txb1, _) = mpsc::channel::<i32>(1);
558 let txb2 = txb1.clone();
559
560 txa1.hash_receiver(&mut hasher_a1);
561 let hash_a1 = hasher_a1.finish();
562 txa2.hash_receiver(&mut hasher_a2);
563 let hash_a2 = hasher_a2.finish();
564 txb1.hash_receiver(&mut hasher_b1);
565 let hash_b1 = hasher_b1.finish();
566 txb2.hash_receiver(&mut hasher_b2);
567 let hash_b2 = hasher_b2.finish();
568
569 assert_eq!(hash_a1, hash_a2);
570 assert_eq!(hash_b1, hash_b2);
571 assert!(hash_a1 != hash_b1);
572
573 txa1.disconnect();
574 txb1.close_channel();
575
576 let mut hasher_a1 = DefaultHasher::new();
577 let mut hasher_a2 = DefaultHasher::new();
578 let mut hasher_b1 = DefaultHasher::new();
579 let mut hasher_b2 = DefaultHasher::new();
580
581 txa1.hash_receiver(&mut hasher_a1);
582 let hash_a1 = hasher_a1.finish();
583 txa2.hash_receiver(&mut hasher_a2);
584 let hash_a2 = hasher_a2.finish();
585 txb1.hash_receiver(&mut hasher_b1);
586 let hash_b1 = hasher_b1.finish();
587 txb2.hash_receiver(&mut hasher_b2);
588 let hash_b2 = hasher_b2.finish();
589
590 assert!(hash_a1 != hash_a2);
591 assert_eq!(hash_b1, hash_b2);
592 }
593
594 #[test]
595 fn send_backpressure() {
596 let (waker, counter) = new_count_waker();
597 let mut cx = Context::from_waker(&waker);
598
599 let (mut tx, mut rx) = mpsc::channel(1);
600 block_on(tx.send(1)).unwrap();
601
602 let mut task = tx.send(2);
603 assert_eq!(task.poll_unpin(&mut cx), Poll::Pending);
604 assert_eq!(counter, 0);
605
606 let item = block_on(rx.next()).unwrap();
607 assert_eq!(item, 1);
608 assert_eq!(counter, 1);
609 assert_eq!(task.poll_unpin(&mut cx), Poll::Ready(Ok(())));
610
611 let item = block_on(rx.next()).unwrap();
612 assert_eq!(item, 2);
613 }
614
615 #[test]
616 fn send_backpressure_multi_senders() {
617 let (waker, counter) = new_count_waker();
618 let mut cx = Context::from_waker(&waker);
619
620 let (mut tx1, mut rx) = mpsc::channel(1);
621 let mut tx2 = tx1.clone();
622 block_on(tx1.send(1)).unwrap();
623
624 let mut task = tx2.send(2);
625 assert_eq!(task.poll_unpin(&mut cx), Poll::Pending);
626 assert_eq!(counter, 0);
627
628 let item = block_on(rx.next()).unwrap();
629 assert_eq!(item, 1);
630 assert_eq!(counter, 1);
631 assert_eq!(task.poll_unpin(&mut cx), Poll::Ready(Ok(())));
632
633 let item = block_on(rx.next()).unwrap();
634 assert_eq!(item, 2);
635 }
636
637 /// Test that empty channel has zero length and that non-empty channel has length equal to number
638 /// of enqueued items
639 #[test]
640 fn unbounded_len() {
641 let (tx, mut rx) = mpsc::unbounded();
642 assert_eq!(tx.len(), 0);
643 assert!(tx.is_empty());
644 tx.unbounded_send(1).unwrap();
645 assert_eq!(tx.len(), 1);
646 assert!(!tx.is_empty());
647 tx.unbounded_send(2).unwrap();
648 assert_eq!(tx.len(), 2);
649 assert!(!tx.is_empty());
650 let item = block_on(rx.next()).unwrap();
651 assert_eq!(item, 1);
652 assert_eq!(tx.len(), 1);
653 assert!(!tx.is_empty());
654 let item = block_on(rx.next()).unwrap();
655 assert_eq!(item, 2);
656 assert_eq!(tx.len(), 0);
657 assert!(tx.is_empty());
658 }