#![allow(
clippy::unwrap_used,
clippy::panic,
clippy::expect_used,
clippy::bool_assert_comparison,
clippy::approx_constant
)]
use agent_first_data::document::{
Addressing, Document, DocumentError, Format, KeyedList, Value, add_keyed, get_path,
remove_keyed, set_path,
};
use std::collections::BTreeMap;
mod preserving {
use super::{Document, DocumentError, Format, Value};
use agent_first_data::document::DocumentResult;
fn set(format: Format, source: &str, path: &str, value: &Value) -> DocumentResult<String> {
let mut document = Document::parse(source, format)?;
document.set(path, value.clone())?;
Ok(document.source().to_string())
}
fn unset(format: Format, source: &str, path: &str) -> DocumentResult<String> {
let mut document = Document::parse(source, format)?;
if !document.unset(path)? {
return Err(DocumentError::PathNotFound { path: path.into() });
}
Ok(document.source().to_string())
}
macro_rules! backend {
($name:ident, $format:expr, $feature:literal) => {
#[cfg(feature = $feature)]
pub mod $name {
use super::*;
pub fn set(source: &str, path: &str, value: &Value) -> DocumentResult<String> {
super::set($format, source, path, value)
}
#[allow(dead_code)]
pub fn unset(source: &str, path: &str) -> DocumentResult<String> {
super::unset($format, source, path)
}
}
};
}
pub mod json {
use super::*;
pub fn set(source: &str, path: &str, value: &Value) -> DocumentResult<String> {
super::set(Format::Json, source, path, value)
}
pub fn unset(source: &str, path: &str) -> DocumentResult<String> {
super::unset(Format::Json, source, path)
}
}
backend!(toml, Format::Toml, "toml");
backend!(yaml, Format::Yaml, "yaml");
backend!(ini, Format::Ini, "ini");
backend!(dotenv, Format::Dotenv, "dotenv");
}
#[cfg(all(unix, feature = "libc"))]
#[test]
fn a_saved_document_refuses_a_target_replaced_by_a_fifo() {
use agent_first_data::document::DocumentFile;
use std::os::unix::ffi::OsStrExt;
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("config.json");
std::fs::write(&path, "{\"a\":1}").unwrap();
let mut document = DocumentFile::open(&path, None).unwrap();
document.set("a", Value::Integer(2)).unwrap();
std::fs::remove_file(&path).unwrap();
let fifo_path = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap();
assert_eq!(unsafe { libc::mkfifo(fifo_path.as_ptr(), 0o600) }, 0);
assert!(document.ensure_mutable("set").is_err());
assert!(document.save().is_err());
assert!(!std::fs::metadata(&path).unwrap().is_file());
}
#[test]
fn source_edits_read_back_the_staged_value_across_container_shapes() {
let mut cases = vec![
(Format::Json, r#"["keep"]"#, "-"),
(Format::Json, r#"{"nested":[[]],"keep":true}"#, "nested.0.-"),
];
#[cfg(feature = "toml")]
cases.extend([
(
Format::Toml,
"settings = { keep = 1 }\n",
"settings.new.text",
),
(Format::Toml, "items = [] # keep\n", "items.-"),
(Format::Toml, "items = [\n 'keep', # keep\n]\n", "items.-"),
(Format::Toml, "nested = [[1]]\n", "nested.0.-"),
]);
#[cfg(feature = "yaml")]
cases.extend([
(Format::Yaml, "[]\n", "-"),
(Format::Yaml, "nested:\n - []\nkeep: true\n", "nested.0.-"),
(Format::Yaml, "root:\n keep: true\n", "root.-"),
]);
for (format, source, path) in cases {
let mut document = Document::parse(source, format).unwrap();
document
.set(path, Value::String("added".into()))
.unwrap_or_else(|error| panic!("{format:?} {path}: {error}"));
let reopened = Document::parse(document.source(), format).unwrap();
assert_eq!(
reopened.value(),
document.value(),
"{format:?} {path}: {}",
document.source()
);
}
}
#[cfg(feature = "yaml")]
#[test]
fn yaml_sequence_edits_through_an_alias_never_rewrite_the_anchor() {
let source = "base: &items\n - id: one\nother: *items\n";
let mut failed = Vec::new();
for verb in ["set", "unset", "add", "remove"] {
let mut document = Document::parse(source, Format::Yaml).unwrap();
let before = document.value().clone();
let fields = [("id".to_string(), Value::String("two".into()))];
let result = match verb {
"set" => document.set(
"other.-",
Value::Object(fields.clone().into_iter().collect()),
),
"unset" => document.unset("other.0").map(|_| ()),
"add" => document.add("other", "two", "id", &fields),
_ => document.remove("other", "one", "id"),
};
if result.is_ok() || document.source() != source || document.value() != &before {
failed.push((verb, result, document.source().to_string()));
}
}
assert!(
failed.is_empty(),
"alias edits must refuse without changes: {failed:?}"
);
}
#[cfg(feature = "toml")]
#[test]
fn replacing_an_array_of_tables_reports_the_requested_operation() {
let source = "[[items]]\nid = 'one'\n";
let mut document = Document::parse(source, Format::Toml).unwrap();
let error = document.set("items", Value::Array(Vec::new())).unwrap_err();
assert!(
matches!(error, DocumentError::UnsupportedOperation { operation, .. } if operation == "set")
);
assert_eq!(document.source(), source);
}
#[cfg(feature = "yaml")]
#[test]
fn yaml_empty_array_append_refuses_non_finite_values_without_staging_changes() {
for (source, path) in [
("[]\n", "-"),
("items: []\n", "items.-"),
("nested:\n - []\n", "nested.0.-"),
] {
for invalid in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
let mut document = Document::parse(source, Format::Yaml).unwrap();
let before = document.value().clone();
assert!(
document.set(path, Value::Float(invalid)).is_err(),
"{source:?} {invalid}"
);
assert_eq!(document.source(), source);
assert_eq!(document.value(), &before);
}
}
}
#[test]
fn test_json_round_trip() {
let json_str = r#"{"imap": {"host": "mail.example.com", "port": 993}}"#;
let value = Format::Json.load(json_str).unwrap();
let host = get_path(&value, "imap.host", Addressing::INDEX_ONLY).unwrap();
assert_eq!(host.as_str().unwrap(), "mail.example.com");
let mut value = value;
set_path(
&mut value,
"imap.port",
&Value::Integer(587),
Addressing::INDEX_ONLY,
)
.unwrap();
let output = Format::Json.save(&value).unwrap();
let reloaded = Format::Json.load(&output).unwrap();
let port = get_path(&reloaded, "imap.port", Addressing::INDEX_ONLY).unwrap();
assert_eq!(port.as_integer().unwrap(), 587);
}
#[test]
fn test_json_scalar_edit_preserves_unrelated_source() {
let source = "{\n \"z\": 1e+3,\n \"nested\": { \"keep\": \"\\u0061\", \"target\": 2 }\n}\n";
let edited = preserving::json::set(source, "nested.target", &Value::Integer(7)).unwrap();
assert_eq!(
edited,
"{\n \"z\": 1e+3,\n \"nested\": { \"keep\": \"\\u0061\", \"target\": 7 }\n}\n"
);
}
#[test]
fn test_json_unset_preserves_unrelated_source() {
let source = "{\n \"keep\": 1e+3,\n \"remove\": 2,\n \"last\": \"x\"\n}\n";
let edited = preserving::json::unset(source, "remove").unwrap();
assert_eq!(edited, "{\n \"keep\": 1e+3,\n \"last\": \"x\"\n}\n");
}
#[test]
fn test_json_unset_last_member_stays_inside_parent() {
let source = r#"{"arr": [{"n": 1}], "b": {"x": 2}}"#;
let edited = preserving::json::unset(source, "b.x").unwrap();
assert_eq!(edited, r#"{"arr": [{"n": 1}], "b": {}}"#);
}
#[test]
fn test_json_golden_variants_preserve_untouched_source() {
let compact = "{\"keep\":\"\\u0061\",\"target\":1e+3,\"tail\":[1,2]}";
let edited = preserving::json::set(compact, "target", &Value::Integer(7)).unwrap();
assert!(edited.contains("\\u0061"));
assert!(edited.contains("[1,2]"));
assert_eq!(edited, "{\"keep\":\"\\u0061\",\"target\":7,\"tail\":[1,2]}");
let crlf = "{\r\n \"keep\": 1e+3,\r\n \"target\": 2\r\n}\r\n";
let edited = preserving::json::unset(crlf, "target").unwrap();
assert_eq!(edited, "{\r\n \"keep\": 1e+3\r\n}\r\n");
}
#[test]
fn test_json_set_creates_missing_parent_objects() {
let source = "{\n \"a\": 1\n}\n";
let edited = preserving::json::set(
source,
"imap.host",
&Value::String("mail.example.com".to_string()),
)
.unwrap();
assert_eq!(
edited,
"{\n \"a\": 1,\n \"imap\": {\n \"host\": \"mail.example.com\"\n }\n}\n"
);
}
#[test]
fn test_json_set_creates_deep_missing_parents_in_empty_object() {
let source = "{\n \"a\": {}\n}\n";
let edited = preserving::json::set(source, "a.b.c", &Value::Integer(1)).unwrap();
let parsed: serde_json::Value = serde_json::from_str(&edited).unwrap();
assert_eq!(parsed["a"]["b"]["c"], serde_json::json!(1));
}
#[test]
fn test_json_set_replaces_existing_array_value() {
let source = "{\n \"steps\": [1, 2]\n}\n";
let edited = preserving::json::set(
source,
"steps",
&Value::Array(vec![Value::Integer(3), Value::Integer(4)]),
)
.unwrap();
assert_eq!(edited, "{\n \"steps\": [3,4]\n}\n");
}
#[test]
fn test_json_set_replaces_scalar_with_empty_array() {
let source = "{\n \"steps\": \"none\"\n}\n";
let edited = preserving::json::set(source, "steps", &Value::Array(vec![])).unwrap();
assert_eq!(edited, "{\n \"steps\": []\n}\n");
}
#[test]
fn test_json_set_rejects_child_under_scalar() {
let source = "{\n \"a\": 1\n}\n";
let error = preserving::json::set(source, "a.b", &Value::Integer(2));
assert!(matches!(error, Err(DocumentError::NotTraversable { .. })));
}
#[cfg(feature = "toml")]
#[test]
fn test_toml_round_trip() {
let toml_str = r#"
[database]
host = "localhost"
port = 5432
"#;
let value = Format::Toml.load(toml_str).unwrap();
let host = get_path(&value, "database.host", Addressing::INDEX_ONLY).unwrap();
assert_eq!(host.as_str().unwrap(), "localhost");
let mut value = value;
set_path(
&mut value,
"database.port",
&Value::Integer(3306),
Addressing::INDEX_ONLY,
)
.unwrap();
let output = Format::Toml.save(&value).unwrap();
let reloaded = Format::Toml.load(&output).unwrap();
let port = get_path(&reloaded, "database.port", Addressing::INDEX_ONLY).unwrap();
assert_eq!(port.as_integer().unwrap(), 3306);
}
#[cfg(feature = "toml")]
#[test]
fn test_toml_scalar_edit_preserves_comments_and_datetime() {
let source = "# keep\n[database]\nport = 5432 # note\nwhen = 2024-01-01T00:00:00Z\n";
let edited = preserving::toml::set(source, "database.port", &Value::Integer(3306)).unwrap();
assert_eq!(
edited,
"# keep\n[database]\nport = 3306 # note\nwhen = 2024-01-01T00:00:00Z\n"
);
}
#[cfg(feature = "toml")]
#[test]
fn test_toml_unset_preserves_comments() {
let source = "# keep\n[database]\nremove = 1 # remove\nkeep = 2024-01-01T00:00:00Z\n";
let edited = preserving::toml::unset(source, "database.remove").unwrap();
assert_eq!(edited, "# keep\n[database]\nkeep = 2024-01-01T00:00:00Z\n");
}
#[cfg(feature = "toml")]
#[test]
fn test_toml_set_and_unset_address_the_same_inline_table_keys() {
let source = "[dependencies]\nfoo = { version = \"1\", path = \"../foo\" } # pinned\n";
let edited = preserving::toml::set(
source,
"dependencies.foo.path",
&Value::String("../bar".to_string()),
)
.unwrap();
assert_eq!(
edited,
"[dependencies]\nfoo = { version = \"1\", path = \"../bar\" } # pinned\n"
);
let removed = preserving::toml::unset(&edited, "dependencies.foo.path").unwrap();
assert_eq!(
removed,
"[dependencies]\nfoo = { version = \"1\" } # pinned\n"
);
let missing = preserving::toml::unset(&removed, "dependencies.foo.absent").unwrap_err();
assert!(
matches!(
missing,
agent_first_data::document::DocumentError::PathNotFound { .. }
),
"{missing:?}"
);
}
#[cfg(feature = "toml")]
#[test]
fn test_toml_set_and_unset_address_the_same_array_elements() {
use preserving::toml::{set as set_preserving, unset as unset_preserving};
let source = "arr = [{ k = 1, j = 2 }, { k = 3 }] # keep\nn = [1, 2, 3]\n";
let set = set_preserving(source, "arr.1.k", &Value::Integer(9)).unwrap();
assert_eq!(
set,
"arr = [{ k = 1, j = 2 }, { k = 9 }] # keep\nn = [1, 2, 3]\n"
);
let inner = unset_preserving(&set, "arr.0.j").unwrap();
assert_eq!(
inner,
"arr = [{ k = 1 }, { k = 9 }] # keep\nn = [1, 2, 3]\n"
);
let element = unset_preserving(&inner, "arr.1").unwrap();
assert_eq!(element, "arr = [{ k = 1 }] # keep\nn = [1, 2, 3]\n");
let first = unset_preserving(&element, "n.0").unwrap();
assert_eq!(first, "arr = [{ k = 1 }] # keep\nn = [2, 3]\n");
for missing in ["n.5", "n.x", "arr.3.k"] {
let error = unset_preserving(&first, missing).unwrap_err();
assert!(error.is_address_miss(), "{missing}: {error:?}");
}
}
#[cfg(feature = "toml")]
#[test]
fn test_toml_escaped_dot_keys_round_trip_through_set_and_unset() {
use preserving::toml::{set as set_preserving, unset as unset_preserving};
let source = "[hosts]\n\"example.com\" = 1 # primary\n";
let set = set_preserving(source, "hosts.example\\.com", &Value::Integer(2)).unwrap();
assert_eq!(set, "[hosts]\n\"example.com\" = 2 # primary\n");
let added = set_preserving(&set, "hosts.new\\.org", &Value::Integer(3)).unwrap();
assert_eq!(
added,
"[hosts]\n\"example.com\" = 2 # primary\n\"new.org\" = 3\n"
);
let removed = unset_preserving(&added, "hosts.example\\.com").unwrap();
assert_eq!(removed, "[hosts]\n\"new.org\" = 3\n");
}
#[cfg(feature = "toml")]
#[test]
fn test_toml_edits_keep_a_byte_order_mark() {
use preserving::toml::{set as set_preserving, unset as unset_preserving};
for source in [
"\u{feff}title = \"a\"\nx = 1\n",
"\u{feff}title = \"a\"\r\nx = 1\r\n",
] {
let set = set_preserving(source, "title", &Value::String("b".into())).unwrap();
assert!(set.starts_with("\u{feff}title = \"b\""), "{set:?}");
let unset = unset_preserving(&set, "x").unwrap();
assert!(unset.starts_with('\u{feff}'), "{unset:?}");
assert_eq!(unset.matches('\u{feff}').count(), 1);
}
}
#[cfg(feature = "toml")]
#[test]
fn test_toml_append_and_new_inline_key_keep_layout() {
use preserving::toml::set as set_preserving;
let three = Value::Integer(3);
for (source, expected) in [
("a = [1]\n", "a = [1, 3]\n"),
("a = [ 1, 2 ]\n", "a = [ 1, 2, 3 ]\n"),
(
"a = [\n \"x\", # c1\n \"y\" # c2\n]\n",
"a = [\n \"x\", # c1\n \"y\", # c2\n 3\n]\n",
),
(
"a = [\n \"x\",\n \"y\",\n # own\n]\n",
"a = [\n \"x\",\n \"y\",\n # own\n 3,\n]\n",
),
(
"a = [\n \"x\",\n \"y\" # c2\n # own\n]\n",
"a = [\n \"x\",\n \"y\", # c2\n # own\n 3\n]\n",
),
] {
assert_eq!(set_preserving(source, "a.-", &three).unwrap(), expected);
}
let v = Value::String("v".into());
for (source, expected) in [
("x = { y = 1 }\n", "x = { y = 1, z = \"v\" }\n"),
("x = {y = 1}\n", "x = {y = 1, z = \"v\"}\n"),
] {
assert_eq!(set_preserving(source, "x.z", &v).unwrap(), expected);
}
for (source, expected) in [
("x = { y = 1 }\n", "x = { y = 1, z = { w = \"v\" } }\n"),
("x = {y = 1}\n", "x = {y = 1, z = { w = \"v\" }}\n"),
] {
assert_eq!(set_preserving(source, "x.z.w", &v).unwrap(), expected);
}
}
#[cfg(feature = "toml")]
#[test]
fn test_toml_unset_array_element_keeps_comments_with_their_elements() {
use preserving::toml::unset as unset_preserving;
for (source, path, expected) in [
(
"a = [\n 1, # one\n 2, # two\n 3, # three\n]\n",
"a.1",
"a = [\n 1, # one\n 3, # three\n]\n",
),
(
"a = [\n 1, # one\n 2, # two\n]\n",
"a.1",
"a = [\n 1, # one\n]\n",
),
(
"a = [\n 1, # one\n 2,\n]\n",
"a.1",
"a = [\n 1, # one\n]\n",
),
(
"a = [\n 1, # one\n 2 # two\n]\n",
"a.1",
"a = [\n 1 # one\n]\n",
),
(
"a = [\n 1, # one\n 2, # two\n]\n",
"a.0",
"a = [\n 2, # two\n]\n",
),
("a = [1, 2, 3]\n", "a.1", "a = [1, 3]\n"),
("a = [1, 2, 3]\n", "a.2", "a = [1, 2]\n"),
("a = [ 1, 2 ]\n", "a.1", "a = [ 1 ]\n"),
(
"a = [\n 1, # one\n # about two\n 2,\n]\n",
"a.0",
"a = [\n # about two\n 2,\n]\n",
),
(
"a = [ # header\n # about one\n 1, # one\n # about two\n 2,\n]\n",
"a.0",
"a = [ # header\n # about two\n 2,\n]\n",
),
(
"a = [ # header\n 1, # one\n]\n",
"a.0",
"a = [ # header\n]\n",
),
(
"a = [\n # about one\n 1, 2\n]\n",
"a.0",
"a = [\n 2\n]\n",
),
("a = [ 1, 2 ]\n", "a.0", "a = [ 2 ]\n"),
("a = [1, 2]\n", "a.0", "a = [2]\n"),
] {
assert_eq!(
unset_preserving(source, path).unwrap(),
expected,
"unset {path} from {source:?}"
);
}
}
#[cfg(feature = "toml")]
#[test]
fn test_toml_golden_array_and_datetime_bytes() {
let source = "# keep\nwhen = 2024-01-01T00:00:00Z\nvalues = [1, 2, 3]\ntarget = 1\n";
let edited = preserving::toml::set(source, "target", &Value::Integer(2)).unwrap();
assert!(edited.contains("when = 2024-01-01T00:00:00Z"));
assert!(edited.contains("values = [1, 2, 3]"));
assert!(edited.ends_with("target = 2\n"));
let arrays =
"global_target = 1\n\n[[servers]]\nname = \"one\"\n\n[[servers]]\nname = \"two\"\n";
let edited = preserving::toml::set(arrays, "global_target", &Value::Integer(2)).unwrap();
assert!(edited.contains("[[servers]]\nname = \"one\""));
assert!(edited.contains("global_target = 2"), "{edited}");
assert!(edited.contains("[[servers]]\nname = \"two\""), "{edited}");
}
#[cfg(feature = "toml")]
#[test]
fn test_toml_rejects_unrepresentable_null_and_u64() {
let null_error = preserving::toml::set("value = 1\n", "value", &Value::Null).unwrap_err();
assert!(null_error.to_string().contains("no null"));
let unsigned_error =
preserving::toml::set("value = 1\n", "value", &Value::Unsigned(u64::MAX)).unwrap_err();
assert!(unsigned_error.to_string().contains("exceeds TOML"));
}
#[cfg(feature = "yaml")]
#[test]
fn test_yaml_round_trip() {
let yaml_str = r#"
server:
host: localhost
port: 8080
"#;
let value = Format::Yaml.load(yaml_str).unwrap();
let host = get_path(&value, "server.host", Addressing::INDEX_ONLY).unwrap();
assert_eq!(host.as_str().unwrap(), "localhost");
let mut value = value;
set_path(
&mut value,
"server.port",
&Value::Integer(9000),
Addressing::INDEX_ONLY,
)
.unwrap();
let output = Format::Yaml.save(&value).unwrap();
let reloaded = Format::Yaml.load(&output).unwrap();
let port = get_path(&reloaded, "server.port", Addressing::INDEX_ONLY).unwrap();
assert_eq!(port.as_integer().unwrap(), 9000);
}
#[cfg(feature = "yaml")]
#[test]
fn test_yaml_scalar_edit_preserves_comments_and_float() {
let source = "# keep\nserver:\n host: localhost # host\n ratio: 1.0\n";
let edited = preserving::yaml::set(
source,
"server.host",
&Value::String("example.com".to_string()),
)
.unwrap();
assert_eq!(
edited,
"# keep\nserver:\n host: example.com # host\n ratio: 1.0\n"
);
}
#[cfg(feature = "yaml")]
#[test]
fn test_yaml_unset_preserves_comments() {
let source = "# keep\nserver:\n remove: 1 # remove\n keep: 1.0\n";
let edited = preserving::yaml::unset(source, "server.remove").unwrap();
assert_eq!(edited, "# keep\nserver:\n keep: 1.0\n");
}
#[cfg(feature = "yaml")]
#[test]
fn test_yaml_golden_styles_and_crlf() {
let source =
"# keep\r\nroot:\r\n quoted: 'old'\r\n literal: |\r\n unchanged\r\n target: 1.0\r\n";
let edited = preserving::yaml::set(source, "root.target", &Value::Float(2.0)).unwrap();
assert!(edited.contains("# keep\r\n"));
assert!(edited.contains("quoted: 'old'\r\n"));
assert!(edited.contains("literal: |\r\n unchanged\r\n"));
}
#[cfg(feature = "yaml")]
#[test]
fn test_yaml_golden_flow_tag_anchor_and_alias_untouched() {
let source = "defaults: &defaults {name: old}\ncopy: *defaults\ntarget: 1\nflow: [1, 2]\n";
let edited = preserving::yaml::set(source, "target", &Value::Integer(2)).unwrap();
assert!(edited.contains("defaults: &defaults {name: old}"));
assert!(edited.contains("copy: *defaults"));
assert!(edited.contains("flow: [1, 2]"));
}
#[cfg(feature = "yaml")]
#[test]
fn test_yaml_keyed_collection_edit_preserves_unrelated_source() {
let source = "# keep\nitems:\n - id: a\n name: A\nkeep: 1.0\n";
let mut document = Document::parse(source, Format::Yaml).unwrap();
document
.add(
"items",
"b",
"id",
&[("name".to_string(), Value::String("B".to_string()))],
)
.unwrap();
let added = document.source().to_string();
assert!(added.contains("keep: 1.0"));
let parsed = Format::Yaml.load(&added).unwrap();
let items = parsed.get("items").unwrap().as_array().unwrap();
assert_eq!(items.len(), 2);
assert_eq!(items[1].get("id").and_then(Value::as_str), Some("b"));
assert_eq!(items[1].get("name").and_then(Value::as_str), Some("B"));
assert!(parsed.get("name").is_none());
document.remove("items", "b", "id").unwrap();
let removed = document.source().to_string();
assert!(removed.contains("keep: 1.0"));
assert_eq!(
Format::Yaml
.load(&removed)
.unwrap()
.get("items")
.unwrap()
.as_array()
.unwrap()
.len(),
1
);
}
#[cfg(feature = "yaml")]
#[test]
fn test_yaml_cst_numeric_path_adapter_and_unsupported_escaped_keys() {
let source = "items:\n - name: first\n - name: second\nkeep: 1.0\n";
let edited = preserving::yaml::set(
source,
"items.1.name",
&Value::String("changed".to_string()),
)
.unwrap();
assert!(edited.contains("name: changed"));
assert!(edited.contains("keep: 1.0"));
let error = preserving::yaml::set(
"map:\n x: 1\n",
r"map.key\.with.dot",
&Value::String("x".to_string()),
)
.unwrap_err();
assert!(matches!(error, DocumentError::UnsupportedOperation { .. }));
}
#[cfg(feature = "yaml")]
#[test]
fn test_yaml_uses_strict_yaml_1_2_parsing() {
let value = Format::Yaml.load("country: NO\nenabled: true\n").unwrap();
assert_eq!(
get_path(&value, "country", Addressing::INDEX_ONLY)
.unwrap()
.as_str(),
Some("NO")
);
assert_eq!(
get_path(&value, "enabled", Addressing::INDEX_ONLY)
.unwrap()
.as_bool(),
Some(true)
);
assert!(Format::Yaml.load("name: first\nname: second\n").is_err());
}
#[test]
fn test_keyed_list_add_and_remove() {
let mut root = Value::Object(BTreeMap::new());
let keyed_lists = [KeyedList {
prefix: "identities",
slug_field: "identity",
}];
if let Some(obj) = root.as_object_mut() {
obj.insert("identities".to_string(), Value::Array(vec![]));
}
add_keyed(
&mut root,
"identities",
"alice",
&keyed_lists,
None,
&[
(
"email".to_string(),
Value::String("alice@example.com".to_string()),
),
("name".to_string(), Value::String("Alice".to_string())),
],
)
.unwrap();
let alice_email = get_path(
&root,
"identities.alice.email",
Addressing::keyed(&keyed_lists),
)
.unwrap();
assert_eq!(alice_email.as_str().unwrap(), "alice@example.com");
add_keyed(
&mut root,
"identities",
"bob",
&keyed_lists,
None,
&[(
"email".to_string(),
Value::String("bob@example.com".to_string()),
)],
)
.unwrap();
let arr = root.get("identities").unwrap().as_array().unwrap();
assert_eq!(arr.len(), 2);
remove_keyed(&mut root, "identities", "alice", &keyed_lists).unwrap();
let arr = root.get("identities").unwrap().as_array().unwrap();
assert_eq!(arr.len(), 1);
let bob_email = get_path(
&root,
"identities.bob.email",
Addressing::keyed(&keyed_lists),
)
.unwrap();
assert_eq!(bob_email.as_str().unwrap(), "bob@example.com");
}
#[test]
fn test_document_edits_a_root_json_keyed_list() {
let source = "[\n {\"id\": \"a\", \"name\": \"\\u0041\"}\n]\n";
let mut document = Document::parse(source, Format::Json).unwrap();
document
.add(
"",
"b",
"id",
&[("name".to_string(), Value::String("B".to_string()))],
)
.unwrap();
assert_eq!(document.value().as_array().unwrap().len(), 2);
assert!(document.source().contains(r#""name": "\u0041""#));
document.remove("", "b", "id").unwrap();
assert_eq!(document.value().as_array().unwrap().len(), 1);
assert_eq!(document.source(), source);
}
#[cfg(feature = "yaml")]
#[test]
fn test_document_edits_a_root_yaml_keyed_list() {
let source = "# keep\n- id: a\n name: 'A'\n";
let mut document = Document::parse(source, Format::Yaml).unwrap();
document
.add(
"",
"b",
"id",
&[("name".to_string(), Value::String("B".to_string()))],
)
.unwrap();
assert_eq!(document.value().as_array().unwrap().len(), 2);
assert!(document.source().contains("# keep"));
assert!(document.source().contains("name: 'A'"));
document.remove("", "b", "id").unwrap();
assert_eq!(document.value().as_array().unwrap().len(), 1);
assert_eq!(document.source(), source);
}
#[test]
fn test_escaped_dotted_key_matching() {
let json_str = r#"{"actions":{"case.add":{"steps":[{"move":"archive"}]}}}"#;
let value = Format::Json.load(json_str).unwrap();
let steps = get_path(&value, r"actions.case\.add.steps", Addressing::INDEX_ONLY).unwrap();
assert!(steps.is_array());
}
#[test]
fn test_escaped_keyed_list_prefix_routes_consistently() {
let mut root = Value::Object(BTreeMap::from([(
"group.list".to_string(),
Value::Object(BTreeMap::from([(
"items".to_string(),
Value::Array(vec![]),
)])),
)]));
let keyed_lists = [KeyedList {
prefix: r"group\.list.items",
slug_field: "id",
}];
add_keyed(
&mut root,
r"group\.list.items",
"one",
&keyed_lists,
None,
&[("name".to_string(), Value::String("first".to_string()))],
)
.unwrap();
assert_eq!(
get_path(
&root,
r"group\.list.items.one.name",
Addressing::keyed(&keyed_lists)
)
.unwrap()
.as_str(),
Some("first")
);
set_path(
&mut root,
r"group\.list.items.one.name",
&Value::String("second".to_string()),
Addressing::keyed(&keyed_lists),
)
.unwrap();
assert_eq!(
get_path(
&root,
r"group\.list.items.one.name",
Addressing::keyed(&keyed_lists)
)
.unwrap()
.as_str(),
Some("second")
);
}
#[test]
fn test_type_coercion() {
let mut root = Value::Object(BTreeMap::new());
set_path(
&mut root,
"port",
&Value::Integer(993),
Addressing::INDEX_ONLY,
)
.unwrap();
let port = get_path(&root, "port", Addressing::INDEX_ONLY).unwrap();
assert_eq!(port.as_integer(), Some(993));
set_path(
&mut root,
"enabled",
&Value::Bool(true),
Addressing::INDEX_ONLY,
)
.unwrap();
let enabled = get_path(&root, "enabled", Addressing::INDEX_ONLY).unwrap();
assert_eq!(enabled.as_bool(), Some(true));
set_path(
&mut root,
"timeout",
&Value::Float(3.14),
Addressing::INDEX_ONLY,
)
.unwrap();
let timeout = get_path(&root, "timeout", Addressing::INDEX_ONLY).unwrap();
match timeout.as_float() {
Some(f) => assert!((f - 3.14).abs() < 0.01),
None => panic!("expected float"),
}
set_path(
&mut root,
"name",
&Value::String("Alice".to_string()),
Addressing::INDEX_ONLY,
)
.unwrap();
let name = get_path(&root, "name", Addressing::INDEX_ONLY).unwrap();
assert_eq!(name.as_str(), Some("Alice"));
}
#[test]
fn test_scalar_array_replacement() {
let mut root = Value::Object(BTreeMap::new());
set_path(
&mut root,
"tags",
&Value::Array(vec![
Value::String("dev".to_string()),
Value::String("staging".to_string()),
Value::String("prod".to_string()),
]),
Addressing::INDEX_ONLY,
)
.unwrap();
let tags = get_path(&root, "tags", Addressing::INDEX_ONLY).unwrap();
let arr = tags.as_array().unwrap();
assert_eq!(arr.len(), 3);
assert_eq!(arr[0].as_str(), Some("dev"));
assert_eq!(arr[1].as_str(), Some("staging"));
assert_eq!(arr[2].as_str(), Some("prod"));
}
#[test]
fn test_nested_object_creation() {
let mut root = Value::Object(BTreeMap::new());
set_path(
&mut root,
"server.database.connection.host",
&Value::String("localhost".to_string()),
Addressing::INDEX_ONLY,
)
.unwrap();
let host = get_path(
&root,
"server.database.connection.host",
Addressing::INDEX_ONLY,
)
.unwrap();
assert_eq!(host.as_str().unwrap(), "localhost");
}
#[test]
fn test_json_array_coercion() {
let mut root = Value::Object(BTreeMap::new());
set_path(
&mut root,
"config",
&Value::Array(vec![
Value::String("a".to_string()),
Value::String("b".to_string()),
Value::String("c".to_string()),
]),
Addressing::INDEX_ONLY,
)
.unwrap();
let config = get_path(&root, "config", Addressing::INDEX_ONLY).unwrap();
let arr = config.as_array().unwrap();
assert_eq!(arr.len(), 3);
}
#[test]
fn test_type_prefix_coercion() {
let mut root = Value::Object(BTreeMap::new());
set_path(
&mut root,
"field1",
&Value::String("true".to_string()),
Addressing::INDEX_ONLY,
)
.unwrap();
let val = get_path(&root, "field1", Addressing::INDEX_ONLY).unwrap();
assert_eq!(val.as_str(), Some("true"));
set_path(
&mut root,
"field2",
&Value::Bool(true),
Addressing::INDEX_ONLY,
)
.unwrap();
let val = get_path(&root, "field2", Addressing::INDEX_ONLY).unwrap();
assert_eq!(val.as_bool(), Some(true));
}
#[test]
fn test_numeric_boundaries_do_not_narrow_unsigned_or_float() {
use agent_first_data::document::{ValueType, value_from_type};
let max = value_from_type(ValueType::Number, Some("18446744073709551615")).unwrap();
assert_eq!(max.as_unsigned(), Some(u64::MAX));
let precise = value_from_type(ValueType::Number, Some("9007199254740993")).unwrap();
assert_eq!(precise.as_integer(), Some(9_007_199_254_740_993));
let float = value_from_type(ValueType::Number, Some("3.0")).unwrap();
assert_eq!(float, Value::Number("3.0".to_string()));
assert_eq!(
value_from_type(ValueType::Number, Some(&i64::MIN.to_string()))
.unwrap()
.as_integer(),
Some(i64::MIN)
);
assert_eq!(
value_from_type(ValueType::Number, Some(&i64::MAX.to_string()))
.unwrap()
.as_integer(),
Some(i64::MAX)
);
assert_eq!(
value_from_type(ValueType::Number, Some("9007199254740991"))
.unwrap()
.as_integer(),
Some(9_007_199_254_740_991)
);
assert_eq!(
value_from_type(ValueType::Number, Some("9007199254740993"))
.unwrap()
.as_integer(),
Some(9_007_199_254_740_993)
);
}
#[test]
fn test_json_unsigned_boundary_round_trip() {
let value = Format::Json
.load("{\"n\":18446744073709551615,\"f\":3.0}")
.unwrap();
assert_eq!(
get_path(&value, "n", Addressing::INDEX_ONLY)
.unwrap()
.as_unsigned(),
Some(u64::MAX)
);
assert_eq!(
get_path(&value, "f", Addressing::INDEX_ONLY).unwrap(),
Value::Number("3.0".to_string())
);
let huge_exponent = Format::Json.load("1e400").unwrap();
assert_eq!(huge_exponent, Value::Number("1e+400".to_string()));
}
#[test]
fn test_json_number_literal_fidelity_matrix() {
let huge_int = "123456789012345678901234567890";
let precise_float = "0.1000000000000000055511151231257827";
let source = format!(
"{{\"huge\":{huge_int},\"precise\":{precise_float},\"exp\":1e+140,\"neg_zero_int\":-0,\"neg_zero_float\":-0.0}}"
);
let value = Format::Json.load(&source).unwrap();
assert_eq!(
get_path(&value, "huge", Addressing::INDEX_ONLY).unwrap(),
Value::Number(huge_int.to_string())
);
assert_eq!(
get_path(&value, "precise", Addressing::INDEX_ONLY).unwrap(),
Value::Number(precise_float.to_string())
);
assert_eq!(
get_path(&value, "exp", Addressing::INDEX_ONLY).unwrap(),
Value::Number("1e+140".to_string())
);
assert_eq!(
get_path(&value, "neg_zero_int", Addressing::INDEX_ONLY).unwrap(),
Value::Number("-0".to_string())
);
assert_eq!(
get_path(&value, "neg_zero_float", Addressing::INDEX_ONLY).unwrap(),
Value::Number("-0.0".to_string())
);
let mut root = value;
set_path(
&mut root,
"set_huge",
&Value::Number(huge_int.to_string()),
Addressing::INDEX_ONLY,
)
.unwrap();
assert_eq!(
get_path(&root, "set_huge", Addressing::INDEX_ONLY).unwrap(),
Value::Number(huge_int.to_string())
);
assert_eq!(
get_path(
&Format::Json.load("{\"u\":18446744073709551615}").unwrap(),
"u",
Addressing::INDEX_ONLY
)
.unwrap()
.as_unsigned(),
Some(u64::MAX)
);
}
#[cfg(feature = "yaml")]
#[test]
fn test_yaml_unsigned_boundary_round_trip() {
let value = Format::Yaml
.load("n: 18446744073709551615\nf: 3.0\n")
.unwrap();
assert_eq!(
get_path(&value, "n", Addressing::INDEX_ONLY)
.unwrap()
.as_unsigned(),
Some(u64::MAX)
);
assert_eq!(
get_path(&value, "f", Addressing::INDEX_ONLY).unwrap(),
Value::Number("3.0".to_string())
);
}
#[test]
fn test_json_numeric_boundary_matrix() {
let source = format!(
"{{\"min\":{},\"max\":{},\"above\":{},\"u\":{},\"p\":9007199254740993,\"f\":1e-10}}",
i64::MIN,
i64::MAX,
i64::MAX as u128 + 1,
u64::MAX
);
let value = Format::Json.load(&source).unwrap();
assert_eq!(
get_path(&value, "min", Addressing::INDEX_ONLY)
.unwrap()
.as_integer(),
Some(i64::MIN)
);
assert_eq!(
get_path(&value, "max", Addressing::INDEX_ONLY)
.unwrap()
.as_integer(),
Some(i64::MAX)
);
assert_eq!(
get_path(&value, "above", Addressing::INDEX_ONLY)
.unwrap()
.as_unsigned(),
Some(i64::MAX as u64 + 1)
);
assert_eq!(
get_path(&value, "u", Addressing::INDEX_ONLY)
.unwrap()
.as_unsigned(),
Some(u64::MAX)
);
assert_eq!(
get_path(&value, "f", Addressing::INDEX_ONLY).unwrap(),
Value::Number("1e-10".to_string())
);
assert_eq!(
Format::Json.load("{\"bad\":1e400}").unwrap().get("bad"),
Some(&Value::Number("1e+400".to_string()))
);
}
#[cfg(feature = "yaml")]
#[test]
fn test_yaml_numeric_boundary_matrix() {
let source = format!(
"min: {}\nmax: {}\nabove: {}\nu: {}\nprecise: 9007199254740993\n",
i64::MIN,
i64::MAX,
i64::MAX as u128 + 1,
u64::MAX
);
let value = Format::Yaml.load(&source).unwrap();
assert_eq!(
get_path(&value, "min", Addressing::INDEX_ONLY)
.unwrap()
.as_integer(),
Some(i64::MIN)
);
assert_eq!(
get_path(&value, "max", Addressing::INDEX_ONLY)
.unwrap()
.as_integer(),
Some(i64::MAX)
);
assert_eq!(
get_path(&value, "above", Addressing::INDEX_ONLY)
.unwrap()
.as_unsigned(),
Some(i64::MAX as u64 + 1)
);
assert_eq!(
get_path(&value, "u", Addressing::INDEX_ONLY)
.unwrap()
.as_unsigned(),
Some(u64::MAX)
);
}
#[cfg(feature = "toml")]
#[test]
fn test_toml_numeric_boundary_matrix() {
let value = Format::Toml
.load(&format!(
"min = {}\nmax = {}\nprecise = 9007199254740993\n",
i64::MIN,
i64::MAX
))
.unwrap();
assert_eq!(
get_path(&value, "min", Addressing::INDEX_ONLY)
.unwrap()
.as_integer(),
Some(i64::MIN)
);
assert_eq!(
get_path(&value, "max", Addressing::INDEX_ONLY)
.unwrap()
.as_integer(),
Some(i64::MAX)
);
assert_eq!(
get_path(&value, "precise", Addressing::INDEX_ONLY)
.unwrap()
.as_integer(),
Some(9_007_199_254_740_993)
);
assert!(Format::Toml.load("bad = 1e9999\n").is_err());
assert!(preserving::toml::set("value = 1\n", "value", &Value::Float(f64::NAN)).is_err());
}
#[test]
fn test_error_on_nonexistent_slug() {
let mut root = Value::Object(BTreeMap::new());
let keyed_lists = [KeyedList {
prefix: "identities",
slug_field: "identity",
}];
if let Some(obj) = root.as_object_mut() {
obj.insert("identities".to_string(), Value::Array(vec![]));
}
let result = remove_keyed(&mut root, "identities", "nonexistent", &keyed_lists);
assert!(result.is_err());
}
#[test]
fn test_format_detection_json() {
assert_eq!(
Format::detect(std::path::Path::new("config.json")),
Some(Format::Json)
);
assert_eq!(Format::detect(std::path::Path::new("config.txt")), None);
}
#[cfg(feature = "toml")]
#[test]
fn test_format_detection_toml() {
assert_eq!(
Format::detect(std::path::Path::new("config.toml")),
Some(Format::Toml)
);
}
#[cfg(feature = "yaml")]
#[test]
fn test_format_detection_yaml() {
assert_eq!(
Format::detect(std::path::Path::new("config.yaml")),
Some(Format::Yaml)
);
assert_eq!(
Format::detect(std::path::Path::new("config.yml")),
Some(Format::Yaml)
);
}
#[cfg(feature = "dotenv")]
#[test]
fn test_format_detection_dotenv() {
for path in [
".env",
".env.local",
".env.test",
".env.example",
"config.env",
"CONFIG.ENV",
] {
assert_eq!(
Format::detect(std::path::Path::new(path)),
Some(Format::Dotenv),
"failed to detect {path}"
);
}
assert_eq!(Format::detect(std::path::Path::new("config.txt")), None);
}
#[cfg(feature = "ini")]
#[test]
fn test_ini_core_v1_strings_and_duplicates() {
let value = Format::Ini
.load("[database]\r\nhost = localhost\r\nport=5432\r\n")
.unwrap();
assert_eq!(
get_path(&value, "database.host", Addressing::INDEX_ONLY)
.unwrap()
.as_str(),
Some("localhost")
);
assert_eq!(
get_path(&value, "database.port", Addressing::INDEX_ONLY)
.unwrap()
.as_str(),
Some("5432")
);
assert!(Format::Ini.load("[database]\na=1\na=2\n").is_err());
assert!(Format::Ini.load("[database]\n[database]\n").is_err());
}
#[cfg(feature = "ini")]
#[test]
fn test_ini_fixtures_and_source_editor() {
let fixture = include_str!("fixtures/ini/core.ini");
let invalid_fixture = include_str!("fixtures/ini/invalid.ini");
assert!(Format::Ini.load(fixture).is_ok());
assert!(Format::Ini.load(invalid_fixture).is_err());
let source =
"; comment\r\n[Database]\r\nkey.with.dot = value # literal\r\nempty=\r\n\r\n[empty]\r\n";
let value = Format::Ini.load(source).unwrap();
assert_eq!(
get_path(&value, r"Database.key\.with\.dot", Addressing::INDEX_ONLY)
.unwrap()
.as_str(),
Some("value # literal")
);
assert!(Format::Ini.load("[s]\na: b\n").is_err());
let edited = preserving::ini::set(
source,
r"Database.key\.with\.dot",
&Value::String("changed".to_string()),
)
.unwrap();
assert!(edited.contains("; comment\r\n"));
assert!(edited.contains("key.with.dot = changed\r\n"));
let removed = preserving::ini::unset(&edited, "Database.empty").unwrap();
assert!(removed.contains("[empty]\r\n"));
let no_final_newline = "[section]\r\nkey = old";
let edited = preserving::ini::set(
no_final_newline,
"section.key",
&Value::String("new".to_string()),
)
.unwrap();
assert_eq!(edited, "[section]\r\nkey = new");
}
#[cfg(feature = "ini")]
#[test]
fn ini_top_of_file_comments_follow_the_blank_line_rule() {
for (source, expected) in [
(
"; file header\n\n; about a\n[a]\nk=1\n[b]\nj=1\n",
"; file header\n\n[b]\nj=1\n",
),
("; about a\n[a]\nk=1\n[b]\nj=1\n", "[b]\nj=1\n"),
] {
let removed = preserving::ini::unset(source, "a").unwrap();
assert_eq!(removed, expected, "unset a on {source:?}");
}
for (source, expected) in [
("; about a\n[a]\nk=1\n", "top=1\n; about a\n[a]\nk=1\n"),
(
"; file header\n\n; about a\n[a]\nk=1\n",
"; file header\n\ntop=1\n; about a\n[a]\nk=1\n",
),
] {
let added = preserving::ini::set(source, "top", &Value::String("1".into())).unwrap();
assert_eq!(added, expected, "set top on {source:?}");
}
}
#[cfg(feature = "ini")]
#[test]
fn test_ini_root_entries_are_addressed_bare() {
let source = "http-password=abc123\nauto-liquidity=2m\n\n[extra]\nk=v\n";
let value = Format::Ini.load(source).unwrap();
assert_eq!(
get_path(&value, "http-password", Addressing::INDEX_ONLY)
.unwrap()
.as_str(),
Some("abc123")
);
assert_eq!(
get_path(&value, "extra.k", Addressing::INDEX_ONLY)
.unwrap()
.as_str(),
Some("v")
);
assert!(Format::Ini.load("name=x\n[name]\nk=v\n").is_err());
assert!(Format::Ini.load("a=1\na=2\n").is_err());
assert!(
preserving::ini::set("[same]\nk=v\n", "same", &Value::String("root".to_string()),).is_err()
);
assert!(
preserving::ini::set("same=v\n", "same.k", &Value::String("nested".to_string()),).is_err()
);
let edited = preserving::ini::set(
source,
"http-password",
&Value::String("changed".to_string()),
)
.unwrap();
assert!(edited.starts_with("http-password=changed\n"), "{edited}");
assert!(edited.contains("[extra]\nk=v\n"), "{edited}");
let added = preserving::ini::set(source, "new-key", &Value::String("v".to_string())).unwrap();
let added_at = added.find("new-key=v").expect("the new entry");
assert!(
added_at < added.find("[extra]").expect("the header"),
"{added}"
);
assert_eq!(
get_path(
&Format::Ini.load(&added).expect("the edit reparses"),
"new-key",
Addressing::INDEX_ONLY
)
.unwrap()
.as_str(),
Some("v")
);
let removed = preserving::ini::unset(source, "auto-liquidity").unwrap();
assert!(!removed.contains("auto-liquidity"), "{removed}");
assert!(Format::Ini.load(&removed).is_ok());
let rendered = Format::Ini.save(&value).unwrap();
assert!(
rendered.find("http-password=").unwrap() < rendered.find("[extra]").unwrap(),
"{rendered}"
);
assert_eq!(Format::Ini.load(&rendered).unwrap(), value);
}
#[cfg(feature = "dotenv")]
#[test]
fn test_dotenv_read_semantics() {
let fixture = include_str!("fixtures/dotenv/core.env");
assert!(Format::Dotenv.load(fixture).is_ok());
assert!(
Format::Dotenv
.load(include_str!("fixtures/dotenv/invalid.env"))
.is_err()
);
let content = concat!(
"# comment\r\n",
" BASIC = value with spaces # comment\r\n",
"export EMPTY=\r\n",
"SINGLE='literal # value'\r\n",
"DOUBLE=\"line\\nquoted\\t\\\"value\\\"\\\\ # value\" # comment\r\n",
"NUMBER=5432\r\n",
"UNICODE=ä½ å¥½\r\n",
"DUPLICATE=first\r\n",
"DUPLICATE=last\r\n",
"REFERENCE=${AFDATA_TEST_PROCESS_VALUE}\r\n",
);
let error = Format::Dotenv
.load(content)
.expect_err("duplicate keys must fail");
assert!(error.to_string().contains("duplicate"));
let content = content
.replace("DUPLICATE=first\r\n", "")
.replace("DUPLICATE=last\r\n", "");
let value = Format::Dotenv.load(&content).expect("dotenv should parse");
let expected = [
("BASIC", "value with spaces"),
("EMPTY", ""),
("SINGLE", "literal # value"),
("DOUBLE", "line\nquoted\t\"value\"\\ # value"),
("NUMBER", "5432"),
("UNICODE", "ä½ å¥½"),
("REFERENCE", "${AFDATA_TEST_PROCESS_VALUE}"),
];
for (key, expected_value) in expected {
let actual = get_path(&value, key, Addressing::INDEX_ONLY).expect("key should exist");
assert_eq!(actual.as_str(), Some(expected_value));
assert!(actual.is_string());
}
}
#[cfg(feature = "dotenv")]
#[test]
fn test_dotenv_multiline_and_missing_set_preserve_source() {
let source = "# keep\nMULTI=\"first\nsecond\"\nOTHER=abc#def\n";
let value = Format::Dotenv.load(source).unwrap();
assert_eq!(
get_path(&value, "MULTI", Addressing::INDEX_ONLY)
.unwrap()
.as_str(),
Some("first\nsecond")
);
let edited =
preserving::dotenv::set(source, "NEW", &Value::String("value".to_string())).unwrap();
assert!(edited.starts_with(source));
let no_final_newline = "export KEY='old'";
let edited = preserving::dotenv::set(
no_final_newline,
"KEY",
&Value::String("new value".to_string()),
)
.unwrap();
assert_eq!(edited, "export KEY=\"new value\"");
}
#[cfg(feature = "dotenv")]
#[test]
fn test_dotenv_rejects_invalid_assignments_without_source_text() {
let error = Format::Dotenv
.load("SECRET_VALUE_WITHOUT_EQUALS")
.expect_err("invalid assignment should fail");
let message = error.to_string();
assert!(message.contains("line 1"));
assert!(!message.contains("SECRET_VALUE_WITHOUT_EQUALS"));
}
#[cfg(feature = "dotenv")]
#[test]
fn test_dotenv_save_is_typed_unsupported_operation() {
let value = Format::Dotenv
.load("KEY=value\n")
.expect("dotenv should parse");
let error = Format::Dotenv
.save(&value)
.expect_err("dotenv save should fail");
assert!(matches!(error, DocumentError::UnsupportedOperation { .. }));
}
#[test]
fn test_json_set_missing_key_inserts_preserving_layout() {
let source = "{\n \"keep\": 1e+3,\n \"obj\": {\n \"a\": 1\n }\n}\n";
let edited = preserving::json::set(source, "obj.b", &Value::Integer(2)).unwrap();
assert_eq!(
edited,
"{\n \"keep\": 1e+3,\n \"obj\": {\n \"a\": 1,\n \"b\": 2\n }\n}\n"
);
let created = preserving::json::set(source, "nope.deep", &Value::Integer(1)).unwrap();
assert_eq!(
created,
"{\n \"keep\": 1e+3,\n \"obj\": {\n \"a\": 1\n },\n \"nope\": {\n \"deep\": 1\n }\n}\n"
);
}
#[test]
fn test_file_operations() {
use std::fs;
use tempfile::TempDir;
let temp_dir = TempDir::new().expect("failed to create temp dir");
let config_path = temp_dir.path().join("config.json");
let initial = r#"{"app":{"name":"test","version":"1.0"}}"#;
fs::write(&config_path, initial).expect("failed to write initial config");
let content = fs::read_to_string(&config_path).expect("failed to read config");
let mut value = Format::Json.load(&content).expect("failed to load JSON");
set_path(
&mut value,
"app.version",
&Value::String("2.0".to_string()),
Addressing::INDEX_ONLY,
)
.expect("failed to set path");
let output = Format::Json.save(&value).expect("failed to save JSON");
fs::write(&config_path, output).expect("failed to write updated config");
let updated = fs::read_to_string(&config_path).expect("failed to read updated config");
let reloaded = Format::Json
.load(&updated)
.expect("failed to load updated JSON");
let version =
get_path(&reloaded, "app.version", Addressing::INDEX_ONLY).expect("failed to get version");
assert_eq!(version.as_str().expect("version should be string"), "2.0");
}
#[test]
fn test_document_file_stages_edits_until_save() {
use agent_first_data::document::DocumentFile;
use std::fs;
use tempfile::TempDir;
let temp_dir = TempDir::new().unwrap();
let path = temp_dir.path().join("config.json");
let initial =
"{\n \"imap\": {\n \"host\": \"old\",\n \"password_secret_env\": \"OLD\"\n }\n}\n";
fs::write(&path, initial).unwrap();
let mut doc = DocumentFile::open(&path, Some(Format::Json)).unwrap();
doc.set("imap.host", Value::String("new".to_string()))
.unwrap();
doc.unset("imap.password_secret_env").unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), initial);
assert_eq!(
get_path(doc.value(), "imap.host", Addressing::INDEX_ONLY)
.unwrap()
.as_str()
.unwrap(),
"new"
);
assert!(
get_path(
doc.value(),
"imap.password_secret_env",
Addressing::INDEX_ONLY
)
.is_err()
);
doc.save().unwrap();
let reloaded = Format::Json
.load(&fs::read_to_string(&path).unwrap())
.unwrap();
assert_eq!(
get_path(&reloaded, "imap.host", Addressing::INDEX_ONLY)
.unwrap()
.as_str()
.unwrap(),
"new"
);
assert!(
get_path(
&reloaded,
"imap.password_secret_env",
Addressing::INDEX_ONLY
)
.is_err()
);
}
#[test]
fn test_document_unset_is_idempotent() {
use agent_first_data::document::Document;
let mut doc = Document::parse("{\n \"a\": 1,\n \"b\": 2\n}\n", Format::Json).unwrap();
assert!(doc.unset("a").unwrap()); assert!(!doc.unset("a").unwrap()); assert!(!doc.unset("missing").unwrap()); assert_eq!(doc.source(), "{\n \"b\": 2\n}\n");
}
#[test]
fn test_document_unset_is_idempotent_at_any_depth() {
use agent_first_data::document::Document;
let mut doc = Document::parse("{\n \"a\": {\n \"b\": 1\n }\n}\n", Format::Json).unwrap();
assert!(!doc.unset("missing").unwrap());
assert!(!doc.unset("missing.nested").unwrap());
assert!(!doc.unset("missing.deeply.nested.key").unwrap());
assert!(!doc.unset("a.missing.key").unwrap());
assert!(doc.unset("a.b").unwrap());
assert_eq!(doc.source(), "{\n \"a\": {}\n}\n");
}
#[test]
fn test_document_unset_still_rejects_an_incoherent_path() {
use agent_first_data::document::Document;
let mut doc = Document::parse("{\n \"scalar\": 1\n}\n", Format::Json).unwrap();
assert!(doc.unset("scalar.child").is_err());
}
#[cfg(feature = "toml")]
#[test]
fn test_toml_set_creates_missing_parent_table() {
let source = "title = \"cfg\"\n";
let edited = preserving::toml::set(
source,
"imap.host",
&Value::String("mail.example.com".to_string()),
)
.unwrap();
let parsed = Format::Toml.load(&edited).unwrap();
assert_eq!(
get_path(&parsed, "imap.host", Addressing::INDEX_ONLY)
.unwrap()
.as_str()
.unwrap(),
"mail.example.com"
);
assert_eq!(
get_path(&parsed, "title", Addressing::INDEX_ONLY)
.unwrap()
.as_str()
.unwrap(),
"cfg"
);
}
#[cfg(not(feature = "toml"))]
#[test]
fn a_known_but_unbuilt_format_names_the_missing_feature() {
let dir = std::env::temp_dir().join(format!("afdata_unbuilt_{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("config.toml");
std::fs::write(&file, "a = 1\n").unwrap();
let error = agent_first_data::document::DocumentFile::open(&file, None).unwrap_err();
assert_eq!(error.code(), "document_unsupported_operation", "{error:?}");
assert!(error.to_string().contains("toml"), "{error}");
let alien = dir.join("config.xyz");
std::fs::write(&alien, "x").unwrap();
let unknown = agent_first_data::document::DocumentFile::open(&alien, None).unwrap_err();
assert_eq!(unknown.code(), "document_format_unknown", "{unknown:?}");
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(feature = "yaml")]
const HAND_EDITED_CONTACT: &str = "---\n# Alice is the Q3 contract contact\ndisplay_name: Alice Example\nkind: contact\nemails:\n - alice@example.com\ntags: []\nrole: ''\n---\n\n# Notes\n\nFirst paragraph.\n";
#[test]
#[cfg(feature = "yaml")]
fn frontmatter_collection_edits_leave_the_rest_of_the_file_alone() {
let mut document = Document::parse(HAND_EDITED_CONTACT, Format::YamlFrontmatter).unwrap();
document
.set("tags", Value::Array(vec![Value::String("vip".into())]))
.unwrap();
let edited = document.source().to_string();
assert_eq!(
edited,
"---\n# Alice is the Q3 contract contact\ndisplay_name: Alice Example\nkind: contact\nemails:\n - alice@example.com\ntags:\n - vip\nrole: ''\n---\n\n# Notes\n\nFirst paragraph.\n"
);
assert!(edited.contains("# Alice is the Q3 contract contact"));
assert!(edited.contains("role: ''"));
assert!(edited.contains("---\n\n# Notes\n\nFirst paragraph.\n"));
}
#[test]
#[cfg(feature = "yaml")]
fn frontmatter_keyed_lists_are_editable_like_a_standalone_yaml_file() {
let source = "---\n# managed by hand\nkind: contact\nidentities: []\n---\n\nBody stays.\n";
let mut document = Document::parse(source, Format::YamlFrontmatter).unwrap();
document
.add(
"identities",
"work",
"identity",
&[("label".to_string(), Value::String("Work".into()))],
)
.unwrap();
let added = document.source().to_string();
assert!(added.contains("# managed by hand"), "{added}");
assert!(added.ends_with("---\n\nBody stays.\n"), "{added}");
assert!(added.contains("identity: work"), "{added}");
document.remove("identities", "work", "identity").unwrap();
assert_eq!(document.source(), source);
}
#[test]
fn append_path_is_array_only_and_numeric_indices_still_require_an_element() {
let mut value = Format::Json
.load(r#"{"features":["a"],"object":{"-":"old"}}"#)
.unwrap();
set_path(
&mut value,
"features.-",
&Value::String("b".into()),
Addressing::INDEX_ONLY,
)
.unwrap();
assert_eq!(
get_path(&value, "features.1", Addressing::INDEX_ONLY)
.unwrap()
.as_str(),
Some("b")
);
set_path(
&mut value,
"object.-",
&Value::String("new".into()),
Addressing::INDEX_ONLY,
)
.unwrap();
assert_eq!(
get_path(&value, "object.-", Addressing::INDEX_ONLY)
.unwrap()
.as_str(),
Some("new")
);
assert!(matches!(
set_path(
&mut value,
"features.5",
&Value::Null,
Addressing::INDEX_ONLY
),
Err(DocumentError::IndexOutOfBounds { .. })
));
}
#[test]
fn array_append_preserves_source_and_comments() {
let cases = [
(
Format::Json,
"{\n \"features\": [\"a\", \"b\"],\n \"keep\": 1e+3\n}\n",
"{\n \"features\": [\"a\", \"b\", \"c\"],\n \"keep\": 1e+3\n}\n",
),
#[cfg(feature = "toml")]
(
Format::Toml,
"features = [\n \"a\", # first\n \"b\", # second\n] # tail\n",
"features = [\n \"a\", # first\n \"b\", # second\n \"c\",\n] # tail\n",
),
#[cfg(feature = "yaml")]
(
Format::Yaml,
"features:\n - a # first\n - b\nkeep: 1\n",
"",
),
];
for (format, source, exact) in cases {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config");
std::fs::write(&path, source).unwrap();
let mut document =
agent_first_data::document::DocumentFile::open(&path, Some(format)).unwrap();
document
.set("features.-", Value::String("c".into()))
.unwrap();
document.save().unwrap();
let edited = std::fs::read_to_string(&path).unwrap();
if !exact.is_empty() {
assert_eq!(edited, exact);
}
if format != Format::Json {
assert!(edited.contains("# first"));
}
if format == Format::Toml {
assert!(edited.contains("# second"));
assert!(edited.contains("] # tail"));
}
let value = format.load(&edited).unwrap();
assert_eq!(
get_path(&value, "features.2", Addressing::INDEX_ONLY)
.unwrap()
.as_str(),
Some("c")
);
assert!(matches!(
document.set("features.5", Value::String("d".into())),
Err(DocumentError::IndexOutOfBounds { .. })
));
}
}
#[cfg(feature = "yaml")]
#[test]
fn yaml_creates_missing_mapping_chain_and_distinguishes_missing_paths() {
use preserving::yaml;
let source = "a: 1\n";
let output = yaml::set(source, "new.deep.key", &Value::String("v".into())).unwrap();
assert_eq!(output, "a: 1\nnew:\n deep:\n key: v\n");
assert!(matches!(
yaml::unset(source, "missing.key"),
Err(DocumentError::PathNotFound { .. })
));
assert!(matches!(
yaml::set("{a: 1}\n", "new.deep.key", &Value::String("v".into())),
Err(DocumentError::UnsupportedOperation { .. })
));
}
#[test]
fn public_atomic_writer_replaces_bytes_preserves_permissions_and_refuses_links() {
use agent_first_data::{AtomicStep, write_atomic};
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("state.json");
write_atomic(&path, b"first").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
0o600
);
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o640)).unwrap();
}
write_atomic(&path, b"second").unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"second");
#[cfg(unix)]
{
use std::os::unix::fs::{PermissionsExt, symlink};
assert_eq!(
std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
0o640
);
let link = dir.path().join("link");
symlink(&path, &link).unwrap();
assert_eq!(
write_atomic(&link, b"bad").unwrap_err().step,
AtomicStep::Guard
);
assert_eq!(std::fs::read(&path).unwrap(), b"second");
}
assert_eq!(
write_atomic(dir.path(), b"bad").unwrap_err().step,
AtomicStep::Guard
);
assert!(
!write_atomic(&dir.path().join("missing/state"), b"bad")
.unwrap_err()
.commit_uncertain()
);
}
#[test]
fn append_handles_empty_arrays_and_root_sequences() {
let mut cases = vec![
(Format::Json, "{\"features\":[]}", "features.-"),
(Format::Json, "[]", "-"),
];
#[cfg(feature = "toml")]
cases.push((Format::Toml, "features = []\n", "features.-"));
#[cfg(feature = "yaml")]
cases.extend([
(Format::Yaml, "features: []\n", "features.-"),
(Format::Yaml, "[]\n", "-"),
(Format::Yaml, "- a # first\n", "-"),
]);
for (format, source, path) in cases {
let mut document = Document::parse(source, format).unwrap();
document.set(path, Value::String("new".into())).unwrap();
let expected_path = if path == "-" {
if source.starts_with("- a") { "1" } else { "0" }
} else {
"features.0"
};
assert_eq!(
get_path(document.value(), expected_path, Addressing::INDEX_ONLY)
.unwrap()
.as_str(),
Some("new")
);
}
}
#[cfg(feature = "yaml")]
#[test]
fn yaml_missing_parents_can_grow_from_an_empty_mapping() {
for source in ["{}\n", "new: {}\n"] {
let mut document = Document::parse(source, Format::Yaml).unwrap();
document
.set("new.deep.key", Value::String("v".into()))
.unwrap();
assert_eq!(
get_path(document.value(), "new.deep.key", Addressing::INDEX_ONLY)
.unwrap()
.as_str(),
Some("v")
);
}
}
#[cfg(feature = "yaml")]
#[test]
fn yaml_writes_reach_every_address_a_read_does() {
let object = |pairs: &[(&str, Value)]| {
Value::Object(
pairs
.iter()
.map(|(key, value)| (key.to_string(), value.clone()))
.collect(),
)
};
for source in ["servers:\n - name: web\n", "servers:\n- name: web # c\n"] {
let mut document = Document::parse(source, Format::Yaml).unwrap();
document.set("servers.0.port", Value::Integer(80)).unwrap();
assert_eq!(
get_path(document.value(), "servers.0.port", Addressing::INDEX_ONLY).unwrap(),
Value::Integer(80),
"{source:?} became {:?}",
document.source()
);
assert_eq!(
Document::parse(document.source(), Format::Yaml)
.unwrap()
.value(),
document.value()
);
}
let mut document = Document::parse("b:\n - 7\n - 8 # c\n", Format::Yaml).unwrap();
let replacement = object(&[("k", Value::Integer(1))]);
document.set("b.0", replacement.clone()).unwrap();
assert_eq!(document.source(), "b:\n - k: 1\n - 8 # c\n");
let mut document = Document::parse("# config\n", Format::Yaml).unwrap();
document.set("a.b", Value::String("c".into())).unwrap();
assert_eq!(document.source(), "# config\na:\n b: c\n");
}
#[cfg(feature = "toml")]
#[test]
fn toml_datetime_text_written_back_stays_a_datetime() {
let mut document = Document::parse("d = 1979-05-27T07:32:00Z\n", Format::Toml).unwrap();
document
.set("d", Value::String("2020-01-01T00:00:00Z".into()))
.unwrap();
assert_eq!(document.source(), "d = 2020-01-01T00:00:00Z\n");
}
#[cfg(feature = "dotenv")]
#[test]
fn an_invalid_dotenv_name_blames_the_path_not_the_file() {
let mut document = Document::parse("Z=1\n", Format::Dotenv).unwrap();
let error = document.set("a b", Value::String("v".into())).unwrap_err();
assert_eq!(error.code(), "document_unsupported_operation", "{error}");
assert_eq!(document.source(), "Z=1\n");
}
#[cfg(feature = "plist")]
#[test]
fn binary_plist_parses_like_xml_and_has_no_source() {
use agent_first_data::document::DocumentFile;
let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/plist/");
let xml = DocumentFile::open(format!("{dir}Info.plist"), None).unwrap();
let temp = tempfile::tempdir().unwrap();
let binary_path = temp.path().join("Info.binary.plist");
plist::Value::from_file(format!("{dir}Info.plist"))
.unwrap()
.to_file_binary(&binary_path)
.unwrap();
let binary = DocumentFile::open_capped(&binary_path, None, 1 << 20).unwrap();
assert_eq!(xml.value(), binary.value());
assert_eq!(binary.source(), "");
let bytes = std::fs::read(&binary_path).unwrap();
assert!(bytes.starts_with(b"bplist"));
let from_reader = Document::from_reader(std::io::Cursor::new(&bytes), Format::Plist).unwrap();
assert_eq!(from_reader.value(), xml.value());
let error = Document::from_reader(std::io::Cursor::new(&bytes), Format::Json).unwrap_err();
assert_eq!(error.code(), "document_parse_failed");
assert!(error.redacted_message().contains("--input-format plist"));
}
#[test]
fn append_position_needs_an_existing_array_in_every_format() {
let mut cases = vec![(Format::Json, r#"{"a":1}"#)];
#[cfg(feature = "toml")]
cases.push((Format::Toml, "a = 1\n"));
#[cfg(feature = "yaml")]
cases.push((Format::Yaml, "a: 1\n"));
for (format, source) in cases {
let mut document = Document::parse(source, format).unwrap();
let error = document
.set("fresh.-", Value::String("v".into()))
.unwrap_err();
assert_eq!(error.code(), "document_invalid_path", "{format:?}");
assert_eq!(document.source(), source);
}
let mut root = Value::Object(Default::default());
let error = set_path(
&mut root,
"fresh.-",
&Value::Integer(1),
Addressing::INDEX_ONLY,
)
.unwrap_err();
assert_eq!(error.code(), "document_invalid_path");
assert_eq!(root, Value::Object(Default::default()));
}
#[test]
fn typed_value_errors_are_argument_errors_not_parse_errors() {
use agent_first_data::document::{ValueType, value_from_type};
for (value_type, raw) in [
(ValueType::Number, Some("abc")),
(ValueType::Bool, Some("maybe")),
(ValueType::Json, Some("{bad")),
(ValueType::Null, Some("x")),
(ValueType::Number, None),
] {
let error = value_from_type(value_type, raw).unwrap_err();
assert_eq!(error.code(), "document_invalid_argument", "{value_type:?}");
}
}
#[test]
fn json_set_follows_crlf_and_tab_layout() {
let nested = Value::Object(BTreeMap::from([(
"f".to_string(),
Value::Array(vec![Value::Integer(1)]),
)]));
let mut crlf = Document::parse(
"{\r\n \"c\": {\r\n \"d\": 1\r\n }\r\n}\r\n",
Format::Json,
)
.unwrap();
crlf.set("c.e", nested.clone()).unwrap();
assert!(
crlf.source()
.split('\n')
.filter(|line| !line.is_empty())
.all(|line| line.ends_with('\r')),
"{:?}",
crlf.source()
);
let mut tabs = Document::parse("{\n\t\"c\": {\n\t\t\"d\": 1\n\t}\n}\n", Format::Json).unwrap();
tabs.set("c.e", nested).unwrap();
assert!(
tabs.source()
.lines()
.all(|line| !line.trim_start_matches('\t').starts_with(' ')),
"{:?}",
tabs.source()
);
}
#[cfg(feature = "yaml")]
#[test]
fn yaml_shared_nodes_report_their_own_code() {
let source = "base: &b\n k: 1\nm:\n <<: *b\nref: *b\n";
for path in ["base.k", "ref.k", "base.new"] {
let mut document = Document::parse(source, Format::Yaml).unwrap();
let error = document.set(path, Value::String("z".into())).unwrap_err();
assert_eq!(error.code(), "document_shared_node", "{path}: {error}");
assert_eq!(document.source(), source);
}
let mut document = Document::parse(source, Format::Yaml).unwrap();
assert_eq!(
document.unset("m.k").unwrap_err().code(),
"document_shared_node"
);
assert_eq!(
document.unset("base.k").unwrap_err().code(),
"document_shared_node"
);
}
#[cfg(feature = "toml")]
#[test]
fn toml_array_of_tables_elements_edit_in_place() {
let source = "[[items]]\nname = \"one\" # keep\n\n[[items]]\nname = \"two\"\n";
let mut document = Document::parse(source, Format::Toml).unwrap();
document
.set("items.1.name", Value::String("x".into()))
.unwrap();
assert_eq!(
document.source(),
"[[items]]\nname = \"one\" # keep\n\n[[items]]\nname = \"x\"\n"
);
assert!(document.unset("items.0").unwrap());
assert_eq!(document.source(), "\n[[items]]\nname = \"x\"\n");
assert!(matches!(
document.set("items", Value::Array(Vec::new())),
Err(DocumentError::UnsupportedOperation { .. })
));
}
#[cfg(feature = "toml")]
#[test]
fn toml_last_table_leaves_an_appendable_empty_array() {
use agent_first_data::document::DocumentFile;
let dir = tempfile::tempdir().unwrap();
for (source, key, unset) in [
("[[items]]\nid = \"one\"\n", "items", false),
("[[a.items]]\nid = \"one\"\n", "a.items", false),
("[[a.items]]\nid = \"one\"\n", "a.items", true),
] {
let path = dir.path().join("items.toml");
std::fs::write(&path, source).unwrap();
let mut doc = DocumentFile::open(&path, None).unwrap();
if unset {
assert!(doc.unset(&format!("{key}.0")).unwrap());
} else {
doc.remove(key, "one", "id").unwrap();
}
doc.save().unwrap();
assert!(
std::fs::read_to_string(&path)
.unwrap()
.contains("items = []")
);
let mut doc = DocumentFile::open(&path, None).unwrap();
assert_eq!(doc.value_at(key).unwrap(), Value::Array(vec![]));
doc.add(key, "two", "id", &[]).unwrap();
doc.save().unwrap();
let doc = DocumentFile::open(&path, None).unwrap();
assert_eq!(
doc.value_at(&format!("{key}.0.id")).unwrap().as_str(),
Some("two")
);
}
let source = "other = []\n";
let mut doc = Document::parse(source, Format::Toml).unwrap();
assert_eq!(
doc.add("items", "two", "id", &[]).unwrap_err().code(),
"document_path_not_found"
);
assert_eq!(doc.source(), source);
}
#[cfg(feature = "yaml")]
#[test]
fn yaml_empty_sequence_round_trips() {
for (source, path) in [
("- id: a\n", ""),
("# keep\n- id: a\n", ""),
("-\n - id: a\n", "0"),
] {
let mut doc = Document::parse(source, Format::Yaml).unwrap();
doc.remove(path, "a", "id")
.unwrap_or_else(|error| panic!("{source:?}: {error}"));
if source.starts_with('#') {
assert!(doc.source().starts_with("# keep\n"));
}
assert!(doc.source().ends_with("[]\n"), "{:?}", doc.source());
let mut doc = Document::parse(doc.source(), Format::Yaml).unwrap();
doc.add(path, "b", "id", &[]).unwrap();
assert!(doc.source().contains("id: b") || doc.source().contains("id: \"b\""));
}
}
#[cfg(feature = "yaml")]
#[test]
fn yaml_subtree_edits_protect_external_aliases() {
let source = "defaults:\n item: &a\n host: old\nref: *a\n";
let mut doc = Document::parse(source, Format::Yaml).unwrap();
assert_eq!(
doc.unset("defaults").unwrap_err().code(),
"document_shared_node"
);
assert_eq!(
doc.set("defaults", Value::Integer(1)).unwrap_err().code(),
"document_shared_node"
);
assert_eq!(doc.source(), source);
let source = "items:\n - id: a\n nested: &x\n value: 1\n - id: b\nref: *x\n";
let mut doc = Document::parse(source, Format::Yaml).unwrap();
assert_eq!(
doc.remove("items", "a", "id").unwrap_err().code(),
"document_shared_node"
);
assert_eq!(doc.source(), source);
let source = "base: &b\n k: 1\nm:\n <<:\n - *b\n";
let mut doc = Document::parse(source, Format::Yaml).unwrap();
let error = doc.set("m.k", Value::Integer(2)).unwrap_err();
assert_eq!(error.code(), "document_unsupported_operation");
assert!(!error.to_string().contains("fragment"));
assert!(!error.to_string().contains("splice"));
}
#[test]
fn json_append_follows_sibling_layout() {
let mut doc = Document::parse(
"{\r\n\t\"items\": [\r\n\t\t{\"id\": \"a\"}\r\n\t]\r\n}\r\n",
Format::Json,
)
.unwrap();
doc.add("items", "b", "id", &[]).unwrap();
doc.set("items.-", Value::Integer(3)).unwrap();
assert!(
doc.source()
.contains(",\r\n\t\t{\r\n\t\t\t\"id\": \"b\"\r\n\t\t},\r\n\t\t3")
);
assert!(!doc.source().replace("\r\n", "").contains('\n'));
let mut doc = Document::parse("{\n \"items\": [1, 2]\n}", Format::Json).unwrap();
doc.set("items.-", Value::Integer(3)).unwrap();
assert_eq!(doc.source(), "{\n \"items\": [1, 2, 3]\n}");
}
#[cfg(feature = "toml")]
#[test]
fn toml_save_requires_the_staged_value_to_survive_reopening() {
use agent_first_data::document::{DocumentFile, ValueType};
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("sample.toml");
let original = "n = 0\n";
std::fs::write(&path, original).unwrap();
let mut doc = DocumentFile::open(&path, None).unwrap();
doc.set_typed("n", Some("9007199254740993.0"), ValueType::Number)
.unwrap();
assert_eq!(
doc.save().unwrap_err().code(),
"document_write_would_corrupt"
);
assert_eq!(std::fs::read_to_string(&path).unwrap(), original);
for original in ["[a.b]\nleaf = 1\n", "a.b.leaf = 1\n"] {
std::fs::write(&path, original).unwrap();
let mut doc = DocumentFile::open(&path, None).unwrap();
assert!(doc.unset("a.b").unwrap());
doc.save().unwrap();
let reopened = DocumentFile::open(&path, None).unwrap();
assert_eq!(reopened.value(), doc.value());
assert_eq!(
reopened.value().as_object().unwrap()["a"],
Value::Object(BTreeMap::new())
);
}
}
#[test]
fn add_keyed_rejects_slug_override_before_creating_parents() {
let mut root = Value::Object(BTreeMap::new());
let original = root.clone();
let lists = [KeyedList {
prefix: "cfg.users",
slug_field: "id",
}];
assert!(
add_keyed(
&mut root,
"cfg.users",
"one",
&lists,
None,
&[("id".into(), Value::Null)]
)
.is_err()
);
assert_eq!(root, original);
add_keyed(&mut root, "cfg.users", "one", &lists, None, &[]).unwrap();
assert_eq!(
get_path(&root, "cfg.users.0.id", Addressing::INDEX_ONLY).unwrap(),
Value::String("one".into())
);
}
#[cfg(feature = "toml")]
#[test]
fn toml_removing_first_array_table_keeps_the_document_preamble() {
for newline in ["\n", "\r\n"] {
for remaining in ["", "\n# second table\n[[servers]]\nname = \"b\"\n"] {
let source = format!(
"# document header\n\n# first table\n[[servers]]\nname = \"a\"\n{remaining}"
)
.replace('\n', newline);
let mut indexed = Document::parse(&source, Format::Toml).unwrap();
let mut keyed = indexed.clone();
assert!(indexed.unset("servers.0").unwrap());
keyed.remove("servers", "a", "name").unwrap();
assert_eq!(indexed.source(), keyed.source());
assert!(
indexed
.source()
.starts_with(&format!("# document header{newline}{newline}"))
);
assert!(!indexed.source().contains("# first table"));
assert_eq!(
indexed.source().contains("# second table"),
!remaining.is_empty()
);
assert_eq!(
Document::parse(indexed.source(), Format::Toml)
.unwrap()
.value(),
indexed.value()
);
}
}
}
#[cfg(feature = "toml")]
#[test]
fn toml_unset_never_duplicates_the_header_for_later_items() {
for (source, path, expected) in [
("# c\n\nx = 1\n# c\n\ny = 2\n", "y", "# c\n\nx = 1\n"),
(
"# c\n\n[s]\nx = 1\n# c\n\n[a]\nk = 1\n",
"a",
"# c\n\n[s]\nx = 1\n",
),
(
"# c\n\n[s]\na = 1\n# c\n\nb = 2\n",
"s.b",
"# c\n\n[s]\na = 1\n",
),
(
"# c\n\n[[t]]\nn = 1\n# c\n\n[[t]]\nn = 2\n",
"t.1",
"# c\n\n[[t]]\nn = 1\n",
),
(
"# header\n\n# about x\nx = 1\ny = 2\n",
"x",
"# header\n\ny = 2\n",
),
] {
let mut document = Document::parse(source, Format::Toml).unwrap();
assert!(document.unset(path).unwrap());
assert_eq!(document.source(), expected, "unset {path} on {source:?}");
}
}
#[test]
fn json_new_members_follow_inline_object_spacing() {
for (source, expected) in [
(r#"{"name":"a"}"#, r#"{"name":"a","port":1}"#),
(r#"{"name": "a"}"#, r#"{"name": "a", "port": 1}"#),
(
r#"{"name":"a", "enabled": true}"#,
r#"{"name":"a", "enabled": true, "port": 1}"#,
),
] {
let mut doc = Document::parse(source, Format::Json).unwrap();
doc.set("port", Value::Integer(1)).unwrap();
assert_eq!(doc.source(), expected);
assert_eq!(
Document::parse(doc.source(), Format::Json).unwrap().value(),
doc.value()
);
}
}
#[test]
fn json_first_items_follow_the_empty_containers_layout() {
let source = "{\r\n\t\"items\": [\r\n\t],\r\n\t\"options\": {\r\n\t}\r\n}\r\n";
let mut doc = Document::parse(source, Format::Json).unwrap();
doc.set("items.-", Value::Integer(1)).unwrap();
doc.set("options.enabled", Value::Bool(true)).unwrap();
assert_eq!(
doc.source(),
"{\r\n\t\"items\": [\r\n\t\t1\r\n\t],\r\n\t\"options\": {\r\n\t\t\"enabled\": true\r\n\t}\r\n}\r\n"
);
assert_eq!(
Document::parse(doc.source(), Format::Json).unwrap().value(),
doc.value()
);
for (source, expected) in [
("{\"items\":[]}", "{\"items\":[{\"id\":\"one\"}]}"),
(
"{\n \"items\": [\n ]\n}\n",
"{\n \"items\": [\n {\n \"id\": \"one\"\n }\n ]\n}\n",
),
] {
let mut doc = Document::parse(source, Format::Json).unwrap();
doc.add("items", "one", "id", &[]).unwrap();
assert_eq!(doc.source(), expected);
assert_eq!(
Document::parse(doc.source(), Format::Json).unwrap().value(),
doc.value()
);
}
}
#[cfg(feature = "yaml")]
#[test]
fn yaml_removes_sequence_items_consistently_by_index_and_slug() {
let source = "base: &base {id: a}\nitems: [*base, {id: b}]\n";
let mut indexed = Document::parse(source, Format::Yaml).unwrap();
let mut keyed = indexed.clone();
assert!(indexed.unset("items.0").unwrap());
keyed.remove("items", "a", "id").unwrap();
assert_eq!(indexed.source(), "base: &base {id: a}\nitems: [{id: b}]\n");
assert_eq!(keyed.source(), indexed.source());
let source = "items: [&base {id: a}, *base]\n";
let mut doc = Document::parse(source, Format::Yaml).unwrap();
assert_eq!(
doc.unset("items.0").unwrap_err().code(),
"document_shared_node"
);
assert_eq!(doc.source(), source);
for source in ["# head\n- id: a\n# tail\n", "# head\n[{id: a}]\n# tail\n"] {
let mut indexed = Document::parse(source, Format::Yaml).unwrap();
let mut keyed = indexed.clone();
assert!(indexed.unset("0").unwrap());
keyed.remove("", "a", "id").unwrap();
assert_eq!(indexed.source(), "# head\n[]\n# tail\n");
assert_eq!(keyed.source(), indexed.source());
assert_eq!(
Document::parse(keyed.source(), Format::Yaml)
.unwrap()
.value(),
&Value::Array(vec![])
);
}
}