1use std::fmt;
6
7use serde::Deserialize;
8use time::OffsetDateTime;
9
10#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
12pub struct KeyInfo {
13 pub id: String,
15 pub tenant: Option<String>,
17 pub scopes: Vec<String>,
19}
20
21#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
23pub struct Row {
24 pub uuid: String,
26 pub stored_at: String,
28 pub updated_at: String,
30 pub version: String,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
36pub struct Page {
37 pub vcons: Vec<Row>,
39 pub next: Option<String>,
41}
42
43#[derive(Debug, Clone, PartialEq, Eq)]
45pub enum ApiError {
46 Unreachable(String),
48 Untrusted(String),
51 Status(u16, Option<String>),
54 Malformed(String),
56}
57
58impl std::error::Error for ApiError {}
59
60impl fmt::Display for ApiError {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 match self {
63 ApiError::Unreachable(why) => write!(f, "the server did not answer: {why}"),
64 ApiError::Untrusted(why) => {
65 write!(f, "the server's certificate was refused: {why}")
66 }
67 ApiError::Status(401, _) => f.write_str("the server refused the key (401)"),
68 ApiError::Status(status, Some(title)) => {
69 write!(f, "the server answered {status} ({title})")
70 }
71 ApiError::Status(status, None) => write!(f, "the server answered {status}"),
72 ApiError::Malformed(why) => {
73 write!(f, "the server's answer could not be read: {why}")
74 }
75 }
76 }
77}
78
79#[derive(Debug, Clone, PartialEq, Eq)]
81pub enum Connection {
82 Connecting,
84 Connected(KeyInfo),
86 Failed(String),
88}
89
90#[derive(Debug, Clone, PartialEq, Eq)]
92pub enum Listing {
93 Loading,
95 Ready,
97 Failed(String),
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum View {
104 List,
106 Detail,
108 Help,
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum Action {
115 Up,
117 Down,
119 Top,
121 Bottom,
123 PageUp,
125 PageDown,
127 Open,
129 Back,
131 Refresh,
133 More,
135 Help,
137 Quit,
139}
140
141#[derive(Debug, Clone, PartialEq, Eq)]
143pub enum Event {
144 Action(Action),
146 Resize(u16, u16),
148 KeyInfo(Result<KeyInfo, ApiError>),
150 Page(Result<Page, ApiError>),
152}
153
154#[derive(Debug, Clone, PartialEq, Eq)]
156pub enum Effect {
157 FetchKey,
159 FetchPage(Option<String>),
161}
162
163const FRAME_LINES: u16 = 5;
166
167#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct State {
170 pub server: String,
172 pub connection: Connection,
174 pub listing: Listing,
176 pub rows: Vec<Row>,
178 pub next: Option<String>,
180 pub selected: usize,
182 pub view: View,
184 pub behind_help: View,
186 pub detail: Option<String>,
188 pub more: bool,
190 pub as_of: Option<OffsetDateTime>,
192 pub notice: Option<String>,
194 pub size: (u16, u16),
196 pub quit: bool,
198}
199
200impl State {
201 #[must_use]
204 pub fn new(server: &str, size: (u16, u16)) -> (Self, Vec<Effect>) {
205 let state = Self {
206 server: server.to_owned(),
207 connection: Connection::Connecting,
208 listing: Listing::Loading,
209 rows: Vec::new(),
210 next: None,
211 selected: 0,
212 view: View::List,
213 behind_help: View::List,
214 detail: None,
215 more: false,
216 as_of: None,
217 notice: None,
218 size,
219 quit: false,
220 };
221 (state, vec![Effect::FetchKey])
222 }
223
224 #[must_use]
226 pub fn list_rows(lines: u16) -> u16 {
227 lines.saturating_sub(FRAME_LINES).max(1)
228 }
229
230 #[must_use]
232 pub fn detail_row(&self) -> Option<&Row> {
233 let uuid = self.detail.as_deref()?;
234 self.rows.iter().find(|row| row.uuid == uuid)
235 }
236
237 fn busy(&self) -> bool {
239 self.more
240 || self.connection == Connection::Connecting
241 || (self.listing == Listing::Loading
242 && matches!(self.connection, Connection::Connected(_)))
243 }
244
245 pub fn step(&mut self, event: Event, now: OffsetDateTime) -> Vec<Effect> {
248 match event {
249 Event::Action(action) => {
250 self.notice = None;
251 self.act(action)
252 }
253 Event::Resize(columns, lines) => {
254 self.size = (columns, lines);
255 Vec::new()
256 }
257 Event::KeyInfo(Ok(info)) => self.connected(info),
258 Event::KeyInfo(Err(error)) => {
259 self.connection = Connection::Failed(error.to_string());
260 self.listing = Listing::Failed(error.to_string());
261 Vec::new()
262 }
263 Event::Page(Ok(page)) => {
264 self.page(page, now);
265 Vec::new()
266 }
267 Event::Page(Err(error)) => {
268 self.page_failed(&error);
269 Vec::new()
270 }
271 }
272 }
273
274 fn connected(&mut self, info: KeyInfo) -> Vec<Effect> {
276 let refusal = if info.tenant.is_none() {
277 Some(
278 "this is an operator key, which reaches no vCon: use a tenant key with the read scope",
279 )
280 } else if info.scopes.iter().all(|scope| scope != "read") {
281 Some("this key lacks the read scope: use a tenant key that holds it")
282 } else {
283 None
284 };
285 self.connection = Connection::Connected(info);
286 match refusal {
287 Some(why) => {
288 self.listing = Listing::Failed(why.to_owned());
289 Vec::new()
290 }
291 None => {
292 self.listing = Listing::Loading;
293 vec![Effect::FetchPage(None)]
294 }
295 }
296 }
297
298 fn page(&mut self, page: Page, now: OffsetDateTime) {
301 if self.more {
302 self.rows.extend(page.vcons);
303 } else {
304 let on = self
305 .detail
306 .clone()
307 .or_else(|| self.rows.get(self.selected).map(|row| row.uuid.clone()));
308 self.rows = page.vcons;
309 if let Some(index) =
310 on.and_then(|uuid| self.rows.iter().position(|row| row.uuid == uuid))
311 {
312 self.selected = index;
313 }
314 }
315 self.selected = self.selected.min(self.rows.len().saturating_sub(1));
316 self.next = page.next;
317 self.more = false;
318 self.listing = Listing::Ready;
319 self.as_of = Some(now);
320 }
321
322 fn page_failed(&mut self, error: &ApiError) {
325 if matches!(error, ApiError::Unreachable(_) | ApiError::Untrusted(_)) {
326 self.connection = Connection::Failed(error.to_string());
327 }
328 if self.more {
329 self.more = false;
330 self.notice = Some(format!("The next page was not read: {error}."));
331 } else {
332 self.rows.clear();
333 self.next = None;
334 self.selected = 0;
335 self.as_of = None;
336 self.listing = Listing::Failed(error.to_string());
337 }
338 }
339
340 fn act(&mut self, action: Action) -> Vec<Effect> {
342 match (self.view, action) {
343 (_, Action::Quit) => self.quit = true,
344 (View::Help, Action::Help | Action::Back) => self.view = self.behind_help,
345 (View::Help, _) | (View::List, Action::Back) | (View::Detail, Action::Open) => {}
346 (view, Action::Help) => {
347 self.behind_help = view;
348 self.view = View::Help;
349 }
350 (View::Detail, Action::Back) => self.view = View::List,
351 (_, Action::Refresh) => return self.refresh(),
352 (_, Action::More) => return self.more(),
353 (View::List, Action::Open) => {
354 if let Some(row) = self.rows.get(self.selected) {
355 self.detail = Some(row.uuid.clone());
356 self.view = View::Detail;
357 }
358 }
359 (
360 view,
361 Action::Up
362 | Action::Down
363 | Action::Top
364 | Action::Bottom
365 | Action::PageUp
366 | Action::PageDown,
367 ) => {
368 self.travel(action);
369 if view == View::Detail
370 && let Some(row) = self.rows.get(self.selected)
371 {
372 self.detail = Some(row.uuid.clone());
373 }
374 }
375 }
376 Vec::new()
377 }
378
379 fn travel(&mut self, action: Action) {
381 let last = self.rows.len().saturating_sub(1);
382 let page = usize::from(Self::list_rows(self.size.1));
383 self.selected = match action {
384 Action::Up => self.selected.saturating_sub(1),
385 Action::Down => self.selected.saturating_add(1),
386 Action::Top => 0,
387 Action::Bottom => last,
388 Action::PageUp => self.selected.saturating_sub(page),
389 Action::PageDown => self.selected.saturating_add(page),
390 _ => self.selected,
391 }
392 .min(last);
393 }
394
395 fn refresh(&mut self) -> Vec<Effect> {
398 if self.busy() {
399 return Vec::new();
400 }
401 if let Connection::Connected(info) = &self.connection {
402 return self.connected(info.clone());
403 }
404 self.connection = Connection::Connecting;
405 self.listing = Listing::Loading;
406 vec![Effect::FetchKey]
407 }
408
409 fn more(&mut self) -> Vec<Effect> {
411 if self.busy() || self.listing != Listing::Ready {
412 return Vec::new();
413 }
414 let Some(cursor) = self.next.clone() else {
415 return Vec::new();
416 };
417 self.more = true;
418 vec![Effect::FetchPage(Some(cursor))]
419 }
420}
421
422#[cfg(test)]
423mod tests {
424 use time::OffsetDateTime;
425 use time::macros::datetime;
426
427 use super::{
428 Action, ApiError, Connection, Effect, Event, KeyInfo, Listing, Page, Row, State, View,
429 };
430
431 const NOW: OffsetDateTime = datetime!(2026-11-10 01:20:00 UTC);
432
433 fn row(n: u8) -> Row {
434 Row {
435 uuid: format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc{n:02}"),
436 stored_at: "2026-10-25T12:00:00.123456789Z".to_owned(),
437 updated_at: "2026-10-25T12:30:00Z".to_owned(),
438 version: format!("4f0c4b0a1d2e3f405162738495a6b7{n:02}"),
439 }
440 }
441
442 fn reader() -> KeyInfo {
443 KeyInfo {
444 id: "0123456789abcdef".to_owned(),
445 tenant: Some("t_example".to_owned()),
446 scopes: vec!["read".to_owned()],
447 }
448 }
449
450 fn page(rows: std::ops::Range<u8>, next: Option<&str>) -> Page {
451 Page {
452 vcons: rows.map(row).collect(),
453 next: next.map(str::to_owned),
454 }
455 }
456
457 fn listed(rows: u8, next: Option<&str>) -> State {
459 let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
460 state.step(Event::KeyInfo(Ok(reader())), NOW);
461 state.step(Event::Page(Ok(page(0..rows, next))), NOW);
462 state
463 }
464
465 fn press(state: &mut State, action: Action) -> Vec<Effect> {
466 state.step(Event::Action(action), NOW)
467 }
468
469 #[test]
472 fn a_new_state_is_connecting_and_asks_for_the_key() {
473 let (state, effects) = State::new("https://vcon.example.com:8443", (80, 24));
474 assert_eq!(
475 state.connection,
476 Connection::Connecting,
477 "nothing has answered yet"
478 );
479 assert_eq!(
480 effects,
481 [Effect::FetchKey],
482 "the key's tenant and scopes come first"
483 );
484 }
485
486 #[test]
487 fn a_reader_key_connects_and_asks_for_the_first_page() {
488 let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
489 let effects = state.step(Event::KeyInfo(Ok(reader())), NOW);
490 assert_eq!(
491 state.connection,
492 Connection::Connected(reader()),
493 "the key answered"
494 );
495 assert_eq!(state.listing, Listing::Loading, "the page is on its way");
496 assert_eq!(
497 effects,
498 [Effect::FetchPage(None)],
499 "the first page has no cursor"
500 );
501 }
502
503 #[test]
504 fn a_page_fills_the_list_and_records_when() {
505 let state = listed(3, Some("cursor-1"));
506 assert_eq!(state.listing, Listing::Ready, "the page arrived");
507 assert_eq!(state.rows.len(), 3, "every row of the page is kept");
508 assert_eq!(
509 state.next.as_deref(),
510 Some("cursor-1"),
511 "the cursor is kept for more"
512 );
513 assert_eq!(
514 state.as_of,
515 Some(NOW),
516 "the clock passed in is when it was read"
517 );
518 }
519
520 #[test]
521 fn down_and_up_move_the_selection() {
522 let mut state = listed(3, None);
523 press(&mut state, Action::Down);
524 press(&mut state, Action::Down);
525 assert_eq!(state.selected, 2, "two rows down");
526 press(&mut state, Action::Up);
527 assert_eq!(state.selected, 1, "one row back up");
528 }
529
530 #[test]
531 fn bottom_and_top_jump_to_the_ends() {
532 let mut state = listed(5, None);
533 press(&mut state, Action::Bottom);
534 assert_eq!(state.selected, 4, "the last row");
535 press(&mut state, Action::Top);
536 assert_eq!(state.selected, 0, "the first row");
537 }
538
539 #[test]
540 fn open_shows_the_selected_vcon_and_back_returns() {
541 let mut state = listed(3, None);
542 press(&mut state, Action::Down);
543 let effects = press(&mut state, Action::Open);
544 assert_eq!(state.view, View::Detail, "the detail view is open");
545 assert_eq!(
546 state.detail,
547 Some(row(1).uuid),
548 "on the row that was selected"
549 );
550 assert_eq!(
551 effects,
552 [],
553 "the detail is drawn from the list row: no request"
554 );
555 press(&mut state, Action::Back);
556 assert_eq!(state.view, View::List, "back at the list");
557 }
558
559 #[test]
560 fn more_asks_for_the_next_page_and_appends_it() {
561 let mut state = listed(2, Some("cursor-1"));
562 let effects = press(&mut state, Action::More);
563 assert_eq!(
564 effects,
565 [Effect::FetchPage(Some("cursor-1".to_owned()))],
566 "the cursor goes back unchanged"
567 );
568 state.step(Event::Page(Ok(page(2..4, None))), NOW);
569 assert_eq!(state.rows.len(), 4, "the second page follows the first");
570 assert_eq!(state.next, None, "the last page has no cursor");
571 }
572
573 #[test]
574 fn refresh_asks_for_the_first_page_again_and_replaces_the_rows() {
575 let mut state = listed(3, None);
576 let effects = press(&mut state, Action::Refresh);
577 assert_eq!(effects, [Effect::FetchPage(None)], "from the start");
578 assert_eq!(
579 state.listing,
580 Listing::Loading,
581 "loading is shown meanwhile"
582 );
583 state.step(Event::Page(Ok(page(0..1, None))), NOW);
584 assert_eq!(state.rows.len(), 1, "the new page replaces the old rows");
585 }
586
587 #[test]
588 fn help_opens_over_a_view_and_returns_to_it() {
589 let mut state = listed(3, None);
590 press(&mut state, Action::Open);
591 press(&mut state, Action::Help);
592 assert_eq!(state.view, View::Help, "help is open");
593 press(&mut state, Action::Back);
594 assert_eq!(
595 state.view,
596 View::Detail,
597 "back at the view help was opened from"
598 );
599 }
600
601 #[test]
602 fn quit_ends_from_every_view() {
603 for open in [None, Some(Action::Open), Some(Action::Help)] {
604 let mut state = listed(1, None);
605 if let Some(open) = open {
606 press(&mut state, open);
607 }
608 press(&mut state, Action::Quit);
609 assert!(state.quit, "quit ends from {:?}", state.view);
610 }
611 }
612
613 #[test]
614 fn page_down_moves_by_the_rows_the_terminal_shows() {
615 let mut state = listed(60, None);
616 press(&mut state, Action::PageDown);
617 assert_eq!(
618 state.selected,
619 usize::from(State::list_rows(24)),
620 "a 24-line terminal pages by its list rows"
621 );
622 press(&mut state, Action::PageUp);
623 assert_eq!(state.selected, 0, "and back");
624 }
625
626 #[test]
627 fn down_in_the_detail_view_shows_the_next_vcon() {
628 let mut state = listed(3, None);
629 press(&mut state, Action::Open);
630 press(&mut state, Action::Down);
631 assert_eq!(
632 state.detail,
633 Some(row(1).uuid),
634 "the detail follows the selection"
635 );
636 }
637
638 #[test]
639 fn a_refresh_keeps_the_selection_on_the_same_vcon() {
640 let mut state = listed(3, None);
641 press(&mut state, Action::Bottom);
642 press(&mut state, Action::Open);
643 press(&mut state, Action::Refresh);
644 state.step(Event::Page(Ok(page(1..3, None))), NOW);
645 assert_eq!(
646 state.selected, 1,
647 "the vCon moved up one row and the selection with it"
648 );
649 assert_eq!(
650 state.detail,
651 Some(row(2).uuid),
652 "the detail is still that vCon"
653 );
654 }
655
656 #[test]
659 fn an_unreachable_server_fails_the_connection_and_the_list() {
660 let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
661 let effects = state.step(
662 Event::KeyInfo(Err(ApiError::Unreachable("connection refused".to_owned()))),
663 NOW,
664 );
665 assert_eq!(
666 effects,
667 [],
668 "nothing more is asked of a server that did not answer"
669 );
670 assert!(
671 matches!(&state.connection, Connection::Failed(why) if why.contains("connection refused")),
672 "the status line says why: {:?}",
673 state.connection
674 );
675 assert!(
676 matches!(state.listing, Listing::Failed(_)),
677 "the list says so too"
678 );
679 }
680
681 #[test]
682 fn a_refused_key_says_the_status() {
683 let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
684 state.step(Event::KeyInfo(Err(ApiError::Status(401, None))), NOW);
685 assert!(
686 matches!(&state.connection, Connection::Failed(why) if why.contains("401")),
687 "the refusal's status is shown: {:?}",
688 state.connection
689 );
690 }
691
692 #[test]
693 fn an_operator_key_connects_but_lists_nothing() {
694 let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
695 let operator = KeyInfo {
696 id: "0123456789abcdef".to_owned(),
697 tenant: None,
698 scopes: vec!["admin".to_owned()],
699 };
700 let effects = state.step(Event::KeyInfo(Ok(operator)), NOW);
701 assert_eq!(
702 effects,
703 [],
704 "an operator key reaches no vCon, so none is asked for"
705 );
706 assert!(
707 matches!(&state.listing, Listing::Failed(why) if why.contains("operator key")),
708 "the list says which key to use: {:?}",
709 state.listing
710 );
711 }
712
713 #[test]
714 fn a_key_without_read_lists_nothing() {
715 let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
716 let writer = KeyInfo {
717 scopes: vec!["write".to_owned()],
718 ..reader()
719 };
720 let effects = state.step(Event::KeyInfo(Ok(writer)), NOW);
721 assert_eq!(effects, [], "the list needs read, so it is not asked for");
722 assert!(
723 matches!(&state.listing, Listing::Failed(why) if why.contains("read scope")),
724 "the list names the scope: {:?}",
725 state.listing
726 );
727 }
728
729 #[test]
730 fn a_failed_first_page_is_an_error_state() {
731 let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
732 state.step(Event::KeyInfo(Ok(reader())), NOW);
733 state.step(
734 Event::Page(Err(ApiError::Status(503, Some("unavailable".to_owned())))),
735 NOW,
736 );
737 assert!(
738 matches!(&state.listing, Listing::Failed(why) if why.contains("503") && why.contains("unavailable")),
739 "the status and the problem's title are shown: {:?}",
740 state.listing
741 );
742 assert_eq!(state.as_of, None, "nothing was read, so no time is claimed");
743 }
744
745 #[test]
746 fn a_failed_next_page_keeps_the_rows_and_leaves_a_notice() {
747 let mut state = listed(2, Some("cursor-1"));
748 press(&mut state, Action::More);
749 state.step(
750 Event::Page(Err(ApiError::Unreachable("timed out".to_owned()))),
751 NOW,
752 );
753 assert_eq!(state.rows.len(), 2, "the rows already read stay");
754 assert_eq!(state.listing, Listing::Ready, "the list is still usable");
755 assert_eq!(
756 state.next.as_deref(),
757 Some("cursor-1"),
758 "the cursor is kept to try again"
759 );
760 assert!(
761 state
762 .notice
763 .as_deref()
764 .is_some_and(|n| n.contains("timed out")),
765 "a notice says why: {:?}",
766 state.notice
767 );
768 }
769
770 #[test]
771 fn a_failed_refresh_drops_the_old_rows() {
772 let mut state = listed(2, None);
773 press(&mut state, Action::Refresh);
774 state.step(Event::Page(Err(ApiError::Status(500, None))), NOW);
775 assert!(
776 matches!(state.listing, Listing::Failed(_)),
777 "the error is shown"
778 );
779 assert_eq!(
780 state.rows,
781 [],
782 "rows that may be out of date are not shown as current"
783 );
784 }
785
786 #[test]
787 fn a_malformed_answer_is_an_error_state() {
788 let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
789 state.step(Event::KeyInfo(Ok(reader())), NOW);
790 state.step(
791 Event::Page(Err(ApiError::Malformed("expected value".to_owned()))),
792 NOW,
793 );
794 assert!(
795 matches!(&state.listing, Listing::Failed(why) if why.contains("expected value")),
796 "what could not be read is shown: {:?}",
797 state.listing
798 );
799 }
800
801 #[test]
802 fn refresh_after_a_failed_connection_asks_for_the_key_again() {
803 let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
804 state.step(
805 Event::KeyInfo(Err(ApiError::Unreachable("refused".to_owned()))),
806 NOW,
807 );
808 let effects = press(&mut state, Action::Refresh);
809 assert_eq!(
810 effects,
811 [Effect::FetchKey],
812 "the connection is made again from the start"
813 );
814 assert_eq!(
815 state.connection,
816 Connection::Connecting,
817 "and shown as such"
818 );
819 }
820
821 #[test]
822 fn a_server_that_stops_answering_is_shown_as_not_connected() {
823 let mut state = listed(2, None);
824 press(&mut state, Action::Refresh);
825 state.step(
826 Event::Page(Err(ApiError::Unreachable("connection reset".to_owned()))),
827 NOW,
828 );
829 assert!(
830 matches!(state.connection, Connection::Failed(_)),
831 "the status line no longer says connected"
832 );
833 }
834
835 #[test]
836 fn a_vcon_gone_after_a_refresh_leaves_the_detail_without_a_row() {
837 let mut state = listed(2, None);
838 press(&mut state, Action::Open);
839 press(&mut state, Action::Refresh);
840 state.step(Event::Page(Ok(page(1..2, None))), NOW);
841 assert_eq!(
842 state.detail,
843 Some(row(0).uuid),
844 "the detail still names what was open"
845 );
846 assert_eq!(state.detail_row(), None, "and has no row to draw");
847 }
848
849 #[test]
850 fn each_api_error_says_what_failed() {
851 for (error, text) in [
852 (
853 ApiError::Unreachable("refused".to_owned()),
854 "the server did not answer: refused",
855 ),
856 (
857 ApiError::Status(401, None),
858 "the server refused the key (401)",
859 ),
860 (
861 ApiError::Status(403, Some("forbidden".to_owned())),
862 "the server answered 403 (forbidden)",
863 ),
864 (ApiError::Status(500, None), "the server answered 500"),
865 (
866 ApiError::Malformed("eof".to_owned()),
867 "the server's answer could not be read: eof",
868 ),
869 ] {
870 assert_eq!(error.to_string(), text, "{error:?}");
871 }
872 }
873
874 #[test]
877 fn up_at_the_top_and_down_at_the_bottom_stay() {
878 let mut state = listed(2, None);
879 press(&mut state, Action::Up);
880 assert_eq!(state.selected, 0, "no row above the first");
881 press(&mut state, Action::Bottom);
882 press(&mut state, Action::Down);
883 assert_eq!(state.selected, 1, "no row below the last");
884 }
885
886 #[test]
887 fn open_on_an_empty_list_does_nothing() {
888 let mut state = listed(0, None);
889 press(&mut state, Action::Open);
890 assert_eq!(state.view, View::List, "there is nothing to open");
891 assert_eq!(state.detail, None, "and no vCon is named");
892 }
893
894 #[test]
895 fn movement_on_an_empty_list_stays_at_zero() {
896 let mut state = listed(0, None);
897 for action in [Action::Down, Action::Bottom, Action::PageDown, Action::Up] {
898 press(&mut state, action);
899 assert_eq!(state.selected, 0, "{action:?} on no rows");
900 }
901 }
902
903 #[test]
904 fn more_on_the_last_page_asks_for_nothing() {
905 let mut state = listed(2, None);
906 assert_eq!(press(&mut state, Action::More), [], "there is no next page");
907 }
908
909 #[test]
910 fn a_second_refresh_while_loading_asks_for_nothing() {
911 let mut state = listed(2, None);
912 press(&mut state, Action::Refresh);
913 assert_eq!(
914 press(&mut state, Action::Refresh),
915 [],
916 "one request is in flight; a second would race it"
917 );
918 }
919
920 #[test]
921 fn more_while_more_is_loading_asks_for_nothing() {
922 let mut state = listed(2, Some("cursor-1"));
923 press(&mut state, Action::More);
924 assert_eq!(
925 press(&mut state, Action::More),
926 [],
927 "the page is already on its way"
928 );
929 assert_eq!(
930 press(&mut state, Action::Refresh),
931 [],
932 "and a refresh would race it"
933 );
934 }
935
936 #[test]
937 fn refresh_while_connecting_asks_for_nothing() {
938 let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
939 assert_eq!(
940 press(&mut state, Action::Refresh),
941 [],
942 "the key request is in flight"
943 );
944 }
945
946 #[test]
947 fn a_resize_changes_only_the_size() {
948 let mut state = listed(3, None);
949 press(&mut state, Action::Down);
950 let before = state.clone();
951 let effects = state.step(Event::Resize(132, 43), NOW);
952 assert_eq!(effects, [], "a resize asks the server nothing");
953 assert_eq!(state.size, (132, 43), "the new size is kept");
954 assert_eq!(
955 State {
956 size: before.size,
957 ..state
958 },
959 before,
960 "nothing else changed"
961 );
962 }
963
964 #[test]
965 fn a_shorter_page_after_refresh_clamps_the_selection() {
966 let mut state = listed(5, None);
967 press(&mut state, Action::Bottom);
968 press(&mut state, Action::Refresh);
969 state.step(Event::Page(Ok(page(10..12, None))), NOW);
970 assert_eq!(
971 state.selected, 1,
972 "the selection is the last row that exists"
973 );
974 }
975
976 #[test]
977 fn page_down_past_the_end_stops_at_the_last_row() {
978 let mut state = listed(3, None);
979 press(&mut state, Action::PageDown);
980 assert_eq!(state.selected, 2, "the last row, not past it");
981 }
982
983 #[test]
984 fn a_terminal_too_short_for_a_list_still_pages_by_one() {
985 assert_eq!(State::list_rows(0), 1, "never zero: paging would not move");
986 assert_eq!(State::list_rows(5), 1, "the frame takes five lines");
987 assert_eq!(State::list_rows(24), 19, "24 lines leave 19 for rows");
988 }
989
990 #[test]
991 fn help_from_help_closes_it() {
992 let mut state = listed(1, None);
993 press(&mut state, Action::Help);
994 press(&mut state, Action::Help);
995 assert_eq!(state.view, View::List, "the same key closes help");
996 }
997
998 #[test]
999 fn a_key_press_clears_the_notice() {
1000 let mut state = listed(2, Some("cursor-1"));
1001 press(&mut state, Action::More);
1002 state.step(
1003 Event::Page(Err(ApiError::Unreachable("timed out".to_owned()))),
1004 NOW,
1005 );
1006 press(&mut state, Action::Down);
1007 assert_eq!(
1008 state.notice, None,
1009 "the notice is about the last request only"
1010 );
1011 }
1012
1013 #[test]
1014 fn back_in_the_list_view_does_not_quit() {
1015 let mut state = listed(1, None);
1016 press(&mut state, Action::Back);
1017 assert!(!state.quit, "only the quit keys end the program");
1018 assert_eq!(state.view, View::List, "and the view stays");
1019 }
1020}