|
| 1 | +use proc_macro::TokenStream; |
| 2 | +use proc_macro2::TokenStream as TokenStream2; |
| 3 | +use quote::quote; |
| 4 | +use syn::{parse2, ItemFn, ItemMod}; |
| 5 | + |
| 6 | +/// An exposed test. This is a test that will run locally and also be |
| 7 | +/// made available to other crates that want to run it in their own context. |
| 8 | +/// |
| 9 | +/// For example: |
| 10 | +/// ```rust |
| 11 | +/// use ext_test_macro::xtest; |
| 12 | +/// |
| 13 | +/// fn f1() {} |
| 14 | +/// |
| 15 | +/// #[xtest(feature = "_test_utils")] |
| 16 | +/// pub fn test_f1() { |
| 17 | +/// f1(); |
| 18 | +/// } |
| 19 | +/// ``` |
| 20 | +/// |
| 21 | +/// May also be applied to modules, like so: |
| 22 | +/// |
| 23 | +/// ```rust |
| 24 | +/// use ext_test_macro::xtest; |
| 25 | +/// |
| 26 | +/// #[xtest(feature = "_test_utils")] |
| 27 | +/// pub mod tests { |
| 28 | +/// use super::*; |
| 29 | +/// |
| 30 | +/// fn f1() {} |
| 31 | +/// |
| 32 | +/// #[xtest] |
| 33 | +/// pub fn test_f1() { |
| 34 | +/// f1(); |
| 35 | +/// } |
| 36 | +/// } |
| 37 | +/// ``` |
| 38 | +/// |
| 39 | +/// Which will include the module if we are testing or the `externalize-the-tests` feature |
| 40 | +/// is on. |
| 41 | +#[proc_macro_attribute] |
| 42 | +pub fn xtest(attrs: TokenStream, item: TokenStream) -> TokenStream { |
| 43 | + let input = syn::parse_macro_input!(item as TokenStream2); |
| 44 | + let attrs = syn::parse_macro_input!(attrs as TokenStream2); |
| 45 | + |
| 46 | + let expanded = if is_module_definition(input.clone()) { |
| 47 | + let cfg = if attrs.is_empty() { |
| 48 | + quote! { #[cfg(test)] } |
| 49 | + } else { |
| 50 | + quote! { #[cfg(any(test, #attrs))] } |
| 51 | + }; |
| 52 | + quote! { |
| 53 | + #cfg |
| 54 | + #input |
| 55 | + } |
| 56 | + } else if is_function_definition(input.clone()) { |
| 57 | + quote! { |
| 58 | + #[cfg_attr(test, ::core::prelude::v1::test)] |
| 59 | + #input |
| 60 | + } |
| 61 | + } else { |
| 62 | + panic!("xtest can only be applied to functions or modules"); |
| 63 | + }; |
| 64 | + expanded.into() |
| 65 | +} |
| 66 | + |
| 67 | +fn is_module_definition(input: TokenStream2) -> bool { |
| 68 | + parse2::<ItemMod>(input).is_ok() |
| 69 | +} |
| 70 | + |
| 71 | +fn is_function_definition(input: TokenStream2) -> bool { |
| 72 | + parse2::<ItemFn>(input).is_ok() |
| 73 | +} |
0 commit comments