use std::fs;
use std::path::{Path, PathBuf};
use serde_json::Value;
use super::{GenerateError, GenerateOptions, SkipField, annotations, generate, generate_chart};
use crate::chart::Chart;
fn fixtures() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/schema-gen")
}
fn skip_fields(list: &str) -> Vec<SkipField> {
list.split(',')
.map(|name| match name {
"type" => SkipField::Type,
"title" => SkipField::Title,
"description" => SkipField::Description,
"required" => SkipField::Required,
"default" => SkipField::Default,
"additionalProperties" => SkipField::AdditionalProperties,
other => panic!("unknown skip field {other}"),
})
.collect()
}
fn options_of(args: &str) -> GenerateOptions {
let mut options = GenerateOptions::default();
let mut words = args.split_whitespace();
while let Some(flag) = words.next() {
match flag {
"--keep-full-comment" => options.keep_full_comment = true,
"--uncomment" => options.uncomment = true,
"--helm-docs-compatibility-mode" => options.helm_docs_compatibility_mode = true,
"--dont-strip-helm-docs-prefix" => options.dont_strip_helm_docs_prefix = true,
"--dont-add-global" => options.dont_add_global = true,
"--no-dependencies" => options.no_dependencies = true,
"--skip-dependencies-schema-validation" => {
options.skip_dependencies_schema_validation = true;
}
"--keep-existing-dep-schemas" => options.keep_existing_dep_schemas = true,
"--skip-auto-generation" => {
options.skip_auto_generation = skip_fields(words.next().expect("value"));
}
"--dependencies-filter" => {
options.dependencies_filter = words
.next()
.expect("value")
.split(',')
.map(str::to_owned)
.collect();
}
other => panic!("unknown flag {other}"),
}
}
options
}
fn cases() -> Vec<(String, String, GenerateOptions, Value)> {
let mut out = Vec::new();
for entry in fs::read_dir(fixtures().join("expected")).expect("expected dir") {
let path = entry.expect("entry").path();
if path.extension().is_none_or(|e| e != "args") {
continue;
}
let name = path
.file_stem()
.and_then(|n| n.to_str())
.expect("name")
.to_owned();
let (chart, variant) = name.split_once('.').expect("chart.variant");
let args = fs::read_to_string(&path).expect("args");
let expected = fs::read_to_string(path.with_extension("json")).expect("expected json");
out.push((
chart.to_owned(),
variant.to_owned(),
options_of(&args),
serde_json::from_str(&expected).expect("expected is json"),
));
}
out
}
fn load(chart: &str) -> Chart {
Chart::load(fixtures().join(chart)).expect("fixture chart loads")
}
#[test]
fn output_equals_helm_schema() {
let cases = cases();
assert!(cases.len() >= 18, "the recorded cases are missing");
for (chart, variant, options, expected) in cases {
let actual = generate_chart(&load(&chart), &options).expect("generates");
assert_eq!(actual, expected, "{chart}.{variant}");
assert_eq!(
serde_json::to_string_pretty(&actual).expect("serialises"),
serde_json::to_string_pretty(&expected).expect("serialises"),
"{chart}.{variant}: key order"
);
}
}
#[test]
fn single_file_generation_matches_for_charts_without_dependencies() {
for (chart, variant, options, expected) in cases() {
if fixtures().join(&chart).join("charts").exists() || chart == "refs" {
continue;
}
let text = fs::read_to_string(fixtures().join(&chart).join("values.yaml")).expect("values");
assert_eq!(
generate(&text, &options).expect("generates"),
expected,
"{chart}.{variant}"
);
}
}
#[test]
fn generated_schemas_validate_the_chart_values() {
for (chart, variant, options, _) in cases() {
if options.uncomment || chart == "refs" {
continue;
}
let mut loaded = load(&chart);
let schema = generate_chart(&loaded, &options).expect("generates");
loaded.schema_raw = Some(serde_json::to_vec(&schema).expect("serialises"));
let values = loaded.values.clone();
crate::schema::validate(&loaded, &values)
.unwrap_or_else(|e| panic!("{chart}.{variant}: {e}"));
}
}
fn unescape(text: &str) -> String {
text.replace("\\n", "\n")
.replace("\\\"", "\"")
.replace("\\\\", "\\")
}
#[test]
fn errors_read_like_helm_schema() {
let mut checked = 0;
for entry in fs::read_dir(fixtures().join("errors/cases")).expect("cases") {
let path = entry.expect("entry").path();
if path.extension().is_none_or(|e| e != "yaml") {
continue;
}
let values = fs::read_to_string(&path).expect("values");
let expected = unescape(
fs::read_to_string(path.with_extension("err"))
.expect("err")
.trim_end(),
);
let error = generate(&values, &GenerateOptions::default()).expect_err("fails");
assert_eq!(error.to_string(), expected, "{}", path.display());
checked += 1;
}
assert!(checked >= 15, "the error cases are missing");
}
#[test]
fn annotation_errors_name_the_line_inside_the_block() {
let values =
"# Some description\n#\n# @schema\n# type: string\n#\n# minLength: x\n# @schema\nkey: a\n";
let error = generate(values, &GenerateOptions::default()).expect_err("fails");
assert!(
matches!(error, GenerateError::Annotation { line: Some(3), .. }),
"{error:?}"
);
}
#[test]
fn annotations_are_exposed_per_values_path() {
let values = "# @schema.root\n# title: Root\n# @schema.root\n# Docs.\n# @schema\n# type: integer\n# minimum: 1\n# @schema\nreplicas: 1\nimage:\n # @schema\n # type: string\n # @schema\n tag: x\n";
let found = annotations(values, false).expect("reads");
let paths: Vec<(Vec<String>, bool)> = found.iter().map(|a| (a.path.clone(), a.root)).collect();
assert_eq!(
paths,
vec![
(vec![], true),
(vec!["replicas".to_owned()], false),
(vec!["image".to_owned(), "tag".to_owned()], false)
]
);
assert_eq!(found[1].keywords["minimum"], 1);
assert_eq!(found[1].description, "Docs.");
}
#[test]
fn an_ambiguous_dependency_is_an_error() {
let mut chart = load("deps");
let twin = chart
.dependencies
.iter()
.find(|c| c.name() == "cache")
.expect("cache")
.clone();
chart.dependencies.push(twin);
let error = generate_chart(&chart, &GenerateOptions::default()).expect_err("fails");
assert!(
error
.to_string()
.starts_with("ambiguous dependency \"cache\""),
"{error}"
);
}
#[test]
#[ignore = "needs helm-schema"]
fn recorded_output_is_current() {
let status = std::process::Command::new(fixtures().join("regen.sh"))
.status()
.expect("runs regen.sh");
assert!(status.success());
output_equals_helm_schema();
}