ocpi-tariffs 0.55.0

OCPI tariff calculations
Documentation
//! Tests for [`defer_enclosing_replacements`]: which edits of a pass wait for a later one.

#![allow(
    clippy::indexing_slicing,
    clippy::panic,
    clippy::unwrap_used,
    reason = "test code with known-structure parsed data"
)]

use crate::json;

use super::{Edit, Json, Meaning, apply, defer_enclosing_replacements};

fn field_id(element: &json::Element<'_>, key: &str) -> json::ElemId {
    element.find_field(key).unwrap().element().id()
}

/// The payloads here are whole JSON values, written verbatim.
fn replace(elem: json::ElemId, json: &str) -> Edit {
    Edit::replace(elem, Json::raw(json), Meaning::Preserves)
}

/// `apply` rejects a replacement together with a removal inside it. So the removal goes first,
/// and the replacement follows on the next pass, against the document that pass wrote.
#[test]
fn a_replacement_enclosing_a_removal_waits_for_the_next_pass() {
    let doc = json::parse_object(r#"{"a": {"b": 1, "c": 2}}"#).unwrap();
    let outer = doc.root().find_field("a").unwrap().element();
    let removal = Edit::remove(field_id(outer, "c"), Meaning::Preserves);
    let edits = vec![replace(outer.id(), r#"{"b": 9}"#), removal.clone()];

    let first_pass = defer_enclosing_replacements(&doc, edits).unwrap();

    assert_eq!(first_pass, vec![removal]);

    let source = apply(&doc, &first_pass).unwrap();
    assert_eq!(source, r#"{"a": {"b": 1}}"#);

    let doc = json::parse_object(&source).unwrap();
    let outer = doc.root().find_field("a").unwrap().element();
    let edits = vec![replace(outer.id(), r#"{"b": 9}"#)];

    let second_pass = defer_enclosing_replacements(&doc, edits.clone()).unwrap();

    assert_eq!(second_pass, edits);
    assert_eq!(apply(&doc, &second_pass).unwrap(), r#"{"a": {"b": 9}}"#);
}

/// A rename rewrites the field's key and the replacement its value, so `apply` makes both in
/// one pass.
#[test]
fn a_replacement_and_a_rename_of_one_field_both_go_in_one_pass() {
    let doc = json::parse_object(r#"{"a": 1}"#).unwrap();
    let value = field_id(doc.root(), "a");
    let edits = vec![
        replace(value, "2"),
        Edit::rename(value, Json::string("b"), Meaning::Preserves),
    ];

    let pass = defer_enclosing_replacements(&doc, edits.clone()).unwrap();

    assert_eq!(pass, edits);
    assert_eq!(apply(&doc, &pass).unwrap(), r#"{"b": 2}"#);
}

/// A removal erases every edit inside it, so `apply` makes the removal and the replacement in one
/// pass.
#[test]
fn a_removal_enclosing_a_replacement_goes_in_the_same_pass() {
    let doc = json::parse_object(r#"{"a": {"b": 1}}"#).unwrap();
    let outer = doc.root().find_field("a").unwrap().element();
    let edits = vec![
        Edit::remove(outer.id(), Meaning::Preserves),
        replace(field_id(outer, "b"), "2"),
    ];

    let pass = defer_enclosing_replacements(&doc, edits.clone()).unwrap();

    assert_eq!(pass, edits);
    assert_eq!(apply(&doc, &pass).unwrap(), "{}");
}