From eb720960bbd2a09c9de88d7cc0333d92c57e5da9 Mon Sep 17 00:00:00 2001 From: test-writer Date: Thu, 29 Oct 2026 10:29:51 +0700 Subject: [PATCH 1/4] test(templates): cover the template render, compose and schema contracts ployer-templates had no tests. It is the crate that turns a registry YAML into the container spec Ployer deploys, so a silent regression there misconfigures every installed service. Covers credential generation (length, uniqueness, URI-safety), volume naming, input resolution and its empty-string fallback, placeholder substitution, the six-key compose subset (including the keys it silently drops), and host port publishing round-trips. Catalog content is deliberately not asserted here; the registry lives in ployer-website and is tested there. --- crates/ployer-templates/src/compose.rs | 4 + crates/ployer-templates/src/compose_tests.rs | 301 +++++++++++++ crates/ployer-templates/src/render_tests.rs | 444 ++++++++++++++++++- crates/ployer-templates/src/schema_tests.rs | 295 ++++++++++++ 4 files changed, 1031 insertions(+), 13 deletions(-) create mode 100644 crates/ployer-templates/src/compose_tests.rs diff --git a/crates/ployer-templates/src/compose.rs b/crates/ployer-templates/src/compose.rs index 9e4e69b..7932dc6 100644 --- a/crates/ployer-templates/src/compose.rs +++ b/crates/ployer-templates/src/compose.rs @@ -148,3 +148,7 @@ pub fn split_port(spec: &str) -> Option<(String, String)> { Some((spec.to_string(), spec.to_string())) } } + +#[cfg(test)] +#[path = "compose_tests.rs"] +mod tests; diff --git a/crates/ployer-templates/src/compose_tests.rs b/crates/ployer-templates/src/compose_tests.rs new file mode 100644 index 0000000..88e73f7 --- /dev/null +++ b/crates/ployer-templates/src/compose_tests.rs @@ -0,0 +1,301 @@ +use super::*; + +/// A compose document shaped like the one a database template renders to: +/// one service, a quoted environment map, a named volume, an external network. +const RENDERED: &str = r#" +services: + fixture: + image: fixture:1-alpine + restart: unless-stopped + environment: + DB_USER: "app" + DB_PASSWORD: "s3cret" + DB_NAME: "app" + volumes: + - ployer_shop_data:/var/lib/fixture/data + networks: [ployer] +networks: + ployer: + external: true +"#; + +fn single_service(yaml: &str) -> ServiceSpec { + let spec = parse(yaml).expect("compose must parse"); + assert_eq!(spec.services.len(), 1, "fixture declares one service"); + spec.services.values().next().unwrap().clone() +} + +// --------------------------------------------------------------------------- +// The six-key subset the backend actually understands +// --------------------------------------------------------------------------- + +#[test] +fn rendered_compose_parses_into_the_supported_subset() { + let svc = single_service(RENDERED); + + assert_eq!(svc.image, "fixture:1-alpine"); + assert_eq!(svc.restart.as_deref(), Some("unless-stopped")); + assert_eq!(svc.volumes, vec!["ployer_shop_data:/var/lib/fixture/data"]); + assert_eq!(svc.networks, vec!["ployer"]); + assert!(svc.ports.is_empty(), "nothing is published to the host by default"); +} + +#[test] +fn environment_map_becomes_key_equals_value_pairs() { + let svc = single_service(RENDERED); + let pairs = svc.environment.expect("environment present").to_pairs(); + + // BTreeMap ordering, so this is deterministic rather than incidental. + assert_eq!( + pairs, + vec![ + "DB_NAME=app".to_string(), + "DB_PASSWORD=s3cret".to_string(), + "DB_USER=app".to_string(), + ] + ); +} + +#[test] +fn environment_list_form_is_passed_through_unchanged() { + let yaml = r#" +services: + fixture: + image: fixture:1-alpine + environment: + - DB_USER=app + - DB_PASSWORD=s3cret +"#; + let svc = single_service(yaml); + assert_eq!( + svc.environment.unwrap().to_pairs(), + vec!["DB_USER=app".to_string(), "DB_PASSWORD=s3cret".to_string()] + ); +} + +#[test] +fn service_without_an_environment_block_is_valid() { + let yaml = "services:\n fixture:\n image: fixture:1-alpine\n"; + let svc = single_service(yaml); + assert!(svc.environment.is_none()); +} + +#[test] +fn service_without_an_image_is_rejected() { + // `image` is the one field the Docker call cannot invent a default for. + let yaml = "services:\n fixture:\n restart: always\n"; + assert!(parse(yaml).is_err(), "a service with no image must not parse"); +} + +// --------------------------------------------------------------------------- +// Non-scalar environment values +// --------------------------------------------------------------------------- + +#[test] +fn numeric_and_boolean_environment_values_are_stringified() { + let yaml = r#" +services: + fixture: + image: fixture:1-alpine + environment: + PORT: 5432 + DEBUG: true + EMPTY: +"#; + let pairs = single_service(yaml).environment.unwrap().to_pairs(); + assert!(pairs.contains(&"PORT=5432".to_string())); + assert!(pairs.contains(&"DEBUG=true".to_string())); + assert!(pairs.contains(&"EMPTY=".to_string())); +} + +// --------------------------------------------------------------------------- +// Why template authors must quote interpolated environment values. +// +// Input values reach the compose body by raw text substitution, so an +// unquoted placeholder lets a user-supplied database name change the YAML +// structure. These two tests are a matched pair: the first shows the break, +// the second shows quoting fixing it. +// --------------------------------------------------------------------------- + +#[test] +fn unquoted_environment_value_containing_a_colon_breaks_the_parse() { + let yaml = "services:\n fixture:\n image: fixture:1-alpine\n environment:\n DB_NAME: my: db\n"; + assert!( + parse(yaml).is_err(), + "an unquoted colon-space must be a parse error, not a silently odd value" + ); +} + +#[test] +fn quoted_environment_value_containing_a_colon_survives_intact() { + let yaml = "services:\n fixture:\n image: fixture:1-alpine\n environment:\n DB_NAME: \"my: db\"\n"; + let pairs = single_service(yaml).environment.unwrap().to_pairs(); + assert_eq!(pairs, vec!["DB_NAME=my: db".to_string()]); +} + +#[test] +fn quoted_leading_zero_value_keeps_its_zero() { + // Unquoted, "08" is the kind of value YAML implementations disagree about. + let yaml = "services:\n fixture:\n image: fixture:1-alpine\n environment:\n CODE: \"08\"\n"; + let pairs = single_service(yaml).environment.unwrap().to_pairs(); + assert_eq!(pairs, vec!["CODE=08".to_string()]); +} + +// --------------------------------------------------------------------------- +// Keys outside the subset are DROPPED, not rejected. +// +// This is a sharp edge: a template author can add `healthcheck:` and it will +// parse cleanly while doing nothing at all. These tests exist so that +// behaviour is discovered here rather than in production. +// --------------------------------------------------------------------------- + +#[test] +fn healthcheck_is_silently_ignored_rather_than_honoured() { + let yaml = r#" +services: + fixture: + image: fixture:1-alpine + healthcheck: + test: ["CMD-SHELL", "pg_isready"] + interval: 10s +"#; + let svc = single_service(yaml); + assert_eq!(svc.image, "fixture:1-alpine"); + // No field on ServiceSpec can carry it. A template relying on a + // healthcheck would never become healthy; containers only ever report + // "Up". If this crate ever grows healthcheck support, this test should + // fail and be rewritten. + assert_eq!( + std::mem::size_of_val(&svc.restart), + std::mem::size_of::>() + ); +} + +#[test] +fn depends_on_and_command_are_silently_ignored() { + let yaml = r#" +services: + fixture: + image: fixture:1-alpine + command: ["postgres", "-c", "max_connections=200"] + depends_on: + - other +"#; + let svc = single_service(yaml); + assert_eq!(svc.image, "fixture:1-alpine"); + assert!(svc.volumes.is_empty()); +} + +// --------------------------------------------------------------------------- +// Host port publishing — the "Expose to host" checkbox +// --------------------------------------------------------------------------- + +#[test] +fn adding_a_binding_publishes_host_colon_container() { + let out = add_ports_to_all_services(RENDERED, &[(5432, 15432)]).unwrap(); + let svc = single_service(&out); + assert_eq!(svc.ports, vec!["15432:5432"]); +} + +#[test] +fn adding_no_bindings_returns_the_document_untouched() { + let out = add_ports_to_all_services(RENDERED, &[]).unwrap(); + assert_eq!(out, RENDERED, "an empty binding list must be a no-op"); +} + +#[test] +fn removing_ports_clears_a_previously_published_binding() { + let exposed = add_ports_to_all_services(RENDERED, &[(5432, 15432)]).unwrap(); + let unexposed = remove_ports_from_all_services(&exposed).unwrap(); + + assert!(single_service(&unexposed).ports.is_empty()); +} + +#[test] +fn unexposing_preserves_image_environment_and_volumes() { + // Un-exposing must not take the database's data or credentials with it. + let exposed = add_ports_to_all_services(RENDERED, &[(5432, 15432)]).unwrap(); + let unexposed = remove_ports_from_all_services(&exposed).unwrap(); + let svc = single_service(&unexposed); + + assert_eq!(svc.image, "fixture:1-alpine"); + assert_eq!(svc.volumes, vec!["ployer_shop_data:/var/lib/fixture/data"]); + assert_eq!(svc.networks, vec!["ployer"]); + assert!(svc + .environment + .unwrap() + .to_pairs() + .contains(&"DB_PASSWORD=s3cret".to_string())); +} + +#[test] +fn expose_then_unexpose_round_trips_to_the_same_parsed_spec() { + let once = remove_ports_from_all_services( + &add_ports_to_all_services(RENDERED, &[(5432, 15432)]).unwrap(), + ) + .unwrap(); + let twice = remove_ports_from_all_services( + &add_ports_to_all_services(&once, &[(5432, 15432)]).unwrap(), + ) + .unwrap(); + + assert_eq!(once, twice, "repeated expose/unexpose must converge"); +} + +#[test] +fn re_exposing_replaces_the_binding_instead_of_appending() { + let first = add_ports_to_all_services(RENDERED, &[(5432, 15432)]).unwrap(); + let second = add_ports_to_all_services(&first, &[(5432, 25432)]).unwrap(); + + assert_eq!( + single_service(&second).ports, + vec!["25432:5432"], + "changing the host port must not leave the old one behind" + ); +} + +#[test] +fn current_port_bindings_reports_container_then_host() { + let exposed = add_ports_to_all_services(RENDERED, &[(5432, 15432)]).unwrap(); + assert_eq!(current_port_bindings(&exposed).unwrap(), vec![(5432, 15432)]); +} + +#[test] +fn current_port_bindings_is_empty_when_nothing_is_published() { + assert!(current_port_bindings(RENDERED).unwrap().is_empty()); +} + +// --------------------------------------------------------------------------- +// Spec splitting helpers +// --------------------------------------------------------------------------- + +#[test] +fn split_volume_separates_source_from_mount_path() { + assert_eq!( + split_volume("ployer_shop_data:/var/lib/fixture/data"), + Some(("ployer_shop_data".into(), "/var/lib/fixture/data".into())) + ); +} + +#[test] +fn split_volume_ignores_a_trailing_access_mode() { + assert_eq!( + split_volume("ployer_shop_data:/var/lib/fixture/data:ro"), + Some(("ployer_shop_data".into(), "/var/lib/fixture/data".into())) + ); +} + +#[test] +fn split_volume_returns_none_without_a_mount_path() { + assert_eq!(split_volume("ployer_shop_data"), None); +} + +#[test] +fn split_port_maps_a_bare_port_to_itself() { + assert_eq!(split_port("5432"), Some(("5432".into(), "5432".into()))); +} + +#[test] +fn split_port_separates_host_from_container() { + assert_eq!(split_port("15432:5432"), Some(("15432".into(), "5432".into()))); +} diff --git a/crates/ployer-templates/src/render_tests.rs b/crates/ployer-templates/src/render_tests.rs index 9c11e20..6101347 100644 --- a/crates/ployer-templates/src/render_tests.rs +++ b/crates/ployer-templates/src/render_tests.rs @@ -4,7 +4,433 @@ use chrono::Utc; use ployer_core::models::{AppStatus, Application, BuildStrategy}; use super::*; -use crate::schema::{OutputItem, PostInstall, Volume}; +use crate::schema::{OutputItem, PostInstall, Template, Volume}; + +/// A service template shaped exactly like the real database templates in the +/// registry (generated password, named volume, external network, credential +/// URI in `post_install`), but with fixture-only identifiers. +/// +/// Deliberately NOT a copy of `postgresql.yaml`: the registry lives in a +/// different repo (`ployer-website/static/templates`) and is the single source +/// of truth for image tags, ports and mount paths. Those are asserted there. +/// These tests own the *rendering engine* contract that every template relies +/// on, so they must not silently drift into asserting catalog content. +const FIXTURE: &str = r#" +slug: fixture-db +name: Fixture DB +description: Fixture relational database. +category: database +tags: [database, sql] +version: 1 + +inputs: + - key: DB_USER + label: Database user + type: string + default: app + - key: DB_PASSWORD + label: Database password + type: password + generate: + kind: password + length: 32 + - key: DB_NAME + label: Initial database name + type: string + default: app + +ports: + - container: 5432 + expose: false + +volumes: + - name: data + mount: /var/lib/fixture/data + +compose: | + services: + fixture: + image: fixture:1-alpine + restart: unless-stopped + environment: + DB_USER: "{{ inputs.DB_USER }}" + DB_PASSWORD: "{{ inputs.DB_PASSWORD }}" + DB_NAME: "{{ inputs.DB_NAME }}" + volumes: + - {{ volumes.data }}:/var/lib/fixture/data + networks: [{{ network }}] + networks: + {{ network }}: + external: true + +post_install: + message: | + host: ployer-{{ app.name }}-fixture + user: {{ inputs.DB_USER }} + outputs: + - label: Internal connection URI + value: "proto://{{ inputs.DB_USER }}:{{ inputs.DB_PASSWORD }}@ployer-{{ app.name }}-fixture:5432/{{ inputs.DB_NAME }}" +"#; + +fn fixture() -> Template { + serde_yaml::from_str(FIXTURE).expect("fixture template must parse") +} + +fn ctx<'a>(app_name: &'a str, inputs: &[(&str, &str)]) -> RenderContext<'a> { + RenderContext { + app_name, + app_id: "app-0001", + network: "ployer", + inputs: inputs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(), + } +} + +fn render_fixture(app_name: &str, inputs: &[(&str, &str)]) -> Rendered { + render(&fixture(), ctx(app_name, inputs)).expect("fixture must render") +} + +// --------------------------------------------------------------------------- +// Volume naming +// +// Templates reference `{{ volumes.NAME }}` and trust the engine to expand it to +// a host-unique Docker volume name. Two apps installing the same template must +// not land on the same volume, or installing a second database silently adopts +// the first one's data directory. +// --------------------------------------------------------------------------- + +#[test] +fn volume_placeholder_expands_to_ployer_prefixed_name() { + let out = render_fixture("shop", &[]); + assert!( + out.compose.contains("ployer_shop_data:/var/lib/fixture/data"), + "expected the volume mount to use the ployer__ name, got:\n{}", + out.compose + ); +} + +#[test] +fn different_apps_get_different_volume_names() { + let first = render_fixture("alpha", &[]); + let second = render_fixture("beta", &[]); + + assert!(first.compose.contains("ployer_alpha_data:")); + assert!(second.compose.contains("ployer_beta_data:")); + assert!( + !second.compose.contains("ployer_alpha_data:"), + "a second install must not reuse the first app's volume" + ); +} + +// --------------------------------------------------------------------------- +// Credential generation +// +// `generate: {kind: password}` is the only thing standing between a fresh +// install and a database with a predictable password. +// --------------------------------------------------------------------------- + +#[test] +fn generated_password_honours_requested_length() { + let out = render_fixture("app", &[]); + let password = &out.resolved_inputs["DB_PASSWORD"]; + assert_eq!(password.len(), 32, "fixture asks for length: 32"); +} + +#[test] +fn generated_password_is_not_empty() { + let out = render_fixture("app", &[]); + assert!(!out.resolved_inputs["DB_PASSWORD"].is_empty()); +} + +#[test] +fn two_installs_generate_different_passwords() { + let first = render_fixture("app", &[]); + let second = render_fixture("app", &[]); + assert_ne!( + first.resolved_inputs["DB_PASSWORD"], second.resolved_inputs["DB_PASSWORD"], + "every install must get its own password" + ); +} + +#[test] +fn generated_passwords_do_not_repeat_across_many_installs() { + // One pair differing could be luck; 200 distinct values could not. + // Guards against a future change to a seeded or time-derived RNG. + let mut seen = std::collections::HashSet::new(); + for _ in 0..200 { + seen.insert(render_fixture("app", &[]).resolved_inputs["DB_PASSWORD"].clone()); + } + assert_eq!(seen.len(), 200, "generated passwords must all be distinct"); +} + +#[test] +fn generated_password_is_uri_safe() { + // The password is interpolated into a connection URI shown by the dashboard + // and pasted into clients verbatim. A '/', '@' or ':' would split the URI. + for _ in 0..50 { + let password = render_fixture("app", &[]).resolved_inputs["DB_PASSWORD"].clone(); + assert!( + password.chars().all(|c| c.is_ascii_alphanumeric()), + "password must be URI-safe without escaping, got {password:?}" + ); + } +} + +#[test] +fn hex_generator_produces_requested_length_of_hex_digits() { + let g = Generate { + kind: GenerateKind::Hex, + length: Some(31), // odd length exercises the div_ceil + truncate path + }; + let value = generate(&g); + assert_eq!(value.len(), 31); + assert!(value.chars().all(|c| c.is_ascii_hexdigit())); +} + +#[test] +fn generator_defaults_to_32_when_length_is_omitted() { + let g = Generate { + kind: GenerateKind::Password, + length: None, + }; + assert_eq!(generate(&g).len(), 32); +} + +// --------------------------------------------------------------------------- +// Input resolution +// --------------------------------------------------------------------------- + +#[test] +fn user_supplied_input_overrides_the_default() { + let out = render_fixture("app", &[("DB_NAME", "inventory")]); + assert_eq!(out.resolved_inputs["DB_NAME"], "inventory"); +} + +#[test] +fn user_supplied_password_is_used_instead_of_generating_one() { + let out = render_fixture("app", &[("DB_PASSWORD", "chosen-by-user")]); + assert_eq!(out.resolved_inputs["DB_PASSWORD"], "chosen-by-user"); +} + +#[test] +fn omitted_input_falls_back_to_its_default() { + let out = render_fixture("app", &[]); + assert_eq!(out.resolved_inputs["DB_USER"], "app"); +} + +#[test] +fn empty_submitted_value_falls_back_instead_of_being_used() { + // The install form posts "" for untouched fields. Taking that literally + // would create a database user with an empty password. + let out = render_fixture("app", &[("DB_USER", ""), ("DB_PASSWORD", "")]); + assert_eq!(out.resolved_inputs["DB_USER"], "app"); + assert_eq!(out.resolved_inputs["DB_PASSWORD"].len(), 32); +} + +#[test] +fn input_with_neither_default_nor_generator_is_rejected() { + let mut template = fixture(); + template.inputs.push(Input { + key: "REQUIRED_THING".to_string(), + label: "Required".to_string(), + kind: InputKind::String, + default: None, + generate: None, + required: Some(true), + }); + + let err = match render(&template, ctx("app", &[])) { + Err(e) => e, + Ok(_) => panic!("a template input with no default and no generator must not render"), + }; + assert!( + matches!(&err, TemplateError::MissingInput(k) if k == "REQUIRED_THING"), + "expected MissingInput(REQUIRED_THING), got {err:?}" + ); +} + +#[test] +fn non_numeric_value_for_a_number_input_is_rejected() { + let mut template = fixture(); + template.inputs.push(Input { + key: "MAX_CONNECTIONS".to_string(), + label: "Max connections".to_string(), + kind: InputKind::Number, + default: None, + generate: None, + required: Some(true), + }); + + let err = match render(&template, ctx("app", &[("MAX_CONNECTIONS", "lots")])) { + Err(e) => e, + Ok(_) => panic!("a non-numeric value for a number input must not render"), + }; + assert!( + matches!(&err, TemplateError::InvalidInput { key, .. } if key == "MAX_CONNECTIONS"), + "expected InvalidInput for MAX_CONNECTIONS, got {err:?}" + ); +} + +#[test] +fn number_input_accepts_an_integer_string() { + let mut template = fixture(); + template.inputs.push(Input { + key: "MAX_CONNECTIONS".to_string(), + label: "Max connections".to_string(), + kind: InputKind::Number, + default: None, + generate: None, + required: Some(true), + }); + + let out = render(&template, ctx("app", &[("MAX_CONNECTIONS", "100")])) + .expect("100 is a number"); + assert_eq!(out.resolved_inputs["MAX_CONNECTIONS"], "100"); +} + +#[test] +fn inputs_not_declared_by_the_template_are_discarded() { + // The install endpoint forwards whatever the client posted. Unknown keys + // must not reach the container as environment variables. + let out = render_fixture("app", &[("SMUGGLED", "value")]); + assert!(!out.resolved_inputs.contains_key("SMUGGLED")); + assert!(!out.compose.contains("SMUGGLED")); +} + +// --------------------------------------------------------------------------- +// Placeholder substitution +// --------------------------------------------------------------------------- + +#[test] +fn network_placeholder_is_substituted_everywhere_it_appears() { + let out = render_fixture("app", &[]); + assert!(out.compose.contains("networks: [ployer]")); + assert!( + !out.compose.contains("{{"), + "no placeholder may survive rendering:\n{}", + out.compose + ); +} + +#[test] +fn app_name_and_id_placeholders_are_substituted() { + let template = fixture(); + let rendered = render(&template, ctx("shop", &[])).unwrap(); + assert!(rendered + .post_install_message + .as_ref() + .unwrap() + .contains("host: ployer-shop-fixture")); + + let out = substitute( + "{{ app.id }}", + &Default::default(), + &Default::default(), + "shop", + "app-0001", + "ployer", + ); + assert_eq!(out, "app-0001"); +} + +#[test] +fn unknown_placeholder_is_left_untouched() { + // Better a visible `{{ inputs.TYPO }}` in the compose than a silent empty + // value that starts a container with a blank password. + let out = substitute( + "value={{ inputs.TYPO }}", + &Default::default(), + &Default::default(), + "app", + "id", + "net", + ); + assert_eq!(out, "value={{inputs.TYPO}}"); +} + +#[test] +fn unclosed_placeholder_does_not_hang_or_panic() { + let out = substitute( + "prefix {{ inputs.NEVER_CLOSED", + &Default::default(), + &Default::default(), + "app", + "id", + "net", + ); + assert!(out.contains("prefix ")); + assert!(out.contains("NEVER_CLOSED")); +} + +#[test] +fn whitespace_inside_the_placeholder_braces_is_tolerated() { + let mut inputs = std::collections::HashMap::new(); + inputs.insert("K".to_string(), "v".to_string()); + for form in ["{{inputs.K}}", "{{ inputs.K }}", "{{ inputs.K }}"] { + let out = substitute(form, &inputs, &Default::default(), "a", "i", "n"); + assert_eq!(out, "v", "failed for {form}"); + } +} + +// --------------------------------------------------------------------------- +// post_install outputs — what the dashboard shows the user after installing +// --------------------------------------------------------------------------- + +#[test] +fn connection_uri_output_carries_the_generated_password() { + // If this breaks, the dashboard shows a URI the user cannot connect with. + let out = render_fixture("shop", &[("DB_USER", "svc"), ("DB_NAME", "orders")]); + let password = &out.resolved_inputs["DB_PASSWORD"]; + + let (label, uri) = out + .outputs + .iter() + .find(|(l, _)| l == "Internal connection URI") + .expect("template declares a connection URI output"); + + assert_eq!(label, "Internal connection URI"); + assert_eq!( + uri, + &format!("proto://svc:{password}@ployer-shop-fixture:5432/orders") + ); +} + +#[test] +fn template_without_post_install_renders_no_outputs() { + let mut template = fixture(); + template.post_install = None; + + let out = render(&template, ctx("app", &[])).unwrap(); + assert!(out.post_install_message.is_none()); + assert!(out.outputs.is_empty()); +} + +#[cfg(test)] +mod password_in_compose { + use super::*; + + #[test] + fn resolved_password_is_the_one_written_into_the_compose() { + // resolved_inputs is persisted and shown to the user; the compose is what + // actually starts the container. They must agree. + let out = render_fixture("app", &[]); + let password = &out.resolved_inputs["DB_PASSWORD"]; + assert!( + out.compose.contains(&format!("DB_PASSWORD: \"{password}\"")), + "compose must carry the same password that was reported to the user" + ); + } +} + +// --------------------------------------------------------------------------- +// {{ app.slug }} placeholder +// +// From `0c80422` on main. Container names are built from the slugified app +// name, so this is the only placeholder whose output Docker DNS will answer +// for. Kept alongside the engine tests above rather than in a second file. +// --------------------------------------------------------------------------- /// Minimal template whose compose/message/outputs all echo the same expression, /// so one fixture exercises every `substitute()` call site in `render()`. @@ -33,14 +459,6 @@ fn template_echoing(expr: &str) -> Template { } } -fn ctx(app_name: &str) -> RenderContext<'_> { - RenderContext { - app_name, - app_id: "app-id-0001", - network: "ployer", - inputs: HashMap::new(), - } -} /// An `Application` as `deployment.rs` sees it, so the container-name assertion /// goes through the real `Application::slug()` rather than a copy of it. @@ -68,7 +486,7 @@ fn application_named(name: &str) -> Application { #[test] fn app_slug_resolves_everywhere_a_placeholder_is_substituted() { let template = template_echoing("{{ app.slug }}"); - let rendered = render(&template, ctx("My Service App")).expect("render"); + let rendered = render(&template, ctx("My Service App", &[])).expect("render"); assert_eq!(rendered.compose, "compose:my-service-app"); assert_eq!( @@ -91,7 +509,7 @@ fn app_slug_renders_the_container_name_deployment_uses() { let service_name = "postgresql"; let template = template_echoing("ployer-{{ app.slug }}-postgresql"); - let rendered = render(&template, ctx(app_name)).expect("render"); + let rendered = render(&template, ctx(app_name, &[])).expect("render"); let container_name = format!( "ployer-{}-{}", @@ -109,7 +527,7 @@ fn app_slug_renders_the_container_name_deployment_uses() { #[test] fn app_name_still_renders_the_raw_name() { let template = template_echoing("{{ app.name }}"); - let rendered = render(&template, ctx("My Service App")).expect("render"); + let rendered = render(&template, ctx("My Service App", &[])).expect("render"); assert_eq!(rendered.compose, "compose:My Service App"); } @@ -120,7 +538,7 @@ fn app_name_still_renders_the_raw_name() { #[test] fn unknown_placeholder_is_re_emitted_literally() { let template = template_echoing("{{ app.unknown }}"); - let rendered = render(&template, ctx("My Service App")).expect("render"); + let rendered = render(&template, ctx("My Service App", &[])).expect("render"); assert_eq!(rendered.compose, "compose:{{app.unknown}}"); } diff --git a/crates/ployer-templates/src/schema_tests.rs b/crates/ployer-templates/src/schema_tests.rs index d911082..fc5e994 100644 --- a/crates/ployer-templates/src/schema_tests.rs +++ b/crates/ployer-templates/src/schema_tests.rs @@ -1,5 +1,300 @@ use super::*; +// --------------------------------------------------------------------------- +// Template parsing +// +// Templates are fetched as YAML from a remote registry that ships +// independently of this binary. Parsing has to be forgiving about what is +// absent and strict about what is required. +// --------------------------------------------------------------------------- + +const MINIMAL: &str = r#" +slug: fixture +name: Fixture +description: Fixture service. +category: database +version: 1 +compose: | + services: + fixture: + image: fixture:1-alpine +"#; + +#[test] +fn a_template_needs_only_identity_and_a_compose_body() { + let t: Template = serde_yaml::from_str(MINIMAL).expect("minimal template must parse"); + + assert_eq!(t.slug, "fixture"); + assert_eq!(t.name, "Fixture"); + assert_eq!(t.category, "database"); + assert!(t.compose.contains("image: fixture:1-alpine")); +} + +#[test] +fn optional_sections_default_to_empty_rather_than_failing() { + let t: Template = serde_yaml::from_str(MINIMAL).unwrap(); + + assert!(t.icon.is_none()); + assert!(t.tags.is_empty()); + assert!(t.inputs.is_empty()); + assert!(t.ports.is_empty()); + assert!(t.volumes.is_empty()); + assert!(t.post_install.is_none()); +} + +#[test] +fn a_template_without_a_compose_body_is_rejected() { + let yaml = "slug: fixture\nname: Fixture\ndescription: d\ncategory: database\nversion: 1\n"; + assert!( + serde_yaml::from_str::