//! Tests for [`super`]. use super::*; use crate::model::SourceState; use chrono::TimeDelta; use ops_status::{Condition, Field, Payload, Status, Value}; use ratatui::Terminal; use ratatui::backend::TestBackend; fn now() -> DateTime { "2026-07-21T18:00:00Z".parse().unwrap() } /// Render a model into a fixed-size buffer and return it as text lines. /// /// This is the whole payoff of keeping render pure: the entire surface is /// verifiable with no daemon running and no terminal attached. fn draw(model: &Model, now: DateTime, width: u16, height: u16) -> Vec { let theme = crate::theme::tests::fixed(); let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); terminal .draw(|frame| render(model, &theme, now, frame)) .unwrap(); let buffer = terminal.backend().buffer().clone(); (0..buffer.area.height) .map(|y| { (0..buffer.area.width) .map(|x| buffer[(x, y)].symbol().to_string()) .collect::() .trim_end() .to_string() }) .collect() } fn node(id: &str, label: &str, status: Status) -> Node { Node { id: id.into(), kind: "tier".into(), label: label.into(), status, fields: Vec::new(), conditions: Vec::new(), children: Vec::new(), actions: Vec::new(), } } fn source(name: &str, at: DateTime, nodes: Vec) -> SourceState { let mut s = SourceState::new(name, TimeDelta::seconds(60)); let mut p = Payload::new(name, at); p.nodes = nodes; s.observe(p, at); s } fn joined(lines: &[String]) -> String { lines.join("\n") } #[test] fn the_live_tab_leads_with_the_worst_source() { let model = Model::new(vec![ source("sando", now(), vec![node("a", "tier a", Status::Ok)]), source("bento", now(), vec![node("b", "goingson", Status::Failed)]), ]); let lines = draw(&model, now(), 80, 12); let text = joined(&lines); assert!( text.contains("live"), "the tab bar names the fixed tabs:\n{text}" ); assert!(text.contains("logs"), "{text}"); assert!(text.contains("store"), "{text}"); // Skip the tab bar, which names every tab regardless of order. let body = &lines[1..]; let bento = body.iter().position(|l| l.contains("bento")).unwrap(); let sando = body.iter().position(|l| l.contains("sando")).unwrap(); assert!(bento < sando, "the failing source must be on top:\n{text}"); assert!(text.contains("FAIL"), "{text}"); } #[test] fn no_source_gets_a_tab_of_its_own() { // The restructure, asserted directly: two sources, three tabs, and the // tab bar names none of them. let model = Model::new(vec![ source("sando", now(), vec![node("a", "tier a", Status::Ok)]), source("bento", now(), vec![node("b", "goingson", Status::Ok)]), ]); let bar = draw(&model, now(), 80, 12)[0].clone(); assert!( bar.contains("live") && bar.contains("logs") && bar.contains("store"), "{bar}" ); assert!( !bar.contains("sando"), "a source must not own a tab:\n{bar}" ); assert!(!bar.contains("bento"), "{bar}"); } #[test] fn a_source_that_has_never_answered_says_so_rather_than_showing_nothing() { let model = Model::new(vec![SourceState::new("bento", TimeDelta::seconds(60))]); let text = joined(&draw(&model, now(), 80, 12)); assert!( text.contains("????"), "an unreachable source must be loud:\n{text}" ); assert!(text.contains("waiting for first poll"), "{text}"); } #[test] fn a_stale_source_shows_its_age_on_the_live_tab() { let model = Model::new(vec![source( "pom", now() - TimeDelta::hours(4), vec![node("backup", "backup", Status::Ok)], )]); let text = joined(&draw(&model, now(), 80, 12)); assert!(text.contains("4h"), "the age must be visible:\n{text}"); assert!(text.contains("degr"), "stale-but-green is not ok:\n{text}"); } #[test] fn a_narrow_live_tab_drops_the_age_before_it_drops_the_detail() { // What the hand-written `Constraint`s could not do: at 80 columns every // column is drawn, and at a width where they no longer all fit the // priority decides which one goes rather than the order they were // written in. Age is the only Secondary column, so it is the only one // that can go. let model = Model::new(vec![source( "pom", now() - TimeDelta::hours(4), vec![node("backup", "backup", Status::Ok)], )]); let wide = joined(&draw(&model, now(), 80, 12)); assert!(wide.contains("age"), "the age column at 80 wide:\n{wide}"); let narrow = joined(&draw(&model, now(), 24, 12)); assert!(!narrow.contains("age"), "age must drop first:\n{narrow}"); assert!(narrow.contains("pom"), "the source stays:\n{narrow}"); assert!(narrow.contains("detail"), "the detail stays:\n{narrow}"); } #[test] fn the_live_tab_nests_nodes_under_their_source_and_children_under_those() { let mut parent = node("tier:b", "b (prod-1)", Status::Ok); parent.children = vec!["node:prod-1".into()]; let child = node("node:prod-1", "prod-1", Status::Ok); let mut model = Model::new(vec![source("sando", now(), vec![parent, child])]); model.selected = 1; let lines = draw(&model, now(), 80, 20); let text = joined(&lines); let source_row = lines .iter() .position(|l| l.contains("sando") && !l.contains("live")) .unwrap(); let parent_row = lines.iter().position(|l| l.contains("b (prod-1)")).unwrap(); let child_row = lines .iter() .rposition(|l| l.contains("prod-1") && !l.contains("b (prod-1)")) .unwrap(); assert!( source_row < parent_row, "the source leads its nodes:\n{text}" ); assert!(parent_row < child_row, "{text}"); // Each level is indented relative to the one above it. let source_col = lines[source_row].find("sando").unwrap(); let parent_col = lines[parent_row].find("b (prod-1)").unwrap(); let child_col = lines[child_row].find("prod-1").unwrap(); assert!( source_col < parent_col, "a node is indented under its source:\n{text}" ); assert!(parent_col < child_col, "child must be indented:\n{text}"); } #[test] fn the_detail_pane_shows_conditions_with_their_why() { let mut n = node("tier:b", "b", Status::Ok); n.conditions = vec![Condition { condition_type: "burn_in".into(), status: Status::Pending, since: None, detail: Some("17 hours remaining of 48".into()), }]; let mut model = Model::new(vec![source("sando", now(), vec![n])]); model.selected = 1; let text = joined(&draw(&model, now(), 80, 20)); assert!(text.contains("burn_in"), "{text}"); assert!( text.contains("17 hours remaining"), "a condition without its why is useless:\n{text}" ); } #[test] fn a_progress_field_renders_as_a_bar() { let mut n = node("tier:b", "b", Status::Ok); n.fields = vec![Field::new( "burn-in", Value::Progress { value: 31.0, max: 48.0, unit: Some("hour".into()), }, )]; let mut model = Model::new(vec![source("sando", now(), vec![n])]); model.selected = 1; let text = joined(&draw(&model, now(), 80, 20)); assert!(text.contains("31/48 hour"), "{text}"); assert!( text.contains('#'), "a progress value must draw a bar:\n{text}" ); } #[test] fn an_instant_renders_relative_to_the_passed_in_clock() { let mut n = node("tier:b", "b", Status::Ok); n.fields = vec![Field::new( "built", Value::Instant { value: now() - TimeDelta::minutes(3), }, )]; let mut model = Model::new(vec![source("sando", now(), vec![n])]); model.selected = 1; let text = joined(&draw(&model, now(), 80, 20)); assert!(text.contains("3m 0s ago"), "{text}"); } #[test] fn render_is_deterministic_for_a_fixed_clock() { // The property every snapshot test rests on. let mut n = node("tier:b", "b", Status::Ok); n.fields = vec![Field::new( "built", Value::Instant { value: now() - TimeDelta::minutes(3), }, )]; let mut model = Model::new(vec![source("sando", now(), vec![n])]); model.selected = 1; assert_eq!(draw(&model, now(), 80, 20), draw(&model, now(), 80, 20)); } #[test] fn an_unknown_value_kind_still_renders_as_text() { // Version skew: a producer one release ahead must not blank the pane. let field: Field = serde_json::from_str(r#"{"label":"temp","kind":"celsius","value":"41"}"#).unwrap(); let mut n = node("tier:b", "b", Status::Ok); n.fields = vec![field]; let mut model = Model::new(vec![source("sando", now(), vec![n])]); model.selected = 1; let text = joined(&draw(&model, now(), 80, 20)); assert!(text.contains("temp"), "{text}"); assert!(text.contains("41"), "{text}"); } #[test] fn a_narrow_terminal_does_not_panic() { // Every widget here has to survive a width no layout was designed for. let mut n = node("tier:b", "a rather long tier label", Status::Failed); n.fields = vec![Field::new( "path", Value::Path { value: "/srv/sando/releases/a3f9c21b7e4d8056/bin/makenotwork".into(), }, )]; n.conditions = vec![Condition { condition_type: "node_health".into(), status: Status::Failed, since: None, detail: Some("prod-1 unhealthy: connection refused after 30s".into()), }]; let mut model = Model::new(vec![source("sando", now(), vec![n])]); model.selected = 1; for width in [8_u16, 12, 20, 40] { for height in [4_u16, 8, 20] { let _ = draw(&model, now(), width, height); } } } #[test] fn a_multiline_detail_is_flattened_not_sprawled() { assert_eq!(truncate("a\nb", 40), "a b"); assert!(truncate(&"x".repeat(100), 10).ends_with('…')); assert_eq!(truncate(&"x".repeat(100), 10).chars().count(), 10); } fn action(label: &str, danger: bool) -> ops_status::Action { ops_status::Action { label: label.into(), method: ops_status::Method::Post, url: "/rollback/b".into(), confirm: true, danger, body: None, } } /// A source with one node declaring `keys`, actions allowed, on its tab. fn actionable(keys: &[(&str, bool)]) -> Model { let mut n = node("tier:b", "b (prod-1)", Status::Ok); n.actions = keys.iter().map(|(k, _)| k.to_string()).collect(); let mut p = Payload::new("sando", now()); p.nodes = vec![n]; p.actions = keys .iter() .map(|(k, d)| (k.to_string(), action(k, *d))) .collect(); let mut s = SourceState::new("sando", TimeDelta::seconds(60)).with_actions(true); s.observe(p, now()); let mut m = Model::new(vec![s]); // Row 0 is the source line, row 1 its only node. m.selected = 1; m } #[test] fn the_detail_hint_says_whether_actions_can_run() { let mut m = actionable(&[("rollback-b", true)]); let text = joined(&draw(&m, now(), 80, 20)); assert!(text.contains("rollback-b"), "{text}"); assert!(text.contains("enter to run"), "{text}"); m.sources[0].allow_actions = false; let text = joined(&draw(&m, now(), 80, 20)); assert!( text.contains("read-only"), "a disabled source must say so:\n{text}" ); } #[test] fn the_picker_lists_a_nodes_actions() { let mut m = actionable(&[("promote-b", false), ("rollback-b", true)]); m.open_actions(now()); let text = joined(&draw(&m, now(), 80, 20)); assert!(text.contains("run action"), "{text}"); assert!(text.contains("[promote-b]"), "{text}"); assert!(text.contains("[rollback-b]"), "{text}"); assert!(text.contains("enter run"), "{text}"); } #[test] fn a_danger_prompt_shows_the_key_to_type() { let mut m = actionable(&[("rollback-b", true)]); m.open_actions(now()); m.prompt_enter(); // Pick -> Type (danger) let text = joined(&draw(&m, now(), 80, 20)); assert!( text.contains("DANGER"), "a danger action must be loud:\n{text}" ); assert!( text.contains("type 'rollback-b'"), "the exact key to type must be shown:\n{text}" ); } #[test] fn a_retracted_action_is_named_in_the_confirmation_not_left_blank() { let mut m = actionable(&[("promote-b", false)]); m.open_actions(now()); m.prompt_enter(); // Pick -> Confirm (confirm, not danger) // A poll drops the action while the confirm box is up. let mut p = Payload::new("sando", now()); p.nodes = vec![node("tier:b", "b", Status::Ok)]; m.sources[0].observe(p, now()); let text = joined(&draw(&m, now(), 80, 20)); assert!(text.contains("no longer offered"), "{text}"); } fn with_events(name: &str, events: Vec) -> SourceState { let mut s = SourceState::new(name, TimeDelta::seconds(60)); let mut p = Payload::new(name, now()); p.events = events; s.observe(p, now()); s } fn ev(minutes_ago: i64, label: &str, status: Option) -> ops_status::Event { ops_status::Event { at: now() - TimeDelta::minutes(minutes_ago), label: label.into(), status, detail: None, node_id: None, } } #[test] fn the_logs_tab_shows_every_sources_events_with_who_said_it() { let mut model = Model::new(vec![ with_events("zebra", vec![ev(5, "sweep finished", Some(Status::Ok))]), with_events( "alpha", vec![ev(1, "promote refused", Some(Status::Failed))], ), ]); model.tab = crate::model::Tab::Logs; let lines = draw(&model, now(), 80, 14); let text = joined(&lines); assert!(text.contains("promote refused"), "{text}"); assert!(text.contains("sweep finished"), "{text}"); // Every line says who said it, so a line read alone is still readable. assert!(text.contains("alpha"), "{text}"); assert!(text.contains("zebra"), "{text}"); // Grouped by source, in name order. let alpha = lines.iter().position(|l| l.contains("alpha")).unwrap(); let zebra = lines.iter().position(|l| l.contains("zebra")).unwrap(); assert!(alpha < zebra, "sources group in name order:\n{text}"); // An event's own status colours it through the same marks as a node's. assert!(text.contains("FAIL"), "{text}"); } #[test] fn a_logs_tab_with_nothing_in_it_says_so_rather_than_showing_an_empty_box() { let mut model = Model::new(vec![source("sando", now(), vec![])]); model.tab = crate::model::Tab::Logs; let text = joined(&draw(&model, now(), 80, 14)); assert!(text.contains("no source has reported an event"), "{text}"); } #[test] fn an_event_with_no_status_is_a_note_and_gets_no_mark() { let mut model = Model::new(vec![with_events( "sando", vec![ev(1, "config reloaded", None)], )]); model.tab = crate::model::Tab::Logs; let lines = draw(&model, now(), 80, 14); let text = joined(&lines); let row = lines .iter() .find(|l| l.contains("config reloaded")) .unwrap_or_else(|| panic!("{text}")); // Only the event's own row: the header chip carries the worst status // across every source, which is a different claim. for mark in ["ok", "FAIL", "degr", "????"] { assert!( !row.contains(mark), "a note must not be given a verdict ({mark}):\n{text}" ); } } fn stored(series: &[(&str, &str, Option<&str>)], readings: Vec) -> Model { let mut store = crate::model::StoreState::new( "witchbroom", series .iter() .map(|(s, label, unit)| crate::config::Series { name: (*s).to_string(), label: (*label).to_string(), unit: unit.map(ToString::to_string), }) .collect(), ); store.observe(readings, now()); let mut model = Model::new(vec![]).with_stores(vec![store]); model.tab = crate::model::Tab::Store; model } fn stored_at(series: &str, labels: &str, value: f64, at: DateTime) -> crate::store::Reading { crate::store::Reading { series: series.into(), labels: labels.into(), value, at, } } #[test] fn the_store_tab_shows_a_configured_series_with_its_label_and_unit() { let model = stored( &[("soak.coverage_edges", "Coverage reached", Some("edges"))], vec![stored_at( "soak.coverage_edges", r#"{"repo":"mnw-server"}"#, 41_200.0, now() - TimeDelta::hours(2), )], ); let text = joined(&draw(&model, now(), 100, 14)); // The config's label, not the store's series name: the store cannot say // what a number means, so what is on screen is what the operator said. assert!(text.contains("Coverage reached"), "{text}"); assert!(!text.contains("soak.coverage_edges"), "{text}"); assert!( text.contains("edges"), "the unit comes from config:\n{text}" ); assert!(text.contains("41.2k"), "{text}"); assert!(text.contains("2h"), "how old the number is:\n{text}"); // The producer's dimensions, verbatim rather than parsed into columns. assert!(text.contains("mnw-server"), "{text}"); } #[test] fn a_configured_series_with_nothing_behind_it_is_shown_not_skipped() { // A soak target that has never reported is the thing worth noticing. let model = stored(&[("soak.coverage_edges", "Coverage reached", None)], vec![]); let text = joined(&draw(&model, now(), 100, 14)); assert!(text.contains("Coverage reached"), "{text}"); assert!(text.contains("no observations"), "{text}"); } #[test] fn an_unreadable_store_is_visibly_unavailable_rather_than_an_empty_tab() { let mut model = stored( &[("s", "Something", None)], vec![stored_at("s", "{}", 7.0, now())], ); model.stores[0].observe_error("unable to open database file"); let lines = draw(&model, now(), 100, 14); let text = joined(&lines); assert!(text.contains("unavailable"), "{text}"); assert!(text.contains("unable to open database file"), "{text}"); // Above the stale numbers, so they are not read as current. let bad = lines .iter() .position(|l| l.contains("unavailable")) .unwrap(); let old = lines.iter().position(|l| l.contains("Something")).unwrap(); assert!(bad < old, "{text}"); } #[test] fn a_store_tab_with_no_store_configured_says_so() { let mut model = Model::new(vec![source("sando", now(), vec![])]); model.tab = crate::model::Tab::Store; let text = joined(&draw(&model, now(), 80, 14)); assert!(text.contains("no [[store]] configured"), "{text}"); } #[test] fn the_detail_pane_on_a_source_line_shows_that_sources_summary() { // The cursor starts on a source line, which has no node to explain. let model = Model::new(vec![source( "sando", now(), vec![node("a", "tier a", Status::Ok)], )]); let text = joined(&draw(&model, now(), 80, 20)); assert!(text.contains("1 node ok"), "{text}"); } #[test] fn the_footer_shows_a_message_when_there_is_one() { let mut model = Model::new(vec![source("sando", now(), vec![])]); let text = joined(&draw(&model, now(), 80, 12)); assert!(text.contains("q quit"), "{text}"); model.message = Some("refreshing".into()); let text = joined(&draw(&model, now(), 80, 12)); assert!(text.contains("refreshing"), "{text}"); }