Crate json_test

Source
Expand description

A testing library for JSON Path assertions in Rust.

json-test provides a fluent API for testing JSON structures using JSONPath expressions. It’s designed to make writing tests for JSON data structures clear, concise, and maintainable.

§Core Concepts

  • JsonTest: The main entry point, providing methods to start assertions
  • JsonPathAssertion: Chainable assertions on JSON values
  • PropertyAssertions: Object property validation
  • Matchers: Flexible value matching and validation

§Features

  • JSONPath-based value extraction and validation
  • Chainable, fluent assertion API
  • Type-safe operations
  • Property existence and value validation
  • String pattern matching with regex support
  • Numeric comparisons
  • Array and object validation
  • Custom matcher support

§Examples

§Value Assertions

use json_test::JsonTest;
use serde_json::json;

let data = json!({
    "user": {
        "name": "John Doe",
        "age": 30
    }
});

let mut test = JsonTest::new(&data);

// Chain multiple assertions on a single value
test.assert_path("$.user.name")
    .exists()
    .is_string()
    .equals(json!("John Doe"));

§Numeric Validation

test.assert_path("$.score")
    .is_number()
    .is_greater_than(80)
    .is_less_than(90)
    .is_between(0, 100);

§Array Testing

test.assert_path("$.roles")
    .is_array()
    .has_length(2)
    .contains(&json!("admin"));

§Property Chaining

let data = json!({
    "user": {
        "name": "John",
        "settings": {
            "theme": "dark",
            "notifications": true
        }
    }
});

let mut test = JsonTest::new(&data);

// Chain property assertions
test.assert_path("$.user")
    .has_property("name")
    .has_property("settings")
    .properties_matching(|key| !key.starts_with("_"))
        .count(2)
        .and()
    .has_property_value("name", json!("John"));

§Advanced Matching

test.assert_path("$.user.email")
    .is_string()
    .contains_string("@")
    .matches_pattern(r"^[^@]+@[^@]+\.[^@]+$")
    .matches(|value| {
        value.as_str()
            .map(|s| !s.starts_with("admin@"))
            .unwrap_or(false)
    });

§Error Messages

The library provides clear, test-friendly error messages:

Property 'email' not found at $.user
Available properties: name, age, roles
Value mismatch at $.user.age
Expected: 25
Actual: 30

§Current Status

This library is in active development (0.1.x). While the core API is stabilizing, minor breaking changes might occur before 1.0.

Structs§

JsonPathAssertion
Provides assertions for JSON values accessed via JSONPath expressions.
JsonTest
Main entry point for JSON testing.
RegexMatcher
TypeMatcher
ValueMatcher

Enums§

JsonPathError

Traits§

ErrorContext
Extension trait for adding context to errors
JsonMatcher
Core trait for implementing JSON value matchers.
PropertyAssertions
Trait providing property testing capabilities for JSON objects.