#mocking #testing #macro #proc-macro

macro arg_ripper

A proc macro for pulling local variables out of functions as arguments

1 unstable release

0.1.0 Jun 17, 2023

#1831 in Procedural macros

Download history 9/week @ 2024-02-19 1/week @ 2024-02-26 17/week @ 2024-03-11 19/week @ 2024-04-01 19/week @ 2024-04-15 17/week @ 2024-04-22

55 downloads per month

MIT license

14KB
88 lines

arg_ripper is a macro that allows for easy Dependency Injection for the purposes of mocking internal variables in functions. It contains a single macro, rip that takes in a list of local bindings (let statements) that occur within the annotated function, and generates a new function with those as arguments instead of local bindings.

Examples

#[rip(inner: i32)]
fn my_func() -> i32 {
    let inner = 42;
    inner
}

fn main() {
    assert_eq!(my_func(), 42);
    assert_eq!(ripped_my_func(69), 69);
}

The key feature that makes this useful for unit testing is the ability to change the type of the argument you are ripping. Note the the type hint on line 1 of the example above, in this case it's the same as the original version of inner, but it doesn't have to be. The only restriction is that the new code must still compile, making things like this possible:

#[rip(answer: &str)]
fn print_answer() {
    let answer: i32 = 42;
    println!("{answer}");
}

fn main() {
    print_answer();
    ripped_print_answer("Fourty Two");
}

The repository has more in depth examples of how to use this with mockall if you're curious.

Dependencies

~320–770KB
~18K SLoC