1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use proc_macro::TokenStream;
use quote::{format_ident, quote, ToTokens};
use syn::parse_macro_input;

/// Attribute to use `wasm_bindgen_test` for wasm32 targets and `tokio::test`
/// for everything else with async-support and custom result-types
#[proc_macro_attribute]
pub fn async_test(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let fun = parse_macro_input!(item as syn::ItemFn);

    if !fun.sig.ident.to_string().starts_with("test_") {
        panic!("test function names must start with test_");
    }

    // on the regular return-case, we can just use cfg_attr and quit early
    if fun.sig.output == syn::ReturnType::Default {
        let attrs = r#"
            #[cfg_attr(not(target_arch = "wasm32"), tokio::test)]
            #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
        "#;

        let mut out: TokenStream = attrs.parse().expect("Static works");
        let inner: TokenStream = fun.into_token_stream().into();
        out.extend(inner);
        return out;
    }

    // on the more complicated case, where we have some `->`-Result-Arrow
    // `wasm_bindgen_test` doesn't yet support
    // - see https://github.com/rustwasm/wasm-bindgen/issues/2565 -
    // we split the attribution into to functions: one with the original
    // to be attributed for non-wasm, and then a second outer-wrapper function
    // that calls the first in wasm32 cases.

    let attrs = r#"
        #[cfg_attr(not(target_arch = "wasm32"), tokio::test)]
    "#;

    let mut out: TokenStream = attrs.parse().expect("Static works.");

    let mut outer = fun.clone();
    let fn_name = fun.sig.ident.clone();
    let fn_call: TokenStream = if fun.sig.asyncness.is_some() {
        quote! {
            {
                let res = #fn_name().await;
                assert!(res.is_ok(), "{:?}", res);
            }
        }
    } else {
        quote! {
            {
                let res = #fn_name();
                assert!(res.is_ok(), "{:?}", res);
            }
        }
    }
    .into();
    outer.sig.output = syn::ReturnType::Default;
    outer.sig.ident = format_ident!("{}_outer", fun.sig.ident);
    outer.block = Box::new(parse_macro_input!(fn_call as syn::Block));

    let inner: TokenStream = fun.into_token_stream().into();
    out.extend(inner);

    let attrs = r#"
        #[cfg(target_arch = "wasm32")]
        #[wasm_bindgen_test::wasm_bindgen_test]
    "#;
    let outer_attrs: TokenStream = attrs.parse().expect("Static works.");
    let of: TokenStream = outer.into_token_stream().into();
    out.extend(outer_attrs);
    out.extend(of);

    out
}