diff --git a/apps/piqueld-ui/src/application.rs b/apps/piqueld-ui/src/application/mod.rs similarity index 51% rename from apps/piqueld-ui/src/application.rs rename to apps/piqueld-ui/src/application/mod.rs index 1010a40a1..aacdc27ff 100644 --- a/apps/piqueld-ui/src/application.rs +++ b/apps/piqueld-ui/src/application/mod.rs @@ -422,375 +422,4 @@ impl ImportDraft { } #[cfg(test)] -mod tests { - use super::*; - use piqueld_client::{ - ApplicationId, ApplicationSpec, EnvironmentId, EnvironmentKind, EnvironmentName, - GitRepository, LocalSnapshot, Metadata, PromotedFrom, RepositoryManifest, RunState, - access::{Permission, Scope}, - }; - use std::collections::BTreeMap; - - const APP: &str = "app-notes-01"; - - fn environment(id: &str, name: &str, source: EnvironmentSource) -> EnvironmentView { - EnvironmentView { - id: EnvironmentId::parse(id).unwrap(), - application_id: ApplicationId::parse(APP).unwrap(), - name: EnvironmentName::parse(name).unwrap(), - source, - kind: EnvironmentKind::Environment, - sync: false, - synced: None, - telemetry: false, - run_state: RunState::Running, - resolved_generation: None, - delete_intent: false, - created_at_ms: 1, - updated_at_ms: 1, - } - } - - fn preview(id: &str, branch: &str) -> EnvironmentView { - let mut preview = environment(id, id, EnvironmentSource::Saved); - preview.kind = EnvironmentKind::Preview(Box::new(piqueld_client::Preview { - branch: branch.parse().unwrap(), - slot: None, - slug: id.parse().unwrap(), - })); - preview - } - - fn promoted(id: &str, name: &str, from: &str) -> EnvironmentView { - environment( - id, - name, - EnvironmentSource::Promoted(PromotedFrom { - environment: EnvironmentId::parse(from).unwrap(), - }), - ) - } - - fn branch(name: &str) -> EnvironmentSource { - EnvironmentSource::Branch(TrackedBranch::new(name.into(), None).unwrap()) - } - - /// Application `notes` at revision 3, updated at 10, reading its - /// manifest from branch `main` when `connected`. - fn view(connected: bool, environments: Vec) -> ApplicationView { - let spec = ApplicationSpec { - manifest: connected.then(|| RepositoryManifest { - repository: GitRepository { - url: "https://example.com/notes.git".into(), - branch: "main".into(), - commit: None, - }, - path: "piqueld.toml".into(), - sync: piqueld_client::sync::RepositorySync::default(), - }), - ..ApplicationSpec::default() - }; - let application = ApplicationManifest { - api_version: "piqueld.dev/v1alpha1".into(), - kind: "Application".into(), - metadata: Metadata { - name: "notes".into(), - }, - spec, - } - .validate_template() - .unwrap() - .normalize(ApplicationId::parse(APP).unwrap()); - ApplicationView { - spec_hash: application.spec_hash(), - application, - generation: 3, - delete_intent: false, - created_at_ms: 1, - updated_at_ms: 10, - environments, - previews: Vec::new(), - drift: Vec::new(), - sync_check: None, - repository: None, - } - } - - #[test] - fn replica_summaries_resolve_variables_per_environment() { - let manifest: ApplicationManifest = serde_json::from_value(serde_json::json!({ - "api_version": "piqueld.dev/v1alpha1", - "kind": "Application", - "metadata": { "name": "notes" }, - "spec": { - "variables": { "web_replicas": 2 }, - "environments": { - "production": { "variables": { "web_replicas": 3, "api_replicas": 4 } }, - "staging": {}, - }, - "services": [ - { "name": "web", "source": { "type": "image", "image": "nginx:1.27" }, "replicas": "${{ vars.web_replicas }}" }, - { "name": "api", "source": { "type": "image", "image": "api:1" }, "replicas": "${{ vars.api_replicas }}" }, - { "name": "db", "source": { "type": "image", "image": "postgres:16" }, "replicas": 1 }, - ], - }, - })) - .unwrap(); - let application = manifest - .validate_template() - .unwrap() - .normalize(ApplicationId::parse(APP).unwrap()); - // Services are kept in name order. - let api = application.spec().services[0].clone(); - let db = application.spec().services[1].clone(); - let web = application.spec().services[2].clone(); - let mut view = ApplicationView { - spec_hash: application.spec_hash(), - application, - generation: 1, - delete_intent: false, - created_at_ms: 1, - updated_at_ms: 1, - environments: Vec::new(), - previews: Vec::new(), - drift: Vec::new(), - sync_check: None, - repository: None, - }; - assert_eq!(view.replica_summary(&db), "1 replica"); - assert_eq!( - view.replica_summary(&web), - "replicas from vars.web_replicas" - ); - view.environments = vec![environment(APP, "production", EnvironmentSource::Saved)]; - assert_eq!(view.replica_summary(&web), "3 replicas"); - view.environments.push(environment( - "app-notes-02", - "staging", - EnvironmentSource::Saved, - )); - assert_eq!( - view.replica_summary(&web), - "replicas: production 3, staging 2" - ); - // A value in only one of several environments names that environment. - assert_eq!(view.replica_summary(&api), "replicas: production 4"); - } - - fn grants(permission: AppPermission, application: &str) -> Grants { - let mut grants = Grants::default(); - grants - .grant( - Permission::App(permission), - &Scope::one(ApplicationId::parse(application).unwrap()), - ) - .unwrap(); - grants - } - - #[test] - fn query_parameters_open_only_tabs_the_page_has() { - let query = |pairs: &'static [(&'static str, &'static str)]| { - let pairs = pairs.iter().copied().collect::>(); - move |key: &str| pairs.get(key).map(|value| (*value).to_owned()) - }; - let environment = Page::Environment("env".into()); - assert_eq!(environment.initial_tab(query(&[("tab", "logs")])), "Logs"); - assert_eq!(slug("Command & arguments"), "command-arguments"); - // Environment pages have no releases; application pages no deployments or logs. - assert_eq!( - environment.initial_tab(query(&[("release", "r1")])), - "Overview" - ); - assert_eq!( - Page::Application.initial_tab(query(&[("tab", "logs")])), - "Overview" - ); - assert_eq!( - Page::Application.initial_tab(query(&[("release", "r1"), ("tab", "jobs")])), - "Releases" - ); - // A deployment's page opens on its timeline. - let deployment = Page::Deployment { - environment: "env".into(), - operation: "op".into(), - }; - assert_eq!(deployment.initial_tab(query(&[])), "Timeline"); - assert_eq!( - deployment.initial_tab(query(&[("tab", "snapshot")])), - "Snapshot" - ); - } - - #[test] - fn sources_and_origins_name_environments_or_their_id_once_gone() { - let saved = view( - false, - vec![ - environment("env-production-01", "production", EnvironmentSource::Saved), - promoted("env-staging-01", "staging", "env-production-01"), - ], - ); - let promotion = |environment: &str| DeploymentOrigin::Promotion { - environment: EnvironmentId::parse(environment).unwrap(), - deployment: "dep-1".into(), - }; - assert_eq!( - saved.describe_origin(&promotion("env-production-01")), - "Promoted from production (deployment dep-1)" - ); - assert_eq!( - saved.describe_origin(&promotion("env-deleted-01")), - "Promoted from env-deleted-01 (deployment dep-1)" - ); - assert_eq!( - saved.describe_source(&saved.environments[1].source), - "promoted from production" - ); - assert_eq!( - saved.describe_origin(&DeploymentOrigin::Restore { - deployment: "dep-good".into(), - rolled_back: Some("dep-failed".into()), - }), - "Rolled back from deployment dep-failed to deployment dep-good" - ); - let snapshot = |base: Option<&str>| { - DeploymentOrigin::Local(LocalSnapshot { - commit: "0123456789abcdef0123456789abcdef01234567".into(), - base: base.map(str::to_owned), - }) - }; - assert_eq!( - saved.describe_origin(&snapshot(Some("89abcdef0123456789abcdef0123456789abcdef"))), - "Local snapshot 0123456789ab on 89abcdef0123" - ); - assert_eq!( - saved.describe_origin(&snapshot(None)), - "Local snapshot 0123456789ab, uploaded complete" - ); - } - - #[test] - fn previews_permissions_allow_only_in_previews() { - let mut saved = view( - false, - vec![environment( - "env-production-01", - "production", - EnvironmentSource::Saved, - )], - ); - saved.previews.push(preview("feature-1a2b3c", "feature")); - let previews = grants(AppPermission::PreviewsDeploy, APP); - assert!( - previews - .require_app(AppPermission::LogsRead, saved.application.id()) - .is_err() - ); - assert!(saved.allows(&previews, AppPermission::LogsRead, Some("feature-1a2b3c"))); - assert!(!saved.allows( - &previews, - AppPermission::LogsRead, - Some("env-production-01") - )); - assert!(!saved.allows(&previews, AppPermission::LogsRead, None)); - // Previews permissions grant only what `on_previews` names. - assert!(!saved.allows(&previews, AppPermission::Exec, Some("feature-1a2b3c"))); - // Grants on another application never apply. - let elsewhere = grants(AppPermission::LogsRead, "app-other-01"); - assert!(!saved.allows(&elsewhere, AppPermission::LogsRead, None)); - } - - #[test] - fn only_a_later_fetch_of_the_same_revision_counts_as_fetched() { - let connected = view(true, Vec::new()); - assert!(connected.fetched_since(3, 11)); - assert!(!connected.fetched_since(3, 10), "not updated since"); - assert!( - !connected.fetched_since(4, 11), - "a newer revision conflicts" - ); - assert!( - !view(false, Vec::new()).fetched_since(3, 11), - "only repositories are fetched" - ); - } - - #[test] - fn only_environments_on_the_connection_branch_deploy_the_saved_manifest() { - let mut saved = view(true, Vec::new()); - let main = environment("env-production-01", "production", branch("main")); - assert!( - !saved.follows_connection(&main), - "nothing was read from the repository yet" - ); - saved.repository = Some(saved.application.clone()); - assert!(saved.follows_connection(&main)); - let other = environment("env-staging-01", "staging", branch("develop")); - assert!(!saved.follows_connection(&other)); - let mut preview = preview("main-1a2b3c", "main"); - preview.source = branch("main"); - assert!(!saved.follows_connection(&preview)); - let mut unconnected = view(false, Vec::new()); - unconnected.repository = Some(unconnected.application.clone()); - assert!(!unconnected.follows_connection(&main)); - } - - #[test] - fn releases_deploy_only_into_live_promoted_environments() { - let mut deleting = promoted("env-qa-01", "qa", "env-production-01"); - deleting.delete_intent = true; - let saved = view( - false, - vec![ - environment("env-production-01", "production", EnvironmentSource::Saved), - promoted("env-staging-01", "staging", "env-production-01"), - deleting, - ], - ); - assert_eq!(saved.release_targets(), ["env-staging-01"]); - } - - #[test] - fn export_rows_trim_names_and_drop_blank_ones() { - let row = ExportDraft { - service: "api".into(), - applications: " notes ,, billing, ".into(), - previews: true, - }; - let export = row.export(); - assert_eq!(export.applications, ["notes", "billing"]); - let mut manifest = view(false, Vec::new()).application.to_manifest(); - manifest.spec.exports.push(export); - assert_eq!( - ExportDraft::rows(&manifest), - [ExportDraft { - service: "api".into(), - applications: "notes, billing".into(), - previews: true, - }] - ); - } - - #[test] - fn imports_without_an_environment_reach_the_same_named_one() { - let row = |environment: &str| ImportDraft { - application: "auth".into(), - service: "api".into(), - environment: environment.into(), - }; - assert_eq!(row("").import().environment, None); - let import = row("production").import(); - assert_eq!( - import - .environment - .as_ref() - .map(ToString::to_string) - .as_deref(), - Some("production") - ); - let mut manifest = view(false, Vec::new()).application.to_manifest(); - manifest.spec.imports = vec![import, row("").import()]; - assert_eq!(ImportDraft::rows(&manifest), [row("production"), row("")]); - } -} +mod tests; diff --git a/apps/piqueld-ui/src/application/tests.rs b/apps/piqueld-ui/src/application/tests.rs new file mode 100644 index 000000000..37a1cdcf1 --- /dev/null +++ b/apps/piqueld-ui/src/application/tests.rs @@ -0,0 +1,370 @@ +use super::*; +use piqueld_client::{ + ApplicationId, ApplicationSpec, EnvironmentId, EnvironmentKind, EnvironmentName, GitRepository, + LocalSnapshot, Metadata, PromotedFrom, RepositoryManifest, RunState, + access::{Permission, Scope}, +}; +use std::collections::BTreeMap; + +const APP: &str = "app-notes-01"; + +fn environment(id: &str, name: &str, source: EnvironmentSource) -> EnvironmentView { + EnvironmentView { + id: EnvironmentId::parse(id).unwrap(), + application_id: ApplicationId::parse(APP).unwrap(), + name: EnvironmentName::parse(name).unwrap(), + source, + kind: EnvironmentKind::Environment, + sync: false, + synced: None, + telemetry: false, + run_state: RunState::Running, + resolved_generation: None, + delete_intent: false, + created_at_ms: 1, + updated_at_ms: 1, + } +} + +fn preview(id: &str, branch: &str) -> EnvironmentView { + let mut preview = environment(id, id, EnvironmentSource::Saved); + preview.kind = EnvironmentKind::Preview(Box::new(piqueld_client::Preview { + branch: branch.parse().unwrap(), + slot: None, + slug: id.parse().unwrap(), + })); + preview +} + +fn promoted(id: &str, name: &str, from: &str) -> EnvironmentView { + environment( + id, + name, + EnvironmentSource::Promoted(PromotedFrom { + environment: EnvironmentId::parse(from).unwrap(), + }), + ) +} + +fn branch(name: &str) -> EnvironmentSource { + EnvironmentSource::Branch(TrackedBranch::new(name.into(), None).unwrap()) +} + +/// Application `notes` at revision 3, updated at 10, reading its +/// manifest from branch `main` when `connected`. +fn view(connected: bool, environments: Vec) -> ApplicationView { + let spec = ApplicationSpec { + manifest: connected.then(|| RepositoryManifest { + repository: GitRepository { + url: "https://example.com/notes.git".into(), + branch: "main".into(), + commit: None, + }, + path: "piqueld.toml".into(), + sync: piqueld_client::sync::RepositorySync::default(), + }), + ..ApplicationSpec::default() + }; + let application = ApplicationManifest { + api_version: "piqueld.dev/v1alpha1".into(), + kind: "Application".into(), + metadata: Metadata { + name: "notes".into(), + }, + spec, + } + .validate_template() + .unwrap() + .normalize(ApplicationId::parse(APP).unwrap()); + ApplicationView { + spec_hash: application.spec_hash(), + application, + generation: 3, + delete_intent: false, + created_at_ms: 1, + updated_at_ms: 10, + environments, + previews: Vec::new(), + drift: Vec::new(), + sync_check: None, + repository: None, + } +} + +#[test] +fn replica_summaries_resolve_variables_per_environment() { + let manifest: ApplicationManifest = serde_json::from_value(serde_json::json!({ + "api_version": "piqueld.dev/v1alpha1", + "kind": "Application", + "metadata": { "name": "notes" }, + "spec": { + "variables": { "web_replicas": 2 }, + "environments": { + "production": { "variables": { "web_replicas": 3, "api_replicas": 4 } }, + "staging": {}, + }, + "services": [ + { "name": "web", "source": { "type": "image", "image": "nginx:1.27" }, "replicas": "${{ vars.web_replicas }}" }, + { "name": "api", "source": { "type": "image", "image": "api:1" }, "replicas": "${{ vars.api_replicas }}" }, + { "name": "db", "source": { "type": "image", "image": "postgres:16" }, "replicas": 1 }, + ], + }, + })) + .unwrap(); + let application = manifest + .validate_template() + .unwrap() + .normalize(ApplicationId::parse(APP).unwrap()); + // Services are kept in name order. + let api = application.spec().services[0].clone(); + let db = application.spec().services[1].clone(); + let web = application.spec().services[2].clone(); + let mut view = ApplicationView { + spec_hash: application.spec_hash(), + application, + generation: 1, + delete_intent: false, + created_at_ms: 1, + updated_at_ms: 1, + environments: Vec::new(), + previews: Vec::new(), + drift: Vec::new(), + sync_check: None, + repository: None, + }; + assert_eq!(view.replica_summary(&db), "1 replica"); + assert_eq!( + view.replica_summary(&web), + "replicas from vars.web_replicas" + ); + view.environments = vec![environment(APP, "production", EnvironmentSource::Saved)]; + assert_eq!(view.replica_summary(&web), "3 replicas"); + view.environments.push(environment( + "app-notes-02", + "staging", + EnvironmentSource::Saved, + )); + assert_eq!( + view.replica_summary(&web), + "replicas: production 3, staging 2" + ); + // A value in only one of several environments names that environment. + assert_eq!(view.replica_summary(&api), "replicas: production 4"); +} + +fn grants(permission: AppPermission, application: &str) -> Grants { + let mut grants = Grants::default(); + grants + .grant( + Permission::App(permission), + &Scope::one(ApplicationId::parse(application).unwrap()), + ) + .unwrap(); + grants +} + +#[test] +fn query_parameters_open_only_tabs_the_page_has() { + let query = |pairs: &'static [(&'static str, &'static str)]| { + let pairs = pairs.iter().copied().collect::>(); + move |key: &str| pairs.get(key).map(|value| (*value).to_owned()) + }; + let environment = Page::Environment("env".into()); + assert_eq!(environment.initial_tab(query(&[("tab", "logs")])), "Logs"); + assert_eq!(slug("Command & arguments"), "command-arguments"); + // Environment pages have no releases; application pages no deployments or logs. + assert_eq!( + environment.initial_tab(query(&[("release", "r1")])), + "Overview" + ); + assert_eq!( + Page::Application.initial_tab(query(&[("tab", "logs")])), + "Overview" + ); + assert_eq!( + Page::Application.initial_tab(query(&[("release", "r1"), ("tab", "jobs")])), + "Releases" + ); + // A deployment's page opens on its timeline. + let deployment = Page::Deployment { + environment: "env".into(), + operation: "op".into(), + }; + assert_eq!(deployment.initial_tab(query(&[])), "Timeline"); + assert_eq!( + deployment.initial_tab(query(&[("tab", "snapshot")])), + "Snapshot" + ); +} + +#[test] +fn sources_and_origins_name_environments_or_their_id_once_gone() { + let saved = view( + false, + vec![ + environment("env-production-01", "production", EnvironmentSource::Saved), + promoted("env-staging-01", "staging", "env-production-01"), + ], + ); + let promotion = |environment: &str| DeploymentOrigin::Promotion { + environment: EnvironmentId::parse(environment).unwrap(), + deployment: "dep-1".into(), + }; + assert_eq!( + saved.describe_origin(&promotion("env-production-01")), + "Promoted from production (deployment dep-1)" + ); + assert_eq!( + saved.describe_origin(&promotion("env-deleted-01")), + "Promoted from env-deleted-01 (deployment dep-1)" + ); + assert_eq!( + saved.describe_source(&saved.environments[1].source), + "promoted from production" + ); + assert_eq!( + saved.describe_origin(&DeploymentOrigin::Restore { + deployment: "dep-good".into(), + rolled_back: Some("dep-failed".into()), + }), + "Rolled back from deployment dep-failed to deployment dep-good" + ); + let snapshot = |base: Option<&str>| { + DeploymentOrigin::Local(LocalSnapshot { + commit: "0123456789abcdef0123456789abcdef01234567".into(), + base: base.map(str::to_owned), + }) + }; + assert_eq!( + saved.describe_origin(&snapshot(Some("89abcdef0123456789abcdef0123456789abcdef"))), + "Local snapshot 0123456789ab on 89abcdef0123" + ); + assert_eq!( + saved.describe_origin(&snapshot(None)), + "Local snapshot 0123456789ab, uploaded complete" + ); +} + +#[test] +fn previews_permissions_allow_only_in_previews() { + let mut saved = view( + false, + vec![environment( + "env-production-01", + "production", + EnvironmentSource::Saved, + )], + ); + saved.previews.push(preview("feature-1a2b3c", "feature")); + let previews = grants(AppPermission::PreviewsDeploy, APP); + assert!( + previews + .require_app(AppPermission::LogsRead, saved.application.id()) + .is_err() + ); + assert!(saved.allows(&previews, AppPermission::LogsRead, Some("feature-1a2b3c"))); + assert!(!saved.allows( + &previews, + AppPermission::LogsRead, + Some("env-production-01") + )); + assert!(!saved.allows(&previews, AppPermission::LogsRead, None)); + // Previews permissions grant only what `on_previews` names. + assert!(!saved.allows(&previews, AppPermission::Exec, Some("feature-1a2b3c"))); + // Grants on another application never apply. + let elsewhere = grants(AppPermission::LogsRead, "app-other-01"); + assert!(!saved.allows(&elsewhere, AppPermission::LogsRead, None)); +} + +#[test] +fn only_a_later_fetch_of_the_same_revision_counts_as_fetched() { + let connected = view(true, Vec::new()); + assert!(connected.fetched_since(3, 11)); + assert!(!connected.fetched_since(3, 10), "not updated since"); + assert!( + !connected.fetched_since(4, 11), + "a newer revision conflicts" + ); + assert!( + !view(false, Vec::new()).fetched_since(3, 11), + "only repositories are fetched" + ); +} + +#[test] +fn only_environments_on_the_connection_branch_deploy_the_saved_manifest() { + let mut saved = view(true, Vec::new()); + let main = environment("env-production-01", "production", branch("main")); + assert!( + !saved.follows_connection(&main), + "nothing was read from the repository yet" + ); + saved.repository = Some(saved.application.clone()); + assert!(saved.follows_connection(&main)); + let other = environment("env-staging-01", "staging", branch("develop")); + assert!(!saved.follows_connection(&other)); + let mut preview = preview("main-1a2b3c", "main"); + preview.source = branch("main"); + assert!(!saved.follows_connection(&preview)); + let mut unconnected = view(false, Vec::new()); + unconnected.repository = Some(unconnected.application.clone()); + assert!(!unconnected.follows_connection(&main)); +} + +#[test] +fn releases_deploy_only_into_live_promoted_environments() { + let mut deleting = promoted("env-qa-01", "qa", "env-production-01"); + deleting.delete_intent = true; + let saved = view( + false, + vec![ + environment("env-production-01", "production", EnvironmentSource::Saved), + promoted("env-staging-01", "staging", "env-production-01"), + deleting, + ], + ); + assert_eq!(saved.release_targets(), ["env-staging-01"]); +} + +#[test] +fn export_rows_trim_names_and_drop_blank_ones() { + let row = ExportDraft { + service: "api".into(), + applications: " notes ,, billing, ".into(), + previews: true, + }; + let export = row.export(); + assert_eq!(export.applications, ["notes", "billing"]); + let mut manifest = view(false, Vec::new()).application.to_manifest(); + manifest.spec.exports.push(export); + assert_eq!( + ExportDraft::rows(&manifest), + [ExportDraft { + service: "api".into(), + applications: "notes, billing".into(), + previews: true, + }] + ); +} + +#[test] +fn imports_without_an_environment_reach_the_same_named_one() { + let row = |environment: &str| ImportDraft { + application: "auth".into(), + service: "api".into(), + environment: environment.into(), + }; + assert_eq!(row("").import().environment, None); + let import = row("production").import(); + assert_eq!( + import + .environment + .as_ref() + .map(ToString::to_string) + .as_deref(), + Some("production") + ); + let mut manifest = view(false, Vec::new()).application.to_manifest(); + manifest.spec.imports = vec![import, row("").import()]; + assert_eq!(ImportDraft::rows(&manifest), [row("production"), row("")]); +} diff --git a/apps/piqueld-ui/src/auth.rs b/apps/piqueld-ui/src/auth/mod.rs similarity index 52% rename from apps/piqueld-ui/src/auth.rs rename to apps/piqueld-ui/src/auth/mod.rs index aeb8979af..ce1f82f06 100644 --- a/apps/piqueld-ui/src/auth.rs +++ b/apps/piqueld-ui/src/auth/mod.rs @@ -218,192 +218,4 @@ impl TokenForm { } #[cfg(test)] -mod tests { - use super::*; - use piqueld_client::{ - access::{AppPermission, GlobalPermission}, - auth::{HostOperator, Principal, User}, - }; - - fn app(id: &str) -> ApplicationId { - ApplicationId::parse(id).unwrap() - } - - fn session(principal: Principal) -> Session { - Session { - principal, - grants: Grants::default(), - scoped: false, - } - } - - fn alice() -> Session { - session(Principal::User(User { - id: "alice-id".into(), - username: "alice".into(), - display_name: String::new(), - })) - } - - fn grants(list: &[(Permission, Scope)]) -> Grants { - let mut grants = Grants::default(); - for (permission, scope) in list { - grants.grant(*permission, scope).unwrap(); - } - grants - } - - const READ: Permission = Permission::App(AppPermission::Read); - const DEPLOY: Permission = Permission::App(AppPermission::Deploy); - const MANAGE: Permission = Permission::Global(GlobalPermission::AccountsManage); - - #[test] - fn invite_links_are_recognized_only_by_their_exact_prefix() { - assert_eq!( - Invite::parse("#operator=s3cret"), - Some(Invite::Operator("s3cret".into())) - ); - assert_eq!( - Invite::parse("#enroll=abc"), - Some(Invite::Enrollment("abc".into())) - ); - for fragment in ["", "#invite", "#device=ABCD-EFGH", "#enrollment=abc"] { - assert_eq!(Invite::parse(fragment), None, "{fragment}"); - } - } - - #[test] - fn a_secret_link_wins_over_setup_and_an_existing_session() { - let invite = Invite::Operator("secret".into()); - let page = SignInPage::new(Some(invite.clone()), false, Some(&alice()), ""); - assert_eq!(page, SignInPage::Redeem(invite)); - assert_eq!(SignInPage::new(None, false, None, ""), SignInPage::Setup); - } - - #[test] - fn the_device_fragment_opens_approval_once_signed_in_as_an_account() { - let alice = alice(); - let page = |fragment| SignInPage::new(None, true, Some(&alice), fragment); - let approval = |code: &str| SignInPage::DeviceApproval { - who: "alice".into(), - code: code.into(), - }; - assert_eq!(page("#device"), approval("")); - assert_eq!(page("#device="), approval("")); - assert_eq!(page("#device=ABCD-EFGH"), approval("ABCD-EFGH")); - let signed_in = SignInPage::SignedIn { - who: "alice".into(), - }; - assert_eq!(page("#devices"), signed_in); - assert_eq!(page(""), signed_in); - // Signed out, the page asks for a passkey first. - assert_eq!( - SignInPage::new(None, true, None, "#device=ABCD-EFGH"), - SignInPage::SignIn - ); - } - - #[test] - fn the_host_operator_cannot_approve_cli_logins() { - let operator = session(Principal::Operator(HostOperator { uid: 0 })); - assert_eq!( - SignInPage::new(None, true, Some(&operator), "#device=ABCD-EFGH"), - SignInPage::OperatorCannotApprove - ); - assert_eq!( - SignInPage::new(None, true, Some(&operator), ""), - SignInPage::SignedIn { - who: "Host operator".into() - } - ); - } - - #[test] - fn device_request_age_rounds_down_to_whole_minutes() { - let request = |age| DeviceRequest { - user_code: "ABCD-EFGH".into(), - requester: None, - age, - expires_in: 600, - grants: None, - confirms: None, - }; - for (age, label) in [ - (59, "less than a minute ago"), - (60, "1 minute ago"), - (119, "1 minute ago"), - (120, "2 minutes ago"), - ] { - assert_eq!(request(age).age_label(), label, "{age}"); - } - } - - #[test] - fn a_single_scope_selection_round_trips() { - let only_blog = grants(&[ - (READ, Scope::Only([app("app-blog")].into())), - (DEPLOY, Scope::Only([app("app-blog")].into())), - (MANAGE, Scope::All), - ]); - let selection = GrantSelection::from(&only_blog); - assert!(!selection.everywhere && !selection.mixed); - assert_eq!(selection.applications, [app("app-blog")].into()); - assert_eq!(selection.grants(), only_blog); - // Installation-wide permissions alone count as every application. - assert!(GrantSelection::from(&grants(&[(MANAGE, Scope::All)])).everywhere); - } - - #[test] - fn mixed_scopes_are_flagged_and_replaced_by_their_union() { - let mixed = grants(&[ - (READ, Scope::Only([app("app-blog")].into())), - (DEPLOY, Scope::Only([app("app-shop")].into())), - ]); - let selection = GrantSelection::from(&mixed); - assert!(selection.mixed && !selection.everywhere); - let both = Scope::Only([app("app-blog"), app("app-shop")].into()); - assert_eq!( - selection.grants(), - grants(&[(READ, both.clone()), (DEPLOY, both)]) - ); - } - - #[test] - fn no_chosen_application_keeps_only_installation_wide_permissions() { - let selection = GrantSelection { - permissions: [READ, MANAGE].into(), - everywhere: false, - applications: BTreeSet::new(), - mixed: false, - }; - assert_eq!(selection.grants(), grants(&[(MANAGE, Scope::All)])); - } - - #[test] - fn token_form_validates_lifetime_before_tailnet() { - let form = |days: &str, tailnet: &str| { - TokenForm { - name: "ci".into(), - days: days.into(), - tailnet: tailnet.into(), - } - .command(Grants::default()) - }; - let Ok(Manage::CreateToken { days, tailnet, .. }) = form("", " tag:ci ") else { - panic!("blank lifetime and a padded tag are valid"); - }; - assert_eq!( - (days, tailnet), - (None, Some(TailnetBinding::parse("tag:ci").unwrap())) - ); - let days_error = "Enter a positive number of days, or leave blank"; - assert_eq!(form("-1", "not a binding").unwrap_err(), days_error); - assert_eq!(form("1.5", "").unwrap_err(), days_error); - assert_eq!(form("0", "").unwrap_err(), days_error); - assert!(form("30", "not a binding").is_err()); - let Ok(Manage::CreateToken { days, .. }) = form("30", "") else { - panic!("a positive lifetime is valid"); - }; - assert_eq!(days, Some(30)); - } -} +mod tests; diff --git a/apps/piqueld-ui/src/auth/tests.rs b/apps/piqueld-ui/src/auth/tests.rs new file mode 100644 index 000000000..8dd004ea2 --- /dev/null +++ b/apps/piqueld-ui/src/auth/tests.rs @@ -0,0 +1,187 @@ +use super::*; +use piqueld_client::{ + access::{AppPermission, GlobalPermission}, + auth::{HostOperator, Principal, User}, +}; + +fn app(id: &str) -> ApplicationId { + ApplicationId::parse(id).unwrap() +} + +fn session(principal: Principal) -> Session { + Session { + principal, + grants: Grants::default(), + scoped: false, + } +} + +fn alice() -> Session { + session(Principal::User(User { + id: "alice-id".into(), + username: "alice".into(), + display_name: String::new(), + })) +} + +fn grants(list: &[(Permission, Scope)]) -> Grants { + let mut grants = Grants::default(); + for (permission, scope) in list { + grants.grant(*permission, scope).unwrap(); + } + grants +} + +const READ: Permission = Permission::App(AppPermission::Read); +const DEPLOY: Permission = Permission::App(AppPermission::Deploy); +const MANAGE: Permission = Permission::Global(GlobalPermission::AccountsManage); + +#[test] +fn invite_links_are_recognized_only_by_their_exact_prefix() { + assert_eq!( + Invite::parse("#operator=s3cret"), + Some(Invite::Operator("s3cret".into())) + ); + assert_eq!( + Invite::parse("#enroll=abc"), + Some(Invite::Enrollment("abc".into())) + ); + for fragment in ["", "#invite", "#device=ABCD-EFGH", "#enrollment=abc"] { + assert_eq!(Invite::parse(fragment), None, "{fragment}"); + } +} + +#[test] +fn a_secret_link_wins_over_setup_and_an_existing_session() { + let invite = Invite::Operator("secret".into()); + let page = SignInPage::new(Some(invite.clone()), false, Some(&alice()), ""); + assert_eq!(page, SignInPage::Redeem(invite)); + assert_eq!(SignInPage::new(None, false, None, ""), SignInPage::Setup); +} + +#[test] +fn the_device_fragment_opens_approval_once_signed_in_as_an_account() { + let alice = alice(); + let page = |fragment| SignInPage::new(None, true, Some(&alice), fragment); + let approval = |code: &str| SignInPage::DeviceApproval { + who: "alice".into(), + code: code.into(), + }; + assert_eq!(page("#device"), approval("")); + assert_eq!(page("#device="), approval("")); + assert_eq!(page("#device=ABCD-EFGH"), approval("ABCD-EFGH")); + let signed_in = SignInPage::SignedIn { + who: "alice".into(), + }; + assert_eq!(page("#devices"), signed_in); + assert_eq!(page(""), signed_in); + // Signed out, the page asks for a passkey first. + assert_eq!( + SignInPage::new(None, true, None, "#device=ABCD-EFGH"), + SignInPage::SignIn + ); +} + +#[test] +fn the_host_operator_cannot_approve_cli_logins() { + let operator = session(Principal::Operator(HostOperator { uid: 0 })); + assert_eq!( + SignInPage::new(None, true, Some(&operator), "#device=ABCD-EFGH"), + SignInPage::OperatorCannotApprove + ); + assert_eq!( + SignInPage::new(None, true, Some(&operator), ""), + SignInPage::SignedIn { + who: "Host operator".into() + } + ); +} + +#[test] +fn device_request_age_rounds_down_to_whole_minutes() { + let request = |age| DeviceRequest { + user_code: "ABCD-EFGH".into(), + requester: None, + age, + expires_in: 600, + grants: None, + confirms: None, + }; + for (age, label) in [ + (59, "less than a minute ago"), + (60, "1 minute ago"), + (119, "1 minute ago"), + (120, "2 minutes ago"), + ] { + assert_eq!(request(age).age_label(), label, "{age}"); + } +} + +#[test] +fn a_single_scope_selection_round_trips() { + let only_blog = grants(&[ + (READ, Scope::Only([app("app-blog")].into())), + (DEPLOY, Scope::Only([app("app-blog")].into())), + (MANAGE, Scope::All), + ]); + let selection = GrantSelection::from(&only_blog); + assert!(!selection.everywhere && !selection.mixed); + assert_eq!(selection.applications, [app("app-blog")].into()); + assert_eq!(selection.grants(), only_blog); + // Installation-wide permissions alone count as every application. + assert!(GrantSelection::from(&grants(&[(MANAGE, Scope::All)])).everywhere); +} + +#[test] +fn mixed_scopes_are_flagged_and_replaced_by_their_union() { + let mixed = grants(&[ + (READ, Scope::Only([app("app-blog")].into())), + (DEPLOY, Scope::Only([app("app-shop")].into())), + ]); + let selection = GrantSelection::from(&mixed); + assert!(selection.mixed && !selection.everywhere); + let both = Scope::Only([app("app-blog"), app("app-shop")].into()); + assert_eq!( + selection.grants(), + grants(&[(READ, both.clone()), (DEPLOY, both)]) + ); +} + +#[test] +fn no_chosen_application_keeps_only_installation_wide_permissions() { + let selection = GrantSelection { + permissions: [READ, MANAGE].into(), + everywhere: false, + applications: BTreeSet::new(), + mixed: false, + }; + assert_eq!(selection.grants(), grants(&[(MANAGE, Scope::All)])); +} + +#[test] +fn token_form_validates_lifetime_before_tailnet() { + let form = |days: &str, tailnet: &str| { + TokenForm { + name: "ci".into(), + days: days.into(), + tailnet: tailnet.into(), + } + .command(Grants::default()) + }; + let Ok(Manage::CreateToken { days, tailnet, .. }) = form("", " tag:ci ") else { + panic!("blank lifetime and a padded tag are valid"); + }; + assert_eq!( + (days, tailnet), + (None, Some(TailnetBinding::parse("tag:ci").unwrap())) + ); + let days_error = "Enter a positive number of days, or leave blank"; + assert_eq!(form("-1", "not a binding").unwrap_err(), days_error); + assert_eq!(form("1.5", "").unwrap_err(), days_error); + assert_eq!(form("0", "").unwrap_err(), days_error); + assert!(form("30", "not a binding").is_err()); + let Ok(Manage::CreateToken { days, .. }) = form("30", "") else { + panic!("a positive lifetime is valid"); + }; + assert_eq!(days, Some(30)); +} diff --git a/apps/piqueld-ui/src/changes.rs b/apps/piqueld-ui/src/changes/mod.rs similarity index 68% rename from apps/piqueld-ui/src/changes.rs rename to apps/piqueld-ui/src/changes/mod.rs index b941720c1..6d119417d 100644 --- a/apps/piqueld-ui/src/changes.rs +++ b/apps/piqueld-ui/src/changes/mod.rs @@ -126,62 +126,4 @@ fn diff_lines(before: &str, after: &str) -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - fn change(before: Option<&str>, after: Option<&str>) -> ManifestChange { - ManifestChange { - field: "services.web.environment".into(), - before: before.map(str::to_owned), - after: after.map(str::to_owned), - } - } - - #[test] - fn scalars_show_side_by_side_and_structures_line_by_line() { - assert_eq!( - ChangeDisplay::of(&change(Some("1"), Some("2"))), - ChangeDisplay::Scalar { - before: Some("1".into()), - after: Some("2".into()), - } - ); - // A string that merely looks like JSON text stays a scalar. - assert_eq!( - ChangeDisplay::of(&change(None, Some("\"nginx:1.27\""))), - ChangeDisplay::Scalar { - before: None, - after: Some("\"nginx:1.27\"".into()), - } - ); - let ChangeDisplay::Lines(lines) = ChangeDisplay::of(&change( - Some(r#"{"PORT":"80","ROLE":"web"}"#), - Some(r#"{"PORT":"8080","ROLE":"web"}"#), - )) else { - panic!("objects are shown line by line"); - }; - let marked: Vec<(&str, Mark)> = lines - .iter() - .map(|line| (line.text.as_str(), line.mark)) - .collect(); - assert_eq!( - marked, - [ - ("{", Mark::Same), - (" \"PORT\": \"80\",", Mark::Removed), - (" \"PORT\": \"8080\",", Mark::Added), - (" \"ROLE\": \"web\"", Mark::Same), - ("}", Mark::Same), - ] - ); - } - - #[test] - fn an_added_structure_is_all_additions() { - let ChangeDisplay::Lines(lines) = ChangeDisplay::of(&change(None, Some("[\"a\"]"))) else { - panic!("arrays are shown line by line"); - }; - assert!(lines.iter().all(|line| line.mark == Mark::Added)); - assert_eq!(lines.len(), 3); - } -} +mod tests; diff --git a/apps/piqueld-ui/src/changes/tests.rs b/apps/piqueld-ui/src/changes/tests.rs new file mode 100644 index 000000000..7a4226c55 --- /dev/null +++ b/apps/piqueld-ui/src/changes/tests.rs @@ -0,0 +1,57 @@ +use super::*; + +fn change(before: Option<&str>, after: Option<&str>) -> ManifestChange { + ManifestChange { + field: "services.web.environment".into(), + before: before.map(str::to_owned), + after: after.map(str::to_owned), + } +} + +#[test] +fn scalars_show_side_by_side_and_structures_line_by_line() { + assert_eq!( + ChangeDisplay::of(&change(Some("1"), Some("2"))), + ChangeDisplay::Scalar { + before: Some("1".into()), + after: Some("2".into()), + } + ); + // A string that merely looks like JSON text stays a scalar. + assert_eq!( + ChangeDisplay::of(&change(None, Some("\"nginx:1.27\""))), + ChangeDisplay::Scalar { + before: None, + after: Some("\"nginx:1.27\"".into()), + } + ); + let ChangeDisplay::Lines(lines) = ChangeDisplay::of(&change( + Some(r#"{"PORT":"80","ROLE":"web"}"#), + Some(r#"{"PORT":"8080","ROLE":"web"}"#), + )) else { + panic!("objects are shown line by line"); + }; + let marked: Vec<(&str, Mark)> = lines + .iter() + .map(|line| (line.text.as_str(), line.mark)) + .collect(); + assert_eq!( + marked, + [ + ("{", Mark::Same), + (" \"PORT\": \"80\",", Mark::Removed), + (" \"PORT\": \"8080\",", Mark::Added), + (" \"ROLE\": \"web\"", Mark::Same), + ("}", Mark::Same), + ] + ); +} + +#[test] +fn an_added_structure_is_all_additions() { + let ChangeDisplay::Lines(lines) = ChangeDisplay::of(&change(None, Some("[\"a\"]"))) else { + panic!("arrays are shown line by line"); + }; + assert!(lines.iter().all(|line| line.mark == Mark::Added)); + assert_eq!(lines.len(), 3); +} diff --git a/apps/piqueld-ui/src/deployments.rs b/apps/piqueld-ui/src/deployments.rs deleted file mode 100644 index 7899dcec8..000000000 --- a/apps/piqueld-ui/src/deployments.rs +++ /dev/null @@ -1,471 +0,0 @@ -//! Transport-independent logic of the dashboard's deployment and preview -//! views: deployment history paging, what a deployment's row says, -//! attempt lists, promotion confirmation, and preview creation. - -use piqueld_client::{ - CreatePreviewRequest, DeploymentOrigin, DeploymentSummary, DeploymentView, Operation, Page, - PlanView, PromoteRequest, ReleaseAvailability, SystemVariable, sync::short_commit, -}; - -/// What a deployment's row in its environment's history, and its page, say -/// of it: from its summary or its whole snapshot. -pub trait DeploymentFacts { - /// The deployment's operation. - fn operation(&self) -> &Operation; - - /// The commit and the branch its manifest was read from; `None` for a - /// saved manifest. - fn source(&self) -> (Option<&str>, Option<&str>); - - /// The branch and commit its manifest was read from, such as - /// "main @ 0123456789ab"; `None` for a saved manifest. - fn commit(&self) -> Option { - let (sha, branch) = self.source(); - let commit = short_commit(sha?); - Some(match branch { - Some(branch) => format!("{branch} @ {commit}"), - None => commit.to_owned(), - }) - } - - /// How long it ran once it ended, from its start, or creation if it - /// never started. - fn duration_ms(&self) -> Option { - let operation = self.operation(); - let started = operation.started_at_ms.unwrap_or(operation.created_at_ms); - u64::try_from(operation.finished_at_ms? - started).ok() - } -} - -impl DeploymentFacts for DeploymentView { - fn operation(&self) -> &Operation { - &self.operation - } - - fn source(&self) -> (Option<&str>, Option<&str>) { - ( - self.system_value(SystemVariable::GitSha), - self.system_value(SystemVariable::GitBranch), - ) - } -} - -impl DeploymentFacts for DeploymentSummary { - fn operation(&self) -> &Operation { - &self.operation - } - - fn source(&self) -> (Option<&str>, Option<&str>) { - (self.git_sha.as_deref(), self.git_branch.as_deref()) - } -} - -/// The deployments of one environment shown in its history, newest first: -/// its newest page, polled, and older pages appended on request. -pub trait DeploymentList { - /// Merges a freshly polled newest page into a list that also holds older - /// pages: deployments are replaced or added by operation ID, keeping the - /// older ones, and the `current_target` and `last_successful` flags are - /// cleared on listed deployments when the page carries them, so only one - /// deployment holds each flag. - fn merge_newest(&mut self, page: Vec); - - /// Appends an older page, skipping deployments already listed. - fn append_older(&mut self, page: Vec); -} - -impl DeploymentList for Vec { - fn merge_newest(&mut self, page: Vec) { - let has_current = page.iter().any(|item| item.current_target); - let has_successful = page.iter().any(|item| item.last_successful); - for item in self.iter_mut() { - item.current_target &= !has_current; - item.last_successful &= !has_successful; - } - for item in page { - match self - .iter_mut() - .find(|old| old.operation.id == item.operation.id) - { - Some(old) => *old = item, - None => self.push(item), - } - } - // Operation IDs are time-ordered, as the daemon pages them. - self.sort_by(|a, b| b.operation.id.cmp(&a.operation.id)); - } - - fn append_older(&mut self, page: Vec) { - for item in page { - if !self.iter().any(|old| old.operation.id == item.operation.id) { - self.push(item); - } - } - } -} - -/// The retained attempt outcomes of one deployment loaded so far, newest -/// first, and the cursor of the next older page. -#[derive(Clone, Debug, Default)] -pub struct Attempts { - items: Vec, - /// Cursor of the next older page, if any. - pub cursor: Option, -} - -impl Attempts { - /// Shows `page`: the newest attempts, replacing those shown, or with - /// `older` the attempts following them. - pub fn show(&mut self, page: Page, older: bool) { - if older { - self.items.extend(page.items); - } else { - self.items = page.items; - } - self.cursor = page.next_cursor; - } - - /// The attempts to list for a deployment whose operation is `live`: the - /// API retains only completed outcomes, so the attempt it is running - /// leads the list until its outcome is retained. - #[must_use] - pub fn visible(&self, live: &Operation) -> Vec { - let running = - live.attempt > 0 && !self.items.iter().any(|item| item.attempt == live.attempt); - running - .then(|| live.clone()) - .into_iter() - .chain(self.items.iter().cloned()) - .collect() - } -} - -/// What a promotion into an environment deploys: its source's current -/// deployment, or an earlier `release`. -#[derive(Clone, Debug)] -pub struct Promotion { - release: Option, -} - -impl Promotion { - /// Promotes the source's current deployment, or deploys `release`. - #[must_use] - pub const fn new(release: Option) -> Self { - Self { release } - } - - /// "Deploy" for an earlier release, else "Promote". - #[must_use] - pub const fn verb(&self) -> &'static str { - if self.release.is_some() { - "Deploy" - } else { - "Promote" - } - } - - /// The request planning this promotion. - #[must_use] - pub fn request(&self) -> PromoteRequest { - PromoteRequest { - release: self.release.clone(), - ..PromoteRequest::default() - } - } - - /// The request promoting exactly what `plan` reviewed: pinned to the - /// source deployment it planned and the application revision it was - /// planned at. None when the plan has no release, or the release mounts - /// secrets the environment lacks or may not use, or its images are gone. - #[must_use] - pub fn confirmed(&self, plan: &PlanView) -> Option { - let release = plan.release.as_ref()?; - if !release.secrets.is_empty() - || matches!( - release.release.availability, - Some(ReleaseAvailability::Unavailable { .. }) - ) - { - return None; - } - let mut request = self.request(); - if let DeploymentOrigin::Promotion { deployment, .. } = &release.origin { - request.deployment = Some(deployment.clone()); - } - request.expected_generation = Some(plan.generation); - Some(request) - } -} - -/// The "Create preview" form: a branch, and an optional slot telling apart -/// several previews of it. -#[derive(Clone, Debug, Default)] -pub struct PreviewForm { - /// Branch to deploy. - pub branch: String, - /// Slot, blank for none. - pub slot: String, -} - -impl PreviewForm { - /// The request creating the preview, trimmed; a blank slot is none. - #[must_use] - pub fn request(&self) -> CreatePreviewRequest { - CreatePreviewRequest { - branch: self.branch.trim().to_owned(), - slot: Some(self.slot.trim().to_owned()).filter(|slot| !slot.is_empty()), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use piqueld_client::{OperationKind, OperationState}; - use serde_json::{Value, json}; - - /// The manifest every fixture deploys. - fn template() -> Value { - json!({ - "id": "app-0123456789abcdef0123456789abcdef", - "api_version": "piqueld.dev/v1alpha1", - "kind": "Application", - "metadata": { "name": "shop" }, - "spec": { "services": [{ "name": "web", "source": { "type": "image", "image": "nginx:alpine" } }] }, - }) - } - - /// Attempt `attempt` of operation `id`, in `state`. - fn operation(id: &str, attempt: u64, state: OperationState) -> Operation { - Operation { - id: id.into(), - environment_id: "env-0123456789abcdef0123456789abcdef".parse().unwrap(), - kind: OperationKind::Refresh, - generation: 1, - attempt, - consecutive_failures: 0, - state, - phase: None, - resource: None, - error_code: None, - error_message: None, - created_at_ms: 0, - updated_at_ms: 0, - started_at_ms: None, - finished_at_ms: None, - } - } - - /// Deployment `id`, with its `current_target` and `last_successful` flags. - fn deployment(id: &str, current: bool, successful: bool) -> DeploymentView { - serde_json::from_value(json!({ - "operation": operation(id, 1, OperationState::Succeeded), - "template": template(), - "variables": {}, - "application": null, - "succeeded_at_ms": 1, - "current_target": current, - "last_successful": successful, - })) - .unwrap() - } - - /// Deployment `id`'s summary, with its flags. - fn summary(id: &str, current: bool, successful: bool) -> DeploymentSummary { - deployment(id, current, successful).into() - } - - fn ids(list: &[DeploymentSummary]) -> Vec<&str> { - list.iter().map(|item| item.operation.id.as_str()).collect() - } - - #[test] - fn a_row_names_the_commit_deployed_and_how_long_it_ran() { - let mut built = deployment("operation-1", true, true); - assert_eq!((built.commit(), built.duration_ms()), (None, None)); - built.variables = serde_json::from_value(json!({ - "git.branch": "main", - "git.sha": "0123456789abcdef0123456789abcdef01234567", - })) - .unwrap(); - built.operation.created_at_ms = 1_000; - built.operation.finished_at_ms = Some(39_000); - assert_eq!(built.commit().as_deref(), Some("main @ 0123456789ab")); - assert_eq!(built.duration_ms(), Some(38_000)); - } - - #[test] - fn a_polled_newest_page_keeps_older_pages_and_moves_the_flags() { - let mut list = vec![ - summary("operation-2", true, true), - summary("operation-1", false, false), - ]; - list.append_older(vec![ - summary("operation-1", false, false), - summary("operation-0", false, false), - ]); - assert_eq!(ids(&list), ["operation-2", "operation-1", "operation-0"]); - - let flags = |list: &[DeploymentSummary]| { - list.iter() - .map(|item| (item.current_target, item.last_successful)) - .collect::>() - }; - // A newer deployment became the current target, but hasn't succeeded - // yet: deployment 2, off the polled page, stays the last successful. - list.merge_newest(vec![summary("operation-3", true, false)]); - assert_eq!( - ids(&list), - ["operation-3", "operation-2", "operation-1", "operation-0"] - ); - assert_eq!( - flags(&list), - [(true, false), (false, true), (false, false), (false, false)] - ); - // Then a newer one succeeded without becoming the current target. - list.merge_newest(vec![summary("operation-4", false, true)]); - assert_eq!( - flags(&list)[..3], - [(false, true), (true, false), (false, false)] - ); - } - - #[test] - fn the_running_attempt_leads_until_its_outcome_is_retained() { - let mut attempts = Attempts::default(); - let retained = |attempt| operation("operation-1", attempt, OperationState::Failed); - attempts.show( - Page { - items: vec![retained(2)], - next_cursor: Some("older".into()), - }, - false, - ); - attempts.show( - Page { - items: vec![retained(1)], - next_cursor: None, - }, - true, - ); - assert_eq!(attempts.cursor, None); - - let listed = |attempts: &Attempts, live: &Operation| { - attempts - .visible(live) - .iter() - .map(|item| (item.attempt, item.state)) - .collect::>() - }; - let running = operation("operation-1", 3, OperationState::Running); - assert_eq!( - listed(&attempts, &running), - [ - (3, OperationState::Running), - (2, OperationState::Failed), - (1, OperationState::Failed) - ] - ); - // Refreshing shows the newest page alone; a retained outcome is listed - // once, and nothing ran before the first attempt. - attempts.show( - Page { - items: vec![retained(3)], - next_cursor: Some("older".into()), - }, - false, - ); - assert_eq!(listed(&attempts, &running), [(3, OperationState::Failed)]); - let requested = operation("operation-1", 0, OperationState::Requested); - assert_eq!(listed(&Attempts::default(), &requested), []); - } - - /// A plan of promoting a release from `origin`, at revision 7, whose - /// images are `availability` and which lacks `secrets`. - fn plan(origin: &Value, availability: &Value, secrets: &Value) -> PlanView { - serde_json::from_value(json!({ - "application_id": "app-0123456789abcdef0123456789abcdef", - "generation": 7, - "identical": false, - "operation": null, - "changes": [], - "plan": { "actions": [], "diagnostics": [] }, - "rollouts": [], - "release": { - "release": { - "id": "rel-0123456789abcdef0123456789abcdef", - "application_id": "app-0123456789abcdef0123456789abcdef", - "content_hash": format!("sha256:{}", "b".repeat(64)), - "created_at_ms": 0, - "release": { - "template": template(), - "sources": { "web": { - "type": "image", - "requested": "nginx:alpine", - "digest_reference": format!("docker.io/library/nginx@sha256:{}", "a".repeat(64)), - } }, - }, - "fingerprint": { "web": { "source.image": "nginx:alpine" } }, - "availability": availability, - }, - "origin": origin, - "new_volumes": [], - "secrets": secrets, - }, - })) - .unwrap() - } - - #[test] - fn a_promotion_confirms_exactly_the_reviewed_source_and_revision() { - let promoted = json!({ - "type": "promotion", - "environment": "env-0123456789abcdef0123456789abcdef", - "deployment": "operation-1", - }); - let (present, none) = (json!({ "state": "present" }), json!([])); - let request = Promotion::new(None) - .confirmed(&plan(&promoted, &present, &none)) - .unwrap(); - assert_eq!(request.deployment.as_deref(), Some("operation-1")); - assert_eq!(request.expected_generation, Some(7)); - assert_eq!(request.release, None); - - // An earlier release is deployed as itself, not pinned to a deployment. - let id = "rel-0123456789abcdef0123456789abcdef"; - let release = Promotion::new(Some(id.into())) - .confirmed(&plan(&json!({ "type": "release" }), &present, &none)) - .unwrap(); - assert_eq!(release.deployment, None); - assert_eq!(release.release.as_deref(), Some(id)); - - // Missing secrets, or built images that are gone, block it; missing - // registry images are pulled again by digest. - let missing = json!([{ "problem": "missing", "secret": "api-key" }]); - let confirmed = |availability: &str, secrets: &Value| { - let availability = json!({ "state": availability, "missing": [] }); - Promotion::new(None) - .confirmed(&plan(&promoted, &availability, secrets)) - .is_some() - }; - assert!(!confirmed("present", &missing)); - assert!(!confirmed("unavailable", &none)); - assert!(confirmed("pullable", &none)); - } - - #[test] - fn a_blank_preview_slot_is_none() { - let form = PreviewForm { - branch: " feat/login ".into(), - slot: " ".into(), - }; - let request = form.request(); - assert_eq!(request.branch, "feat/login"); - assert_eq!(request.slot, None); - let slotted = PreviewForm { - slot: " agent-2 ".into(), - ..form - }; - assert_eq!(slotted.request().slot.as_deref(), Some("agent-2")); - } -} diff --git a/apps/piqueld-ui/src/deployments/mod.rs b/apps/piqueld-ui/src/deployments/mod.rs new file mode 100644 index 000000000..cc76e8262 --- /dev/null +++ b/apps/piqueld-ui/src/deployments/mod.rs @@ -0,0 +1,222 @@ +//! Transport-independent logic of the dashboard's deployment and preview +//! views: deployment history paging, what a deployment's row says, +//! attempt lists, promotion confirmation, and preview creation. + +use piqueld_client::{ + CreatePreviewRequest, DeploymentOrigin, DeploymentSummary, DeploymentView, Operation, Page, + PlanView, PromoteRequest, ReleaseAvailability, SystemVariable, sync::short_commit, +}; + +/// What a deployment's row in its environment's history, and its page, say +/// of it: from its summary or its whole snapshot. +pub trait DeploymentFacts { + /// The deployment's operation. + fn operation(&self) -> &Operation; + + /// The commit and the branch its manifest was read from; `None` for a + /// saved manifest. + fn source(&self) -> (Option<&str>, Option<&str>); + + /// The branch and commit its manifest was read from, such as + /// "main @ 0123456789ab"; `None` for a saved manifest. + fn commit(&self) -> Option { + let (sha, branch) = self.source(); + let commit = short_commit(sha?); + Some(match branch { + Some(branch) => format!("{branch} @ {commit}"), + None => commit.to_owned(), + }) + } + + /// How long it ran once it ended, from its start, or creation if it + /// never started. + fn duration_ms(&self) -> Option { + let operation = self.operation(); + let started = operation.started_at_ms.unwrap_or(operation.created_at_ms); + u64::try_from(operation.finished_at_ms? - started).ok() + } +} + +impl DeploymentFacts for DeploymentView { + fn operation(&self) -> &Operation { + &self.operation + } + + fn source(&self) -> (Option<&str>, Option<&str>) { + ( + self.system_value(SystemVariable::GitSha), + self.system_value(SystemVariable::GitBranch), + ) + } +} + +impl DeploymentFacts for DeploymentSummary { + fn operation(&self) -> &Operation { + &self.operation + } + + fn source(&self) -> (Option<&str>, Option<&str>) { + (self.git_sha.as_deref(), self.git_branch.as_deref()) + } +} + +/// The deployments of one environment shown in its history, newest first: +/// its newest page, polled, and older pages appended on request. +pub trait DeploymentList { + /// Merges a freshly polled newest page into a list that also holds older + /// pages: deployments are replaced or added by operation ID, keeping the + /// older ones, and the `current_target` and `last_successful` flags are + /// cleared on listed deployments when the page carries them, so only one + /// deployment holds each flag. + fn merge_newest(&mut self, page: Vec); + + /// Appends an older page, skipping deployments already listed. + fn append_older(&mut self, page: Vec); +} + +impl DeploymentList for Vec { + fn merge_newest(&mut self, page: Vec) { + let has_current = page.iter().any(|item| item.current_target); + let has_successful = page.iter().any(|item| item.last_successful); + for item in self.iter_mut() { + item.current_target &= !has_current; + item.last_successful &= !has_successful; + } + for item in page { + match self + .iter_mut() + .find(|old| old.operation.id == item.operation.id) + { + Some(old) => *old = item, + None => self.push(item), + } + } + // Operation IDs are time-ordered, as the daemon pages them. + self.sort_by(|a, b| b.operation.id.cmp(&a.operation.id)); + } + + fn append_older(&mut self, page: Vec) { + for item in page { + if !self.iter().any(|old| old.operation.id == item.operation.id) { + self.push(item); + } + } + } +} + +/// The retained attempt outcomes of one deployment loaded so far, newest +/// first, and the cursor of the next older page. +#[derive(Clone, Debug, Default)] +pub struct Attempts { + items: Vec, + /// Cursor of the next older page, if any. + pub cursor: Option, +} + +impl Attempts { + /// Shows `page`: the newest attempts, replacing those shown, or with + /// `older` the attempts following them. + pub fn show(&mut self, page: Page, older: bool) { + if older { + self.items.extend(page.items); + } else { + self.items = page.items; + } + self.cursor = page.next_cursor; + } + + /// The attempts to list for a deployment whose operation is `live`: the + /// API retains only completed outcomes, so the attempt it is running + /// leads the list until its outcome is retained. + #[must_use] + pub fn visible(&self, live: &Operation) -> Vec { + let running = + live.attempt > 0 && !self.items.iter().any(|item| item.attempt == live.attempt); + running + .then(|| live.clone()) + .into_iter() + .chain(self.items.iter().cloned()) + .collect() + } +} + +/// What a promotion into an environment deploys: its source's current +/// deployment, or an earlier `release`. +#[derive(Clone, Debug)] +pub struct Promotion { + release: Option, +} + +impl Promotion { + /// Promotes the source's current deployment, or deploys `release`. + #[must_use] + pub const fn new(release: Option) -> Self { + Self { release } + } + + /// "Deploy" for an earlier release, else "Promote". + #[must_use] + pub const fn verb(&self) -> &'static str { + if self.release.is_some() { + "Deploy" + } else { + "Promote" + } + } + + /// The request planning this promotion. + #[must_use] + pub fn request(&self) -> PromoteRequest { + PromoteRequest { + release: self.release.clone(), + ..PromoteRequest::default() + } + } + + /// The request promoting exactly what `plan` reviewed: pinned to the + /// source deployment it planned and the application revision it was + /// planned at. None when the plan has no release, or the release mounts + /// secrets the environment lacks or may not use, or its images are gone. + #[must_use] + pub fn confirmed(&self, plan: &PlanView) -> Option { + let release = plan.release.as_ref()?; + if !release.secrets.is_empty() + || matches!( + release.release.availability, + Some(ReleaseAvailability::Unavailable { .. }) + ) + { + return None; + } + let mut request = self.request(); + if let DeploymentOrigin::Promotion { deployment, .. } = &release.origin { + request.deployment = Some(deployment.clone()); + } + request.expected_generation = Some(plan.generation); + Some(request) + } +} + +/// The "Create preview" form: a branch, and an optional slot telling apart +/// several previews of it. +#[derive(Clone, Debug, Default)] +pub struct PreviewForm { + /// Branch to deploy. + pub branch: String, + /// Slot, blank for none. + pub slot: String, +} + +impl PreviewForm { + /// The request creating the preview, trimmed; a blank slot is none. + #[must_use] + pub fn request(&self) -> CreatePreviewRequest { + CreatePreviewRequest { + branch: self.branch.trim().to_owned(), + slot: Some(self.slot.trim().to_owned()).filter(|slot| !slot.is_empty()), + } + } +} + +#[cfg(test)] +mod tests; diff --git a/apps/piqueld-ui/src/deployments/tests.rs b/apps/piqueld-ui/src/deployments/tests.rs new file mode 100644 index 000000000..94c1d9e8d --- /dev/null +++ b/apps/piqueld-ui/src/deployments/tests.rs @@ -0,0 +1,248 @@ +use super::*; +use piqueld_client::{OperationKind, OperationState}; +use serde_json::{Value, json}; + +/// The manifest every fixture deploys. +fn template() -> Value { + json!({ + "id": "app-0123456789abcdef0123456789abcdef", + "api_version": "piqueld.dev/v1alpha1", + "kind": "Application", + "metadata": { "name": "shop" }, + "spec": { "services": [{ "name": "web", "source": { "type": "image", "image": "nginx:alpine" } }] }, + }) +} + +/// Attempt `attempt` of operation `id`, in `state`. +fn operation(id: &str, attempt: u64, state: OperationState) -> Operation { + Operation { + id: id.into(), + environment_id: "env-0123456789abcdef0123456789abcdef".parse().unwrap(), + kind: OperationKind::Refresh, + generation: 1, + attempt, + consecutive_failures: 0, + state, + phase: None, + resource: None, + error_code: None, + error_message: None, + created_at_ms: 0, + updated_at_ms: 0, + started_at_ms: None, + finished_at_ms: None, + } +} + +/// Deployment `id`, with its `current_target` and `last_successful` flags. +fn deployment(id: &str, current: bool, successful: bool) -> DeploymentView { + serde_json::from_value(json!({ + "operation": operation(id, 1, OperationState::Succeeded), + "template": template(), + "variables": {}, + "application": null, + "succeeded_at_ms": 1, + "current_target": current, + "last_successful": successful, + })) + .unwrap() +} + +/// Deployment `id`'s summary, with its flags. +fn summary(id: &str, current: bool, successful: bool) -> DeploymentSummary { + deployment(id, current, successful).into() +} + +fn ids(list: &[DeploymentSummary]) -> Vec<&str> { + list.iter().map(|item| item.operation.id.as_str()).collect() +} + +#[test] +fn a_row_names_the_commit_deployed_and_how_long_it_ran() { + let mut built = deployment("operation-1", true, true); + assert_eq!((built.commit(), built.duration_ms()), (None, None)); + built.variables = serde_json::from_value(json!({ + "git.branch": "main", + "git.sha": "0123456789abcdef0123456789abcdef01234567", + })) + .unwrap(); + built.operation.created_at_ms = 1_000; + built.operation.finished_at_ms = Some(39_000); + assert_eq!(built.commit().as_deref(), Some("main @ 0123456789ab")); + assert_eq!(built.duration_ms(), Some(38_000)); +} + +#[test] +fn a_polled_newest_page_keeps_older_pages_and_moves_the_flags() { + let mut list = vec![ + summary("operation-2", true, true), + summary("operation-1", false, false), + ]; + list.append_older(vec![ + summary("operation-1", false, false), + summary("operation-0", false, false), + ]); + assert_eq!(ids(&list), ["operation-2", "operation-1", "operation-0"]); + + let flags = |list: &[DeploymentSummary]| { + list.iter() + .map(|item| (item.current_target, item.last_successful)) + .collect::>() + }; + // A newer deployment became the current target, but hasn't succeeded + // yet: deployment 2, off the polled page, stays the last successful. + list.merge_newest(vec![summary("operation-3", true, false)]); + assert_eq!( + ids(&list), + ["operation-3", "operation-2", "operation-1", "operation-0"] + ); + assert_eq!( + flags(&list), + [(true, false), (false, true), (false, false), (false, false)] + ); + // Then a newer one succeeded without becoming the current target. + list.merge_newest(vec![summary("operation-4", false, true)]); + assert_eq!( + flags(&list)[..3], + [(false, true), (true, false), (false, false)] + ); +} + +#[test] +fn the_running_attempt_leads_until_its_outcome_is_retained() { + let mut attempts = Attempts::default(); + let retained = |attempt| operation("operation-1", attempt, OperationState::Failed); + attempts.show( + Page { + items: vec![retained(2)], + next_cursor: Some("older".into()), + }, + false, + ); + attempts.show( + Page { + items: vec![retained(1)], + next_cursor: None, + }, + true, + ); + assert_eq!(attempts.cursor, None); + + let listed = |attempts: &Attempts, live: &Operation| { + attempts + .visible(live) + .iter() + .map(|item| (item.attempt, item.state)) + .collect::>() + }; + let running = operation("operation-1", 3, OperationState::Running); + assert_eq!( + listed(&attempts, &running), + [ + (3, OperationState::Running), + (2, OperationState::Failed), + (1, OperationState::Failed) + ] + ); + // Refreshing shows the newest page alone; a retained outcome is listed + // once, and nothing ran before the first attempt. + attempts.show( + Page { + items: vec![retained(3)], + next_cursor: Some("older".into()), + }, + false, + ); + assert_eq!(listed(&attempts, &running), [(3, OperationState::Failed)]); + let requested = operation("operation-1", 0, OperationState::Requested); + assert_eq!(listed(&Attempts::default(), &requested), []); +} + +/// A plan of promoting a release from `origin`, at revision 7, whose +/// images are `availability` and which lacks `secrets`. +fn plan(origin: &Value, availability: &Value, secrets: &Value) -> PlanView { + serde_json::from_value(json!({ + "application_id": "app-0123456789abcdef0123456789abcdef", + "generation": 7, + "identical": false, + "operation": null, + "changes": [], + "plan": { "actions": [], "diagnostics": [] }, + "rollouts": [], + "release": { + "release": { + "id": "rel-0123456789abcdef0123456789abcdef", + "application_id": "app-0123456789abcdef0123456789abcdef", + "content_hash": format!("sha256:{}", "b".repeat(64)), + "created_at_ms": 0, + "release": { + "template": template(), + "sources": { "web": { + "type": "image", + "requested": "nginx:alpine", + "digest_reference": format!("docker.io/library/nginx@sha256:{}", "a".repeat(64)), + } }, + }, + "fingerprint": { "web": { "source.image": "nginx:alpine" } }, + "availability": availability, + }, + "origin": origin, + "new_volumes": [], + "secrets": secrets, + }, + })) + .unwrap() +} + +#[test] +fn a_promotion_confirms_exactly_the_reviewed_source_and_revision() { + let promoted = json!({ + "type": "promotion", + "environment": "env-0123456789abcdef0123456789abcdef", + "deployment": "operation-1", + }); + let (present, none) = (json!({ "state": "present" }), json!([])); + let request = Promotion::new(None) + .confirmed(&plan(&promoted, &present, &none)) + .unwrap(); + assert_eq!(request.deployment.as_deref(), Some("operation-1")); + assert_eq!(request.expected_generation, Some(7)); + assert_eq!(request.release, None); + + // An earlier release is deployed as itself, not pinned to a deployment. + let id = "rel-0123456789abcdef0123456789abcdef"; + let release = Promotion::new(Some(id.into())) + .confirmed(&plan(&json!({ "type": "release" }), &present, &none)) + .unwrap(); + assert_eq!(release.deployment, None); + assert_eq!(release.release.as_deref(), Some(id)); + + // Missing secrets, or built images that are gone, block it; missing + // registry images are pulled again by digest. + let missing = json!([{ "problem": "missing", "secret": "api-key" }]); + let confirmed = |availability: &str, secrets: &Value| { + let availability = json!({ "state": availability, "missing": [] }); + Promotion::new(None) + .confirmed(&plan(&promoted, &availability, secrets)) + .is_some() + }; + assert!(!confirmed("present", &missing)); + assert!(!confirmed("unavailable", &none)); + assert!(confirmed("pullable", &none)); +} + +#[test] +fn a_blank_preview_slot_is_none() { + let form = PreviewForm { + branch: " feat/login ".into(), + slot: " ".into(), + }; + let request = form.request(); + assert_eq!(request.branch, "feat/login"); + assert_eq!(request.slot, None); + let slotted = PreviewForm { + slot: " agent-2 ".into(), + ..form + }; + assert_eq!(slotted.request().slot.as_deref(), Some("agent-2")); +} diff --git a/apps/piqueld-ui/src/environments.rs b/apps/piqueld-ui/src/environments/mod.rs similarity index 57% rename from apps/piqueld-ui/src/environments.rs rename to apps/piqueld-ui/src/environments/mod.rs index 11518746f..5c7c2a32f 100644 --- a/apps/piqueld-ui/src/environments.rs +++ b/apps/piqueld-ui/src/environments/mod.rs @@ -309,239 +309,4 @@ impl SourceDraft { } #[cfg(test)] -mod tests { - use super::*; - use piqueld_client::{ - ApplicationId, ApplicationManifest, EnvironmentKind, EnvironmentName, Metadata, - PromotedFrom, RunState, - }; - - const COMMIT: &str = "0123456789abcdef0123456789abcdef01234567"; - - fn environment(id: &str, name: &str, source: EnvironmentSource) -> EnvironmentView { - EnvironmentView { - id: EnvironmentId::parse(id).unwrap(), - application_id: ApplicationId::parse("app-00000001").unwrap(), - name: EnvironmentName::parse(name).unwrap(), - source, - kind: EnvironmentKind::Environment, - sync: false, - synced: None, - telemetry: false, - run_state: RunState::Running, - resolved_generation: None, - delete_intent: false, - created_at_ms: 0, - updated_at_ms: 0, - } - } - - /// An application at generation 3 with `environments`. - fn application(environments: Vec) -> ApplicationView { - let id = ApplicationId::parse("app-00000001").unwrap(); - let application = ApplicationManifest { - api_version: "piqueld.dev/v1alpha1".into(), - kind: "Application".into(), - metadata: Metadata { - name: "notes".into(), - }, - spec: ApplicationSpec::default(), - } - .validate_template() - .unwrap() - .normalize(id); - ApplicationView { - spec_hash: application.spec_hash(), - application, - generation: 3, - delete_intent: false, - created_at_ms: 0, - updated_at_ms: 0, - environments, - previews: Vec::new(), - drift: Vec::new(), - sync_check: None, - repository: None, - } - } - - fn names(saved: &ApplicationView) -> Vec<&str> { - saved - .environments - .iter() - .map(|env| env.name.as_str()) - .collect() - } - - fn branch(branch: &str, commit: Option<&str>) -> TrackedBranch { - TrackedBranch::new(branch.into(), commit.map(Into::into)).unwrap() - } - - fn promoted(from: &str) -> EnvironmentSource { - EnvironmentSource::Promoted(PromotedFrom { - environment: EnvironmentId::parse(from).unwrap(), - }) - } - - /// The form showing `branch` and `commit`, building its own source. - fn building(branch: &str, commit: &str) -> SourceDraft { - SourceDraft { - branch: BranchDraft { - branch: branch.into(), - commit: commit.into(), - }, - promote_from: String::new(), - } - } - - #[test] - fn a_renamed_environment_moves_to_its_name_order_and_advances_the_revision() { - let mut saved = application(vec![ - environment("env-00000001", "alpha", EnvironmentSource::Saved), - environment("env-00000002", "beta", EnvironmentSource::Saved), - ]); - let renamed = environment("env-00000001", "zeta", EnvironmentSource::Saved); - let edit = EnvironmentEdit::Rename { - id: "env-00000001".into(), - name: "zeta".into(), - }; - edit.apply(&mut saved, Some(renamed)); - assert_eq!(names(&saved), ["beta", "zeta"]); - assert_eq!(saved.generation, 4); - } - - #[test] - fn unguarded_changes_keep_the_revision_later_edits_expect() { - let mut saved = application(vec![environment( - "env-00000001", - "alpha", - EnvironmentSource::Saved, - )]); - let mut changed = saved.environments[0].clone(); - changed.sync = true; - let id = String::from("env-00000001"); - EnvironmentEdit::Sync { - id: id.clone(), - enabled: true, - } - .apply(&mut saved, Some(changed.clone())); - changed.telemetry = true; - EnvironmentEdit::Telemetry { - id: id.clone(), - granted: true, - } - .apply(&mut saved, Some(changed.clone())); - EnvironmentEdit::RetryDeletion(id).apply(&mut saved, None); - assert_eq!(saved.generation, 3); - assert_eq!(saved.environments, [changed]); - } - - #[test] - fn an_accepted_deletion_marks_only_that_environment() { - let mut saved = application(vec![ - environment("env-00000001", "alpha", EnvironmentSource::Saved), - environment("env-00000002", "beta", EnvironmentSource::Saved), - ]); - EnvironmentEdit::Delete("env-00000002".into()).apply(&mut saved, None); - let deleting: Vec<_> = saved - .environments - .iter() - .map(|env| env.delete_intent) - .collect(); - assert_eq!(deleting, [false, true]); - assert_eq!(saved.generation, 4); - } - - #[test] - fn a_blank_commit_follows_the_branch_head_and_whitespace_is_ignored() { - assert_eq!( - building(" main ", " ").branch.tracked(), - Ok(branch("main", None)) - ); - assert_eq!( - building("main", &format!(" {COMMIT}\n")).branch.tracked(), - Ok(branch("main", Some(COMMIT))) - ); - assert!(building("main", "abc").branch.tracked().is_err()); - assert!(building("", "").branch.tracked().is_err()); - } - - #[test] - fn a_branch_form_changes_only_when_it_names_another_branch_or_commit() { - let saved = EnvironmentSource::Branch(branch("release", None)); - let change = |draft: SourceDraft| draft.change("env-00000001".into(), Some(&saved), true); - assert_eq!(change(building(" release", "")), None); - assert_eq!( - change(building("release", COMMIT)), - Some(Ok(EnvironmentEdit::Branch { - id: "env-00000001".into(), - branch: branch("release", Some(COMMIT)), - })) - ); - assert!(matches!(change(building("release", "abc")), Some(Err(_)))); - } - - #[test] - fn a_promoted_environment_changes_its_source_or_builds_again() { - let saved = promoted("env-00000002"); - let id = || String::from("env-00000001"); - let promoting = |from: &str| SourceDraft { - promote_from: from.into(), - ..building("main", "") - }; - assert_eq!( - promoting("env-00000002").change(id(), Some(&saved), true), - None - ); - assert_eq!( - promoting("env-00000003").change(id(), Some(&saved), false), - Some(Ok(EnvironmentEdit::Source { - id: id(), - promote_from: Some("env-00000003".into()), - })) - ); - // Building again follows the shown branch, even the default one, in - // a repository-backed application, and its saved manifest otherwise. - assert_eq!( - building("main", "").change(id(), Some(&saved), true), - Some(Ok(EnvironmentEdit::Branch { - id: id(), - branch: branch("main", None), - })) - ); - assert_eq!( - building("", "").change(id(), Some(&saved), false), - Some(Ok(EnvironmentEdit::Source { - id: id(), - promote_from: None, - })) - ); - } - - #[test] - fn an_untouched_form_reports_no_change_so_it_never_blocks_deploys() { - let default = BranchDraft { - branch: "main".into(), - commit: String::new(), - }; - // Repository-backed environments follow a branch unless promoted; - // the others build the saved manifest. - let sources = [ - ( - EnvironmentSource::Branch(branch("release", Some(COMMIT))), - true, - ), - (promoted("env-00000002"), true), - (EnvironmentSource::Saved, false), - (promoted("env-00000002"), false), - ]; - for (source, repository) in sources { - let draft = SourceDraft::saved(Some(&source), default.clone()); - assert_eq!( - draft.change("env-00000001".into(), Some(&source), repository), - None, - "{source}" - ); - } - } -} +mod tests; diff --git a/apps/piqueld-ui/src/environments/tests.rs b/apps/piqueld-ui/src/environments/tests.rs new file mode 100644 index 000000000..f90e9c228 --- /dev/null +++ b/apps/piqueld-ui/src/environments/tests.rs @@ -0,0 +1,234 @@ +use super::*; +use piqueld_client::{ + ApplicationId, ApplicationManifest, EnvironmentKind, EnvironmentName, Metadata, PromotedFrom, + RunState, +}; + +const COMMIT: &str = "0123456789abcdef0123456789abcdef01234567"; + +fn environment(id: &str, name: &str, source: EnvironmentSource) -> EnvironmentView { + EnvironmentView { + id: EnvironmentId::parse(id).unwrap(), + application_id: ApplicationId::parse("app-00000001").unwrap(), + name: EnvironmentName::parse(name).unwrap(), + source, + kind: EnvironmentKind::Environment, + sync: false, + synced: None, + telemetry: false, + run_state: RunState::Running, + resolved_generation: None, + delete_intent: false, + created_at_ms: 0, + updated_at_ms: 0, + } +} + +/// An application at generation 3 with `environments`. +fn application(environments: Vec) -> ApplicationView { + let id = ApplicationId::parse("app-00000001").unwrap(); + let application = ApplicationManifest { + api_version: "piqueld.dev/v1alpha1".into(), + kind: "Application".into(), + metadata: Metadata { + name: "notes".into(), + }, + spec: ApplicationSpec::default(), + } + .validate_template() + .unwrap() + .normalize(id); + ApplicationView { + spec_hash: application.spec_hash(), + application, + generation: 3, + delete_intent: false, + created_at_ms: 0, + updated_at_ms: 0, + environments, + previews: Vec::new(), + drift: Vec::new(), + sync_check: None, + repository: None, + } +} + +fn names(saved: &ApplicationView) -> Vec<&str> { + saved + .environments + .iter() + .map(|env| env.name.as_str()) + .collect() +} + +fn branch(branch: &str, commit: Option<&str>) -> TrackedBranch { + TrackedBranch::new(branch.into(), commit.map(Into::into)).unwrap() +} + +fn promoted(from: &str) -> EnvironmentSource { + EnvironmentSource::Promoted(PromotedFrom { + environment: EnvironmentId::parse(from).unwrap(), + }) +} + +/// The form showing `branch` and `commit`, building its own source. +fn building(branch: &str, commit: &str) -> SourceDraft { + SourceDraft { + branch: BranchDraft { + branch: branch.into(), + commit: commit.into(), + }, + promote_from: String::new(), + } +} + +#[test] +fn a_renamed_environment_moves_to_its_name_order_and_advances_the_revision() { + let mut saved = application(vec![ + environment("env-00000001", "alpha", EnvironmentSource::Saved), + environment("env-00000002", "beta", EnvironmentSource::Saved), + ]); + let renamed = environment("env-00000001", "zeta", EnvironmentSource::Saved); + let edit = EnvironmentEdit::Rename { + id: "env-00000001".into(), + name: "zeta".into(), + }; + edit.apply(&mut saved, Some(renamed)); + assert_eq!(names(&saved), ["beta", "zeta"]); + assert_eq!(saved.generation, 4); +} + +#[test] +fn unguarded_changes_keep_the_revision_later_edits_expect() { + let mut saved = application(vec![environment( + "env-00000001", + "alpha", + EnvironmentSource::Saved, + )]); + let mut changed = saved.environments[0].clone(); + changed.sync = true; + let id = String::from("env-00000001"); + EnvironmentEdit::Sync { + id: id.clone(), + enabled: true, + } + .apply(&mut saved, Some(changed.clone())); + changed.telemetry = true; + EnvironmentEdit::Telemetry { + id: id.clone(), + granted: true, + } + .apply(&mut saved, Some(changed.clone())); + EnvironmentEdit::RetryDeletion(id).apply(&mut saved, None); + assert_eq!(saved.generation, 3); + assert_eq!(saved.environments, [changed]); +} + +#[test] +fn an_accepted_deletion_marks_only_that_environment() { + let mut saved = application(vec![ + environment("env-00000001", "alpha", EnvironmentSource::Saved), + environment("env-00000002", "beta", EnvironmentSource::Saved), + ]); + EnvironmentEdit::Delete("env-00000002".into()).apply(&mut saved, None); + let deleting: Vec<_> = saved + .environments + .iter() + .map(|env| env.delete_intent) + .collect(); + assert_eq!(deleting, [false, true]); + assert_eq!(saved.generation, 4); +} + +#[test] +fn a_blank_commit_follows_the_branch_head_and_whitespace_is_ignored() { + assert_eq!( + building(" main ", " ").branch.tracked(), + Ok(branch("main", None)) + ); + assert_eq!( + building("main", &format!(" {COMMIT}\n")).branch.tracked(), + Ok(branch("main", Some(COMMIT))) + ); + assert!(building("main", "abc").branch.tracked().is_err()); + assert!(building("", "").branch.tracked().is_err()); +} + +#[test] +fn a_branch_form_changes_only_when_it_names_another_branch_or_commit() { + let saved = EnvironmentSource::Branch(branch("release", None)); + let change = |draft: SourceDraft| draft.change("env-00000001".into(), Some(&saved), true); + assert_eq!(change(building(" release", "")), None); + assert_eq!( + change(building("release", COMMIT)), + Some(Ok(EnvironmentEdit::Branch { + id: "env-00000001".into(), + branch: branch("release", Some(COMMIT)), + })) + ); + assert!(matches!(change(building("release", "abc")), Some(Err(_)))); +} + +#[test] +fn a_promoted_environment_changes_its_source_or_builds_again() { + let saved = promoted("env-00000002"); + let id = || String::from("env-00000001"); + let promoting = |from: &str| SourceDraft { + promote_from: from.into(), + ..building("main", "") + }; + assert_eq!( + promoting("env-00000002").change(id(), Some(&saved), true), + None + ); + assert_eq!( + promoting("env-00000003").change(id(), Some(&saved), false), + Some(Ok(EnvironmentEdit::Source { + id: id(), + promote_from: Some("env-00000003".into()), + })) + ); + // Building again follows the shown branch, even the default one, in + // a repository-backed application, and its saved manifest otherwise. + assert_eq!( + building("main", "").change(id(), Some(&saved), true), + Some(Ok(EnvironmentEdit::Branch { + id: id(), + branch: branch("main", None), + })) + ); + assert_eq!( + building("", "").change(id(), Some(&saved), false), + Some(Ok(EnvironmentEdit::Source { + id: id(), + promote_from: None, + })) + ); +} + +#[test] +fn an_untouched_form_reports_no_change_so_it_never_blocks_deploys() { + let default = BranchDraft { + branch: "main".into(), + commit: String::new(), + }; + // Repository-backed environments follow a branch unless promoted; + // the others build the saved manifest. + let sources = [ + ( + EnvironmentSource::Branch(branch("release", Some(COMMIT))), + true, + ), + (promoted("env-00000002"), true), + (EnvironmentSource::Saved, false), + (promoted("env-00000002"), false), + ]; + for (source, repository) in sources { + let draft = SourceDraft::saved(Some(&source), default.clone()); + assert_eq!( + draft.change("env-00000001".into(), Some(&source), repository), + None, + "{source}" + ); + } +} diff --git a/apps/piqueld-ui/src/log_output.rs b/apps/piqueld-ui/src/log_output/mod.rs similarity index 64% rename from apps/piqueld-ui/src/log_output.rs rename to apps/piqueld-ui/src/log_output/mod.rs index 093eefc9c..89b5cd6f6 100644 --- a/apps/piqueld-ui/src/log_output.rs +++ b/apps/piqueld-ui/src/log_output/mod.rs @@ -87,62 +87,4 @@ impl LogLine { } #[cfg(test)] -mod tests { - use super::*; - #[test] - fn interleaved_chunks_keep_partial_lines_and_severity() { - let chunk = |offset, stream, text: &str| BuildLogChunk { - offset, - stream, - timestamp_ms: 1000, - text: text.into(), - }; - let lines = LogLine::build( - &[ - chunk(0, LogStream::Stdout, "hel"), - chunk(3, LogStream::Stderr, "progress\n"), - chunk(12, LogStream::Stdout, "lo\n\x1b[31mERROR\x1b[0m failed\n"), - ], - "web", - ); - assert_eq!( - lines.iter().map(|l| l.message.as_str()).collect::>(), - ["hello", "progress", "ERROR failed"] - ); - assert_eq!(lines[1].severity(), "stderr"); - assert_eq!(lines[2].severity(), "error"); - } - - #[test] - fn build_lines_keep_the_timestamp_of_their_first_chunk() { - let chunks = [ - (0, LogStream::Stdout, "first\nse"), - (8, LogStream::Stderr, "warn"), - (12, LogStream::Stdout, "co"), - (14, LogStream::Stdout, "nd\nthird\nfour"), - (27, LogStream::Stderr, "ing\n"), - (31, LogStream::Stdout, "th\nfifth"), - ] - .map(|(offset, stream, text)| BuildLogChunk { - offset, - stream, - timestamp_ms: offset, - text: text.into(), - }); - let lines = LogLine::build(&chunks, "web"); - assert_eq!( - lines - .iter() - .map(|line| (line.message.as_str(), line.timestamp.as_str())) - .collect::>(), - [ - ("first", "0"), - ("second", "0"), - ("warning", "8"), - ("third", "14"), - ("fourth", "14"), - ("fifth", "31") - ], - ); - } -} +mod tests; diff --git a/apps/piqueld-ui/src/log_output/tests.rs b/apps/piqueld-ui/src/log_output/tests.rs new file mode 100644 index 000000000..c469ebb95 --- /dev/null +++ b/apps/piqueld-ui/src/log_output/tests.rs @@ -0,0 +1,57 @@ +use super::*; +#[test] +fn interleaved_chunks_keep_partial_lines_and_severity() { + let chunk = |offset, stream, text: &str| BuildLogChunk { + offset, + stream, + timestamp_ms: 1000, + text: text.into(), + }; + let lines = LogLine::build( + &[ + chunk(0, LogStream::Stdout, "hel"), + chunk(3, LogStream::Stderr, "progress\n"), + chunk(12, LogStream::Stdout, "lo\n\x1b[31mERROR\x1b[0m failed\n"), + ], + "web", + ); + assert_eq!( + lines.iter().map(|l| l.message.as_str()).collect::>(), + ["hello", "progress", "ERROR failed"] + ); + assert_eq!(lines[1].severity(), "stderr"); + assert_eq!(lines[2].severity(), "error"); +} + +#[test] +fn build_lines_keep_the_timestamp_of_their_first_chunk() { + let chunks = [ + (0, LogStream::Stdout, "first\nse"), + (8, LogStream::Stderr, "warn"), + (12, LogStream::Stdout, "co"), + (14, LogStream::Stdout, "nd\nthird\nfour"), + (27, LogStream::Stderr, "ing\n"), + (31, LogStream::Stdout, "th\nfifth"), + ] + .map(|(offset, stream, text)| BuildLogChunk { + offset, + stream, + timestamp_ms: offset, + text: text.into(), + }); + let lines = LogLine::build(&chunks, "web"); + assert_eq!( + lines + .iter() + .map(|line| (line.message.as_str(), line.timestamp.as_str())) + .collect::>(), + [ + ("first", "0"), + ("second", "0"), + ("warning", "8"), + ("third", "14"), + ("fourth", "14"), + ("fifth", "31") + ], + ); +} diff --git a/apps/piqueld-ui/src/overview/dashboard.rs b/apps/piqueld-ui/src/overview/dashboard/mod.rs similarity index 54% rename from apps/piqueld-ui/src/overview/dashboard.rs rename to apps/piqueld-ui/src/overview/dashboard/mod.rs index 75f78d8a6..5821653c8 100644 --- a/apps/piqueld-ui/src/overview/dashboard.rs +++ b/apps/piqueld-ui/src/overview/dashboard/mod.rs @@ -175,135 +175,4 @@ impl PreviewLoad { } #[cfg(test)] -mod tests { - use super::*; - use crate::overview::fixtures::{application, environment}; - use piqueld_client::ApplicationState; - use serde_json::json; - - #[test] - fn an_application_shows_its_least_healthy_environment() { - let row = |environments| application("app-shop0001", environments, &[]).health(); - assert_eq!(row(Vec::new()), ApplicationHealth::NotDeployed); - assert_eq!( - row(vec![ - environment("production", false, Some((ApplicationState::Ready, None))), - environment("staging", false, Some((ApplicationState::Failed, None))), - environment("qa", false, Some((ApplicationState::Degraded, None))), - ]), - ApplicationHealth::Failed - ); - // A missing status is pending, never healthy. - assert_eq!( - row(vec![ - environment("production", false, Some((ApplicationState::Ready, None))), - environment("staging", false, None), - ]), - ApplicationHealth::Pending - ); - // A stopped environment reads as stopped whatever its last status, - // which ranks above a healthy one but below any problem. - assert_eq!( - row(vec![ - environment("production", false, Some((ApplicationState::Ready, None))), - environment("staging", true, Some((ApplicationState::Failed, None))), - ]), - ApplicationHealth::Stopped - ); - assert_eq!( - row(vec![ - environment("production", false, Some((ApplicationState::Pending, None))), - environment("staging", true, None), - ]), - ApplicationHealth::Pending - ); - } - - #[test] - fn the_subtitle_prefers_deletion_then_the_first_status_message() { - let mut row = application( - "app-shop0001", - vec![ - environment("production", false, Some((ApplicationState::Ready, None))), - environment("staging", false, None), - environment( - "qa", - false, - Some((ApplicationState::Failed, Some("image pull failed"))), - ), - environment( - "dev", - false, - Some((ApplicationState::Degraded, Some("1 of 2"))), - ), - ], - &[], - ); - assert_eq!(row.subtitle(), "qa: image pull failed"); - row.application.delete_intent = true; - assert_eq!(row.subtitle(), "Deletion requested"); - let quiet = application( - "app-shop0001", - vec![environment("production", false, None)], - &[], - ); - assert_eq!(quiet.subtitle(), "Generation 4"); - } - - #[test] - fn recent_deployments_are_the_newest_across_applications() { - let rows = [ - application( - "app-shop0001", - Vec::new(), - &[("op-a1", 10), ("op-a2", 50), ("op-a3", 30)], - ), - application("app-notes001", Vec::new(), &[("op-b1", 40), ("op-b2", 50)]), - application("app-empty001", Vec::new(), &[]), - ]; - let recent = ApplicationRow::recent_deployments(&rows, 4) - .into_iter() - .map(|(application, operation)| (application.id.as_str(), operation.id.as_str())) - .collect::>(); - assert_eq!( - recent, - [ - ("app-notes001", "op-b2"), - ("app-shop0001", "op-a2"), - ("app-notes001", "op-b1"), - ("app-shop0001", "op-a3"), - ] - ); - assert_eq!(rows[0].last_deployed_ms(), Some(50)); - assert_eq!(rows[2].last_deployed_ms(), None); - } - - #[test] - fn previews_report_their_most_constrained_limit() { - let usage = |total, applications: &[u32]| { - serde_json::from_value::(json!({ - "limits": { "max_total": 5, "max_per_application": 2 }, - "total": total, - "applications": applications - .iter() - .enumerate() - .map(|(index, previews)| json!({ - "id": format!("app-shop000{index}"), - "name": format!("shop{index}"), - "previews": previews, - })) - .collect::>(), - "cpu_millis": 0, - "memory_bytes": 0, - })) - .expect("usage") - }; - assert_eq!(PreviewLoad::of(&usage(3, &[1, 1])), PreviewLoad::Within); - // One application at its own limit refuses its next preview while - // the installation still has room. - assert_eq!(PreviewLoad::of(&usage(3, &[2, 1])), PreviewLoad::AtLimit); - assert_eq!(PreviewLoad::of(&usage(5, &[1])), PreviewLoad::AtLimit); - // A count over a lowered limit outweighs one at its limit. - assert_eq!(PreviewLoad::of(&usage(5, &[3, 2])), PreviewLoad::OverLimit); - } -} +mod tests; diff --git a/apps/piqueld-ui/src/overview/dashboard/tests.rs b/apps/piqueld-ui/src/overview/dashboard/tests.rs new file mode 100644 index 000000000..6ead90868 --- /dev/null +++ b/apps/piqueld-ui/src/overview/dashboard/tests.rs @@ -0,0 +1,130 @@ +use super::*; +use crate::overview::fixtures::{application, environment}; +use piqueld_client::ApplicationState; +use serde_json::json; + +#[test] +fn an_application_shows_its_least_healthy_environment() { + let row = |environments| application("app-shop0001", environments, &[]).health(); + assert_eq!(row(Vec::new()), ApplicationHealth::NotDeployed); + assert_eq!( + row(vec![ + environment("production", false, Some((ApplicationState::Ready, None))), + environment("staging", false, Some((ApplicationState::Failed, None))), + environment("qa", false, Some((ApplicationState::Degraded, None))), + ]), + ApplicationHealth::Failed + ); + // A missing status is pending, never healthy. + assert_eq!( + row(vec![ + environment("production", false, Some((ApplicationState::Ready, None))), + environment("staging", false, None), + ]), + ApplicationHealth::Pending + ); + // A stopped environment reads as stopped whatever its last status, + // which ranks above a healthy one but below any problem. + assert_eq!( + row(vec![ + environment("production", false, Some((ApplicationState::Ready, None))), + environment("staging", true, Some((ApplicationState::Failed, None))), + ]), + ApplicationHealth::Stopped + ); + assert_eq!( + row(vec![ + environment("production", false, Some((ApplicationState::Pending, None))), + environment("staging", true, None), + ]), + ApplicationHealth::Pending + ); +} + +#[test] +fn the_subtitle_prefers_deletion_then_the_first_status_message() { + let mut row = application( + "app-shop0001", + vec![ + environment("production", false, Some((ApplicationState::Ready, None))), + environment("staging", false, None), + environment( + "qa", + false, + Some((ApplicationState::Failed, Some("image pull failed"))), + ), + environment( + "dev", + false, + Some((ApplicationState::Degraded, Some("1 of 2"))), + ), + ], + &[], + ); + assert_eq!(row.subtitle(), "qa: image pull failed"); + row.application.delete_intent = true; + assert_eq!(row.subtitle(), "Deletion requested"); + let quiet = application( + "app-shop0001", + vec![environment("production", false, None)], + &[], + ); + assert_eq!(quiet.subtitle(), "Generation 4"); +} + +#[test] +fn recent_deployments_are_the_newest_across_applications() { + let rows = [ + application( + "app-shop0001", + Vec::new(), + &[("op-a1", 10), ("op-a2", 50), ("op-a3", 30)], + ), + application("app-notes001", Vec::new(), &[("op-b1", 40), ("op-b2", 50)]), + application("app-empty001", Vec::new(), &[]), + ]; + let recent = ApplicationRow::recent_deployments(&rows, 4) + .into_iter() + .map(|(application, operation)| (application.id.as_str(), operation.id.as_str())) + .collect::>(); + assert_eq!( + recent, + [ + ("app-notes001", "op-b2"), + ("app-shop0001", "op-a2"), + ("app-notes001", "op-b1"), + ("app-shop0001", "op-a3"), + ] + ); + assert_eq!(rows[0].last_deployed_ms(), Some(50)); + assert_eq!(rows[2].last_deployed_ms(), None); +} + +#[test] +fn previews_report_their_most_constrained_limit() { + let usage = |total, applications: &[u32]| { + serde_json::from_value::(json!({ + "limits": { "max_total": 5, "max_per_application": 2 }, + "total": total, + "applications": applications + .iter() + .enumerate() + .map(|(index, previews)| json!({ + "id": format!("app-shop000{index}"), + "name": format!("shop{index}"), + "previews": previews, + })) + .collect::>(), + "cpu_millis": 0, + "memory_bytes": 0, + })) + .expect("usage") + }; + assert_eq!(PreviewLoad::of(&usage(3, &[1, 1])), PreviewLoad::Within); + // One application at its own limit refuses its next preview while + // the installation still has room. + assert_eq!(PreviewLoad::of(&usage(3, &[2, 1])), PreviewLoad::AtLimit); + assert_eq!(PreviewLoad::of(&usage(5, &[1])), PreviewLoad::AtLimit); + // A count over a lowered limit outweighs one at its limit. + assert_eq!(PreviewLoad::of(&usage(5, &[3, 2])), PreviewLoad::OverLimit); +} diff --git a/apps/piqueld-ui/src/overview/notifications.rs b/apps/piqueld-ui/src/overview/notifications/mod.rs similarity index 57% rename from apps/piqueld-ui/src/overview/notifications.rs rename to apps/piqueld-ui/src/overview/notifications/mod.rs index 12d886557..e1e2743f2 100644 --- a/apps/piqueld-ui/src/overview/notifications.rs +++ b/apps/piqueld-ui/src/overview/notifications/mod.rs @@ -160,127 +160,4 @@ impl DestinationDraft { } #[cfg(test)] -mod tests { - use super::*; - use crate::overview::fixtures::application; - use serde_json::json; - - /// Destination `ops` receiving build failures with a mention, and - /// deployment failures, about `shop` and its previews. - fn destination() -> NotificationDestination { - serde_json::from_value(json!({ - "name": "ops", - "settings": { - "kind": "json", - "enabled": false, - "categories": { - "build_failures": { "message": "<@&42>" }, - "deployment_failures": {}, - }, - "applications": { "only": ["app-shop0001"] }, - "previews": true, - }, - "created_at_ms": 0, - "updated_at_ms": 0, - })) - .expect("destination") - } - - #[test] - fn an_unedited_destination_saves_its_settings_and_keeps_its_url() { - let destination = destination(); - let draft = DestinationDraft::new(Some(&destination)); - assert!(draft.existing); - let (name, request) = draft.request().expect("request"); - assert_eq!(name, "ops"); - assert_eq!(request.settings, destination.settings); - assert_eq!(request.url, None); - } - - #[test] - fn only_checked_categories_send_their_trimmed_messages() { - let mut draft = DestinationDraft::new(Some(&destination())); - draft.name = " ops ".into(); - draft.url = " https://hooks.example.com/a ".into(); - // An unchecked category's message is not sent. - draft - .categories - .remove(&NotificationCategory::BuildFailures); - draft - .categories - .insert(NotificationCategory::DaemonFailures); - draft.messages.insert( - NotificationCategory::DeploymentFailures, - " on call ".into(), - ); - draft - .messages - .insert(NotificationCategory::DaemonFailures, " ".into()); - let (name, request) = draft.request().expect("request"); - assert_eq!(name, "ops"); - assert_eq!(request.url.as_deref(), Some("https://hooks.example.com/a")); - let messages = request - .settings - .categories - .iter() - .map(|(category, rule)| (*category, rule.message.as_ref().map(ToString::to_string))) - .collect::>(); - assert_eq!( - messages, - [ - ( - NotificationCategory::DeploymentFailures, - Some("on call".into()) - ), - (NotificationCategory::DaemonFailures, None), - ] - ); - } - - #[test] - fn an_invalid_message_names_its_category() { - let mut draft = DestinationDraft::new(None); - draft.messages.insert( - NotificationCategory::BuildFailures, - "x".repeat(NotificationMessage::MAX_CHARS + 1), - ); - let error = draft.request().expect_err("too long"); - assert!(error.starts_with("Build failures: "), "{error}"); - // The same message on an unchecked category is not sent, so it saves. - draft - .categories - .remove(&NotificationCategory::BuildFailures); - assert!(draft.request().is_ok()); - } - - #[test] - fn receives_names_listed_applications_and_falls_back_to_ids() { - let mut shop = application("app-shop0001", Vec::new(), &[]); - shop.application.name = "shop".into(); - let applications = [shop]; - let mut settings = destination().settings; - let text = |settings: &DestinationSettings| { - Receives { - settings, - applications: &applications, - } - .to_string() - }; - settings.applications = ApplicationSelection::Only( - ["app-shop0001", "app-gone0001"] - .map(|id| ApplicationId::parse(id).expect("id")) - .into(), - ); - assert_eq!( - text(&settings), - "2 categories · app-gone0001, shop · previews" - ); - settings.applications = ApplicationSelection::Only(BTreeSet::new()); - settings.previews = false; - assert_eq!(text(&settings), "2 categories · no application"); - settings.applications = ApplicationSelection::All; - assert_eq!(text(&settings), "2 categories · every application"); - settings.categories.pop_first(); - assert_eq!(text(&settings), "1 category · every application"); - } -} +mod tests; diff --git a/apps/piqueld-ui/src/overview/notifications/tests.rs b/apps/piqueld-ui/src/overview/notifications/tests.rs new file mode 100644 index 000000000..e13fb10cf --- /dev/null +++ b/apps/piqueld-ui/src/overview/notifications/tests.rs @@ -0,0 +1,122 @@ +use super::*; +use crate::overview::fixtures::application; +use serde_json::json; + +/// Destination `ops` receiving build failures with a mention, and +/// deployment failures, about `shop` and its previews. +fn destination() -> NotificationDestination { + serde_json::from_value(json!({ + "name": "ops", + "settings": { + "kind": "json", + "enabled": false, + "categories": { + "build_failures": { "message": "<@&42>" }, + "deployment_failures": {}, + }, + "applications": { "only": ["app-shop0001"] }, + "previews": true, + }, + "created_at_ms": 0, + "updated_at_ms": 0, + })) + .expect("destination") +} + +#[test] +fn an_unedited_destination_saves_its_settings_and_keeps_its_url() { + let destination = destination(); + let draft = DestinationDraft::new(Some(&destination)); + assert!(draft.existing); + let (name, request) = draft.request().expect("request"); + assert_eq!(name, "ops"); + assert_eq!(request.settings, destination.settings); + assert_eq!(request.url, None); +} + +#[test] +fn only_checked_categories_send_their_trimmed_messages() { + let mut draft = DestinationDraft::new(Some(&destination())); + draft.name = " ops ".into(); + draft.url = " https://hooks.example.com/a ".into(); + // An unchecked category's message is not sent. + draft + .categories + .remove(&NotificationCategory::BuildFailures); + draft + .categories + .insert(NotificationCategory::DaemonFailures); + draft.messages.insert( + NotificationCategory::DeploymentFailures, + " on call ".into(), + ); + draft + .messages + .insert(NotificationCategory::DaemonFailures, " ".into()); + let (name, request) = draft.request().expect("request"); + assert_eq!(name, "ops"); + assert_eq!(request.url.as_deref(), Some("https://hooks.example.com/a")); + let messages = request + .settings + .categories + .iter() + .map(|(category, rule)| (*category, rule.message.as_ref().map(ToString::to_string))) + .collect::>(); + assert_eq!( + messages, + [ + ( + NotificationCategory::DeploymentFailures, + Some("on call".into()) + ), + (NotificationCategory::DaemonFailures, None), + ] + ); +} + +#[test] +fn an_invalid_message_names_its_category() { + let mut draft = DestinationDraft::new(None); + draft.messages.insert( + NotificationCategory::BuildFailures, + "x".repeat(NotificationMessage::MAX_CHARS + 1), + ); + let error = draft.request().expect_err("too long"); + assert!(error.starts_with("Build failures: "), "{error}"); + // The same message on an unchecked category is not sent, so it saves. + draft + .categories + .remove(&NotificationCategory::BuildFailures); + assert!(draft.request().is_ok()); +} + +#[test] +fn receives_names_listed_applications_and_falls_back_to_ids() { + let mut shop = application("app-shop0001", Vec::new(), &[]); + shop.application.name = "shop".into(); + let applications = [shop]; + let mut settings = destination().settings; + let text = |settings: &DestinationSettings| { + Receives { + settings, + applications: &applications, + } + .to_string() + }; + settings.applications = ApplicationSelection::Only( + ["app-shop0001", "app-gone0001"] + .map(|id| ApplicationId::parse(id).expect("id")) + .into(), + ); + assert_eq!( + text(&settings), + "2 categories · app-gone0001, shop · previews" + ); + settings.applications = ApplicationSelection::Only(BTreeSet::new()); + settings.previews = false; + assert_eq!(text(&settings), "2 categories · no application"); + settings.applications = ApplicationSelection::All; + assert_eq!(text(&settings), "2 categories · every application"); + settings.categories.pop_first(); + assert_eq!(text(&settings), "1 category · every application"); +} diff --git a/apps/piqueld-ui/src/secrets.rs b/apps/piqueld-ui/src/secrets/mod.rs similarity index 70% rename from apps/piqueld-ui/src/secrets.rs rename to apps/piqueld-ui/src/secrets/mod.rs index 1534665dc..12603574a 100644 --- a/apps/piqueld-ui/src/secrets.rs +++ b/apps/piqueld-ui/src/secrets/mod.rs @@ -95,48 +95,4 @@ impl DeclarationDraft { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn switching_the_generator_resets_its_size_and_keeps_the_name() { - let mut draft = DeclarationDraft { - name: "signing-key".into(), - rsa: false, - size: "64".into(), - encoding: SecretEncoding::Base64url, - }; - draft.set_kind(true); - assert_eq!( - (draft.name.as_str(), draft.size.as_str()), - ("signing-key", "3072") - ); - draft.size = "4096".into(); - draft.set_kind(true); - assert_eq!(draft.size, "4096"); - draft.set_kind(false); - assert_eq!( - draft, - DeclarationDraft { - name: "signing-key".into(), - ..DeclarationDraft::default() - } - ); - } - - #[test] - fn a_size_that_does_not_parse_is_reported_for_its_secret_before_saving() { - for size in ["", "3.5", "-1", "65536"] { - let draft = DeclarationDraft { - name: "token".into(), - size: size.into(), - ..DeclarationDraft::default() - }; - assert_eq!( - draft.declaration(), - Err("The size of token must be a whole number".into()), - "{size:?}" - ); - } - } -} +mod tests; diff --git a/apps/piqueld-ui/src/secrets/tests.rs b/apps/piqueld-ui/src/secrets/tests.rs new file mode 100644 index 000000000..10affb27e --- /dev/null +++ b/apps/piqueld-ui/src/secrets/tests.rs @@ -0,0 +1,43 @@ +use super::*; + +#[test] +fn switching_the_generator_resets_its_size_and_keeps_the_name() { + let mut draft = DeclarationDraft { + name: "signing-key".into(), + rsa: false, + size: "64".into(), + encoding: SecretEncoding::Base64url, + }; + draft.set_kind(true); + assert_eq!( + (draft.name.as_str(), draft.size.as_str()), + ("signing-key", "3072") + ); + draft.size = "4096".into(); + draft.set_kind(true); + assert_eq!(draft.size, "4096"); + draft.set_kind(false); + assert_eq!( + draft, + DeclarationDraft { + name: "signing-key".into(), + ..DeclarationDraft::default() + } + ); +} + +#[test] +fn a_size_that_does_not_parse_is_reported_for_its_secret_before_saving() { + for size in ["", "3.5", "-1", "65536"] { + let draft = DeclarationDraft { + name: "token".into(), + size: size.into(), + ..DeclarationDraft::default() + }; + assert_eq!( + draft.declaration(), + Err("The size of token must be a whole number".into()), + "{size:?}" + ); + } +} diff --git a/docs/dev/rust-conventions.md b/docs/dev/rust-conventions.md index f8476d10e..a58fbfa49 100644 --- a/docs/dev/rust-conventions.md +++ b/docs/dev/rust-conventions.md @@ -64,8 +64,8 @@ helpers with no owner. Limits and timeouts are named constants. ## Modules, tests and docs A module with children is `foo/mod.rs` (`self_named_module_files`). Unit tests -live in `#[cfg(test)] mod tests;` with a sibling `tests.rs`; a block of 30 lines -or fewer may stay inline. Tests prove one behaviour each, named for it, and +live in `#[cfg(test)] mod tests;` with a sibling `tests.rs` once the block is +more than 30% of its file; a smaller one may stay inline. Tests prove one behaviour each, named for it, and assert the outcome; [automated validation](validation.md) lists the suites and what each covers. @@ -82,8 +82,6 @@ the docs, private items included, with warnings denied. - `unwrap_used` is off: the tests still call `unwrap` about 4,400 times. They move to `expect("what should have held")` crate by crate (PQD-124); new tests use `expect`. -- Most unit tests are inline `mod tests { ... }` blocks longer than 30 lines. - Move a block to a sibling `tests.rs` when you change it. - `just doc` allows links from public items to private ones (`rustdoc::private_intra_doc_links`), since most of the code is internal and documented for its developers.