Skip to main content

max / makenotwork

19.2 KB · 577 lines History Blame Raw
1 //! Tests for [`super`].
2
3 use super::*;
4 use crate::model::SourceState;
5 use chrono::TimeDelta;
6 use ops_status::{Condition, Field, Payload, Status, Value};
7 use ratatui::Terminal;
8 use ratatui::backend::TestBackend;
9
10 fn now() -> DateTime<Utc> {
11 "2026-07-21T18:00:00Z".parse().unwrap()
12 }
13
14 /// Render a model into a fixed-size buffer and return it as text lines.
15 ///
16 /// This is the whole payoff of keeping render pure: the entire surface is
17 /// verifiable with no daemon running and no terminal attached.
18 fn draw(model: &Model, now: DateTime<Utc>, width: u16, height: u16) -> Vec<String> {
19 let theme = crate::theme::tests::fixed();
20 let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
21 terminal
22 .draw(|frame| render(model, &theme, now, frame))
23 .unwrap();
24 let buffer = terminal.backend().buffer().clone();
25 (0..buffer.area.height)
26 .map(|y| {
27 (0..buffer.area.width)
28 .map(|x| buffer[(x, y)].symbol().to_string())
29 .collect::<String>()
30 .trim_end()
31 .to_string()
32 })
33 .collect()
34 }
35
36 fn node(id: &str, label: &str, status: Status) -> Node {
37 Node {
38 id: id.into(),
39 kind: "tier".into(),
40 label: label.into(),
41 status,
42 fields: Vec::new(),
43 conditions: Vec::new(),
44 children: Vec::new(),
45 actions: Vec::new(),
46 }
47 }
48
49 fn source(name: &str, at: DateTime<Utc>, nodes: Vec<Node>) -> SourceState {
50 let mut s = SourceState::new(name, TimeDelta::seconds(60));
51 let mut p = Payload::new(name, at);
52 p.nodes = nodes;
53 s.observe(p, at);
54 s
55 }
56
57 fn joined(lines: &[String]) -> String {
58 lines.join("\n")
59 }
60
61 #[test]
62 fn the_live_tab_leads_with_the_worst_source() {
63 let model = Model::new(vec![
64 source("sando", now(), vec![node("a", "tier a", Status::Ok)]),
65 source("bento", now(), vec![node("b", "goingson", Status::Failed)]),
66 ]);
67 let lines = draw(&model, now(), 80, 12);
68 let text = joined(&lines);
69
70 assert!(
71 text.contains("live"),
72 "the tab bar names the fixed tabs:\n{text}"
73 );
74 assert!(text.contains("logs"), "{text}");
75 assert!(text.contains("store"), "{text}");
76 // Skip the tab bar, which names every tab regardless of order.
77 let body = &lines[1..];
78 let bento = body.iter().position(|l| l.contains("bento")).unwrap();
79 let sando = body.iter().position(|l| l.contains("sando")).unwrap();
80 assert!(bento < sando, "the failing source must be on top:\n{text}");
81 assert!(text.contains("FAIL"), "{text}");
82 }
83
84 #[test]
85 fn no_source_gets_a_tab_of_its_own() {
86 // The restructure, asserted directly: two sources, three tabs, and the
87 // tab bar names none of them.
88 let model = Model::new(vec![
89 source("sando", now(), vec![node("a", "tier a", Status::Ok)]),
90 source("bento", now(), vec![node("b", "goingson", Status::Ok)]),
91 ]);
92 let bar = draw(&model, now(), 80, 12)[0].clone();
93 assert!(
94 bar.contains("live") && bar.contains("logs") && bar.contains("store"),
95 "{bar}"
96 );
97 assert!(
98 !bar.contains("sando"),
99 "a source must not own a tab:\n{bar}"
100 );
101 assert!(!bar.contains("bento"), "{bar}");
102 }
103
104 #[test]
105 fn a_source_that_has_never_answered_says_so_rather_than_showing_nothing() {
106 let model = Model::new(vec![SourceState::new("bento", TimeDelta::seconds(60))]);
107 let text = joined(&draw(&model, now(), 80, 12));
108 assert!(
109 text.contains("????"),
110 "an unreachable source must be loud:\n{text}"
111 );
112 assert!(text.contains("waiting for first poll"), "{text}");
113 }
114
115 #[test]
116 fn a_stale_source_shows_its_age_on_the_live_tab() {
117 let model = Model::new(vec![source(
118 "pom",
119 now() - TimeDelta::hours(4),
120 vec![node("backup", "backup", Status::Ok)],
121 )]);
122 let text = joined(&draw(&model, now(), 80, 12));
123 assert!(text.contains("4h"), "the age must be visible:\n{text}");
124 assert!(text.contains("degr"), "stale-but-green is not ok:\n{text}");
125 }
126
127 #[test]
128 fn a_narrow_live_tab_drops_the_age_before_it_drops_the_detail() {
129 // What the hand-written `Constraint`s could not do: at 80 columns every
130 // column is drawn, and at a width where they no longer all fit the
131 // priority decides which one goes rather than the order they were
132 // written in. Age is the only Secondary column, so it is the only one
133 // that can go.
134 let model = Model::new(vec![source(
135 "pom",
136 now() - TimeDelta::hours(4),
137 vec![node("backup", "backup", Status::Ok)],
138 )]);
139
140 let wide = joined(&draw(&model, now(), 80, 12));
141 assert!(wide.contains("age"), "the age column at 80 wide:\n{wide}");
142
143 let narrow = joined(&draw(&model, now(), 24, 12));
144 assert!(!narrow.contains("age"), "age must drop first:\n{narrow}");
145 assert!(narrow.contains("pom"), "the source stays:\n{narrow}");
146 assert!(narrow.contains("detail"), "the detail stays:\n{narrow}");
147 }
148
149 #[test]
150 fn the_live_tab_nests_nodes_under_their_source_and_children_under_those() {
151 let mut parent = node("tier:b", "b (prod-1)", Status::Ok);
152 parent.children = vec!["node:prod-1".into()];
153 let child = node("node:prod-1", "prod-1", Status::Ok);
154
155 let mut model = Model::new(vec![source("sando", now(), vec![parent, child])]);
156 model.selected = 1;
157 let lines = draw(&model, now(), 80, 20);
158 let text = joined(&lines);
159
160 let source_row = lines
161 .iter()
162 .position(|l| l.contains("sando") && !l.contains("live"))
163 .unwrap();
164 let parent_row = lines.iter().position(|l| l.contains("b (prod-1)")).unwrap();
165 let child_row = lines
166 .iter()
167 .rposition(|l| l.contains("prod-1") && !l.contains("b (prod-1)"))
168 .unwrap();
169 assert!(
170 source_row < parent_row,
171 "the source leads its nodes:\n{text}"
172 );
173 assert!(parent_row < child_row, "{text}");
174
175 // Each level is indented relative to the one above it.
176 let source_col = lines[source_row].find("sando").unwrap();
177 let parent_col = lines[parent_row].find("b (prod-1)").unwrap();
178 let child_col = lines[child_row].find("prod-1").unwrap();
179 assert!(
180 source_col < parent_col,
181 "a node is indented under its source:\n{text}"
182 );
183 assert!(parent_col < child_col, "child must be indented:\n{text}");
184 }
185
186 #[test]
187 fn the_detail_pane_shows_conditions_with_their_why() {
188 let mut n = node("tier:b", "b", Status::Ok);
189 n.conditions = vec![Condition {
190 condition_type: "burn_in".into(),
191 status: Status::Pending,
192 since: None,
193 detail: Some("17 hours remaining of 48".into()),
194 }];
195 let mut model = Model::new(vec![source("sando", now(), vec![n])]);
196 model.selected = 1;
197 let text = joined(&draw(&model, now(), 80, 20));
198
199 assert!(text.contains("burn_in"), "{text}");
200 assert!(
201 text.contains("17 hours remaining"),
202 "a condition without its why is useless:\n{text}"
203 );
204 }
205
206 #[test]
207 fn a_progress_field_renders_as_a_bar() {
208 let mut n = node("tier:b", "b", Status::Ok);
209 n.fields = vec![Field::new(
210 "burn-in",
211 Value::Progress {
212 value: 31.0,
213 max: 48.0,
214 unit: Some("hour".into()),
215 },
216 )];
217 let mut model = Model::new(vec![source("sando", now(), vec![n])]);
218 model.selected = 1;
219 let text = joined(&draw(&model, now(), 80, 20));
220
221 assert!(text.contains("31/48 hour"), "{text}");
222 assert!(
223 text.contains('#'),
224 "a progress value must draw a bar:\n{text}"
225 );
226 }
227
228 #[test]
229 fn an_instant_renders_relative_to_the_passed_in_clock() {
230 let mut n = node("tier:b", "b", Status::Ok);
231 n.fields = vec![Field::new(
232 "built",
233 Value::Instant {
234 value: now() - TimeDelta::minutes(3),
235 },
236 )];
237 let mut model = Model::new(vec![source("sando", now(), vec![n])]);
238 model.selected = 1;
239 let text = joined(&draw(&model, now(), 80, 20));
240 assert!(text.contains("3m 0s ago"), "{text}");
241 }
242
243 #[test]
244 fn render_is_deterministic_for_a_fixed_clock() {
245 // The property every snapshot test rests on.
246 let mut n = node("tier:b", "b", Status::Ok);
247 n.fields = vec![Field::new(
248 "built",
249 Value::Instant {
250 value: now() - TimeDelta::minutes(3),
251 },
252 )];
253 let mut model = Model::new(vec![source("sando", now(), vec![n])]);
254 model.selected = 1;
255 assert_eq!(draw(&model, now(), 80, 20), draw(&model, now(), 80, 20));
256 }
257
258 #[test]
259 fn an_unknown_value_kind_still_renders_as_text() {
260 // Version skew: a producer one release ahead must not blank the pane.
261 let field: Field =
262 serde_json::from_str(r#"{"label":"temp","kind":"celsius","value":"41"}"#).unwrap();
263 let mut n = node("tier:b", "b", Status::Ok);
264 n.fields = vec![field];
265 let mut model = Model::new(vec![source("sando", now(), vec![n])]);
266 model.selected = 1;
267 let text = joined(&draw(&model, now(), 80, 20));
268 assert!(text.contains("temp"), "{text}");
269 assert!(text.contains("41"), "{text}");
270 }
271
272 #[test]
273 fn a_narrow_terminal_does_not_panic() {
274 // Every widget here has to survive a width no layout was designed for.
275 let mut n = node("tier:b", "a rather long tier label", Status::Failed);
276 n.fields = vec![Field::new(
277 "path",
278 Value::Path {
279 value: "/srv/sando/releases/a3f9c21b7e4d8056/bin/makenotwork".into(),
280 },
281 )];
282 n.conditions = vec![Condition {
283 condition_type: "node_health".into(),
284 status: Status::Failed,
285 since: None,
286 detail: Some("prod-1 unhealthy: connection refused after 30s".into()),
287 }];
288 let mut model = Model::new(vec![source("sando", now(), vec![n])]);
289 model.selected = 1;
290 for width in [8_u16, 12, 20, 40] {
291 for height in [4_u16, 8, 20] {
292 let _ = draw(&model, now(), width, height);
293 }
294 }
295 }
296
297 #[test]
298 fn a_multiline_detail_is_flattened_not_sprawled() {
299 assert_eq!(truncate("a\nb", 40), "a b");
300 assert!(truncate(&"x".repeat(100), 10).ends_with('…'));
301 assert_eq!(truncate(&"x".repeat(100), 10).chars().count(), 10);
302 }
303
304 fn action(label: &str, danger: bool) -> ops_status::Action {
305 ops_status::Action {
306 label: label.into(),
307 method: ops_status::Method::Post,
308 url: "/rollback/b".into(),
309 confirm: true,
310 danger,
311 body: None,
312 }
313 }
314
315 /// A source with one node declaring `keys`, actions allowed, on its tab.
316 fn actionable(keys: &[(&str, bool)]) -> Model {
317 let mut n = node("tier:b", "b (prod-1)", Status::Ok);
318 n.actions = keys.iter().map(|(k, _)| k.to_string()).collect();
319 let mut p = Payload::new("sando", now());
320 p.nodes = vec![n];
321 p.actions = keys
322 .iter()
323 .map(|(k, d)| (k.to_string(), action(k, *d)))
324 .collect();
325 let mut s = SourceState::new("sando", TimeDelta::seconds(60)).with_actions(true);
326 s.observe(p, now());
327 let mut m = Model::new(vec![s]);
328 // Row 0 is the source line, row 1 its only node.
329 m.selected = 1;
330 m
331 }
332
333 #[test]
334 fn the_detail_hint_says_whether_actions_can_run() {
335 let mut m = actionable(&[("rollback-b", true)]);
336 let text = joined(&draw(&m, now(), 80, 20));
337 assert!(text.contains("rollback-b"), "{text}");
338 assert!(text.contains("enter to run"), "{text}");
339
340 m.sources[0].allow_actions = false;
341 let text = joined(&draw(&m, now(), 80, 20));
342 assert!(
343 text.contains("read-only"),
344 "a disabled source must say so:\n{text}"
345 );
346 }
347
348 #[test]
349 fn the_picker_lists_a_nodes_actions() {
350 let mut m = actionable(&[("promote-b", false), ("rollback-b", true)]);
351 m.open_actions(now());
352 let text = joined(&draw(&m, now(), 80, 20));
353 assert!(text.contains("run action"), "{text}");
354 assert!(text.contains("[promote-b]"), "{text}");
355 assert!(text.contains("[rollback-b]"), "{text}");
356 assert!(text.contains("enter run"), "{text}");
357 }
358
359 #[test]
360 fn a_danger_prompt_shows_the_key_to_type() {
361 let mut m = actionable(&[("rollback-b", true)]);
362 m.open_actions(now());
363 m.prompt_enter(); // Pick -> Type (danger)
364 let text = joined(&draw(&m, now(), 80, 20));
365 assert!(
366 text.contains("DANGER"),
367 "a danger action must be loud:\n{text}"
368 );
369 assert!(
370 text.contains("type 'rollback-b'"),
371 "the exact key to type must be shown:\n{text}"
372 );
373 }
374
375 #[test]
376 fn a_retracted_action_is_named_in_the_confirmation_not_left_blank() {
377 let mut m = actionable(&[("promote-b", false)]);
378 m.open_actions(now());
379 m.prompt_enter(); // Pick -> Confirm (confirm, not danger)
380 // A poll drops the action while the confirm box is up.
381 let mut p = Payload::new("sando", now());
382 p.nodes = vec![node("tier:b", "b", Status::Ok)];
383 m.sources[0].observe(p, now());
384 let text = joined(&draw(&m, now(), 80, 20));
385 assert!(text.contains("no longer offered"), "{text}");
386 }
387
388 fn with_events(name: &str, events: Vec<ops_status::Event>) -> SourceState {
389 let mut s = SourceState::new(name, TimeDelta::seconds(60));
390 let mut p = Payload::new(name, now());
391 p.events = events;
392 s.observe(p, now());
393 s
394 }
395
396 fn ev(minutes_ago: i64, label: &str, status: Option<Status>) -> ops_status::Event {
397 ops_status::Event {
398 at: now() - TimeDelta::minutes(minutes_ago),
399 label: label.into(),
400 status,
401 detail: None,
402 node_id: None,
403 }
404 }
405
406 #[test]
407 fn the_logs_tab_shows_every_sources_events_with_who_said_it() {
408 let mut model = Model::new(vec![
409 with_events("zebra", vec![ev(5, "sweep finished", Some(Status::Ok))]),
410 with_events(
411 "alpha",
412 vec![ev(1, "promote refused", Some(Status::Failed))],
413 ),
414 ]);
415 model.tab = crate::model::Tab::Logs;
416 let lines = draw(&model, now(), 80, 14);
417 let text = joined(&lines);
418
419 assert!(text.contains("promote refused"), "{text}");
420 assert!(text.contains("sweep finished"), "{text}");
421 // Every line says who said it, so a line read alone is still readable.
422 assert!(text.contains("alpha"), "{text}");
423 assert!(text.contains("zebra"), "{text}");
424 // Grouped by source, in name order.
425 let alpha = lines.iter().position(|l| l.contains("alpha")).unwrap();
426 let zebra = lines.iter().position(|l| l.contains("zebra")).unwrap();
427 assert!(alpha < zebra, "sources group in name order:\n{text}");
428 // An event's own status colours it through the same marks as a node's.
429 assert!(text.contains("FAIL"), "{text}");
430 }
431
432 #[test]
433 fn a_logs_tab_with_nothing_in_it_says_so_rather_than_showing_an_empty_box() {
434 let mut model = Model::new(vec![source("sando", now(), vec![])]);
435 model.tab = crate::model::Tab::Logs;
436 let text = joined(&draw(&model, now(), 80, 14));
437 assert!(text.contains("no source has reported an event"), "{text}");
438 }
439
440 #[test]
441 fn an_event_with_no_status_is_a_note_and_gets_no_mark() {
442 let mut model = Model::new(vec![with_events(
443 "sando",
444 vec![ev(1, "config reloaded", None)],
445 )]);
446 model.tab = crate::model::Tab::Logs;
447 let lines = draw(&model, now(), 80, 14);
448 let text = joined(&lines);
449 let row = lines
450 .iter()
451 .find(|l| l.contains("config reloaded"))
452 .unwrap_or_else(|| panic!("{text}"));
453 // Only the event's own row: the header chip carries the worst status
454 // across every source, which is a different claim.
455 for mark in ["ok", "FAIL", "degr", "????"] {
456 assert!(
457 !row.contains(mark),
458 "a note must not be given a verdict ({mark}):\n{text}"
459 );
460 }
461 }
462
463 fn stored(series: &[(&str, &str, Option<&str>)], readings: Vec<crate::store::Reading>) -> Model {
464 let mut store = crate::model::StoreState::new(
465 "witchbroom",
466 series
467 .iter()
468 .map(|(s, label, unit)| crate::config::Series {
469 name: (*s).to_string(),
470 label: (*label).to_string(),
471 unit: unit.map(ToString::to_string),
472 })
473 .collect(),
474 );
475 store.observe(readings, now());
476 let mut model = Model::new(vec![]).with_stores(vec![store]);
477 model.tab = crate::model::Tab::Store;
478 model
479 }
480
481 fn stored_at(series: &str, labels: &str, value: f64, at: DateTime<Utc>) -> crate::store::Reading {
482 crate::store::Reading {
483 series: series.into(),
484 labels: labels.into(),
485 value,
486 at,
487 }
488 }
489
490 #[test]
491 fn the_store_tab_shows_a_configured_series_with_its_label_and_unit() {
492 let model = stored(
493 &[("soak.coverage_edges", "Coverage reached", Some("edges"))],
494 vec![stored_at(
495 "soak.coverage_edges",
496 r#"{"repo":"mnw-server"}"#,
497 41_200.0,
498 now() - TimeDelta::hours(2),
499 )],
500 );
501 let text = joined(&draw(&model, now(), 100, 14));
502
503 // The config's label, not the store's series name: the store cannot say
504 // what a number means, so what is on screen is what the operator said.
505 assert!(text.contains("Coverage reached"), "{text}");
506 assert!(!text.contains("soak.coverage_edges"), "{text}");
507 assert!(
508 text.contains("edges"),
509 "the unit comes from config:\n{text}"
510 );
511 assert!(text.contains("41.2k"), "{text}");
512 assert!(text.contains("2h"), "how old the number is:\n{text}");
513 // The producer's dimensions, verbatim rather than parsed into columns.
514 assert!(text.contains("mnw-server"), "{text}");
515 }
516
517 #[test]
518 fn a_configured_series_with_nothing_behind_it_is_shown_not_skipped() {
519 // A soak target that has never reported is the thing worth noticing.
520 let model = stored(&[("soak.coverage_edges", "Coverage reached", None)], vec![]);
521 let text = joined(&draw(&model, now(), 100, 14));
522 assert!(text.contains("Coverage reached"), "{text}");
523 assert!(text.contains("no observations"), "{text}");
524 }
525
526 #[test]
527 fn an_unreadable_store_is_visibly_unavailable_rather_than_an_empty_tab() {
528 let mut model = stored(
529 &[("s", "Something", None)],
530 vec![stored_at("s", "{}", 7.0, now())],
531 );
532 model.stores[0].observe_error("unable to open database file");
533 let lines = draw(&model, now(), 100, 14);
534 let text = joined(&lines);
535
536 assert!(text.contains("unavailable"), "{text}");
537 assert!(text.contains("unable to open database file"), "{text}");
538 // Above the stale numbers, so they are not read as current.
539 let bad = lines
540 .iter()
541 .position(|l| l.contains("unavailable"))
542 .unwrap();
543 let old = lines.iter().position(|l| l.contains("Something")).unwrap();
544 assert!(bad < old, "{text}");
545 }
546
547 #[test]
548 fn a_store_tab_with_no_store_configured_says_so() {
549 let mut model = Model::new(vec![source("sando", now(), vec![])]);
550 model.tab = crate::model::Tab::Store;
551 let text = joined(&draw(&model, now(), 80, 14));
552 assert!(text.contains("no [[store]] configured"), "{text}");
553 }
554
555 #[test]
556 fn the_detail_pane_on_a_source_line_shows_that_sources_summary() {
557 // The cursor starts on a source line, which has no node to explain.
558 let model = Model::new(vec![source(
559 "sando",
560 now(),
561 vec![node("a", "tier a", Status::Ok)],
562 )]);
563 let text = joined(&draw(&model, now(), 80, 20));
564 assert!(text.contains("1 node ok"), "{text}");
565 }
566
567 #[test]
568 fn the_footer_shows_a_message_when_there_is_one() {
569 let mut model = Model::new(vec![source("sando", now(), vec![])]);
570 let text = joined(&draw(&model, now(), 80, 12));
571 assert!(text.contains("q quit"), "{text}");
572
573 model.message = Some("refreshing".into());
574 let text = joined(&draw(&model, now(), 80, 12));
575 assert!(text.contains("refreshing"), "{text}");
576 }
577