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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
//! A simple way to run code before and after every unit test.
//!
//! Suppose you want to set up a tracing subscriber to display log and tracing
//! events before some tests:
//!
//! ```
//! #[cfg(test)]
//! #[wraptest::wrap_tests(before = setup_logs)]
//! mod tests {
//!     use tracing::info;
//!     use tracing_subscriber::fmt::format::FmtSpan;
//!
//!     fn setup_logs() {
//!         tracing_subscriber::fmt::fmt()
//!             .with_env_filter("debug")
//!             .with_span_events(FmtSpan::NEW | FmtSpan::CLOSE)
//!             .init();
//!     }
//!
//!     #[test]    
//!     fn with_tracing() {
//!         info!("with tracing");
//!     }
//!
//!     #[tokio::test]
//!     async fn with_tracing_async() {
//!         info!("with tracing -- but async");
//!     }
//! }
//! ```
//!
//! This translates to essentially:
//!
//! ```
//! # use tracing::info;
//! #
//! #[test]
//! fn with_tracing() {
//!     fn with_tracing() {
//!         info!("with tracing");
//!     }
//!     setup_logs();
//!     with_tracing();
//! }
//!
//! #[tokio::test]
//! async fn with_tracing_async() {
//!     async fn with_tracing_async() {
//!         info!("with tracing -- but async");
//!     }
//!     setup_logs();
//!     with_tracing_async().await;
//! }
//! ```
//!
//! You can also specify `#[wraptest(after = after_fn)]` to run code after each
//! test.

#![warn(clippy::cargo)]

use proc_macro2::TokenStream;
use proc_macro_error::{abort, proc_macro_error};
use quote::quote;
use syn::{
    parse::{Parse, ParseStream},
    parse_quote,
    punctuated::Punctuated,
    visit_mut::{self, VisitMut},
    ItemFn, ItemMod, Token,
};
use syn::{parse_macro_input, Ident};

struct Args {
    before: Option<Ident>,
    after: Option<Ident>,
}

impl Parse for Args {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut before = None;
        let mut after = None;

        let args = Punctuated::<Arg, Token![,]>::parse_terminated(input)?;

        for pair in args.into_pairs() {
            match pair.into_value() {
                Arg::Before(ident) => before = Some(ident),
                Arg::After(ident) => after = Some(ident),
            }
        }

        Ok(Self { before, after })
    }
}

enum Arg {
    Before(Ident),
    After(Ident),
}

impl Parse for Arg {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let name = input.parse::<Ident>()?;
        input.parse::<Token![=]>()?;
        let value = input.parse::<Ident>()?;

        let arg = match name.to_string().as_str() {
            "before" => Arg::Before(value),
            "after" => Arg::After(value),
            _ => abort!(name, "Unexpected argument name"),
        };
        Ok(arg)
    }
}

#[proc_macro_error]
#[proc_macro_attribute]
pub fn wrap_tests(
    args: proc_macro::TokenStream,
    input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
    let Args { before, after } = parse_macro_input!(args as Args);
    let mut module = parse_macro_input!(input as ItemMod);

    let mut visitor = ModVisitor { before, after };
    visitor.visit_item_mod_mut(&mut module);

    let out = quote! { #module };
    out.into()
}

struct ModVisitor {
    before: Option<Ident>,
    after: Option<Ident>,
}

impl VisitMut for ModVisitor {
    fn visit_item_fn_mut(&mut self, node: &mut ItemFn) {
        if self.is_test_fn(node) {
            if !node.sig.inputs.is_empty() {
                abort!(
                    node.sig.inputs,
                    "wraptest doesn't support test functions that take arguments"
                );
            }

            if node.sig.asyncness.is_some() {
                self.visit_async_test_fn(node);
            } else {
                self.visit_non_async_test_fn(node);
            }
        }

        visit_mut::visit_item_fn_mut(self, node);
    }
}

impl ModVisitor {
    fn is_test_fn(&self, node: &ItemFn) -> bool {
        node.attrs.iter().any(|attr| {
            if attr.path.is_ident("test") {
                return true;
            }

            let pairs = attr
                .path
                .segments
                .pairs()
                .map(|pair| pair.value().ident.to_string())
                .collect::<Vec<_>>();
            if pairs.len() == 2 && pairs[0] == "tokio" && pairs[1] == "test" {
                return true;
            }

            false
        })
    }

    fn visit_async_test_fn(&mut self, node: &mut ItemFn) {
        let call_before = self.call_before_quote();
        let call_after = self.call_after_quote();

        let wrapped = Self::without_attrs(node);
        let name = &wrapped.sig.ident;

        node.block.stmts = parse_quote! {
            #wrapped
            #call_before
            let result = #name().await;
            #call_after
            result
        }
    }

    fn visit_non_async_test_fn(&mut self, node: &mut ItemFn) {
        let call_before = self.call_before_quote();
        let call_after = self.call_after_quote();

        let wrapped = Self::without_attrs(node);
        let name = &wrapped.sig.ident;

        node.block.stmts = parse_quote! {
            #wrapped
            #call_before
            let result = #name();
            #call_after
            result
        }
    }

    fn without_attrs(node: &ItemFn) -> ItemFn {
        let mut node = node.clone();
        node.attrs = vec![];
        node
    }

    fn call_before_quote(&mut self) -> TokenStream {
        if let Some(before) = &self.before {
            quote! { #before(); }
        } else {
            quote! {}
        }
    }

    fn call_after_quote(&mut self) -> TokenStream {
        if let Some(after) = &self.after {
            quote! { #after(); }
        } else {
            quote! {}
        }
    }
}