https://github.com/dimo414/parameterized_test
A Rust macro to simplify creating repeated tests with different arguments
https://github.com/dimo414/parameterized_test
Last synced: 8 months ago
JSON representation
A Rust macro to simplify creating repeated tests with different arguments
- Host: GitHub
- URL: https://github.com/dimo414/parameterized_test
- Owner: dimo414
- Created: 2020-12-01T11:46:40.000Z (over 5 years ago)
- Default Branch: main
- Last Pushed: 2023-06-16T08:19:52.000Z (about 3 years ago)
- Last Synced: 2025-02-02T04:41:13.166Z (over 1 year ago)
- Language: Rust
- Size: 8.79 KB
- Stars: 4
- Watchers: 2
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# `parameterized_test::create!()` macro
[](https://crates.io/crates/parameterized_test)
[](https://docs.rs/parameterized_test)
[](https://github.com/dimo414/parameterized_test/actions)
[](https://github.com/dimo414/parameterized_test/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](https://stackoverflow.com/a/34666891/113632) and
originally documented in [this answer](https://stackoverflow.com/a/56663823/113632), 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`.
```rust
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:
```rust
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](https://doc.rust-lang.org/rust-by-example/testing/unit_testing.html#tests-and-):
```rust
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",
}
}
```