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
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
// Copyright 2020 nytopop (Eric Izoita)
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//! Runtime-agnostic attribute macros to use quickcheck with async tests.
#![warn(rust_2018_idioms, missing_docs)]

use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{
    parse_macro_input, punctuated::Punctuated, token::Comma, AttributeArgs, Error, FnArg, ItemFn,
    NestedMeta, Pat, Type,
};

struct Arguments {
    ids: Punctuated<Pat, Comma>,
    tys: Punctuated<Type, Comma>,
}

fn parse_args(fn_item: &ItemFn) -> Result<Arguments, TokenStream> {
    let mut args = Arguments {
        ids: Punctuated::new(),
        tys: Punctuated::new(),
    };

    for pt in fn_item.sig.inputs.iter() {
        match pt {
            FnArg::Receiver(_) => {
                return Err(
                    Error::new_spanned(&fn_item, "test fn cannot take a receiver")
                        .to_compile_error()
                        .into(),
                )
            }

            FnArg::Typed(pt) => {
                args.ids.push(*pt.pat.clone());
                args.tys.push(*pt.ty.clone());
            }
        }
    }

    Ok(args)
}

/// Mark an async function to be fuzz-tested using [quickcheck][qc], within a tokio
/// executor.
///
/// # Usage
///
/// ```
/// #[quickcheck_async::tokio]
/// async fn fuzz_me(fuzz_arg: String) -> bool {
///     fuzz_arg != "fuzzed".to_owned()
/// }
/// ```
///
/// # Attribute arguments
///
/// Arguments to this attribute are passed through to [tokio::test][tt].
///
/// ```
/// #[quickcheck_async::tokio(core_threads = 3)]
/// async fn fuzz_me(fuzz_arg: String) -> bool {
///     fuzz_arg != "fuzzed".to_owned()
/// }
/// ```
/// [qc]: https://docs.rs/quickcheck/latest/quickcheck/fn.quickcheck.html
/// [tt]: https://docs.rs/tokio/latest/tokio/attr.test.html
#[proc_macro_attribute]
pub fn tokio(args: TokenStream, item: TokenStream) -> TokenStream {
    let fn_item = parse_macro_input!(item as ItemFn);

    for attr in &fn_item.attrs {
        if attr.path.is_ident("test") {
            return Error::new_spanned(&fn_item, "multiple #[test] attributes were supplied")
                .to_compile_error()
                .into();
        }
    }

    if fn_item.sig.asyncness.is_none() {
        return Error::new_spanned(&fn_item, "test fn must be async")
            .to_compile_error()
            .into();
    }

    let p_args = parse_macro_input!(args as AttributeArgs);
    let attrib: Punctuated<NestedMeta, Comma> = p_args.into_iter().collect();

    let call_by = format_ident!("{}", fn_item.sig.ident);

    let Arguments { ids, tys } = match parse_args(&fn_item) {
        Err(e) => return e,
        Ok(ts) => ts,
    };

    let ret = &fn_item.sig.output;

    quote! (
        #[::tokio::test(#attrib)]
        async fn #call_by() {
            #fn_item

            let test_fn: fn(#tys) #ret = |#ids| {
                ::futures::executor::block_on(#call_by(#ids))
            };

            ::tokio::task::spawn_blocking(move || {
                ::quickcheck::quickcheck(test_fn)
            })
            .await
            .unwrap()
        }
    )
    .into()
}

/// Mark an async function to be fuzz-tested using [quickcheck][qc], within an async_std
/// executor.
///
/// # Usage
///
/// ```
/// #[quickcheck_async::async_std]
/// async fn fuzz_me(fuzz_arg: String) -> bool {
///     fuzz_arg != "fuzzed".to_owned()
/// }
/// ```
/// [qc]: https://docs.rs/quickcheck/latest/quickcheck/fn.quickcheck.html
#[proc_macro_attribute]
pub fn async_std(args: TokenStream, item: TokenStream) -> TokenStream {
    let fn_item = parse_macro_input!(item as ItemFn);

    for attr in &fn_item.attrs {
        if attr.path.is_ident("test") {
            return Error::new_spanned(&fn_item, "multiple #[test] attributes were supplied")
                .to_compile_error()
                .into();
        }
    }

    if fn_item.sig.asyncness.is_none() {
        return Error::new_spanned(&fn_item, "test fn must be async")
            .to_compile_error()
            .into();
    }

    let p_args = parse_macro_input!(args as AttributeArgs);
    let attrib: Punctuated<NestedMeta, Comma> = p_args.into_iter().collect();

    let call_by = format_ident!("{}", fn_item.sig.ident);

    let Arguments { ids, tys } = match parse_args(&fn_item) {
        Err(e) => return e,
        Ok(ts) => ts,
    };

    let ret = &fn_item.sig.output;

    quote! (
        #[::async_std::test(#attrib)]
        async fn #call_by() {
            #fn_item

            let test_fn: fn(#tys) #ret = |#ids| {
                ::futures::executor::block_on(#call_by(#ids))
            };

            ::quickcheck::quickcheck(test_fn);
        }
    )
    .into()
}