timeout_macro/
lib.rs

1// Author: D.S. Ljungmark <spider@skuggor.se>, Modio AB
2// SPDX-License-Identifier: AGPL-3.0-or-later
3//
4use proc_macro::TokenStream;
5use quote::{quote, quote_spanned};
6use syn::spanned::Spanned;
7
8/// Enables an async test function.
9///
10/// # Examples
11///
12/// ```ignore
13/// #[async_std::test]
14/// async fn my_test() -> std::io::Result<()> {
15///     assert_eq!(2 * 2, 4);
16///     Ok(())
17/// }
18/// ```
19#[proc_macro_attribute]
20pub fn timeouttest(_attr: TokenStream, item: TokenStream) -> TokenStream {
21    let input = syn::parse_macro_input!(item as syn::ItemFn);
22
23    let ret = &input.sig.output;
24    let name = &input.sig.ident;
25    let body = &input.block;
26    let attrs = &input.attrs;
27    let vis = &input.vis;
28
29    if input.sig.asyncness.is_none() {
30        return TokenStream::from(quote_spanned! { input.span() =>
31            compile_error!("the async keyword is missing from the function declaration"),
32        });
33    }
34
35    let result = quote! {
36        #[::core::prelude::v1::test]
37        #(#attrs)*
38        #vis fn #name() #ret {
39            async_std::task::block_on(async {
40                async_std::future::timeout(std::time::Duration::from_secs(130), async {#body}).await.expect("Timeout occured for testcase")
41            })
42        }
43    };
44
45    result.into()
46}