helm-rs 0.1.0

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
use std::collections::BTreeSet;
use std::path::PathBuf;

use serde_json::{Value, json};

use super::{Error, final_values, validate};
use crate::chart::{Chart, Dependency, read_values_file};

fn fixture(name: &str) -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/schema")
        .join(name)
}

fn violation_paths(error: &Error) -> BTreeSet<String> {
    match error {
        Error::Invalid(charts) => charts
            .iter()
            .flat_map(|c| c.violations.iter())
            .map(|v| v.path.clone())
            .collect(),
        other => panic!("not a violation list: {other}"),
    }
}

/// Paths from Helm's `- at '<path>': ...` lines.
fn helm_paths(verdict: &str) -> BTreeSet<String> {
    verdict
        .lines()
        .filter_map(|l| l.trim_start().strip_prefix("- at '"))
        .filter_map(|l| l.split_once("': ").map(|(path, _)| path.to_owned()))
        .collect()
}

/// Cases whose Helm output names other paths than the Rust validator does: Helm's evaluator
/// reports `unevaluatedProperties` per property.
const PATH_DIVERGENCE: &[&str] = &["modern/unevaluated"];

/// Every `<chart>/cases/<case>.yaml` fixture: Helm 4.3.0's verdict was recorded in `<case>.helm`
/// by `regen.sh`; the native validator must agree on ok/error and on the failing paths.
#[test]
fn verdicts_match_recorded_helm_output() {
    let mut checked = 0;

    for chart_name in ["strict", "withsub", "modern", "urn", "remote"] {
        let chart = Chart::load(fixture(chart_name)).expect("fixture chart loads");
        let cases = fixture(&format!("{chart_name}/cases"));
        let mut entries: Vec<_> = std::fs::read_dir(cases)
            .expect("cases dir")
            .map(|e| e.expect("entry").path())
            .collect();

        entries.sort();

        for path in entries
            .iter()
            .filter(|p| p.extension().is_some_and(|e| e == "yaml"))
        {
            let case = format!(
                "{chart_name}/{}",
                path.file_stem().and_then(|s| s.to_str()).expect("name")
            );
            let verdict =
                std::fs::read_to_string(path.with_extension("helm")).expect("recorded verdict");
            let user = read_values_file(path).expect("case values parse");
            let values = if chart.dependencies.is_empty() {
                final_values(&chart, &user).expect("coalesces")
            } else {
                user
            };
            let result = validate(&chart, &values);

            assert_eq!(
                result.is_ok(),
                verdict.starts_with("ok"),
                "case {case}: helm said {verdict:?}, got {result:?}"
            );
            checked += 1;

            let expected = helm_paths(&verdict);

            if let (Err(error), false, false) = (
                &result,
                expected.is_empty(),
                PATH_DIVERGENCE.contains(&case.as_str()),
            ) {
                assert_eq!(violation_paths(error), expected, "case {case}");
            }
        }
    }

    assert_eq!(checked, 20);
}

#[test]
fn display_follows_helms_layout() {
    let chart = Chart::load(fixture("withsub")).expect("loads");
    let error = validate(&chart, &json!({"name": 7, "sub": {"port": "x"}})).expect_err("invalid");
    let text = error.to_string();

    assert!(text.starts_with("values don't meet the specifications of the schema(s) in the following chart(s):\nwithsub:\n- at '/name': "));
    assert!(text.contains("\nsub:\n- at '/port': "));
}

#[test]
fn every_violation_is_reported() {
    let chart = Chart::load(fixture("strict")).expect("loads");
    let values = json!({"replicaCount": 0, "mode": "z", "image": {"tag": "x", "extra": 1}});
    let error = validate(&chart, &values).expect_err("invalid");

    assert_eq!(
        violation_paths(&error),
        ["/image", "/image/tag", "/mode", "/replicaCount"]
            .map(String::from)
            .into()
    );
}

#[test]
fn urn_references_are_permissive_like_helm() {
    let chart = Chart::load(fixture("urn")).expect("loads");

    assert!(validate(&chart, &json!({"a": 1})).is_ok());
}

