#parameterized #macro #test-cases #generate

parameterized_test

A macro to support providing arguments to test functions

2 unstable releases

0.2.1 Dec 10, 2022
0.2.0 Dec 4, 2022
0.1.0 Dec 1, 2020

#2105 in Rust patterns

Download history 437/week @ 2024-01-04 284/week @ 2024-01-11 203/week @ 2024-01-18 195/week @ 2024-01-25 162/week @ 2024-02-01 224/week @ 2024-02-08 234/week @ 2024-02-15 358/week @ 2024-02-22 228/week @ 2024-02-29 236/week @ 2024-03-07 210/week @ 2024-03-14 263/week @ 2024-03-21 226/week @ 2024-03-28 273/week @ 2024-04-04 352/week @ 2024-04-11 271/week @ 2024-04-18

1,198 downloads per month
Used in task-mon

MIT/Apache

9KB
79 lines

parameterized_test::create!() macro

crates.io docs.rs build status issues

This small crate provides a parameterized_test::create!() macro to simplify creating repeated tests with different arguments.

Inspired by Chris Morgan's StackOverflow post and originally documented in this answer, this macro works by dynamically generating a new macro which, in turn, generates separate tests for each test case passed to the generated macro.

Note: the exact API is still in development and may change in subsequent (pre-1.0) releases.

Syntax

parameterized_test::create() expects four arguments:

  • A name for the test group, which will be used as the submodule name and the name of the generated parameters macro.
  • One or more variable names, e.g. foo or (bar, baz) (note multiple variables must be parenthesized).
  • The test body, multiple statements can be enclosed in { ... }.

Example

This example creates two test cases, tests::even::bad_case and tests::even::good_case.

use parameterized_test::create;

#[cfg(test)]
mod tests {
    use super::*;

    parameterized_test::create!{ even, n, { assert_eq!(n % 2, 0); } }
    even! {
        bad_case:  1, // this test case will fail
        good_case: 2,
    }
}

Tests can also specify multiple parameters:

use parameterized_test::create;

#[cfg(test)]
mod tests {
    use super::*;

    parameterized_test::create!{ commutative, (i, j, k), {
      assert_eq!(i, j);
      assert_eq!(j, k);
      assert_eq!(k, i); 
    }}
    commutative! {
        small: (1, 1, 1),
        large: (100, 100, 100),
    }
}

The ? operator is also supported, similar to standalone tests:

use parameterized_test::create;

#[cfg(test)]
mod tests {
    use super::*;

    parameterized_test::create!{ socket, path, {
      let socket: SocketAddr = fs::read_to_string(path)?.parse()?;
      assert_eq!(socket.is_ipv6(), true);
    }}
  socket! {
        relative: "foo.txt",
        absolute: "/tmp/bar.txt",
    }
}

Dependencies

~32KB