wsb 0.275.7622

Workspace tools for every project under $PRJ: git across submodules, template stamping, GitHub, and the workbench
Documentation
use super::*;

/// TEST20141: a string is replaced at its path and nowhere else — not a
/// member of the same name deeper or shallower, not one in an array — with
/// every other byte as written; a path that is not there is said, and one
/// that holds no string is refused.
#[test]
fn test20141_a_json_string_is_replaced_at_its_path_alone() {
    let lock = "{\n  \"name\": \"ui\",\n  \"version\": \"1.0.0\",\n  \"deps\": [{\"version\": \"9\"}, \"x\"],\n  \"packages\": {\n    \"node_modules/a\": { \"version\": \"7\" },\n    \"\": {\n      \"name\": \"ui\",\n      \"version\": \"1.0.0\",\n      \"e\": \"\\\"\\\\\"\n    }\n  }\n}\n";
    assert_eq!(
        replace_string(lock, &["packages", "", "version"], "2.0.0").unwrap().unwrap(),
        lock.replacen("\"version\": \"1.0.0\",\n      \"e\"", "\"version\": \"2.0.0\",\n      \"e\"", 1)
    );
    assert_eq!(
        replace_string(lock, &["version"], "2.0.0").unwrap().unwrap(),
        lock.replacen("\"1.0.0\"", "\"2.0.0\"", 1)
    );
    assert_eq!(
        replace_string("{\"a\": [], \"version\": \"1\"}", &["version"], "2").unwrap().as_deref(),
        Some("{\"a\": [], \"version\": \"2\"}"),
        "an array before the member closes itself, not the object around it"
    );
    assert_eq!(replace_string(lock, &["packages", "x", "version"], "2").unwrap(), None);
    assert_eq!(replace_string(lock, &["absent"], "2").unwrap(), None);
    assert!(replace_string(lock, &["deps"], "2").is_err(), "an array was replaced by a string");
    assert!(replace_string(lock, &["packages"], "2").is_err(), "an object was replaced by a string");
    assert!(replace_string("{\"version\": 3}", &["version"], "2").is_err(), "a number was replaced by a string");
    assert!(replace_string("{\"a\": ", &["a"], "2").is_err(), "a text that is not JSON was edited");
    assert_eq!(
        replace_string("{\"v\\u0065rsion\": \"1\"}", &["version"], "a\"b").unwrap().unwrap(),
        "{\"v\\u0065rsion\": \"a\\\"b\"}",
        "a key is read as JSON reads it, and the value written as JSON writes it"
    );

    assert_eq!(set_top_level_string("{\n  \"name\": \"p\"\n}\n", "version", "2").unwrap(), "{\n  \"version\": \"2\",\n  \"name\": \"p\"\n}\n");
    assert_eq!(set_top_level_string("{}", "version", "2").unwrap(), "{\"version\": \"2\"}");
    assert!(set_top_level_string("[]", "version", "2").is_err(), "an array was given a member");
}