1use ratatui::Frame;
9use ratatui::layout::Rect;
10use ratatui::style::{Color, Modifier, Style};
11use ratatui::text::{Line, Span};
12use ratatui::widgets::{Paragraph, Wrap};
13use time::format_description::well_known::Rfc3339;
14use time::{OffsetDateTime, UtcOffset};
15
16use crate::tui::keys::{BINDINGS, binding};
17use crate::tui::state::{Action, Connection, Listing, Row, State, View};
18
19const MIN_COLUMNS: u16 = 40;
21const MIN_LINES: u16 = 8;
22const ZONE: &str = "UTC+00:00";
24const UUID_COLUMNS: u16 = 38;
27const TIME_COLUMNS: u16 = 21;
28const VERSION_COLUMNS: u16 = 34;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub struct Theme {
33 pub color: bool,
35}
36
37#[must_use]
41pub fn theme(no_color: Option<&str>, term: Option<&str>) -> Theme {
42 let refused = no_color.is_some_and(|value| !value.is_empty());
43 let capable = term.is_some_and(|term| term != "dumb");
44 Theme {
45 color: capable && !refused,
46 }
47}
48
49#[must_use]
52pub fn utc(text: &str) -> String {
53 OffsetDateTime::parse(text, &Rfc3339).map_or_else(|_| text.to_owned(), stamp)
54}
55
56fn stamp(at: OffsetDateTime) -> String {
58 let at = at.to_offset(UtcOffset::UTC);
59 format!(
60 "{:04}-{:02}-{:02} {:02}:{:02}:{:02}",
61 at.year(),
62 u8::from(at.month()),
63 at.day(),
64 at.hour(),
65 at.minute(),
66 at.second()
67 )
68}
69
70pub fn draw(frame: &mut Frame<'_>, state: &State, theme: Theme) {
72 let area = frame.area();
73 if area.width < MIN_COLUMNS || area.height < MIN_LINES {
74 let message = format!(
75 "Terminal too small: {MIN_COLUMNS}x{MIN_LINES} is needed. Enlarge it, or press q to quit."
76 );
77 frame.render_widget(Paragraph::new(message).wrap(Wrap { trim: true }), area);
78 return;
79 }
80 let line = |y: u16| Rect {
81 y: area.y.saturating_add(y),
82 height: 1,
83 ..area
84 };
85 let most = usize::from(area.height.saturating_sub(2) / 2).max(1);
88 let said = fitted(¬ice(state), usize::from(area.width), most);
89 let notice_lines = u16::try_from(said.len()).unwrap_or(1).max(1);
90 let body = Rect {
91 y: area.y.saturating_add(1),
92 height: area.height.saturating_sub(notice_lines.saturating_add(2)),
93 ..area
94 };
95 frame.render_widget(Paragraph::new(status(state, area.width, theme)), line(0));
96 match state.view {
97 View::List => list(frame, state, body),
98 View::Detail => detail(frame, state, body),
99 View::Help => help(frame, body),
100 }
101 let said: Vec<Line<'_>> = said.into_iter().map(Line::from).collect();
102 frame.render_widget(
103 Paragraph::new(said),
104 Rect {
105 y: area.y.saturating_add(body.height).saturating_add(1),
106 height: notice_lines,
107 ..area
108 },
109 );
110 frame.render_widget(
111 Paragraph::new(hints(state, usize::from(area.width))),
112 line(area.height.saturating_sub(1)),
113 );
114}
115
116fn wrapped(text: &str, columns: usize) -> Vec<String> {
119 let columns = columns.max(1);
120 let mut lines: Vec<String> = Vec::new();
121 let mut line = String::new();
122 let mut used = 0_usize;
123 for word in text.split(' ').filter(|word| !word.is_empty()) {
124 let mut rest: Vec<char> = word.chars().collect();
125 if used > 0 && used.saturating_add(1).saturating_add(rest.len()) > columns {
126 lines.push(std::mem::take(&mut line));
127 used = 0;
128 }
129 while rest.len() > columns {
130 lines.push(rest.drain(..columns).collect());
131 }
132 if used > 0 {
133 line.push(' ');
134 used = used.saturating_add(1);
135 }
136 used = used.saturating_add(rest.len());
137 line.extend(rest);
138 }
139 if !line.is_empty() {
140 lines.push(line);
141 }
142 lines
143}
144
145fn fitted(parts: &[String], columns: usize, most: usize) -> Vec<String> {
150 let whole = parts.join(BETWEEN);
151 if whole.chars().count() <= columns {
152 return vec![whole];
153 }
154 let mut lines: Vec<String> = parts
155 .iter()
156 .flat_map(|part| wrapped(part, columns))
157 .collect();
158 if lines.len() > most {
159 lines.truncate(most);
160 if let Some(last) = lines.last_mut() {
161 let kept = columns.saturating_sub(CUT.chars().count());
162 *last = last.chars().take(kept).collect();
163 last.push_str(CUT);
164 }
165 }
166 lines
167}
168
169enum Owner<'a> {
171 Unknown,
173 Operator,
175 Tenant(&'a str),
177}
178
179const SCHEME: &str = "https://";
181const BETWEEN: &str = " | ";
183const CUT: &str = "...";
185const ID_MIN: usize = 4;
187
188fn status_lead(server: &str, owner: &Owner<'_>, word: &str, columns: usize) -> String {
204 let length = |text: &str| text.chars().count();
205 let owner_whole = match owner {
206 Owner::Unknown => "tenant unknown".to_owned(),
207 Owner::Operator => "no tenant (operator key)".to_owned(),
208 Owner::Tenant(id) => format!("tenant {id}"),
209 };
210 let room = columns.saturating_sub(length(word));
212 let with_owner = |address: &str, owner: &str| format!("{address}{BETWEEN}{owner}{BETWEEN}");
213 let whole = with_owner(server, &owner_whole);
214 if length(&whole) <= room {
215 return whole;
216 }
217 let bare = server.strip_prefix(SCHEME).unwrap_or(server);
218 let unschemed = with_owner(bare, &owner_whole);
219 if length(&unschemed) <= room {
220 return unschemed;
221 }
222 if let Owner::Tenant(id) = owner {
223 let around = length(&with_owner(bare, "tenant ")).saturating_add(length(CUT));
224 let kept = room.saturating_sub(around);
225 if kept >= ID_MIN {
226 let id: String = id.chars().take(kept).collect();
227 return with_owner(bare, &format!("tenant {id}{CUT}"));
228 }
229 }
230 let alone = format!("{bare}{BETWEEN}");
231 if length(&alone) <= room {
232 return alone;
233 }
234 let kept = room.saturating_sub(length(BETWEEN).saturating_add(length(CUT)));
235 let address: String = bare.chars().take(kept).collect();
236 format!("{address}{CUT}{BETWEEN}")
237}
238
239fn status(state: &State, columns: u16, theme: Theme) -> Line<'static> {
242 let (owner, word, color) = match &state.connection {
243 Connection::Connecting => (Owner::Unknown, "connecting", Color::Yellow),
244 Connection::Failed(_) => (Owner::Unknown, "not connected", Color::Red),
245 Connection::Connected(info) => (
246 info.tenant
247 .as_deref()
248 .map_or(Owner::Operator, Owner::Tenant),
249 "connected",
250 Color::Green,
251 ),
252 };
253 let lead = status_lead(&state.server, &owner, word, usize::from(columns));
254 let mut style = Style::new().add_modifier(Modifier::BOLD);
255 if theme.color {
256 style = style.fg(color);
257 }
258 Line::from(vec![Span::raw(lead), Span::styled(word, style)])
259}
260
261fn message(frame: &mut Frame<'_>, body: Rect, lines: Vec<String>) {
263 let lines: Vec<Line<'_>> = lines.into_iter().map(Line::from).collect();
264 frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), body);
265}
266
267fn waiting(state: &State, loading: &str) -> Option<Vec<String>> {
270 if state.connection == Connection::Connecting {
271 return Some(vec![
272 "Connecting to the server...".to_owned(),
273 String::new(),
274 "Press q to quit.".to_owned(),
275 ]);
276 }
277 match &state.listing {
278 Listing::Ready => None,
279 Listing::Loading => Some(vec![
280 loading.to_owned(),
281 String::new(),
282 "Press q to quit.".to_owned(),
283 ]),
284 Listing::Failed(why) => {
285 let mut lines = vec![format!("Could not list vCons: {why}."), String::new()];
286 if why.contains("(401)") {
287 lines
288 .push("Check that key_file holds a key the server has not revoked.".to_owned());
289 }
290 lines.push(if state.acts(Action::Refresh) {
293 "Press r to try again, or q to quit.".to_owned()
294 } else {
295 "Press q to quit.".to_owned()
296 });
297 lines.push(
300 "A change to the client file or the key file takes effect at the next start."
301 .to_owned(),
302 );
303 Some(lines)
304 }
305 }
306}
307
308fn list(frame: &mut Frame<'_>, state: &State, body: Rect) {
310 if let Some(lines) = waiting(state, "Loading vCons...") {
311 return message(frame, body, lines);
312 }
313 if state.rows.is_empty() {
314 let lines = vec![
315 "This tenant has no vCons.".to_owned(),
316 String::new(),
317 "Press r to read again, or q to quit.".to_owned(),
318 ];
319 return message(frame, body, lines);
320 }
321 let times = u16::from(body.width >= UUID_COLUMNS.saturating_add(TIME_COLUMNS)).saturating_add(
322 u16::from(body.width >= UUID_COLUMNS.saturating_add(TIME_COLUMNS.saturating_mul(2))),
323 );
324 let version = body.width
325 >= UUID_COLUMNS
326 .saturating_add(TIME_COLUMNS.saturating_mul(2))
327 .saturating_add(VERSION_COLUMNS);
328 let columns = |marker: &str, uuid: &str, stored: &str, updated: &str, tag: &str| {
329 let mut text = format!("{marker}{uuid:<36}");
330 if times >= 1 {
331 text.push_str(&format!(" {stored:<19}"));
332 }
333 if times >= 2 {
334 text.push_str(&format!(" {updated:<19}"));
335 }
336 if version {
337 text.push_str(&format!(" {tag}"));
338 }
339 text
340 };
341 let visible = usize::from(body.height.saturating_sub(1));
342 let first = state.selected.saturating_add(1).saturating_sub(visible);
343 let mut lines = vec![Line::styled(
344 columns(
345 " ",
346 "UUID",
347 &format!("STORED ({ZONE})"),
348 &format!("UPDATED ({ZONE})"),
349 "VERSION",
350 ),
351 Style::new().add_modifier(Modifier::BOLD),
352 )];
353 for (index, row) in state.rows.iter().enumerate().skip(first).take(visible) {
354 let selected = index == state.selected;
355 let text = columns(
356 if selected { "> " } else { " " },
357 &row.uuid,
358 &utc(&row.stored_at),
359 &utc(&row.updated_at),
360 &row.version,
361 );
362 let style = if selected {
363 Style::new().add_modifier(Modifier::REVERSED)
364 } else {
365 Style::new()
366 };
367 lines.push(Line::styled(text, style));
368 }
369 frame.render_widget(Paragraph::new(lines), body);
370}
371
372fn detail(frame: &mut Frame<'_>, state: &State, body: Rect) {
374 if let Some(lines) = waiting(state, "Reading the list again...") {
375 return message(frame, body, lines);
376 }
377 let lines = match state.detail_row() {
378 Some(row) => metadata(row),
379 None => vec![
380 "This vCon is no longer in the list: it was deleted, or it is past the pages read."
381 .to_owned(),
382 String::new(),
383 "Press Esc to go back.".to_owned(),
384 ],
385 };
386 message(frame, body, lines);
387}
388
389fn metadata(row: &Row) -> Vec<String> {
391 vec![
392 format!("vCon {}", row.uuid),
393 String::new(),
394 format!("Version {}", row.version),
395 format!("First stored {} {ZONE}", utc(&row.stored_at)),
396 format!("Last updated {} {ZONE}", utc(&row.updated_at)),
397 String::new(),
398 "Content is not shown: this view lists metadata only.".to_owned(),
399 ]
400}
401
402fn help(frame: &mut Frame<'_>, body: Rect) {
404 let mut lines = vec!["Keys".to_owned()];
405 for binding in &BINDINGS {
406 lines.push(format!(" {:<7}{}", binding.label, binding.does));
407 }
408 lines.push(String::new());
409 lines.push(format!("Every time shown is in UTC ({ZONE})."));
410 message(frame, body, lines);
411}
412
413fn notice(state: &State) -> Vec<String> {
417 if let Some(notice) = &state.notice {
418 return vec![notice.clone()];
419 }
420 if state.more {
421 return vec!["Reading the next page...".to_owned()];
422 }
423 let (Listing::Ready, Some(as_of)) = (&state.listing, state.as_of) else {
424 return Vec::new();
425 };
426 let as_of = format!("as of {} {ZONE}", stamp(as_of));
427 if state.rows.is_empty() {
428 return vec![as_of];
429 }
430 let more = if state.next.is_some() {
431 ", more on the server"
432 } else {
433 ""
434 };
435 vec![
436 format!(
437 "{} of {} read{more}",
438 state.selected.saturating_add(1),
439 state.rows.len()
440 ),
441 as_of,
442 ]
443}
444
445fn hints(state: &State, columns: usize) -> String {
450 const KEPT: usize = 2;
452 let mut shown = state_hints(state);
453 let length = |shown: &[String]| {
454 shown
455 .iter()
456 .map(|hint| hint.chars().count())
457 .sum::<usize>()
458 .saturating_add(shown.len().saturating_sub(1).saturating_mul(2))
459 };
460 while shown.len() > KEPT && length(&shown) > columns {
461 shown.remove(shown.len().saturating_sub(KEPT).saturating_sub(1));
462 }
463 shown.join(" ")
464}
465
466fn state_hints(state: &State) -> Vec<String> {
470 let actions: &[Action] = match state.view {
471 View::List => &[
472 Action::Down,
473 Action::Up,
474 Action::Open,
475 Action::Refresh,
476 Action::More,
477 Action::Help,
478 Action::Quit,
479 ],
480 View::Detail => &[
481 Action::Back,
482 Action::Down,
483 Action::Up,
484 Action::Refresh,
485 Action::Help,
486 Action::Quit,
487 ],
488 View::Help => &[Action::Back, Action::Quit],
489 };
490 actions
491 .iter()
492 .filter(|action| state.acts(**action))
493 .filter_map(|action| binding(*action))
494 .map(|binding| format!("{} {}", binding.label, binding.hint))
495 .collect()
496}
497
498#[cfg(test)]
499mod tests {
500 use ratatui::Terminal;
501 use ratatui::backend::TestBackend;
502 use ratatui::buffer::Cell;
503 use ratatui::style::{Color, Modifier};
504 use time::OffsetDateTime;
505 use time::macros::datetime;
506
507 use super::{Theme, draw, theme, utc};
508 use crate::tui::client;
509 use crate::tui::keys::BINDINGS;
510 use crate::tui::screens::{SHOWN_TENANT, Screen, shown_key, shown_page, shown_refusal};
511 use crate::tui::state::{Action, ApiError, Event, KeyInfo, Page, Row, State};
512
513 const NOW: OffsetDateTime = datetime!(2026-11-10 01:20:00 UTC);
514 const MONO: Theme = Theme { color: false };
515 const COLOR: Theme = Theme { color: true };
516
517 fn row(n: u8) -> Row {
518 Row {
519 uuid: format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc{n:02}"),
520 stored_at: "2026-10-25T12:00:00.123456789Z".to_owned(),
521 updated_at: "2026-10-25T12:30:00Z".to_owned(),
522 version: format!("4f0c4b0a1d2e3f405162738495a6b7{n:02}"),
523 }
524 }
525
526 fn connecting() -> State {
527 State::new("https://vcon.example.com:8443", (80, 24)).0
528 }
529
530 fn connected() -> State {
531 let mut state = connecting();
532 state.step(
533 Event::KeyInfo(Ok(KeyInfo {
534 id: "0123456789abcdef".to_owned(),
535 tenant: Some("t_example".to_owned()),
536 scopes: vec!["read".to_owned()],
537 })),
538 NOW,
539 );
540 state
541 }
542
543 fn listed(rows: u8, next: Option<&str>) -> State {
544 let mut state = connected();
545 state.step(
546 Event::Page(Ok(Page {
547 vcons: (0..rows).map(row).collect(),
548 next: next.map(str::to_owned),
549 })),
550 NOW,
551 );
552 state
553 }
554
555 fn press(mut state: State, actions: &[Action]) -> State {
556 for action in actions {
557 state.step(Event::Action(*action), NOW);
558 }
559 state
560 }
561
562 fn terminal(state: &State, columns: u16, lines: u16, theme: Theme) -> Terminal<TestBackend> {
563 let mut terminal = Terminal::new(TestBackend::new(columns, lines)).expect("a terminal");
564 terminal
565 .draw(|frame| draw(frame, state, theme))
566 .expect("a frame");
567 terminal
568 }
569
570 fn screen(state: &State, columns: u16, lines: u16) -> Vec<String> {
572 let terminal = terminal(state, columns, lines, MONO);
573 let buffer = terminal.backend().buffer();
574 (0..lines)
575 .map(|y| (0..columns).map(|x| buffer[(x, y)].symbol()).collect())
576 .collect()
577 }
578
579 fn text(state: &State) -> String {
580 screen(state, 80, 24).join("\n")
581 }
582
583 #[test]
586 fn the_status_line_names_the_server_the_tenant_and_the_connection() {
587 let lines = screen(&listed(1, None), 80, 24);
588 assert!(
589 lines[0].contains("https://vcon.example.com:8443"),
590 "the server: {}",
591 lines[0]
592 );
593 assert!(
594 lines[0].contains("tenant t_example"),
595 "the tenant: {}",
596 lines[0]
597 );
598 assert!(
599 lines[0].contains("connected"),
600 "the connection, in words: {}",
601 lines[0]
602 );
603 }
604
605 #[test]
606 fn the_list_shows_each_vcon_with_its_times_in_utc() {
607 let lines = screen(&listed(2, None), 80, 24);
608 assert!(
609 lines[1].contains("STORED (UTC+00:00)"),
610 "the header states the offset: {}",
611 lines[1]
612 );
613 assert!(
614 lines[2].contains(&row(0).uuid),
615 "the first row's uuid: {}",
616 lines[2]
617 );
618 assert!(
619 lines[2].contains("2026-10-25 12:00:00"),
620 "its stored time: {}",
621 lines[2]
622 );
623 assert!(
624 lines[2].contains("2026-10-25 12:30:00"),
625 "its updated time: {}",
626 lines[2]
627 );
628 assert!(
629 lines[3].contains(&row(1).uuid),
630 "the second row: {}",
631 lines[3]
632 );
633 }
634
635 #[test]
636 fn the_selected_row_is_marked_with_a_character() {
637 let lines = screen(&press(listed(3, None), &[Action::Down]), 80, 24);
638 assert!(
639 lines[3].starts_with("> "),
640 "the selected row has a marker: {}",
641 lines[3]
642 );
643 assert!(
644 lines[2].starts_with(" "),
645 "the others do not: {}",
646 lines[2]
647 );
648 }
649
650 #[test]
651 fn the_list_footer_hints_are_real_bindings() {
652 let lines = screen(&listed(1, None), 80, 24);
653 let footer = &lines[23];
654 for wanted in [Action::Open, Action::Refresh, Action::Help, Action::Quit] {
655 let binding = BINDINGS
656 .iter()
657 .find(|b| b.action == wanted)
658 .expect("a binding");
659 assert!(
660 footer.contains(&format!("{} {}", binding.label, binding.hint)),
661 "the footer shows {wanted:?} as bound: {footer}"
662 );
663 }
664 }
665
666 #[test]
667 fn the_notice_line_says_how_many_are_loaded_and_as_of_when() {
668 let lines = screen(&listed(2, Some("cursor-1")), 80, 24);
669 assert!(lines[22].contains("1 of 2"), "the position: {}", lines[22]);
670 assert!(
671 lines[22].contains("more on the server"),
672 "that more exist: {}",
673 lines[22]
674 );
675 assert!(
676 lines[22].contains("as of 2026-11-10 01:20:00 UTC+00:00"),
677 "when it was read, with the offset: {}",
678 lines[22]
679 );
680 }
681
682 #[test]
683 fn the_detail_view_shows_the_metadata_and_says_content_is_not_shown() {
684 let shown = text(&press(listed(2, None), &[Action::Open]));
685 assert!(shown.contains(&row(0).uuid), "the uuid: {shown}");
686 assert!(shown.contains(&row(0).version), "the version: {shown}");
687 assert!(
688 shown.contains("2026-10-25 12:00:00 UTC+00:00"),
689 "first stored: {shown}"
690 );
691 assert!(
692 shown.contains("2026-10-25 12:30:00 UTC+00:00"),
693 "last updated: {shown}"
694 );
695 assert!(
696 shown.contains("Content is not shown"),
697 "what is left out: {shown}"
698 );
699 assert!(shown.contains("Esc back"), "how to leave: {shown}");
700 }
701
702 #[test]
703 fn the_help_view_lists_every_binding() {
704 let shown = text(&press(listed(1, None), &[Action::Help]));
705 for binding in &BINDINGS {
706 assert!(
707 shown.contains(binding.label),
708 "{} is listed: {shown}",
709 binding.label
710 );
711 assert!(
712 shown.contains(binding.does),
713 "{} is described: {shown}",
714 binding.does
715 );
716 }
717 }
718
719 #[test]
720 fn the_list_scrolls_to_keep_the_selection_on_screen() {
721 let state = press(listed(60, None), &[Action::Bottom]);
722 let shown = text(&state);
723 assert!(
724 shown.contains(&format!("> {}", row(59).uuid)),
725 "the last row is drawn selected"
726 );
727 assert!(
728 !shown.contains(&row(0).uuid),
729 "the first row has scrolled off"
730 );
731 }
732
733 #[test]
734 fn with_color_the_connection_is_colored_and_still_in_words() {
735 let state = listed(1, None);
736 let terminal = terminal(&state, 80, 24, COLOR);
737 let buffer = terminal.backend().buffer();
738 let colored = (0..80).any(|x| buffer[(x, 0)].fg != Color::Reset);
739 assert!(colored, "a color terminal gets color");
740 assert!(
741 screen(&state, 80, 24)[0].contains("connected"),
742 "and the word is still there"
743 );
744 }
745
746 #[test]
747 fn rfc_3339_times_are_shown_to_the_second_in_utc() {
748 assert_eq!(
749 utc("2026-10-25T12:00:00.123456789Z"),
750 "2026-10-25 12:00:00",
751 "fractions dropped"
752 );
753 assert_eq!(
754 utc("2026-10-25T14:30:00+02:00"),
755 "2026-10-25 12:30:00",
756 "an offset is converted"
757 );
758 }
759
760 #[test]
761 fn a_color_terminal_gets_color() {
762 assert_eq!(
763 theme(None, Some("xterm-256color")),
764 COLOR,
765 "nothing asks for none"
766 );
767 }
768
769 #[test]
770 fn a_wider_terminal_shows_the_version_column() {
771 let lines = screen(&listed(1, None), 132, 43);
772 assert!(lines[1].contains("VERSION"), "the header: {}", lines[1]);
773 assert!(
774 lines[2].contains(&row(0).version),
775 "the version: {}",
776 lines[2]
777 );
778 }
779
780 #[test]
783 fn a_failed_connection_is_said_in_the_status_line_and_the_list() {
784 let mut state = connecting();
785 state.step(
786 Event::KeyInfo(Err(ApiError::Unreachable("connection refused".to_owned()))),
787 NOW,
788 );
789 let lines = screen(&state, 80, 24);
790 assert!(
791 lines[0].contains("not connected"),
792 "the status line: {}",
793 lines[0]
794 );
795 let shown = lines.join("\n");
796 assert!(shown.contains("connection refused"), "why: {shown}");
797 assert!(
798 shown.contains("Press r to try again"),
799 "what to press: {shown}"
800 );
801 }
802
803 #[test]
804 fn a_long_error_wraps_instead_of_being_cut() {
805 let mut state = connected();
806 let long = format!("{} the-end", "word ".repeat(30));
807 state.step(Event::Page(Err(ApiError::Malformed(long))), NOW);
808 assert!(
809 text(&state).contains("the-end"),
810 "the whole reason is on screen"
811 );
812 }
813
814 #[test]
815 fn an_operator_key_is_named_in_the_status_line() {
816 let mut state = connecting();
817 state.step(
818 Event::KeyInfo(Ok(KeyInfo {
819 id: "0123456789abcdef".to_owned(),
820 tenant: None,
821 scopes: vec!["admin".to_owned()],
822 })),
823 NOW,
824 );
825 let lines = screen(&state, 80, 24);
826 assert!(
827 lines[0].contains("no tenant (operator key)"),
828 "the status line: {}",
829 lines[0]
830 );
831 assert!(
832 lines
833 .join("\n")
834 .contains("this is an operator key, which reaches no vCon"),
835 "and the list says why it is empty"
836 );
837 }
838
839 #[test]
840 fn a_failed_next_page_shows_its_notice_over_the_rows() {
841 let mut state = press(listed(2, Some("cursor-1")), &[Action::More]);
842 state.step(
843 Event::Page(Err(ApiError::Unreachable("timed out".to_owned()))),
844 NOW,
845 );
846 let lines = screen(&state, 80, 24);
847 assert!(
848 lines[22].contains("The next page was not read"),
849 "the notice: {}",
850 lines[22]
851 );
852 assert!(
853 lines[2].contains(&row(0).uuid),
854 "the rows stay: {}",
855 lines[2]
856 );
857 }
858
859 #[test]
860 fn the_detail_of_a_vcon_no_longer_listed_says_so() {
861 let mut state = press(listed(2, None), &[Action::Open, Action::Refresh]);
862 state.step(
863 Event::Page(Ok(Page {
864 vcons: vec![row(1)],
865 next: None,
866 })),
867 NOW,
868 );
869 let shown = text(&state);
870 assert!(
871 shown.contains("no longer in the list"),
872 "what happened: {shown}"
873 );
874 assert!(
875 shown.contains("Press Esc to go back"),
876 "what to press: {shown}"
877 );
878 }
879
880 #[test]
881 fn the_detail_view_shows_a_failed_refresh() {
882 let mut state = press(listed(2, None), &[Action::Open, Action::Refresh]);
883 state.step(Event::Page(Err(ApiError::Status(503, None))), NOW);
884 let shown = text(&state);
885 assert!(shown.contains("the server answered 503"), "why: {shown}");
886 assert!(
887 shown.contains("Press r to try again"),
888 "what to press: {shown}"
889 );
890 }
891
892 #[test]
893 fn a_terminal_too_small_says_so_and_how_to_quit() {
894 let lines = screen(&listed(3, None), 30, 5);
895 let shown = lines.join("\n");
896 assert!(shown.contains("too small"), "what is wrong: {shown}");
897 assert!(shown.contains("q"), "the way out: {shown}");
898 assert!(!shown.contains("01a07da8"), "no half-drawn list");
899 }
900
901 #[test]
902 fn a_time_that_does_not_parse_is_shown_as_sent() {
903 assert_eq!(utc("yesterday"), "yesterday", "nothing is invented for it");
904 }
905
906 #[test]
907 fn a_refused_key_says_to_check_the_key_file() {
908 let mut state = connecting();
909 state.step(Event::KeyInfo(Err(ApiError::Status(401, None))), NOW);
910 let shown = text(&state);
911 assert!(shown.contains("refused the key (401)"), "why: {shown}");
912 assert!(shown.contains("key_file"), "where to look: {shown}");
913 }
914
915 #[test]
918 fn the_loading_state_says_so_and_how_to_quit() {
919 let shown = text(&connected());
920 assert!(
921 shown.contains("Loading vCons"),
922 "what is happening: {shown}"
923 );
924 assert!(shown.contains("q quit"), "the way out: {shown}");
925 }
926
927 #[test]
928 fn the_connecting_state_is_in_the_status_line() {
929 let lines = screen(&connecting(), 80, 24);
930 assert!(
931 lines[0].contains("connecting"),
932 "the status line: {}",
933 lines[0]
934 );
935 assert!(
936 lines.join("\n").contains("Connecting to the server"),
937 "and the body"
938 );
939 }
940
941 #[test]
942 fn an_empty_tenant_says_so_and_what_to_press() {
943 let shown = text(&listed(0, None));
944 assert!(
945 shown.contains("This tenant has no vCons"),
946 "what happened: {shown}"
947 );
948 assert!(
949 shown.contains("Press r to read again"),
950 "what to press: {shown}"
951 );
952 }
953
954 #[test]
955 fn the_detail_view_says_refreshing_while_a_refresh_is_in_flight() {
956 let shown = text(&press(listed(2, None), &[Action::Open, Action::Refresh]));
957 assert!(
958 shown.contains("Reading the list again"),
959 "what is happening: {shown}"
960 );
961 }
962
963 #[test]
964 fn at_80_columns_every_list_column_fits() {
965 let lines = screen(&listed(1, None), 80, 24);
966 assert!(
967 lines[2].trim_end().ends_with("2026-10-25 12:30:00"),
968 "the last column is whole: {}",
969 lines[2]
970 );
971 }
972
973 #[test]
974 fn below_80_columns_the_updated_column_is_dropped_not_cut() {
975 let lines = screen(&listed(1, None), 60, 24);
976 assert!(
977 lines[2].contains("2026-10-25 12:00:00"),
978 "stored stays: {}",
979 lines[2]
980 );
981 assert!(
982 !lines[2].contains("2026-10-25 12:3"),
983 "no part of updated: {}",
984 lines[2]
985 );
986 assert!(
987 !lines[1].contains("UPDATED"),
988 "nor its header: {}",
989 lines[1]
990 );
991 }
992
993 #[test]
994 fn every_size_from_1x1_up_draws_without_a_panic() {
995 let states = [
996 connecting(),
997 listed(0, None),
998 listed(60, Some("cursor-1")),
999 press(listed(3, None), &[Action::Open]),
1000 press(listed(3, None), &[Action::Help]),
1001 ];
1002 for state in &states {
1003 for columns in [1, 2, 10, 39, 40, 79, 80, 200] {
1004 for lines in [1, 2, 7, 8, 24, 60] {
1005 let drawn = screen(state, columns, lines);
1006 assert_eq!(
1007 drawn.len(),
1008 usize::from(lines),
1009 "{columns}x{lines} drew a frame"
1010 );
1011 }
1012 }
1013 }
1014 }
1015
1016 #[test]
1017 fn no_color_and_a_dumb_terminal_turn_color_off() {
1018 assert_eq!(
1019 theme(Some("1"), Some("xterm-256color")),
1020 MONO,
1021 "NO_COLOR set"
1022 );
1023 assert_eq!(theme(None, Some("dumb")), MONO, "a terminal with no color");
1024 assert_eq!(theme(None, None), MONO, "no TERM at all");
1025 assert_eq!(
1026 theme(Some(""), Some("xterm")),
1027 COLOR,
1028 "an empty NO_COLOR is not set"
1029 );
1030 }
1031
1032 #[test]
1033 fn without_color_no_cell_has_a_color() {
1034 for state in [
1035 listed(3, None),
1036 press(listed(3, None), &[Action::Help]),
1037 connecting(),
1038 ] {
1039 let terminal = terminal(&state, 80, 24, MONO);
1040 let buffer = terminal.backend().buffer();
1041 for cell in buffer.content() {
1042 assert_eq!(cell.fg, Color::Reset, "no foreground color");
1043 assert_eq!(cell.bg, Color::Reset, "no background color");
1044 }
1045 }
1046 }
1047
1048 #[test]
1049 fn the_status_line_keeps_the_connection_when_the_address_is_long() {
1050 let mut state = State::new(
1051 &format!("https://{}.example.com:8443", "a".repeat(90)),
1052 (80, 24),
1053 )
1054 .0;
1055 state.step(Event::KeyInfo(Err(ApiError::Status(401, None))), NOW);
1056 let lines = screen(&state, 80, 24);
1057 assert!(
1058 lines[0].contains("not connected"),
1059 "the state is never pushed off: {}",
1060 lines[0]
1061 );
1062 }
1063
1064 const SERVER: &str = "https://vcon.example.com:8443";
1068 const LONG_ID: &str = "658a6d102142fea77f47ee8a332323d8";
1069
1070 fn keyed(server: &str, tenant: Option<&str>) -> State {
1072 let mut state = State::new(server, (80, 24)).0;
1073 state.step(
1074 Event::KeyInfo(Ok(KeyInfo {
1075 id: "0123456789abcdef".to_owned(),
1076 tenant: tenant.map(str::to_owned),
1077 scopes: vec!["read".to_owned()],
1078 })),
1079 NOW,
1080 );
1081 state
1082 }
1083
1084 fn refused(server: &str) -> State {
1086 let mut state = State::new(server, (80, 24)).0;
1087 state.step(Event::KeyInfo(Err(ApiError::Status(401, None))), NOW);
1088 state
1089 }
1090
1091 fn status_at(state: &State, columns: u16) -> String {
1093 screen(state, columns, 24)[0].trim_end().to_owned()
1094 }
1095
1096 #[test]
1097 fn at_120_columns_the_status_line_is_whole() {
1098 assert_eq!(
1099 status_at(&keyed(SERVER, Some(LONG_ID)), 120),
1100 format!("{SERVER} | tenant {LONG_ID} | connected"),
1101 "everything fits"
1102 );
1103 }
1104
1105 #[test]
1106 fn at_80_columns_the_address_loses_only_its_scheme() {
1107 assert_eq!(
1108 status_at(&keyed(SERVER, Some(LONG_ID)), 80),
1109 format!("vcon.example.com:8443 | tenant {LONG_ID} | connected"),
1110 "https:// says nothing a reader needs: every address has it"
1111 );
1112 }
1113
1114 #[test]
1115 fn at_60_columns_the_tenant_id_is_shortened_and_the_address_is_not() {
1116 assert_eq!(
1117 status_at(&keyed(SERVER, Some(LONG_ID)), 60),
1118 "vcon.example.com:8443 | tenant 658a6d102142fe... | connected",
1119 "the tenant gives way before the server does"
1120 );
1121 }
1122
1123 #[test]
1124 fn at_40_columns_the_tenant_is_left_out_and_the_address_is_not() {
1125 assert_eq!(
1126 status_at(&keyed(SERVER, Some(LONG_ID)), 40),
1127 "vcon.example.com:8443 | connected",
1128 "the server and the connection"
1129 );
1130 }
1131
1132 #[test]
1133 fn a_line_that_fits_exactly_keeps_its_scheme() {
1134 assert_eq!(
1135 status_at(&keyed(SERVER, Some(LONG_ID)), 83),
1136 format!("{SERVER} | tenant {LONG_ID} | connected"),
1137 "83 characters in 83 columns"
1138 );
1139 }
1140
1141 #[test]
1142 fn a_short_tenant_id_is_whole_at_60_columns() {
1143 assert_eq!(
1144 status_at(&keyed(SERVER, Some("t_example")), 60),
1145 format!("{SERVER} | tenant t_example | connected"),
1146 "60 characters in 60 columns"
1147 );
1148 }
1149
1150 #[test]
1151 fn an_address_with_a_path_is_shown_with_it() {
1152 let line = status_at(
1153 &keyed("https://vcon.example.com:8443/base", Some("t_example")),
1154 120,
1155 );
1156 assert!(
1157 line.starts_with("https://vcon.example.com:8443/base | "),
1158 "the path is part of the address: {line}"
1159 );
1160 }
1161
1162 #[test]
1163 fn a_refused_key_at_40_columns_shows_the_address_and_not_connected() {
1164 assert_eq!(
1165 status_at(&refused(SERVER), 40),
1166 "vcon.example.com:8443 | not connected",
1167 "`tenant unknown` is the part left out"
1168 );
1169 }
1170
1171 #[test]
1172 fn a_refused_key_at_60_columns_keeps_tenant_unknown() {
1173 assert_eq!(
1174 status_at(&refused(SERVER), 60),
1175 "vcon.example.com:8443 | tenant unknown | not connected",
1176 "without the scheme the three parts fit"
1177 );
1178 }
1179
1180 #[test]
1181 fn a_refused_key_at_80_columns_is_whole() {
1182 assert_eq!(
1183 status_at(&refused(SERVER), 80),
1184 format!("{SERVER} | tenant unknown | not connected"),
1185 "everything fits"
1186 );
1187 }
1188
1189 #[test]
1190 fn connecting_at_40_columns_shows_the_address_and_connecting() {
1191 assert_eq!(
1192 status_at(&State::new(SERVER, (40, 24)).0, 40),
1193 "vcon.example.com:8443 | connecting",
1194 "`tenant unknown` is the part left out"
1195 );
1196 }
1197
1198 #[test]
1199 fn an_operator_key_at_60_columns_is_named_whole() {
1200 assert_eq!(
1201 status_at(&keyed(SERVER, None), 60),
1202 "vcon.example.com:8443 | no tenant (operator key) | connected",
1203 "60 characters in 60 columns"
1204 );
1205 }
1206
1207 #[test]
1208 fn an_operator_key_at_40_columns_is_left_out_not_cut() {
1209 assert_eq!(
1210 status_at(&keyed(SERVER, None), 40),
1211 "vcon.example.com:8443 | connected",
1212 "a phrase is whole or absent"
1213 );
1214 }
1215
1216 #[test]
1217 fn a_long_address_is_cut_at_its_end_and_the_connection_is_whole() {
1218 let server = format!("https://{}.example.com:8443", "a".repeat(90));
1219 assert_eq!(
1220 status_at(&refused(&server), 40),
1221 format!("{}... | not connected", "a".repeat(21)),
1222 "40 columns: 21 of the address, the mark, and the connection"
1223 );
1224 }
1225
1226 #[test]
1227 fn four_characters_of_a_tenant_id_are_the_fewest_shown() {
1228 assert_eq!(
1229 status_at(&keyed(SERVER, Some(LONG_ID)), 50),
1230 "vcon.example.com:8443 | tenant 658a... | connected",
1231 "50 columns leave room for four"
1232 );
1233 }
1234
1235 #[test]
1236 fn a_tenant_id_with_room_for_three_characters_is_left_out() {
1237 assert_eq!(
1238 status_at(&keyed(SERVER, Some(LONG_ID)), 49),
1239 "vcon.example.com:8443 | connected",
1240 "three characters name no tenant"
1241 );
1242 }
1243
1244 #[test]
1245 fn one_column_short_of_whole_the_scheme_goes_first() {
1246 assert_eq!(
1247 status_at(&keyed(SERVER, Some(LONG_ID)), 82),
1248 format!("vcon.example.com:8443 | tenant {LONG_ID} | connected"),
1249 "the tenant id stays whole"
1250 );
1251 }
1252
1253 #[test]
1254 fn one_column_short_of_a_whole_id_shortens_it_to_fit() {
1255 let line = status_at(&keyed(SERVER, Some(LONG_ID)), 74);
1256 assert_eq!(
1257 line,
1258 format!(
1259 "vcon.example.com:8443 | tenant {}... | connected",
1260 &LONG_ID[..28]
1261 ),
1262 "74 columns: 28 characters and the mark"
1263 );
1264 }
1265
1266 #[test]
1267 fn an_address_that_is_not_https_is_shown_as_it_is() {
1268 assert_eq!(
1269 status_at(&refused("vcon.example.com:8443"), 40),
1270 "vcon.example.com:8443 | not connected",
1271 "there is no scheme to leave out"
1272 );
1273 }
1274
1275 #[test]
1276 fn an_address_that_fits_exactly_at_40_columns_is_whole() {
1277 let server = format!("https://{}", "b".repeat(28));
1278 assert_eq!(
1279 status_at(&keyed(&server, Some(LONG_ID)), 40),
1280 format!("{} | connected", "b".repeat(28)),
1281 "28 characters, the separator and the connection are 40"
1282 );
1283 }
1284
1285 #[test]
1286 fn the_status_line_fits_and_ends_with_the_connection_at_every_width() {
1287 let long = format!("https://{}.example.com:8443", "a".repeat(90));
1288 for server in [SERVER, long.as_str()] {
1289 let states = [
1290 (State::new(server, (80, 24)).0, "connecting"),
1291 (refused(server), "not connected"),
1292 (keyed(server, Some(LONG_ID)), "connected"),
1293 (keyed(server, None), "connected"),
1294 ];
1295 for (state, word) in &states {
1296 for columns in 40..=130 {
1297 let line = status_at(state, columns);
1298 assert!(
1299 line.chars().count() <= usize::from(columns),
1300 "{columns} columns: {line}"
1301 );
1302 assert!(
1303 line.ends_with(&format!(" | {word}")),
1304 "{columns} columns, the connection is whole and last: {line}"
1305 );
1306 }
1307 }
1308 }
1309 }
1310
1311 #[test]
1312 fn a_tenant_phrase_is_whole_or_absent_at_every_width() {
1313 for (state, phrase) in [
1314 (refused(SERVER), "tenant unknown"),
1315 (keyed(SERVER, None), "no tenant (operator key)"),
1316 ] {
1317 for columns in 40..=130 {
1318 let line = status_at(&state, columns);
1319 assert!(
1320 line.contains(phrase) || !line.contains("tenant"),
1321 "{columns} columns: {line}"
1322 );
1323 }
1324 }
1325 }
1326
1327 #[test]
1328 fn the_help_view_states_the_time_zone() {
1329 let shown = text(&press(listed(1, None), &[Action::Help]));
1330 assert!(
1331 shown.contains("UTC+00:00"),
1332 "times are UTC, stated: {shown}"
1333 );
1334 }
1335
1336 fn footer_at(state: &State, columns: u16) -> String {
1340 screen(state, columns, 24)[23].trim_end().to_owned()
1341 }
1342
1343 #[test]
1344 fn at_40_columns_the_list_footer_still_shows_help_and_quit() {
1345 let footer = footer_at(&listed(2, None), 40);
1346 assert!(
1347 footer.ends_with("? help q quit"),
1348 "how to get help and how to leave are whole: {footer:?}"
1349 );
1350 assert!(
1351 footer.starts_with("j down k up"),
1352 "the first keys stay first: {footer:?}"
1353 );
1354 }
1355
1356 #[test]
1357 fn at_40_columns_the_detail_footer_still_shows_help_and_quit() {
1358 let footer = footer_at(&press(listed(2, None), &[Action::Open]), 40);
1359 assert!(
1360 footer.ends_with("? help q quit"),
1361 "how to get help and how to leave are whole: {footer:?}"
1362 );
1363 assert!(
1364 footer.starts_with("Esc back"),
1365 "how to go back stays first: {footer:?}"
1366 );
1367 }
1368
1369 #[test]
1370 fn at_80_columns_the_footers_are_whole() {
1371 assert_eq!(
1372 footer_at(&listed(2, Some("cursor-2")), 80),
1373 "j down k up Enter open r refresh n more ? help q quit",
1374 "the list's keys"
1375 );
1376 assert_eq!(
1377 footer_at(&press(listed(2, None), &[Action::Open]), 80),
1378 "Esc back j down k up r refresh ? help q quit",
1379 "the detail's keys"
1380 );
1381 assert_eq!(
1382 footer_at(&press(listed(2, None), &[Action::Help]), 80),
1383 "Esc back q quit",
1384 "help's keys"
1385 );
1386 }
1387
1388 #[test]
1389 fn no_footer_ends_in_a_cut_hint_at_any_width() {
1390 for view in [&[][..], &[Action::Open][..], &[Action::Help][..]] {
1391 let state = press(listed(2, None), view);
1392 for columns in 40..=100 {
1393 let footer = footer_at(&state, columns);
1394 assert!(
1395 footer.ends_with("q quit"),
1396 "at {columns} columns the last hint is whole: {footer:?}"
1397 );
1398 assert!(
1399 footer.chars().count() <= usize::from(columns),
1400 "at {columns} columns the footer fits: {footer:?}"
1401 );
1402 }
1403 }
1404 }
1405
1406 #[test]
1407 fn one_column_short_of_the_whole_list_footer_drops_one_hint() {
1408 assert_eq!(
1409 footer_at(&listed(2, Some("cursor-2")), 58),
1410 "j down k up Enter open r refresh ? help q quit",
1411 "the hint before help goes first"
1412 );
1413 assert_eq!(
1414 footer_at(&listed(2, Some("cursor-2")), 59),
1415 "j down k up Enter open r refresh n more ? help q quit",
1416 "at its own width the footer is whole"
1417 );
1418 }
1419
1420 const HELP_QUIT: &str = "? help q quit";
1423 const RETRY: &str = "r refresh ? help q quit";
1424 const LIST_KEYS: &str = "j down k up Enter open r refresh n more ? help q quit";
1425
1426 fn failed(error: ApiError) -> State {
1427 let mut state = connecting();
1428 state.step(Event::KeyInfo(Err(error)), NOW);
1429 state
1430 }
1431
1432 fn with_key(tenant: Option<&str>, scope: &str) -> State {
1433 let mut state = connecting();
1434 state.step(
1435 Event::KeyInfo(Ok(KeyInfo {
1436 id: "0123456789abcdef".to_owned(),
1437 tenant: tenant.map(str::to_owned),
1438 scopes: vec![scope.to_owned()],
1439 })),
1440 NOW,
1441 );
1442 state
1443 }
1444
1445 fn page_failed(mut state: State, error: ApiError) -> State {
1446 state.step(Event::Page(Err(error)), NOW);
1447 state
1448 }
1449
1450 fn detail_gone(left: u8) -> State {
1453 let mut state = press(
1454 listed(5, None),
1455 &[Action::Bottom, Action::Open, Action::Refresh],
1456 );
1457 state.step(
1458 Event::Page(Ok(Page {
1459 vcons: (0..left).map(row).collect(),
1460 next: None,
1461 })),
1462 NOW,
1463 );
1464 state
1465 }
1466
1467 #[test]
1468 fn the_connecting_screen_names_help_and_quit_only() {
1469 assert_eq!(
1470 footer_at(&connecting(), 80),
1471 HELP_QUIT,
1472 "nothing is listed, and r waits for the request that is out"
1473 );
1474 }
1475
1476 #[test]
1477 fn the_loading_screen_names_help_and_quit_only() {
1478 assert_eq!(
1479 footer_at(&connected(), 80),
1480 HELP_QUIT,
1481 "the first page is on its way"
1482 );
1483 }
1484
1485 #[test]
1486 fn an_empty_tenant_names_refresh_help_and_quit() {
1487 assert_eq!(
1488 footer_at(&listed(0, None), 80),
1489 RETRY,
1490 "there is no vCon to select, open or read more of"
1491 );
1492 }
1493
1494 #[test]
1495 fn a_server_that_did_not_answer_names_refresh_help_and_quit() {
1496 assert_eq!(
1497 footer_at(&failed(client::no_answer(client::TIMEOUT)), 80),
1498 RETRY,
1499 "r asks again"
1500 );
1501 }
1502
1503 #[test]
1504 fn a_refused_key_names_refresh_help_and_quit() {
1505 assert_eq!(
1506 footer_at(&failed(ApiError::Status(401, None)), 80),
1507 RETRY,
1508 "r asks the server for the key again"
1509 );
1510 }
1511
1512 #[test]
1513 fn a_refused_certificate_names_refresh_help_and_quit() {
1514 assert_eq!(
1515 footer_at(
1516 &failed(ApiError::Untrusted("it has expired".to_owned())),
1517 80
1518 ),
1519 RETRY,
1520 "a clock that was corrected lets r succeed"
1521 );
1522 }
1523
1524 #[test]
1525 fn a_first_page_that_failed_names_refresh_help_and_quit() {
1526 let state = page_failed(connected(), ApiError::Status(503, None));
1527 assert_eq!(footer_at(&state, 80), RETRY, "r reads the first page again");
1528 }
1529
1530 #[test]
1531 fn an_operator_key_names_help_and_quit_only() {
1532 let state = with_key(None, "admin");
1533 assert_eq!(
1534 footer_at(&state, 80),
1535 HELP_QUIT,
1536 "r cannot read another key: the key file is read at start"
1537 );
1538 let shown = text(&state);
1539 assert!(
1540 shown.contains("\nPress q to quit.") && !shown.contains("Press r"),
1541 "the message names no key that does nothing: {shown}"
1542 );
1543 assert!(
1544 shown.contains(AT_START),
1545 "and says when another key is read: {shown}"
1546 );
1547 }
1548
1549 #[test]
1550 fn a_key_without_the_read_scope_names_help_and_quit_only() {
1551 let state = with_key(Some("t_example"), "write");
1552 assert_eq!(footer_at(&state, 80), HELP_QUIT, "as for an operator key");
1553 let shown = text(&state);
1554 assert!(
1555 shown.contains("\nPress q to quit.") && !shown.contains("Press r"),
1556 "the message names no key that does nothing: {shown}"
1557 );
1558 }
1559
1560 #[test]
1561 fn a_list_of_one_vcon_names_no_key_that_moves() {
1562 assert_eq!(
1563 footer_at(&listed(1, None), 80),
1564 "Enter open r refresh ? help q quit",
1565 "there is no other row, and no next page"
1566 );
1567 }
1568
1569 #[test]
1570 fn a_list_that_is_all_read_does_not_name_more() {
1571 assert_eq!(
1572 footer_at(&listed(3, None), 80),
1573 "j down k up Enter open r refresh ? help q quit",
1574 "n does nothing when the server holds no more"
1575 );
1576 }
1577
1578 #[test]
1579 fn a_list_with_more_on_the_server_names_every_list_key() {
1580 assert_eq!(
1581 footer_at(&listed(3, Some("cursor-2")), 80),
1582 LIST_KEYS,
1583 "every key acts"
1584 );
1585 }
1586
1587 #[test]
1588 fn while_the_next_page_is_read_refresh_and_more_are_not_named() {
1589 let state = press(listed(3, Some("cursor-2")), &[Action::More]);
1590 assert_eq!(
1591 footer_at(&state, 80),
1592 "j down k up Enter open ? help q quit",
1593 "a second request would race the one that is out"
1594 );
1595 }
1596
1597 #[test]
1598 fn after_a_next_page_that_failed_refresh_and_more_are_named_again() {
1599 let state = page_failed(
1600 press(listed(3, Some("cursor-2")), &[Action::More]),
1601 client::no_answer(client::TIMEOUT),
1602 );
1603 assert_eq!(footer_at(&state, 80), LIST_KEYS, "n and r both try again");
1604 }
1605
1606 #[test]
1607 fn while_the_list_is_read_again_only_help_and_quit_are_named() {
1608 let state = press(listed(3, Some("cursor-2")), &[Action::Refresh]);
1609 assert_eq!(
1610 footer_at(&state, 80),
1611 HELP_QUIT,
1612 "the rows are not on the screen"
1613 );
1614 }
1615
1616 #[test]
1617 fn the_detail_of_the_only_vcon_names_no_key_that_moves() {
1618 assert_eq!(
1619 footer_at(&press(listed(1, None), &[Action::Open]), 80),
1620 "Esc back r refresh ? help q quit",
1621 "there is no other vCon to show"
1622 );
1623 }
1624
1625 #[test]
1626 fn the_detail_view_names_back_while_the_list_is_read_again() {
1627 let state = press(listed(3, None), &[Action::Open, Action::Refresh]);
1628 assert_eq!(
1629 footer_at(&state, 80),
1630 "Esc back ? help q quit",
1631 "Esc still returns to the list"
1632 );
1633 }
1634
1635 #[test]
1636 fn the_detail_view_names_back_and_refresh_after_a_failure() {
1637 let state = page_failed(
1638 press(listed(3, None), &[Action::Open, Action::Refresh]),
1639 ApiError::Status(503, None),
1640 );
1641 assert_eq!(
1642 footer_at(&state, 80),
1643 "Esc back r refresh ? help q quit",
1644 "there is no row to move to"
1645 );
1646 }
1647
1648 #[test]
1649 fn a_detail_view_whose_vcon_is_gone_names_the_keys_that_show_another() {
1650 for left in [1, 3] {
1651 assert_eq!(
1652 footer_at(&detail_gone(left), 80),
1653 "Esc back j down k up r refresh ? help q quit",
1654 "with {left} left, j and k show a vCon that is listed"
1655 );
1656 }
1657 }
1658
1659 #[test]
1660 fn a_detail_view_with_no_vcon_left_names_back_and_refresh() {
1661 assert_eq!(
1662 footer_at(&detail_gone(0), 80),
1663 "Esc back r refresh ? help q quit",
1664 "no vCon is left to show"
1665 );
1666 }
1667
1668 #[test]
1669 fn help_names_back_and_quit_over_every_state() {
1670 for state in [
1671 connecting(),
1672 connected(),
1673 listed(0, None),
1674 listed(3, Some("cursor-2")),
1675 failed(ApiError::Status(401, None)),
1676 with_key(None, "admin"),
1677 press(listed(3, None), &[Action::Open]),
1678 ] {
1679 assert_eq!(
1680 footer_at(&press(state, &[Action::Help]), 80),
1681 "Esc back q quit",
1682 "help has two keys of its own"
1683 );
1684 }
1685 }
1686
1687 #[test]
1688 fn at_40_columns_the_short_footers_are_whole() {
1689 for (state, wanted) in [
1690 (connecting(), HELP_QUIT),
1691 (listed(0, None), RETRY),
1692 (failed(ApiError::Status(401, None)), RETRY),
1693 (with_key(None, "admin"), HELP_QUIT),
1694 ] {
1695 assert_eq!(footer_at(&state, 40), wanted, "the hints fit 40 columns");
1696 }
1697 }
1698
1699 #[test]
1700 fn every_hint_on_every_shown_screen_is_a_key_that_acts() {
1701 for one in Screen::ALL {
1702 let (name, state, (columns, rows)) = (one.name(), one.state(), one.size());
1703 if columns < 40 || rows < 8 {
1704 continue;
1705 }
1706 let lines = screen(&state, columns, rows);
1707 let footer = lines[usize::from(rows) - 1].trim_end().to_owned();
1708 assert!(!footer.is_empty(), "{name}: the last line holds hints");
1709 for hint in footer.split(" ") {
1710 let binding = BINDINGS
1711 .iter()
1712 .find(|b| format!("{} {}", b.label, b.hint) == hint)
1713 .unwrap_or_else(|| panic!("{name}: {hint:?} is a binding's hint"));
1714 assert!(
1715 state.acts(binding.action),
1716 "{name}: {hint:?} is shown, and the key does nothing there"
1717 );
1718 }
1719 }
1720 }
1721
1722 #[test]
1723 fn a_failure_the_server_made_still_says_to_press_r() {
1724 for state in [
1725 failed(client::no_answer(client::TIMEOUT)),
1726 failed(ApiError::Status(401, None)),
1727 page_failed(connected(), ApiError::Status(503, None)),
1728 ] {
1729 let shown = text(&state);
1730 assert!(
1731 shown.contains("Press r to try again, or q to quit."),
1732 "r asks the server again: {shown}"
1733 );
1734 }
1735 }
1736
1737 fn joined(lines: &[String], first: usize) -> String {
1740 lines[first..lines.len().saturating_sub(1)]
1741 .iter()
1742 .map(|line| line.trim())
1743 .collect::<Vec<_>>()
1744 .join(" ")
1745 }
1746
1747 #[test]
1748 fn a_notice_longer_than_the_terminal_is_wrapped_not_cut() {
1749 let mut state = press(listed(2, Some("cursor-1")), &[Action::More]);
1750 state.step(
1751 Event::Page(Err(ApiError::Unreachable(
1752 "error sending request for url (https://vcon.example.com:8443/vcons): client error (Connect): tcp connect error: Connection refused (os error 111)".to_owned(),
1753 ))),
1754 NOW,
1755 );
1756 let lines = screen(&state, 80, 24);
1757 let said = joined(&lines, 19);
1758 assert!(
1759 said.contains("The next page was not read: the server did not answer: ")
1760 && said.ends_with("Connection refused (os error 111)."),
1761 "the whole sentence is on screen, to its end: {said}"
1762 );
1763 assert!(
1764 lines[2].contains(&row(0).uuid),
1765 "the rows stay: {}",
1766 lines[2]
1767 );
1768 }
1769
1770 #[test]
1771 fn a_short_notice_takes_one_line() {
1772 let mut state = press(listed(2, Some("cursor-1")), &[Action::More]);
1773 state.step(
1774 Event::Page(Err(ApiError::Unreachable("timed out".to_owned()))),
1775 NOW,
1776 );
1777 let lines = screen(&state, 80, 24);
1778 assert!(
1779 lines[22].starts_with("The next page was not read"),
1780 "on the line above the key hints: {}",
1781 lines[22]
1782 );
1783 assert_eq!(lines[21].trim(), "", "and the line above it is empty");
1784 }
1785
1786 #[test]
1787 fn at_60_columns_the_position_line_keeps_when_the_list_was_read() {
1788 let lines = screen(&listed(2, Some("cursor-1")), 60, 24);
1789 let said = joined(&lines, 20);
1790 assert!(
1791 said.contains("1 of 2 read, more on the server")
1792 && said.ends_with("as of 2026-11-10 01:20:00 UTC+00:00"),
1793 "the position and the time are whole: {said}"
1794 );
1795 }
1796
1797 const AT_START: &str =
1801 "A change to the client file or the key file takes effect at the next start.";
1802
1803 #[test]
1804 fn a_refused_key_says_that_a_new_key_file_needs_a_new_start() {
1805 let shown = text(&shown_refusal(ApiError::Status(401, None)));
1806 assert!(
1807 shown.contains(AT_START),
1808 "the token is read once, so r cannot read a corrected key file: {shown}"
1809 );
1810 }
1811
1812 #[test]
1813 fn a_refused_certificate_says_that_a_new_ca_needs_a_new_start() {
1814 let advice =
1815 client::certificate_advice(&rustls::CertificateError::UnknownIssuer).expect("advice");
1816 let shown = text(&shown_refusal(ApiError::Untrusted(advice.to_owned())));
1817 assert!(
1818 shown
1819 .replace('\n', " ")
1820 .contains("set ca in the client file")
1821 && shown.contains(AT_START),
1822 "the advice names the client file, which is read once: {shown}"
1823 );
1824 }
1825
1826 #[test]
1827 fn a_key_that_may_not_list_says_that_another_key_needs_a_new_start() {
1828 for state in [
1829 shown_key(None, &[]),
1830 shown_key(Some(SHOWN_TENANT), &["write"]),
1831 ] {
1832 let shown = text(&state);
1833 assert!(
1834 shown.contains(AT_START),
1835 "another key is another key file, read at start: {shown}"
1836 );
1837 }
1838 }
1839
1840 #[test]
1841 fn a_failure_still_names_r_and_q() {
1842 let shown = text(&shown_refusal(client::no_answer(client::TIMEOUT)));
1843 assert!(
1844 shown.contains("Press r to try again, or q to quit."),
1845 "a server that did not answer may answer the next request: {shown}"
1846 );
1847 }
1848
1849 #[test]
1850 fn an_empty_tenant_does_not_mention_the_files() {
1851 let shown = text(&shown_page(
1852 shown_key(Some(SHOWN_TENANT), &["read"]),
1853 0..0,
1854 false,
1855 ));
1856 assert!(
1857 !shown.contains(AT_START),
1858 "nothing failed, so there is nothing to correct: {shown}"
1859 );
1860 }
1861
1862 fn screens_file() -> std::path::PathBuf {
1867 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../website/data/tui-screens.json")
1868 }
1869
1870 fn classes(cell: &Cell) -> String {
1872 assert_eq!(cell.bg, Color::Reset, "the site draws no background color");
1873 let mut out = Vec::new();
1874 if cell.modifier.contains(Modifier::BOLD) {
1875 out.push("bold");
1876 }
1877 if cell.modifier.contains(Modifier::REVERSED) {
1878 out.push("reversed");
1879 }
1880 match cell.fg {
1881 Color::Reset => {}
1882 Color::Green => out.push("green"),
1883 Color::Yellow => out.push("yellow"),
1884 Color::Red => out.push("red"),
1885 other => panic!("the site has no class for {other:?}"),
1886 }
1887 out.join(" ")
1888 }
1889
1890 fn styled(state: &State, columns: u16, rows: u16) -> serde_json::Value {
1893 let terminal = terminal(state, columns, rows, COLOR);
1894 let buffer = terminal.backend().buffer();
1895 let lines: Vec<serde_json::Value> = (0..rows)
1896 .map(|y| {
1897 let mut runs: Vec<(String, String)> = Vec::new();
1898 for x in 0..columns {
1899 let cell = &buffer[(x, y)];
1900 let class = classes(cell);
1901 match runs.last_mut() {
1902 Some((last, text)) if *last == class => text.push_str(cell.symbol()),
1903 _ => runs.push((class, cell.symbol().to_owned())),
1904 }
1905 }
1906 if let Some((class, text)) = runs.last_mut()
1907 && class.is_empty()
1908 {
1909 text.truncate(text.trim_end().len());
1910 }
1911 runs.retain(|(_, text)| !text.is_empty());
1912 runs.into_iter()
1913 .map(|(class, text)| serde_json::json!({"class": class, "text": text}))
1914 .collect()
1915 })
1916 .collect();
1917 serde_json::json!({"columns": columns, "lines": lines})
1918 }
1919
1920 #[test]
1921 fn the_site_shows_the_screens_draw_makes() {
1922 let mut made = serde_json::Map::new();
1923 for screen in Screen::ALL {
1924 let (name, (columns, rows)) = (screen.name(), screen.size());
1925 let mut drawn = styled(&screen.state(), columns, rows);
1926 drawn["keys"] = screen
1929 .keys()
1930 .into_iter()
1931 .map(|binding| serde_json::json!({"key": binding.label, "does": binding.does}))
1932 .collect();
1933 let before = made.insert(name.to_owned(), drawn);
1934 assert!(before.is_none(), "the screen {name} is made once");
1935 }
1936 let made = format!(
1937 "{}\n",
1938 serde_json::to_string_pretty(&serde_json::Value::Object(made)).expect("JSON")
1939 );
1940 let path = screens_file();
1941 if std::env::var_os("VCON_SERVER_WRITE_SCREENS").is_some() {
1942 std::fs::write(&path, &made)
1943 .unwrap_or_else(|e| panic!("write {}: {e}", path.display()));
1944 }
1945 let shown = std::fs::read_to_string(&path)
1946 .unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
1947 assert!(
1948 shown == made,
1949 "{} is not the screens draw makes now: run this test with VCON_SERVER_WRITE_SCREENS=1 to write them again",
1950 path.display()
1951 );
1952 }
1953}