diff --git a/crates/turborepo-lib/src/rewrite_json.rs b/crates/turborepo-lib/src/rewrite_json.rs index 7a8c0d27373029..cdc9641fcdb331 100644 --- a/crates/turborepo-lib/src/rewrite_json.rs +++ b/crates/turborepo-lib/src/rewrite_json.rs @@ -326,3 +326,86 @@ fn find_all_paths<'a>( return ranges; } + +#[cfg(test)] +mod test { + use crate::rewrite_json::{set_path, unset_path}; + + macro_rules! set_tests { + ($($name:ident: $value:expr,)*) => { + $( + #[test] + fn $name() { + let (json_document_string, expected) = $value; + assert_eq!(expected, set_path(json_document_string, vec!["parent", "child"], "\"Junior\"").unwrap()); + } + )* + } + } + + macro_rules! unset_tests { + ($($name:ident: $value:expr,)*) => { + $( + #[test] + fn $name() { + let (json_document_string, path, expected) = $value; + assert_eq!(expected, unset_path(json_document_string, path).unwrap()); + } + )* + } + } + + set_tests! { + empty_object: ( + "{}", + "{\"parent\":{\"child\":\"Junior\"}}" + ), + populated_object: ( + "{ \"other\": \"thing\" }", + "{\"parent\":{\"child\":\"Junior\"}, \"other\": \"thing\" }" + ), + trailing_comma: ( + "{ \"trailing\": \"comma\", }", + "{\"parent\":{\"child\":\"Junior\"}, \"trailing\": \"comma\", }" + ), + existing_primitive: ( + "{ \"parent\": \"thing\" }", + "{ \"parent\": {\"child\":\"Junior\"} }" + ), + existing_empty_object: ( + "{ \"parent\": {} }", + "{ \"parent\": {\"child\":\"Junior\"} }" + ), + existing_matching_object: ( + "{ \"parent\": { \"child\": \"Jerry\" } }", + "{ \"parent\": { \"child\": \"Junior\" } }" + ), + existing_bonus_child: ( + "{ \"parent\": { \"child\": { \"grandchild\": \"Morty\" } } }", + "{ \"parent\": { \"child\": \"Junior\" } }" + ), + } + + unset_tests! { + nonexistent_path: ( + r#"{ "before": {}, "experimentalSpaces": { "id": "one" }, "experimentalSpaces": { "id": "two" }, "after": {} }"#, + vec!["experimentalSpaces", "id", "nope"], + "{ \"before\": {}, \"experimentalSpaces\": { \"id\": \"one\" }, \"experimentalSpaces\": { \"id\": \"two\" }, \"after\": {} }", + ), + leaf_node: ( + r#"{ "before": {}, "experimentalSpaces": { "id": "one" }, "experimentalSpaces": { "id": "two" }, "after": {} }"#, + vec!["experimentalSpaces", "id"], + "{ \"before\": {}, \"experimentalSpaces\": { }, \"experimentalSpaces\": { }, \"after\": {} }", + ), + parent_node: ( + r#"{ "before": {}, "experimentalSpaces": { "id": "one" }, "middle": {}, "experimentalSpaces": { "id": "two" }, "after": {} }"#, + vec!["experimentalSpaces"], + "{ \"before\": {},\"middle\": {},\"after\": {} }", + ), + empty_path: ( + r#"{ "before": {}, "experimentalSpaces": { "id": "one" }, "experimentalSpaces": { "id": "two" }, "after": {} }"#, + vec![], + "{ \"before\": {}, \"experimentalSpaces\": { \"id\": \"one\" }, \"experimentalSpaces\": { \"id\": \"two\" }, \"after\": {} }", + ), + } +}