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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
//! A simple way to run code before or after every unit test.
//!
//! The wrapper function you specify is called with each of your tests. In the
//! wrapper you do any setup you want, call the test function you were provided,
//! and then do any cleanup.
//!
//! # Examples
//!
//! ## Basic
//!
//! Suppose you want to set up a tracing subscriber to display log and tracing
//! events before some tests:
//!
//! ```
//! #[wraptest::wrap_tests(wrapper = with_logs)]
//! mod tests {
//!     use tracing::info;
//!     use tracing_subscriber::fmt::format::FmtSpan;
//!
//!     fn with_logs<T>(test_fn: T)
//!     where T: FnOnce() -> () {
//!         let subscriber = tracing_subscriber::fmt::fmt()
//!            .with_env_filter("debug")
//!            .with_span_events(FmtSpan::NEW | FmtSpan::CLOSE)
//!            .with_test_writer()
//!            .finish();
//!         let _guard = tracing::subscriber::set_default(subscriber);
//!         test_fn();
//!     }
//!
//!     #[test]    
//!     fn with_tracing() {
//!         info!("with tracing!");
//!     }
//! }
//! ```
//!
//! ## Async
//!
//! If you have async tests (currently only [`tokio::test`] is supported) you
//! can provide an async wrapper.
//!
//! ```
//! #[wraptest::wrap_tests(async_wrapper = with_logs)]
//! mod tests {
//! #   use tracing::info;
//! #   use tracing_subscriber::fmt::format::FmtSpan;
//! #   use std::future::Future;
//!     async fn with_logs<T, F>(test_fn: T)
//!     where
//!         T: FnOnce() -> F,
//!         F: Future<Output = ()>,
//!     {
//!         let subscriber = /* ... */
//! #           tracing_subscriber::fmt::fmt()
//! #               .with_env_filter("debug")
//! #               .with_span_events(FmtSpan::NEW | FmtSpan::CLOSE)
//! #               .with_test_writer()
//! #               .finish();
//!         let _guard = tracing::subscriber::set_default(subscriber);
//!         test_fn();
//!     }
//!
//!     #[tokio::test]    
//!     async fn with_tracing() {
//!         info!("with tracing, but async!");
//!     }
//! }
//! ```
//!
//! ## Custom return type
//!
//! If you want to return something other than `()` from your tests you just
//! need to change the signature of your wrapper. Here's how you can make your
//! wrappers generic over any return type:
//!
//! ```
//! #[wraptest::wrap_tests(wrapper = with_setup, async_wrapper = with_setup_async)]
//! mod tests {
//!     # use std::{future::Future, time::Duration};
//!
//!     fn with_setup<T, R>(test_fn: T) -> R
//!     where
//!         T: FnOnce() -> R,
//!     {
//!         eprintln!("Setting up...");
//!         let result = test_fn();
//!         eprintln!("Cleaning up...");
//!         result
//!     }
//!
//!     async fn with_setup_async<T, F, R>(test_fn: T) -> R
//!     where
//!         T: FnOnce() -> F,
//!         F: Future<Output = R>,
//!     {
//!         eprintln!("Setting up...");
//!         let result = test_fn().await;
//!         eprintln!("Cleaning up...");
//!         result
//!     }
//! }
//! ```
//!
//! # Alternatives
//!
//! - [minimal-fixtures][minimal-fixtures]
//! - [rstest][rstest]
//! - [test-env-log][test-env-log]
//!
//! I want to especially thank d-e-s-o for test-env-log. If I hadn't seen it, using
//! macros to reduce redundant test setup wouldn't have occurred to me.
//!
//! [minimal-fixtures]: https://github.com/vorner/minimal-fixtures
//! [rstest]: https://github.com/la10736/rstest
//! [test-env-log]: https://github.com/d-e-s-o/test-env-log
//! [crates-io]: https://crates.io/crates/wraptest

#![warn(clippy::cargo)]

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

const USAGE: &str = "Usage is generally `#[wraptest::wrap_tests(wrapper = your_fn)]`, or
`#[wraptest::wrap_tests(wrapper = your_fn, async_wrapper = your_fn_async)]` if
you have async tests.";

struct Args {
    wrapper: Option<Ident>,
    async_wrapper: Option<Ident>,
}

impl Parse for Args {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let punct = Punctuated::<Arg, Token![,]>::parse_terminated(input)?;

        let mut wrapper = None;
        let mut async_wrapper = None;

        for pair in punct.into_pairs() {
            match pair.into_value() {
                Arg::Wrapper(ident) => wrapper = Some(ident),
                Arg::AsyncWrapper(ident) => async_wrapper = Some(ident),
            }
        }

        Ok(Self {
            wrapper,
            async_wrapper,
        })
    }
}

enum Arg {
    Wrapper(Ident),
    AsyncWrapper(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 = if name == "wrapper" {
            Self::Wrapper(value)
        } else if name == "async_wrapper" {
            Self::AsyncWrapper(value)
        } else {
            abort!(name, "wraptest: Unexpected parameter"; note = USAGE)
        };

        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 {
        wrapper,
        async_wrapper,
    } = parse_macro_input!(args as Args);
    let mut module = parse_macro_input!(input as ItemMod);

    let mut visitor = ModVisitor {
        wrapper,
        async_wrapper,
    };
    visitor.visit_item_mod_mut(&mut module);

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

struct ModVisitor {
    wrapper: Option<Ident>,
    async_wrapper: 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: Test functions that take arguments aren't supported";
                    note = USAGE,
                );
            }

            self.visit_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_test_fn(&mut self, node: &mut ItemFn) {
        let wrapped = Self::strip_attrs(node);
        let name = &wrapped.sig.ident;

        node.block.stmts = if node.sig.asyncness.is_some() {
            let async_wrapper = match &self.async_wrapper {
                Some(wrapper) => wrapper,
                None => abort!(
                    node,
                    "wraptest: Must specify `async_wrapper` to wrap async test functions";
                    note = USAGE
                ),
            };

            parse_quote! {
                #wrapped
                #async_wrapper(#name).await
            }
        } else {
            let wrapper = match &self.wrapper {
                Some(wrapper) => wrapper,
                None => abort!(
                    node,
                    "wraptest: Must specify `wrapper` to wrap async test functions";
                    note = USAGE
                ),
            };
            parse_quote! {
                #wrapped
                #wrapper(#name)
            }
        };
    }

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