#[cfg(not(feature = "schema-remote-refs"))]
#[test]
fn remote_references_error_clearly_by_default() {
    let chart = Chart::load(fixture("remote")).expect("loads");
    let error = validate(&chart, &json!({"a": 1})).expect_err("refused");

    assert!(matches!(
        &error,
        Error::RemoteRef { chart, uri } if chart == "remote" && uri == "https://example.invalid/missing.json"
    ));
    assert!(error.to_string().contains("schema-remote-refs"));
}

#[test]
fn invalid_schema_json_is_a_violation_of_that_chart() {
    let chart = Chart {
        schema_raw: Some(b"{".to_vec()),
        ..Chart::default()
    };
    let error = validate(&chart, &json!({})).expect_err("invalid schema");

    assert!(matches!(error, Error::Invalid(charts) if charts[0].violations[0].path.is_empty()));
}

fn chart_with_sub(alias: &str) -> Chart {
    let sub = Chart {
        metadata: crate::chart::Metadata {
            name: "sub".into(),
            ..crate::chart::Metadata::default()
        },
        schema_raw: Some(br#"{"properties": {"port": {"type": "integer"}}}"#.to_vec()),
        ..Chart::default()
    };
    let mut parent = Chart::default();

    parent.metadata.name = "parent".into();
    parent.metadata.dependencies = vec![Some(Dependency {
        name: "sub".into(),
        alias: alias.into(),
        ..Dependency::default()
    })];
    parent.dependencies = vec![sub];

    parent
}

#[test]
fn subchart_values_live_under_the_alias() {
    let aliased = chart_with_sub("web");
    let plain = chart_with_sub("");

    assert!(validate(&aliased, &json!({"sub": {"port": "x"}})).is_ok());
    assert!(validate(&aliased, &json!({"web": {"port": "x"}})).is_err());
    assert!(validate(&plain, &json!({"sub": {"port": "x"}})).is_err());
    assert!(validate(&plain, &json!({})).is_ok());
    assert!(validate(&plain, &json!({"sub": null})).is_ok());

    let error = validate(&plain, &json!({"sub": [1]})).expect_err("not a mapping");

    assert!(
        error
            .to_string()
            .contains("sub:\ninvalid type for values: expected object (map), got []interface {}")
    );
}

/// Cases follow Helm's `coalesce_test.go` rules (verified against `helm template` 4.3.0).
#[test]
fn final_values_coalesce_like_helm() {
    let cases: &[(Value, Value, Value)] = &[
        (
            json!({"a": 1, "b": {"c": 2, "d": 3}}),
            json!({"b": {"c": 9}}),
            json!({"a": 1, "b": {"c": 9, "d": 3}}),
        ),
        (json!({"a": 1, "b": 2}), json!({"a": null}), json!({"b": 2})),
        (
            json!({"a": null, "b": {"c": null, "d": 1}}),
            json!({}),
            json!({"b": {"d": 1}}),
        ),
        (json!({"a": [1, 2]}), json!({"a": [3]}), json!({"a": [3]})),
        (
            json!({"a": {"b": 1}}),
            json!({"a": "scalar"}),
            json!({"a": "scalar"}),
        ),
        (
            json!({"a": "scalar"}),
            json!({"a": {"b": 1}}),
            json!({"a": {"b": 1}}),
        ),
        (
            json!({"a": {"b": 1, "c": 2}}),
            json!({"a": {"b": null}}),
            json!({"a": {"c": 2}}),
        ),
        (
            json!({"a": {"b": null}}),
            json!({"a": {"b": null}}),
            json!({"a": {"b": null}}),
        ),
        (
            json!({"a": 1}),
            json!({"extra": {"x": null}}),
            json!({"a": 1, "extra": {"x": null}}),
        ),
    ];

    for (defaults, user, expected) in cases {
        let chart = Chart {
            values: defaults.clone(),
            ..Chart::default()
        };

        assert_eq!(
            &final_values(&chart, user).expect("coalesces"),
            expected,
            "defaults {defaults} user {user}"
        );
    }
}

#[test]
fn final_values_refuse_what_helm_must_decide() {
    let with_sub = chart_with_sub("");

    assert!(matches!(
        final_values(&with_sub, &json!({})),
        Err(Error::Unsupported(_))
    ));
    assert!(matches!(
        final_values(&Chart::default(), &json!([1])),
        Err(Error::Unsupported(_))
    ));
    assert_eq!(
        final_values(&Chart::default(), &Value::Null).expect("empty"),
        json!({})
    );
}