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
//! Part of the ntest library. Add test cases to the rust test framework.

extern crate proc_macro;
extern crate syn;

use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use syn::export::TokenStream2;
use syn::parse_macro_input;

/// Test cases can be used to have multiple inputs for a given function.
/// With the *test_case* attribute multiple tests will be generated using the
/// [Procedural Macros](https://blog.rust-lang.org/2018/12/21/Procedural-Macros-in-Rust-2018.html)
/// capabilities of rust.
///
/// The function input can be of type `int`, `bool`, or `str`.
///
/// WARNING!
/// It is currently not possible to have negative numbers as macro input. For example
/// this `#[test_case(-13)]` will not work.
///
/// # Examples
///
/// Example with a single argument
/// ```ignore
/// #[test_case(13)]
/// #[test_case(42)]
/// fn one_arg(x: u32) {
///     assert!(x == 13 || x == 42)
/// }
/// ```
///
/// Example with multiple arguments:
/// ```ignore
/// #[test_case(true, "true", 1)]
/// fn test_mix(x: bool, y: &str, z: u16) {
///     assert!(x);
///     assert_eq!(y, "true");
///     assert_eq!(z, 1);
/// }
///```
#[proc_macro_attribute]
pub fn test_case(attr: TokenStream, item: TokenStream) -> TokenStream {
    let mut test_case_descriptions: Vec<TestCaseDescription> = vec![];
    let input = parse_macro_input!(item as syn::ItemFn);

    // Collect test case descriptions
    let attributes_first_test_case = parse_macro_input!(attr as syn::AttributeArgs);
    test_case_descriptions.push(parse_test_case_attributes(&attributes_first_test_case));
    for attribute in &input.attrs {
        let meta = attribute.parse_meta();
        match meta {
            Ok(m) => match m {
                syn::Meta::Path(p) => {
                    let identifier = p.get_ident().expect("Expected identifier!");
                    if identifier != "test_case" {
                        panic!(
                            "Only test_case attributes expected, but found {:?}.",
                            identifier
                        );
                    }
                }
                syn::Meta::List(ml) => {
                    let argument_args: syn::AttributeArgs = ml.nested.into_iter().collect();
                    test_case_descriptions.push(parse_test_case_attributes(&argument_args));
                }
                syn::Meta::NameValue(_) => {
                    unimplemented!("Named values currently not supported.");
                }
            },
            Err(e) => panic!("Could not determine meta data. Error {}.", e),
        }
    }

    let fn_args = &input.sig.inputs;
    let fn_body = &input.block;
    let mut fn_args_idents: Vec<syn::Ident> = vec![];

    for i in fn_args {
        match i {
            syn::FnArg::Typed(t) => {
                let ubox_t = *(t.pat.clone());
                match ubox_t {
                    syn::Pat::Ident(i) => {
                        fn_args_idents.push(i.ident.clone());
                    }
                    _ => panic!("Unexpected function identifier."),
                }
            }
            syn::FnArg::Receiver(_) => {
                panic!("Receiver function not expected for test case attribute.")
            }
        }
    }

    let mut result = TokenStream2::new();
    for test_case_description in test_case_descriptions {
        let test_case_name = syn::Ident::new(
            &format!("{}{}", &input.sig.ident, &test_case_description.name),
            Span::call_site(),
        );
        let literals = test_case_description.literals;
        if &literals.len() != &fn_args_idents.len() {
            panic!("Test case arguments and function input signature mismatch.");
        }

        // Needs to be immutable
        let fn_args_idents = fn_args_idents.clone();

        let test_case_quote = quote! {
            #[test]
            fn #test_case_name() {
                #(let #fn_args_idents = #literals;)*
                #fn_body
            }
        };
        result.extend(test_case_quote);
    }
    result.into()
}

struct TestCaseDescription {
    literals: Vec<syn::Lit>,
    name: String,
    // TODO add Meta attributes expected_result
}

fn parse_test_case_attributes(attr: &syn::AttributeArgs) -> TestCaseDescription {
    let mut literals: Vec<syn::Lit> = vec![];
    let mut name = "".to_string();

    for a in attr {
        match a {
            syn::NestedMeta::Meta(_) => {
                panic!("Unknown test case input type.");
            }
            syn::NestedMeta::Lit(lit) => {
                literals.push((*lit).clone());
                name.push_str(&format!("_{}", lit_to_str(lit)));
            }
        }
    }

    TestCaseDescription { literals, name }
}

fn lit_to_str(lit: &syn::Lit) -> String {
    match lit {
        syn::Lit::Bool(s) => s.value.to_string(),
        syn::Lit::Str(s) => string_to_identifier(&s.value()),
        syn::Lit::Int(s) => number_to_identifier(s.base10_digits()),
        syn::Lit::Float(s) => number_to_identifier(s.base10_digits()),
        _ => unimplemented!("String conversion for literal. Only bool, str, positive int, and float values are supported."),
    }
}

fn number_to_identifier(num: &str) -> String {
    num.chars()
        .map(|x| match x {
            '.' => 'd',
            '0'...'9' => x,
            _ => panic!("This is not a valid number. Contains unknown sign {}", x),
        })
        .collect()
}

fn string_to_identifier(num: &str) -> String {
    num.chars()
        .map(|x| match x {
            '0'...'9' => x,
            'a'...'z' => x,
            'A'...'Z' => x,
            _ => '_',
        })
        .collect()
}