1use async_stream::try_stream;
2
3use futures_core::stream::Stream;
4use futures_util::stream::StreamExt;
5
6#[tokio::test]
7async fn single_err() {
8 let s = try_stream! {
9 if true {
10 Err("hello")?;
11 } else {
12 yield "world";
13 }
14
15 unreachable!();
16 };
17
18 let values: Vec<_> = s.collect().await;
19 assert_eq!(1, values.len());
20 assert_eq!(Err("hello"), values[0]);
21}
22
23#[tokio::test]
24async fn yield_then_err() {
25 let s = try_stream! {
26 yield "hello";
27 Err("world")?;
28 unreachable!();
29 };
30
31 let values: Vec<_> = s.collect().await;
32 assert_eq!(2, values.len());
33 assert_eq!(Ok("hello"), values[0]);
34 assert_eq!(Err("world"), values[1]);
35}
36
37#[tokio::test]
38async fn convert_err() {
39 struct ErrorA(u8);
40 #[derive(PartialEq, Debug)]
41 struct ErrorB(u8);
42 impl From<ErrorA> for ErrorB {
43 fn from(a: ErrorA) -> ErrorB {
44 ErrorB(a.0)
45 }
46 }
47
48 fn test() -> impl Stream<Item = Result<&'static str, ErrorB>> {
49 try_stream! {
50 if true {
51 Err(ErrorA(1))?;
52 } else {
53 Err(ErrorB(2))?;
54 }
55 yield "unreachable";
56 }
57 }
58
59 let values: Vec<_> = test().collect().await;
60 assert_eq!(1, values.len());
61 assert_eq!(Err(ErrorB(1)), values[0]);
62}
63
64#[tokio::test]
65async fn multi_try() {
66 fn test() -> impl Stream<Item = Result<i32, String>> {
67 try_stream! {
68 let a = Ok::<_, String>(Ok::<_, String>(123))??;
69 for _ in 1..10 {
70 yield a;
71 }
72 }
73 }
74 let values: Vec<_> = test().collect().await;
75 assert_eq!(9, values.len());
76 assert_eq!(
77 std::iter::repeat(123).take(9).map(Ok).collect::<Vec<_>>(),
78 values
79 );
80}
81
82#[allow(unused)]
83fn issue_65() -> impl Stream<Item = Result<u32, ()>> {
84 try_stream! {
85 yield Err(())?;
86 }
87}
88