From 8e5210b57c9a0c27111cdc081c60095ee7b75419 Mon Sep 17 00:00:00 2001 From: Russell Cousineau Date: Fri, 28 Jun 2024 18:45:02 -0700 Subject: [PATCH] add write tests --- tests/write-tests.rs | 60 ++++++++++++++++++++++++++++++++++++++++++++ utilities/Cargo.toml | 1 + utilities/src/lib.rs | 5 ++++ 3 files changed, 66 insertions(+) create mode 100644 tests/write-tests.rs diff --git a/tests/write-tests.rs b/tests/write-tests.rs new file mode 100644 index 0000000..69dbefc --- /dev/null +++ b/tests/write-tests.rs @@ -0,0 +1,60 @@ +use std::error::Error; + +use hq_rs::{parser::Field, write}; + +#[test] +fn attr() -> Result<(), Box> { + // filter '.version' + let fields = vec![Field::new("version")]; + // hcl: + // version = "test" + let mut body = utilities::edit_hcl("version = \"test\"")?; + + let value: hcl_edit::expr::Expression = "\"new_value\"".parse()?; + + write(fields, &mut body, &value)?; + + assert_eq!("version = \"new_value\"", body.to_string()); + + Ok(()) +} + +#[test] +fn block_attr() -> Result<(), Box> { + // filter '.options.enabled' + let fields = vec![Field::new("options"), Field::new("enabled")]; + // hcl: + // options { enabled = false } + let mut body = utilities::edit_hcl("options { enabled = false }")?; + + let value: hcl_edit::expr::Expression = "true".parse()?; + + write(fields, &mut body, &value)?; + + assert_eq!("options { enabled = true }", body.to_string()); + + Ok(()) +} + +#[test] +fn labeled_block_attr() -> Result<(), Box> { + // filter '.module[label="cool-module"].version' + let fields = vec![ + Field::labeled("module", &["cool-module"]), + Field::new("version"), + ]; + // hcl: + // module "cool-module" { version = "1.0" } + let mut body = utilities::edit_hcl("module \"cool-module\" { version = \"1.0\" }")?; + + let value: hcl_edit::expr::Expression = "\"2.0\"".parse()?; + + write(fields, &mut body, &value)?; + + assert_eq!( + "module \"cool-module\" { version = \"2.0\" }", + body.to_string() + ); + + Ok(()) +} diff --git a/utilities/Cargo.toml b/utilities/Cargo.toml index 3a3c7d2..71d2197 100644 --- a/utilities/Cargo.toml +++ b/utilities/Cargo.toml @@ -6,3 +6,4 @@ pulish = false [dependencies] hcl-rs = "0.17" +hcl-edit = "0.8" diff --git a/utilities/src/lib.rs b/utilities/src/lib.rs index 25c7284..a0a70d3 100644 --- a/utilities/src/lib.rs +++ b/utilities/src/lib.rs @@ -5,3 +5,8 @@ pub fn read_test_hcl() -> Result> { let body: hcl::Body = hcl::from_str(&contents)?; Ok(body) } + +pub fn edit_hcl(contents: &str) -> Result> { + let body: hcl_edit::structure::Body = contents.parse()?; + Ok(body) +}