json2tests — Generate Rust Tests from a Given JSON File
The macro provided in this crate allows for generating test cases from a given JSON file following the schema defined in schema.json.
The example code shows how to use the macro. Notice how you can run cargo test for this example and the tests from the JSON files are executed.
Requirements
Add the following to your Cargo.toml (if not already in it):
[]
= "2.0"
= { = "0.1.0", = "YOUR_PATH" }
= { = "1.0", = ["derive"] }
= "1.0"
= "1.0"
Please note that this macro is not yet available via cargo add, you need to clone the repository and specify the local path!
Usage
Add the following to your source code:
Generate tests from JSON takes a file path as input and will invoke a run() function for each testcase contained in the JSON. Your run function needs to be defined as follows:
;
[!NOTE] Cargo will not detect if you change something on your test files. I therefore recommend to add a
build.rsfile declaring a dependency on your JSON file(s), to ensure a recompilation when you change your tests.Example:
Panics
You can specify that your code is expected to panic by setting the panic property in the JSON file. This will add the #[should_panic] attribute to the test.
When the panic property is set to a string, it will be matched against the panic message using the #[should_panic(expected = "...")] attribute.
Example
This JSON script
will generate the following code, when implemented as described in Usage:
You (probably)

(This shall include all Rustaceans equally, without regard to gender :crab:).
Happy coding (and testing)! :rocket: