helm-rs 0.1.2

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
use base64::{Engine, engine::general_purpose::STANDARD};
use serde_json::{Value, json};

use super::*;

const INSTALL_JSON: &str = include_str!("../../tests/fixtures/release/install.json");

/// Record fixtures: a file name (for the format) and its text. A `.json` file is a kubectl
/// Secret or `ConfigMap` object; anything else is the base64 record text. Add a row per fixture.
const RECORDS: [(&str, &str); 2] = [
    (
        "record-python-gzip.b64",
        include_str!("../../tests/fixtures/release/record-python-gzip.b64"),
    ),
    (
        "record-python-plain.b64",
        include_str!("../../tests/fixtures/release/record-python-plain.b64"),
    ),
];

fn fixture() -> Release {
    serde_json::from_str(INSTALL_JSON).expect("fixture parses")
}

/// The bytes to hand to `Release::decode` for a fixture: for a kubectl Secret object the
/// `data.release` value base64-decoded once (kubectl shows the API's encoding), for a `ConfigMap`
/// the string as is, for a plain record file its text.
fn record_bytes(file: &str, text: &str) -> Vec<u8> {
    if std::path::Path::new(file)
        .extension()
        .is_none_or(|ext| ext != "json")
    {
        return text.trim().as_bytes().to_vec();
    }

    let object: Value = serde_json::from_str(text).expect("object JSON");
    let data = object["data"]["release"].as_str().expect("data.release");

    match object["kind"].as_str() {
        Some("Secret") => STANDARD.decode(data).expect("secret data is base64"),
        Some("ConfigMap") => data.as_bytes().to_vec(),
        other => panic!("unsupported kind {other:?}"),
    }
}

fn parse(value: &Value) -> Release {
    serde_json::from_value(value.clone()).expect("release parses")
}

#[test]
fn fixture_carries_every_part_of_the_record() {
    let release = fixture();
    let info = release.info.as_ref().expect("info");
    let chart = release.chart.as_ref().expect("chart");
    let metadata = &chart.metadata;

    assert_eq!(release.name, "myrel");
    assert_eq!(release.namespace, "prod");
    assert_eq!(release.version, Revision(1));
    assert_eq!(release.config["replicaCount"], 2);
    assert_eq!(info.status, Status::PendingInstall);
    assert!(info.first_deployed.is_some());
    assert!(info.notes.starts_with("1. Get the application URL"));
    assert_eq!(metadata.name, "demo");
    assert_eq!(
        metadata.dependencies[0].as_ref().expect("dependency").name,
        "sub"
    );
    assert_ne!(chart.lock.as_ref().expect("lock").generated, "");
    assert_eq!(chart.schema_mod_time, None);
    assert!(
        chart
            .templates
            .iter()
            .any(|file| file.name == "templates/deployment.yaml")
    );
    assert!(
        chart
            .files
            .iter()
            .any(|file| file.name == "crds/widget.yaml")
    );
    assert!(
        release
            .manifest
            .contains("# Source: demo/templates/service.yaml")
    );
}

#[test]
fn fixture_hooks_keep_events_policies_and_the_unset_phase() {
    let hooks = fixture().hooks;
    let job = hooks
        .iter()
        .find(|hook| hook.kind == "Job")
        .expect("job hook");

    assert_eq!(hooks.len(), 3);
    assert_eq!(job.events, [HookEvent::PreInstall, HookEvent::PreUpgrade]);
    assert_eq!(job.weight, -5);
    assert_eq!(
        job.delete_policies,
        [
            DeletePolicy::BeforeHookCreation,
            DeletePolicy::HookSucceeded
        ]
    );
    assert_eq!(job.output_log_policies, [OutputLogPolicy::HookFailed]);
    assert_eq!(job.path, "demo/templates/hooks.yaml");
    assert!(hooks.iter().all(|hook| hook.last_run.phase.is_empty()));
}

#[test]
fn file_bytes_are_decoded_from_base64() {
    let chart = fixture().chart.expect("chart");
    let widget = chart
        .files
        .iter()
        .find(|file| file.name == "crds/widget.yaml")
        .expect("crd file");

    assert!(
        String::from_utf8_lossy(&widget.data).starts_with("apiVersion: apiextensions.k8s.io/v1")
    );
}

#[test]
fn json_round_trip_preserves_the_record() {
    let release = fixture();
    let again: Release = serde_json::from_str(&serde_json::to_string(&release).expect("serialize"))
        .expect("parse again");

    assert_eq!(release, again);
}

#[test]
fn decodes_every_record_fixture_to_the_installed_release() {
    let expected = fixture();

    for (file, text) in RECORDS {
        let record = record_bytes(file, text);

        assert_eq!(
            Release::decode(&record).expect("decodes"),
            expected,
            "{file}"
        );
    }
}

#[test]
fn object_fixtures_are_unwrapped_by_kind() {
    let release = fixture();
    let record = release.encode().expect("encodes");
    let configmap = json!({"kind": "ConfigMap", "data": {"release": record}}).to_string();
    let secret =
        json!({"kind": "Secret", "data": {"release": STANDARD.encode(&record)}}).to_string();

    for (file, text) in [("configmap.json", configmap), ("secret.json", secret)] {
        let bytes = record_bytes(file, &text);

        assert_eq!(Release::decode(&bytes).expect("decodes"), release, "{file}");
    }
}

#[test]
fn encode_then_decode_round_trips_and_is_gzipped() {
    let release = fixture();
    let encoded = release.encode().expect("encodes");
    let raw = STANDARD.decode(&encoded).expect("base64");

    assert_eq!(raw[..3], GZIP_MAGIC);
    assert_eq!(
        Release::decode(encoded.as_bytes()).expect("decodes"),
        release
    );
}

#[test]
fn a_raw_secret_value_needs_one_more_base64_decode() {
    let release = fixture();
    let configmap_value = release.encode().expect("encodes");
    let secret_wire_value = STANDARD.encode(&configmap_value);
    let secret_data = STANDARD
        .decode(&secret_wire_value)
        .expect("api decodes once");

    assert_eq!(
        Release::decode(configmap_value.as_bytes()).expect("configmap"),
        release
    );
    assert_eq!(Release::decode(&secret_data).expect("secret"), release);
    assert!(Release::decode(secret_wire_value.as_bytes()).is_err());
}

#[test]
fn bad_records_report_the_failing_stage() {
    let truncated_gzip = STANDARD.encode([0x1f, 0x8b, 0x08, 0x00, 0x01]);
    let not_json = STANDARD.encode("not json");

    assert!(matches!(Release::decode(b"!!!"), Err(Error::Base64(_))));
    assert!(matches!(
        Release::decode(truncated_gzip.as_bytes()),
        Err(Error::Gzip(_))
    ));
    assert!(matches!(
        Release::decode(not_json.as_bytes()),
        Err(Error::Json(_))
    ));
}

#[test]
fn every_status_round_trips() {
    let table = [
        ("unknown", Status::Unknown, false),
        ("deployed", Status::Deployed, false),
        ("uninstalled", Status::Uninstalled, false),
        ("superseded", Status::Superseded, false),
        ("failed", Status::Failed, false),
        ("uninstalling", Status::Uninstalling, false),
        ("pending-install", Status::PendingInstall, true),
        ("pending-upgrade", Status::PendingUpgrade, true),
        ("pending-rollback", Status::PendingRollback, true),
    ];

    for (text, status, pending) in table {
        let release = parse(&json!({"info": {"status": text}}));
        let info = release.info.as_ref().expect("info");

        assert_eq!(info.status, status, "{text}");
        assert_eq!(info.status.is_pending(), pending, "{text}");
        assert_eq!(
            serde_json::to_value(&release).expect("serialize")["info"]["status"],
            text
        );
    }
}

#[test]
fn unlisted_and_missing_values_survive_as_other() {
    let release = parse(&json!({
        "info": {"status": "frozen"},
        "hooks": [{"last_run": {"phase": "Weird"}, "delete_policies": ["custom"]}],
        "apply_method": "ssa",
    }));
    let unset = parse(&json!({"info": {}, "apply_method": ""}));

    assert_eq!(
        release.info.as_ref().expect("info").status,
        Status::Other("frozen".into())
    );
    assert_eq!(
        release.hooks[0].last_run.phase,
        HookPhase::Other("Weird".into())
    );
    assert_eq!(
        release.hooks[0].delete_policies,
        [DeletePolicy::Other("custom".into())]
    );
    assert_eq!(release.apply_method, Some(ApplyMethod::ServerSide));
    assert_eq!(unset.apply_method, None);
    assert!(unset.info.expect("info").status.is_empty());
}

#[test]
fn hook_phases_round_trip() {
    for phase in ["Unknown", "Running", "Succeeded", "Failed", ""] {
        let hook: Hook =
            serde_json::from_value(json!({"last_run": {"phase": phase}})).expect("hook");

        assert_eq!(
            serde_json::to_value(&hook).expect("serialize")["last_run"]["phase"],
            phase
        );
    }
}

#[test]
fn zero_empty_and_missing_times_read_as_none() {
    let times = [
        json!({"first_deployed": "0001-01-01T00:00:00Z"}),
        json!({"first_deployed": ""}),
        json!({"first_deployed": null}),
        json!({}),
    ];

    for info in times {
        let release = parse(&json!({"info": info}));

        assert_eq!(release.info.expect("info").first_deployed, None, "{info}");
    }
}

#[test]
fn times_keep_their_instant_and_go_zero_is_written_where_go_writes_it() {
    let release = parse(&json!({
        "info": {"last_deployed": "2026-11-27T20:23:31.003475818+01:00"},
        "chart": {"lock": {"generated": "0001-01-01T00:00:00Z"}},
    }));
    let value = serde_json::to_value(&release).expect("serialize");

    assert_eq!(
        value["info"]["last_deployed"],
        "2026-11-27T19:23:31.003475818Z"
    );
    assert!(value["info"].get("first_deployed").is_none());
    assert_eq!(value["chart"]["schemamodtime"], "0001-01-01T00:00:00Z");
    assert_eq!(value["chart"]["lock"]["generated"], "0001-01-01T00:00:00Z");
    assert_eq!(value["chart"]["schema"], Value::Null);
}

#[test]
fn null_collections_read_as_empty() {
    let release = parse(&json!({
        "hooks": null,
        "chart": {"templates": null, "files": null, "schema": null, "values": null},
    }));
    let chart = release.chart.expect("chart");

    assert_eq!(release.hooks.len(), 0);
    assert!(chart.templates.is_empty() && chart.files.is_empty() && chart.schema_raw.is_none());
}

/// A record Helm 4.3.0 wrote to the kind cluster and what it must decode to.
struct Written {
    file: &'static str,
    text: &'static str,
    name: &'static str,
    revision: u32,
    status: Status,
    /// `replicaCount` from the user-supplied values; `None` when none were given.
    replicas: Option<u64>,
}

const HELM_WRITTEN: [Written; 3] = [
    Written {
        file: "secret-v1.json",
        text: include_str!("../../tests/fixtures/release/secret-v1.json"),
        name: "demo",
        revision: 1,
        status: Status::Superseded,
        replicas: None,
    },
    Written {
        file: "secret-v2.json",
        text: include_str!("../../tests/fixtures/release/secret-v2.json"),
        name: "demo",
        revision: 2,
        status: Status::Deployed,
        replicas: Some(2),
    },
    Written {
        file: "configmap-v1.json",
        text: include_str!("../../tests/fixtures/release/configmap-v1.json"),
        name: "demo-cm",
        revision: 1,
        status: Status::Deployed,
        replicas: None,
    },
];

#[test]
fn decodes_records_helm_wrote_to_a_cluster() {
    for Written {
        file,
        text,
        name,
        revision,
        status,
        replicas,
    } in HELM_WRITTEN
    {
        let release = Release::decode(&record_bytes(file, text)).expect("decodes");
        let manifest = crate::manifest::Manifest::parse(&release.manifest).expect("manifest");
        let chart = release.chart.as_ref().expect("chart");
        let info = release.info.as_ref().expect("info");
        let metadata = &chart.metadata;

        assert_eq!(release.name, name, "{file}");
        assert_eq!(release.version, Revision(revision), "{file}");
        assert_eq!(info.status, status, "{file}");
        assert!(info.last_deployed.is_some(), "{file}");
        assert_eq!(metadata.name, "demo", "{file}");
        assert!(!manifest.objects.is_empty(), "{file}");
        assert_eq!(
            release
                .config
                .get("replicaCount")
                .and_then(serde_json::Value::as_u64),
            replicas,
            "{file}"
        );
        assert_eq!(
            Release::decode(release.encode().expect("encodes").as_bytes()).expect("again"),
            release,
            "{file}"
        );
    }
}