Debian Codegraph @

tests/async.rs

raw symbols SCIP
1 #[cfg(all(feature = "async", not(target_os = "unknown")))]
2 use {
3 flume::*,
4 futures::{stream::FuturesUnordered, StreamExt, TryFutureExt, Future},
5 futures::task::{Context, Waker, Poll},
6 async_std::prelude::FutureExt,
7 std::{time::Duration, sync::{atomic::{AtomicUsize, Ordering}, Arc}},
8 };
9
10 #[cfg(all(feature = "async", not(target_os = "unknown")))]
11 #[test]
12 fn r#async_recv() {
13 let (tx, rx) = unbounded();
14
15 let t = std::thread::spawn(move || {
16 std::thread::sleep(std::time::Duration::from_millis(250));
17 tx.send(42u32).unwrap();
18 });
19
20 async_std::task::block_on(async {
21 assert_eq!(rx.recv_async().await.unwrap(), 42);
22 });
23
24 t.join().unwrap();
25 }
26
27 #[cfg(all(feature = "async", not(target_os = "unknown")))]
28 #[test]
29 fn r#async_send() {
30 let (tx, rx) = bounded(1);
31
32 let t = std::thread::spawn(move || {
33 std::thread::sleep(std::time::Duration::from_millis(250));
34 assert_eq!(rx.recv(), Ok(42));
35 });
36
37 async_std::task::block_on(async {
38 tx.send_async(42u32).await.unwrap();
39 });
40
41 t.join().unwrap();
42 }
43
44 #[cfg(all(feature = "async", not(target_os = "unknown")))]
45 #[test]
46 fn r#async_recv_disconnect() {
47 let (tx, rx) = bounded::<i32>(0);
48
49 let t = std::thread::spawn(move || {
50 std::thread::sleep(std::time::Duration::from_millis(250));
51 drop(tx)
52 });
53
54 async_std::task::block_on(async {
55 assert_eq!(rx.recv_async().await, Err(RecvError::Disconnected));
56 });
57
58 t.join().unwrap();
59 }
60
61 #[cfg(all(feature = "async", not(target_os = "unknown")))]
62 #[test]
63 fn r#async_send_disconnect() {
64 let (tx, rx) = bounded(0);
65
66 let t = std::thread::spawn(move || {
67 std::thread::sleep(std::time::Duration::from_millis(250));
68 drop(rx)
69 });
70
71 async_std::task::block_on(async {
72 assert_eq!(tx.send_async(42u32).await, Err(SendError(42)));
73 });
74
75 t.join().unwrap();
76 }
77
78 #[cfg(all(feature = "async", not(target_os = "unknown")))]
79 #[test]
80 fn r#async_recv_drop_recv() {
81 let (tx, rx) = bounded::<i32>(10);
82
83 let recv_fut = rx.recv_async();
84
85 async_std::task::block_on(async {
86 let res = async_std::future::timeout(std::time::Duration::from_millis(500), rx.recv_async()).await;
87 assert!(res.is_err());
88 });
89
90 let rx2 = rx.clone();
91 let t = std::thread::spawn(move || {
92 async_std::task::block_on(async {
93 rx2.recv_async().await
94 })
95 });
96
97 std::thread::sleep(std::time::Duration::from_millis(500));
98
99 tx.send(42).unwrap();
100
101 drop(recv_fut);
102
103 assert_eq!(t.join().unwrap(), Ok(42))
104 }
105
106 #[cfg(all(feature = "async", not(target_os = "unknown")))]
107 #[async_std::test]
108 async fn r#async_send_1_million_no_drop_or_reorder() {
109 #[derive(Debug)]
110 enum Message {
111 Increment {
112 old: u64,
113 },
114 ReturnCount,
115 }
116
117 let (tx, rx) = unbounded();
118
119 let t = async_std::task::spawn(async move {
120 let mut count = 0u64;
121
122 while let Ok(Message::Increment { old }) = rx.recv_async().await {
123 assert_eq!(old, count);
124 count += 1;
125 }
126
127 count
128 });
129
130 for next in 0..1_000_000 {
131 tx.send(Message::Increment { old: next }).unwrap();
132 }
133
134 tx.send(Message::ReturnCount).unwrap();
135
136 let count = t.await;
137 assert_eq!(count, 1_000_000)
138 }
139
140 #[cfg(all(feature = "async", not(target_os = "unknown")))]
141 #[async_std::test]
142 async fn parallel_async_receivers() {
143 let (tx, rx) = flume::unbounded();
144 let send_fut = async move {
145 let n_sends: usize = 100000;
146 for _ in 0..n_sends {
147 tx.send_async(()).await.unwrap();
148 }
149 };
150
151 async_std::task::spawn(
152 send_fut
153 .timeout(Duration::from_secs(5))
154 .map_err(|_| panic!("Send timed out!"))
155 );
156
157 let mut futures_unordered = (0..250)
158 .map(|_| async {
159 while let Ok(()) = rx.recv_async().await
160 /* rx.recv() is OK */
161 {}
162 })
163 .collect::<FuturesUnordered<_>>();
164
165 let recv_fut = async {
166 while futures_unordered.next().await.is_some() {}
167 };
168
169 recv_fut
170 .timeout(Duration::from_secs(5))
171 .map_err(|_| panic!("Receive timed out!"))
172 .await
173 .unwrap();
174
175 println!("recv end");
176 }
177
178 #[cfg(all(feature = "async", not(target_os = "unknown")))]
179 #[test]
180 fn change_waker() {
181 let (tx, rx) = flume::bounded(1);
182 tx.send(()).unwrap();
183
184 struct DebugWaker(Arc<AtomicUsize>, Waker);
185
186 impl DebugWaker {
187 fn new() -> Self {
188 let woken = Arc::new(AtomicUsize::new(0));
189 let woken_cloned = woken.clone();
190 let waker = waker_fn::waker_fn(move || {
191 woken.fetch_add(1, Ordering::SeqCst);
192 });
193 DebugWaker(woken_cloned, waker)
194 }
195
196 fn woken(&self) -> usize {
197 self.0.load(Ordering::SeqCst)
198 }
199
200 fn ctx(&self) -> Context {
201 Context::from_waker(&self.1)
202 }
203 }
204
205 // Check that the waker is correctly updated when sending tasks change their wakers
206 {
207 let send_fut = tx.send_async(());
208 futures::pin_mut!(send_fut);
209
210 let (waker1, waker2) = (DebugWaker::new(), DebugWaker::new());
211
212 // Set the waker to waker1
213 assert_eq!(send_fut.as_mut().poll(&mut waker1.ctx()), Poll::Pending);
214
215 // Change the waker to waker2
216 assert_eq!(send_fut.poll(&mut waker2.ctx()), Poll::Pending);
217
218 // Wake the future
219 rx.recv().unwrap();
220
221 // Check that waker2 was woken and waker1 was not
222 assert_eq!(waker1.woken(), 0);
223 assert_eq!(waker2.woken(), 1);
224 }
225
226 // Check that the waker is correctly updated when receiving tasks change their wakers
227 {
228 rx.recv().unwrap();
229 let recv_fut = rx.recv_async();
230 futures::pin_mut!(recv_fut);
231
232 let (waker1, waker2) = (DebugWaker::new(), DebugWaker::new());
233
234 // Set the waker to waker1
235 assert_eq!(recv_fut.as_mut().poll(&mut waker1.ctx()), Poll::Pending);
236
237 // Change the waker to waker2
238 assert_eq!(recv_fut.poll(&mut waker2.ctx()), Poll::Pending);
239
240 // Wake the future
241 tx.send(()).unwrap();
242
243 // Check that waker2 was woken and waker1 was not
244 assert_eq!(waker1.woken(), 0);
245 assert_eq!(waker2.woken(), 1);
246 }
247 }
248
249 #[cfg(all(feature = "async", not(target_os = "unknown")))]
250 #[test]
251 fn spsc_single_threaded_value_ordering() {
252 async fn test() {
253 let (tx, rx) = flume::bounded(4);
254 tokio::select! {
255 _ = producer(tx) => {},
256 _ = consumer(rx) => {},
257 }
258 }
259
260 async fn producer(tx: flume::Sender<usize>) {
261 for i in 0..100 {
262 tx.send_async(i).await.unwrap();
263 }
264 }
265
266 async fn consumer(rx: flume::Receiver<usize>) {
267 let mut expected = 0;
268 while let Ok(value) = rx.recv_async().await {
269 assert_eq!(value, expected);
270 expected += 1;
271 }
272 }
273
274 let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
275 rt.block_on(test());
276 }