Crates.io | json-test |
lib.rs | json-test |
version | 0.1.0 |
source | src |
created_at | 2024-11-14 10:35:44.709221 |
updated_at | 2024-11-14 10:35:44.709221 |
description | A testing library for JSON Path assertions in Rust |
homepage | |
repository | https://github.com/tylium/json-test-rs |
max_upload_size | |
id | 1447672 |
size | 95,647 |
A testing library for JSON Path assertions in Rust, providing a fluent API for validating JSON structures in tests.
Add to your Cargo.toml
:
[dev-dependencies]
json-test = "0.1"
Basic usage:
use json_test::JsonTest;
use serde_json::json;
#[test]
fn test_json_structure() {
let data = json!({
"user": {
"name": "John Doe",
"age": 30,
"roles": ["user", "admin"]
}
});
let mut test = JsonTest::new(&data);
test.assert_path("$.user.name")
.exists()
.is_string()
.equals(json!("John Doe"));
test.assert_path("$.user.roles")
.is_array()
.has_length(2)
.contains(&json!("admin"));
}
test.assert_path("$.user")
.exists()
.has_property("name")
.has_property_value("age", json!(30));
test.assert_path("$.user.email")
.is_string()
.contains_string("@")
.matches_pattern(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$");
test.assert_path("$.user.age")
.is_number()
.is_greater_than(18)
.is_less_than(100);
test.assert_path("$.user.roles")
.is_array()
.has_length(2)
.contains(&json!("admin"));
test.assert_path("$.user")
.has_properties(vec!["name", "age", "roles"])
.properties_matching(|key| key.starts_with("meta_"))
.count(0)
.and()
.has_property_matching("age", |v| v.as_u64().unwrap_or(0) > 18);
test.assert_path("$.timestamp")
.matches(|value| {
value.as_str()
.map(|s| s.parse::<DateTime<Utc>>().is_ok())
.unwrap_or(false)
});
Looking for more examples? Check out the examples/
directory which showcases:
The library provides clear, test-friendly error messages:
Property 'email' not found at $.user
Available properties: name, age, roles
Array at $.user.roles has wrong length
Expected: 3
Actual: 2
This library is in active development (0.1.x). While the core API is stabilizing, minor breaking changes might occur before 1.0.
Contributions are welcome! Please see our Contributing Guide for details.
Licensed under either of:
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.