Skip to main content

vcon_server/tui/
state.rs

1//! The terminal UI's state machine: a state and an event give the next
2//! state and the requests to make. It draws nothing, reads no clock and
3//! calls no server, so every transition can be tested as a value.
4
5use std::fmt;
6
7use serde::Deserialize;
8use time::OffsetDateTime;
9
10use crate::reveal::Part;
11
12/// What `GET /key` answers: the key in use.
13#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
14pub struct KeyInfo {
15    /// The key's id. Not the token: an id opens nothing.
16    pub id: String,
17    /// The key's tenant; `None` for an operator key.
18    pub tenant: Option<String>,
19    /// The scopes the key holds.
20    pub scopes: Vec<String>,
21}
22
23/// One vCon of a `GET /vcons` page: the metadata the API lists.
24#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
25pub struct Row {
26    /// The vCon's uuid.
27    pub uuid: String,
28    /// When the uuid was first stored, RFC 3339 in UTC.
29    pub stored_at: String,
30    /// When the current version was stored, RFC 3339 in UTC.
31    pub updated_at: String,
32    /// The current version: the `ETag` without quotes.
33    pub version: String,
34}
35
36/// One page of `GET /vcons`.
37#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
38pub struct Page {
39    /// The page's vCons, newest first.
40    pub vcons: Vec<Row>,
41    /// The cursor of the next page; `None` on the last.
42    pub next: Option<String>,
43}
44
45/// Why a request gave no answer to show. None of these holds the token.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum ApiError {
48    /// No answer arrived: the address, TLS or the network.
49    Unreachable(String),
50    /// The client refused the server's certificate, so no request was
51    /// sent: what is wrong with it and what to do.
52    Untrusted(String),
53    /// The server answered this status, with the problem's title if it
54    /// sent one.
55    Status(u16, Option<String>),
56    /// The answer was not the JSON the API describes.
57    Malformed(String),
58}
59
60impl std::error::Error for ApiError {}
61
62impl fmt::Display for ApiError {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        match self {
65            ApiError::Unreachable(why) => write!(f, "the server did not answer: {why}"),
66            ApiError::Untrusted(why) => {
67                write!(f, "the server's certificate was refused: {why}")
68            }
69            ApiError::Status(401, _) => f.write_str("the server refused the key (401)"),
70            ApiError::Status(status, Some(title)) => {
71                write!(f, "the server answered {status} ({title})")
72            }
73            ApiError::Status(status, None) => write!(f, "the server answered {status}"),
74            ApiError::Malformed(why) => {
75                write!(f, "the server's answer could not be read: {why}")
76            }
77        }
78    }
79}
80
81/// Whether the server has answered for the key.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub enum Connection {
84    /// `GET /key` is in flight.
85    Connecting,
86    /// The server answered for this key.
87    Connected(KeyInfo),
88    /// The server did not answer, or refused the key; why.
89    Failed(String),
90}
91
92/// The state of the list of vCons.
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub enum Listing {
95    /// The first page is in flight.
96    Loading,
97    /// The rows are what the server last answered.
98    Ready,
99    /// There is no list to show; why.
100    Failed(String),
101}
102
103/// Which view is drawn.
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub enum View {
106    /// The tenant's vCons.
107    List,
108    /// One vCon's metadata.
109    Detail,
110    /// The key bindings.
111    Help,
112}
113
114/// What a key press asks for.
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116pub enum Action {
117    /// Select the row above.
118    Up,
119    /// Select the row below.
120    Down,
121    /// Select the first row.
122    Top,
123    /// Select the last row.
124    Bottom,
125    /// Move up by the rows on screen.
126    PageUp,
127    /// Move down by the rows on screen.
128    PageDown,
129    /// Open the selected vCon.
130    Open,
131    /// Leave the detail or help view.
132    Back,
133    /// Read the list again from the server.
134    Refresh,
135    /// Read the next page.
136    More,
137    /// Open or close help.
138    Help,
139    /// End the program.
140    Quit,
141    /// Reveal a part of the vCon open: ask the server for it as a reveal
142    /// of that part, which the audit log records, and show it.
143    Reveal(Part),
144}
145
146/// The masked view of the vCon open in the detail view.
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub enum Content {
149    /// No vCon is open.
150    None,
151    /// `GET /vcons/{uuid}?view=masked` is in flight.
152    Reading,
153    /// The masked view, as the lines the detail view shows.
154    Ready(Vec<String>),
155    /// The masked view was not read: why.
156    Failed(String),
157}
158
159/// The part of the vCon open that was revealed, if one was asked for.
160#[derive(Debug, Clone, PartialEq, Eq)]
161pub enum Revealed {
162    /// The reveal is in flight.
163    Reading(Part),
164    /// The part, as text.
165    Shown(Part, String),
166    /// The reveal was refused or did not arrive: why.
167    Failed(Part, String),
168}
169
170/// What happened.
171#[derive(Debug, Clone, PartialEq, Eq)]
172pub enum Event {
173    /// A key press, as its action.
174    Action(Action),
175    /// The terminal is now this many columns and lines.
176    Resize(u16, u16),
177    /// `GET /key` finished.
178    KeyInfo(Result<KeyInfo, ApiError>),
179    /// `GET /vcons` finished.
180    Page(Result<Page, ApiError>),
181    /// `GET /vcons/{uuid}?view=masked` finished for this uuid: the masked
182    /// view as lines.
183    Masked(String, Result<Vec<String>, ApiError>),
184    /// `GET /vcons/{uuid}?reveal=<part>` finished for this uuid and part:
185    /// the part as text.
186    Revealed(String, Part, Result<String, ApiError>),
187}
188
189/// A request for the caller to make; its answer comes back as an [`Event`].
190#[derive(Debug, Clone, PartialEq, Eq)]
191pub enum Effect {
192    /// `GET /key`.
193    FetchKey,
194    /// `GET /vcons`, from this cursor or from the start.
195    FetchPage(Option<String>),
196    /// `GET /vcons/{uuid}?view=masked`.
197    FetchMasked(String),
198    /// `GET /vcons/{uuid}?reveal=<part>`.
199    FetchReveal(String, Part),
200}
201
202/// The lines a frame takes around the list's rows: the status line, the
203/// column header, a blank line, the notice line and the key hints.
204const FRAME_LINES: u16 = 5;
205
206/// Everything the UI shows. It never holds the token.
207#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct State {
209    /// The server's address, as the client file gives it.
210    pub server: String,
211    /// Whether the server has answered for the key.
212    pub connection: Connection,
213    /// The state of the list.
214    pub listing: Listing,
215    /// The vCons read so far, newest first.
216    pub rows: Vec<Row>,
217    /// The cursor of the next page, if there is one.
218    pub next: Option<String>,
219    /// The selected row's index in `rows`.
220    pub selected: usize,
221    /// The view drawn.
222    pub view: View,
223    /// The view help was opened from.
224    pub behind_help: View,
225    /// The uuid the detail view shows.
226    pub detail: Option<String>,
227    /// Whether a next page is in flight.
228    pub more: bool,
229    /// When the rows were last read from the server.
230    pub as_of: Option<OffsetDateTime>,
231    /// What went wrong with the last request, when the list is still shown.
232    pub notice: Option<String>,
233    /// The terminal's columns and lines.
234    pub size: (u16, u16),
235    /// Whether the program should end.
236    pub quit: bool,
237    /// The masked view of the vCon open.
238    pub content: Content,
239    /// The part of the vCon open that was revealed. It is dropped when the
240    /// detail view is left, another vCon is shown, or the list is read
241    /// again.
242    pub revealed: Option<Revealed>,
243    /// The first line of the detail view shown, for a text longer than
244    /// the screen.
245    pub scroll: usize,
246}
247
248impl State {
249    /// The state at start for the server at `server` in a terminal of
250    /// `size` columns and lines, and the first request.
251    #[must_use]
252    pub fn new(server: &str, size: (u16, u16)) -> (Self, Vec<Effect>) {
253        let state = Self {
254            server: server.to_owned(),
255            connection: Connection::Connecting,
256            listing: Listing::Loading,
257            rows: Vec::new(),
258            next: None,
259            selected: 0,
260            view: View::List,
261            behind_help: View::List,
262            detail: None,
263            more: false,
264            as_of: None,
265            notice: None,
266            size,
267            quit: false,
268            content: Content::None,
269            revealed: None,
270            scroll: 0,
271        };
272        (state, vec![Effect::FetchKey])
273    }
274
275    /// The rows of the list a terminal of `lines` lines shows: at least 1.
276    #[must_use]
277    pub fn list_rows(lines: u16) -> u16 {
278        lines.saturating_sub(FRAME_LINES).max(1)
279    }
280
281    /// The row the detail view shows, if the list still holds it.
282    #[must_use]
283    pub fn detail_row(&self) -> Option<&Row> {
284        let uuid = self.detail.as_deref()?;
285        self.rows.iter().find(|row| row.uuid == uuid)
286    }
287
288    /// Whether a request is in flight, so another would race it.
289    fn busy(&self) -> bool {
290        self.more
291            || self.connection == Connection::Connecting
292            || (self.listing == Listing::Loading
293                && matches!(self.connection, Connection::Connected(_)))
294    }
295
296    /// Whether a press of the key for `action` can do anything in this
297    /// state. The footer names only keys that act.
298    #[must_use]
299    pub fn acts(&self, action: Action) -> bool {
300        match (self.view, action) {
301            (_, Action::Quit | Action::Help) | (View::Help | View::Detail, Action::Back) => true,
302            (View::Help, _)
303            | (View::List, Action::Back | Action::Reveal(_))
304            | (View::Detail, Action::Open) => false,
305            (View::Detail, Action::Reveal(_)) => {
306                matches!(self.content, Content::Ready(_)) && self.detail_row().is_some()
307            }
308            (View::Detail, Action::PageDown) => self.scroll < self.scroll_most(),
309            (View::Detail, Action::PageUp) => self.scroll > 0,
310            (_, Action::Refresh) => !self.busy() && self.key_refusal().is_none(),
311            (_, Action::More) => {
312                !self.busy() && self.listing == Listing::Ready && self.next.is_some()
313            }
314            (View::List, Action::Open) => self.rows_shown() && !self.rows.is_empty(),
315            (
316                view,
317                Action::Up
318                | Action::Down
319                | Action::Top
320                | Action::Bottom
321                | Action::PageUp
322                | Action::PageDown,
323            ) => {
324                // In a detail view whose vCon left the list, a key that
325                // moves shows the selected row, even when it is the only one.
326                let reselects =
327                    view == View::Detail && !self.rows.is_empty() && self.detail_row().is_none();
328                self.rows_shown() && (self.rows.len() > 1 || reselects)
329            }
330        }
331    }
332
333    /// Whether the screen shows the rows, or the detail of one: the list
334    /// is read. Otherwise a message stands in their place, and there is no
335    /// selection to move or open. While a connection is being made the
336    /// list is being read too, so the listing alone decides.
337    #[must_use]
338    pub fn rows_shown(&self) -> bool {
339        self.listing == Listing::Ready
340    }
341
342    /// Why the key the server answered for may not list vCons, if it may
343    /// not. The key is read once, at start, so no request changes this.
344    #[must_use]
345    pub fn key_refusal(&self) -> Option<&'static str> {
346        match &self.connection {
347            Connection::Connected(info) => refusal(info),
348            Connection::Connecting | Connection::Failed(_) => None,
349        }
350    }
351
352    /// Applies `event`, which happened at `now`, and returns the requests
353    /// to make.
354    pub fn step(&mut self, event: Event, now: OffsetDateTime) -> Vec<Effect> {
355        match event {
356            Event::Action(action) => {
357                self.notice = None;
358                self.act(action)
359            }
360            Event::Resize(columns, lines) => {
361                self.size = (columns, lines);
362                Vec::new()
363            }
364            Event::KeyInfo(Ok(info)) => self.connected(info),
365            Event::KeyInfo(Err(error)) => {
366                self.connection = Connection::Failed(error.to_string());
367                self.listing = Listing::Failed(error.to_string());
368                Vec::new()
369            }
370            Event::Page(Ok(page)) => {
371                self.page(page, now);
372                Vec::new()
373            }
374            Event::Page(Err(error)) => {
375                self.page_failed(&error);
376                Vec::new()
377            }
378            Event::Masked(uuid, answer) => {
379                self.masked_arrived(&uuid, answer);
380                Vec::new()
381            }
382            Event::Revealed(uuid, part, answer) => {
383                self.reveal_arrived(&uuid, part, answer);
384                Vec::new()
385            }
386        }
387    }
388
389    /// The key answered: asks for the first page if the key may list.
390    fn connected(&mut self, info: KeyInfo) -> Vec<Effect> {
391        let refusal = refusal(&info);
392        self.connection = Connection::Connected(info);
393        match refusal {
394            Some(why) => {
395                self.listing = Listing::Failed(why.to_owned());
396                Vec::new()
397            }
398            None => {
399                self.listing = Listing::Loading;
400                vec![Effect::FetchPage(None)]
401            }
402        }
403    }
404
405    /// A page arrived: a next page is appended, a first page replaces the
406    /// rows and the selection follows the vCon it was on.
407    fn page(&mut self, page: Page, now: OffsetDateTime) {
408        if self.more {
409            self.rows.extend(page.vcons);
410        } else {
411            let on = self
412                .detail
413                .clone()
414                .or_else(|| self.rows.get(self.selected).map(|row| row.uuid.clone()));
415            self.rows = page.vcons;
416            if let Some(index) =
417                on.and_then(|uuid| self.rows.iter().position(|row| row.uuid == uuid))
418            {
419                self.selected = index;
420            }
421        }
422        self.selected = self.selected.min(self.rows.len().saturating_sub(1));
423        self.next = page.next;
424        self.more = false;
425        self.listing = Listing::Ready;
426        self.as_of = Some(now);
427    }
428
429    /// A page did not arrive: a next page leaves the rows and a notice, a
430    /// first page leaves an error in place of rows that may be out of date.
431    /// A server that did not answer, or that no longer takes the key (401),
432    /// is not connected, as at start, so the next refresh asks for the key
433    /// again.
434    fn page_failed(&mut self, error: &ApiError) {
435        if matches!(
436            error,
437            ApiError::Unreachable(_) | ApiError::Untrusted(_) | ApiError::Status(401, _)
438        ) {
439            self.connection = Connection::Failed(error.to_string());
440        }
441        if self.more {
442            self.more = false;
443            self.notice = Some(format!("The next page was not read: {error}."));
444        } else {
445            self.rows.clear();
446            self.next = None;
447            self.selected = 0;
448            self.as_of = None;
449            self.listing = Listing::Failed(error.to_string());
450        }
451    }
452
453    /// Applies a key press.
454    fn act(&mut self, action: Action) -> Vec<Effect> {
455        match (self.view, action) {
456            (_, Action::Quit) => self.quit = true,
457            (View::Help, Action::Help | Action::Back) => self.view = self.behind_help,
458            (View::Help, _)
459            | (View::List, Action::Back | Action::Reveal(_))
460            | (View::Detail, Action::Open) => {}
461            (view, Action::Help) => {
462                self.behind_help = view;
463                self.view = View::Help;
464            }
465            (View::Detail, Action::Back) => {
466                self.view = View::List;
467                self.content = Content::None;
468                self.drop_revealed();
469            }
470            (View::Detail, Action::Reveal(part)) => return self.reveal(part),
471            (View::Detail, Action::PageDown) => {
472                let page = Self::page_lines(self.size.1);
473                self.scroll = self.scroll.saturating_add(page).min(self.scroll_most());
474            }
475            (View::Detail, Action::PageUp) => {
476                self.scroll = self.scroll.saturating_sub(Self::page_lines(self.size.1));
477            }
478            (view, Action::Refresh) => {
479                let mut effects = self.refresh();
480                if view == View::Detail {
481                    self.drop_revealed();
482                    if !effects.is_empty()
483                        && let Some(uuid) = self.detail.clone()
484                    {
485                        self.content = Content::Reading;
486                        effects.push(Effect::FetchMasked(uuid));
487                    }
488                }
489                return effects;
490            }
491            (_, Action::More) => return self.more(),
492            // A message stands in place of the rows: nothing to open or
493            // to move from.
494            (
495                _,
496                Action::Open
497                | Action::Up
498                | Action::Down
499                | Action::Top
500                | Action::Bottom
501                | Action::PageUp
502                | Action::PageDown,
503            ) if !self.rows_shown() => {}
504            (View::List, Action::Open) => {
505                if let Some(row) = self.rows.get(self.selected) {
506                    let uuid = row.uuid.clone();
507                    self.view = View::Detail;
508                    return self.show(uuid);
509                }
510            }
511            (
512                view,
513                Action::Up
514                | Action::Down
515                | Action::Top
516                | Action::Bottom
517                | Action::PageUp
518                | Action::PageDown,
519            ) => {
520                self.travel(action);
521                if view == View::Detail
522                    && let Some(row) = self.rows.get(self.selected)
523                    && self.detail.as_deref() != Some(row.uuid.as_str())
524                {
525                    let uuid = row.uuid.clone();
526                    return self.show(uuid);
527                }
528            }
529        }
530        Vec::new()
531    }
532
533    /// Shows `uuid` in the detail view: its masked view is asked for, and
534    /// nothing of another vCon is kept.
535    fn show(&mut self, uuid: String) -> Vec<Effect> {
536        self.detail = Some(uuid.clone());
537        self.content = Content::Reading;
538        self.drop_revealed();
539        vec![Effect::FetchMasked(uuid)]
540    }
541
542    /// Asks for `part` of the vCon open, once its masked view is shown.
543    fn reveal(&mut self, part: Part) -> Vec<Effect> {
544        if !self.acts(Action::Reveal(part)) {
545            return Vec::new();
546        }
547        let Some(uuid) = self.detail.clone() else {
548            return Vec::new();
549        };
550        self.revealed = Some(Revealed::Reading(part));
551        self.scroll_to_revealed();
552        vec![Effect::FetchReveal(uuid, part)]
553    }
554
555    /// Moves the view to the line above the part revealed, as far as the
556    /// text allows, so the part is on the screen.
557    fn scroll_to_revealed(&mut self) {
558        let kept = self.revealed.take();
559        let top = crate::tui::view::detail_lines(self, self.size.0).len();
560        self.revealed = kept;
561        self.scroll = top.min(self.scroll_most());
562    }
563
564    /// Drops the revealed text and goes back to the top of the view.
565    fn drop_revealed(&mut self) {
566        self.revealed = None;
567        self.scroll = 0;
568    }
569
570    /// Whether an answer for `uuid` is for the detail view as it stands:
571    /// that vCon is open, under help or not.
572    fn showing(&self, uuid: &str) -> bool {
573        let detail = self.view == View::Detail
574            || (self.view == View::Help && self.behind_help == View::Detail);
575        detail && self.detail.as_deref() == Some(uuid)
576    }
577
578    /// A masked view arrived: it is shown if it is the one awaited.
579    fn masked_arrived(&mut self, uuid: &str, answer: Result<Vec<String>, ApiError>) {
580        if self.showing(uuid) && self.content == Content::Reading {
581            self.content = match answer {
582                Ok(lines) => Content::Ready(lines),
583                Err(error) => Content::Failed(error.to_string()),
584            };
585        }
586    }
587
588    /// A revealed part arrived: it is shown if it is the one awaited.
589    fn reveal_arrived(&mut self, uuid: &str, part: Part, answer: Result<String, ApiError>) {
590        if self.showing(uuid) && self.revealed == Some(Revealed::Reading(part)) {
591            self.revealed = Some(match answer {
592                Ok(text) => Revealed::Shown(part, text),
593                Err(error) => Revealed::Failed(part, error.to_string()),
594            });
595            self.scroll_to_revealed();
596        }
597    }
598
599    /// The lines PgUp and PgDn move the detail view by, in a terminal of
600    /// `lines` lines: the lines its body shows at least.
601    #[must_use]
602    pub fn page_lines(lines: u16) -> usize {
603        usize::from(Self::list_rows(lines))
604    }
605
606    /// The furthest the detail view can be moved down: its text, at the
607    /// terminal's width, less one page.
608    fn scroll_most(&self) -> usize {
609        crate::tui::view::detail_lines(self, self.size.0)
610            .len()
611            .saturating_sub(Self::page_lines(self.size.1))
612    }
613
614    /// Moves the selection, staying within the rows.
615    fn travel(&mut self, action: Action) {
616        let last = self.rows.len().saturating_sub(1);
617        let page = usize::from(Self::list_rows(self.size.1));
618        self.selected = match action {
619            Action::Up => self.selected.saturating_sub(1),
620            Action::Down => self.selected.saturating_add(1),
621            Action::Top => 0,
622            Action::Bottom => last,
623            Action::PageUp => self.selected.saturating_sub(page),
624            Action::PageDown => self.selected.saturating_add(page),
625            _ => self.selected,
626        }
627        .min(last);
628    }
629
630    /// Reads from the start again: the key first if the server had not
631    /// answered for it, the first page otherwise.
632    fn refresh(&mut self) -> Vec<Effect> {
633        if self.busy() {
634            return Vec::new();
635        }
636        if let Connection::Connected(info) = &self.connection {
637            return self.connected(info.clone());
638        }
639        self.connection = Connection::Connecting;
640        self.listing = Listing::Loading;
641        vec![Effect::FetchKey]
642    }
643
644    /// Reads the next page, if there is one and nothing is in flight.
645    fn more(&mut self) -> Vec<Effect> {
646        if self.busy() || self.listing != Listing::Ready {
647            return Vec::new();
648        }
649        let Some(cursor) = self.next.clone() else {
650            return Vec::new();
651        };
652        self.more = true;
653        vec![Effect::FetchPage(Some(cursor))]
654    }
655}
656
657/// Why a key may not list vCons, if it may not: an operator key reaches no
658/// tenant, and a tenant key needs the read scope.
659fn refusal(info: &KeyInfo) -> Option<&'static str> {
660    if info.tenant.is_none() {
661        Some("this is an operator key, which reaches no vCon: use a tenant key with the read scope")
662    } else if info.scopes.iter().all(|scope| scope != "read") {
663        Some("this key lacks the read scope: use a tenant key that holds it")
664    } else {
665        None
666    }
667}
668
669#[cfg(test)]
670mod tests {
671    use time::OffsetDateTime;
672    use time::macros::datetime;
673
674    use super::{
675        Action, ApiError, Connection, Effect, Event, KeyInfo, Listing, Page, Row, State, View,
676    };
677
678    const NOW: OffsetDateTime = datetime!(2026-11-10 01:20:00 UTC);
679
680    fn row(n: u8) -> Row {
681        Row {
682            uuid: format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc{n:02}"),
683            stored_at: "2026-10-25T12:00:00.123456789Z".to_owned(),
684            updated_at: "2026-10-25T12:30:00Z".to_owned(),
685            version: format!("4f0c4b0a1d2e3f405162738495a6b7{n:02}"),
686        }
687    }
688
689    fn reader() -> KeyInfo {
690        KeyInfo {
691            id: "0123456789abcdef".to_owned(),
692            tenant: Some("t_example".to_owned()),
693            scopes: vec!["read".to_owned()],
694        }
695    }
696
697    fn page(rows: std::ops::Range<u8>, next: Option<&str>) -> Page {
698        Page {
699            vcons: rows.map(row).collect(),
700            next: next.map(str::to_owned),
701        }
702    }
703
704    /// A state that is connected and holds `rows` rows of one page.
705    fn listed(rows: u8, next: Option<&str>) -> State {
706        let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
707        state.step(Event::KeyInfo(Ok(reader())), NOW);
708        state.step(Event::Page(Ok(page(0..rows, next))), NOW);
709        state
710    }
711
712    fn press(state: &mut State, action: Action) -> Vec<Effect> {
713        state.step(Event::Action(action), NOW)
714    }
715
716    // Success.
717
718    #[test]
719    fn a_new_state_is_connecting_and_asks_for_the_key() {
720        let (state, effects) = State::new("https://vcon.example.com:8443", (80, 24));
721        assert_eq!(
722            state.connection,
723            Connection::Connecting,
724            "nothing has answered yet"
725        );
726        assert_eq!(
727            effects,
728            [Effect::FetchKey],
729            "the key's tenant and scopes come first"
730        );
731    }
732
733    #[test]
734    fn a_reader_key_connects_and_asks_for_the_first_page() {
735        let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
736        let effects = state.step(Event::KeyInfo(Ok(reader())), NOW);
737        assert_eq!(
738            state.connection,
739            Connection::Connected(reader()),
740            "the key answered"
741        );
742        assert_eq!(state.listing, Listing::Loading, "the page is on its way");
743        assert_eq!(
744            effects,
745            [Effect::FetchPage(None)],
746            "the first page has no cursor"
747        );
748    }
749
750    #[test]
751    fn a_page_fills_the_list_and_records_when() {
752        let state = listed(3, Some("cursor-1"));
753        assert_eq!(state.listing, Listing::Ready, "the page arrived");
754        assert_eq!(state.rows.len(), 3, "every row of the page is kept");
755        assert_eq!(
756            state.next.as_deref(),
757            Some("cursor-1"),
758            "the cursor is kept for more"
759        );
760        assert_eq!(
761            state.as_of,
762            Some(NOW),
763            "the clock passed in is when it was read"
764        );
765    }
766
767    #[test]
768    fn down_and_up_move_the_selection() {
769        let mut state = listed(3, None);
770        press(&mut state, Action::Down);
771        press(&mut state, Action::Down);
772        assert_eq!(state.selected, 2, "two rows down");
773        press(&mut state, Action::Up);
774        assert_eq!(state.selected, 1, "one row back up");
775    }
776
777    #[test]
778    fn bottom_and_top_jump_to_the_ends() {
779        let mut state = listed(5, None);
780        press(&mut state, Action::Bottom);
781        assert_eq!(state.selected, 4, "the last row");
782        press(&mut state, Action::Top);
783        assert_eq!(state.selected, 0, "the first row");
784    }
785
786    #[test]
787    fn open_shows_the_selected_vcon_and_back_returns() {
788        let mut state = listed(3, None);
789        press(&mut state, Action::Down);
790        let effects = press(&mut state, Action::Open);
791        assert_eq!(state.view, View::Detail, "the detail view is open");
792        assert_eq!(
793            state.detail,
794            Some(row(1).uuid),
795            "on the row that was selected"
796        );
797        assert_eq!(
798            effects,
799            [Effect::FetchMasked(row(1).uuid)],
800            "the metadata is the list row's; the content is asked for masked"
801        );
802        press(&mut state, Action::Back);
803        assert_eq!(state.view, View::List, "back at the list");
804    }
805
806    #[test]
807    fn more_asks_for_the_next_page_and_appends_it() {
808        let mut state = listed(2, Some("cursor-1"));
809        let effects = press(&mut state, Action::More);
810        assert_eq!(
811            effects,
812            [Effect::FetchPage(Some("cursor-1".to_owned()))],
813            "the cursor goes back unchanged"
814        );
815        state.step(Event::Page(Ok(page(2..4, None))), NOW);
816        assert_eq!(state.rows.len(), 4, "the second page follows the first");
817        assert_eq!(state.next, None, "the last page has no cursor");
818    }
819
820    #[test]
821    fn refresh_asks_for_the_first_page_again_and_replaces_the_rows() {
822        let mut state = listed(3, None);
823        let effects = press(&mut state, Action::Refresh);
824        assert_eq!(effects, [Effect::FetchPage(None)], "from the start");
825        assert_eq!(
826            state.listing,
827            Listing::Loading,
828            "loading is shown meanwhile"
829        );
830        state.step(Event::Page(Ok(page(0..1, None))), NOW);
831        assert_eq!(state.rows.len(), 1, "the new page replaces the old rows");
832    }
833
834    #[test]
835    fn help_opens_over_a_view_and_returns_to_it() {
836        let mut state = listed(3, None);
837        press(&mut state, Action::Open);
838        press(&mut state, Action::Help);
839        assert_eq!(state.view, View::Help, "help is open");
840        press(&mut state, Action::Back);
841        assert_eq!(
842            state.view,
843            View::Detail,
844            "back at the view help was opened from"
845        );
846    }
847
848    #[test]
849    fn quit_ends_from_every_view() {
850        for open in [None, Some(Action::Open), Some(Action::Help)] {
851            let mut state = listed(1, None);
852            if let Some(open) = open {
853                press(&mut state, open);
854            }
855            press(&mut state, Action::Quit);
856            assert!(state.quit, "quit ends from {:?}", state.view);
857        }
858    }
859
860    #[test]
861    fn page_down_moves_by_the_rows_the_terminal_shows() {
862        let mut state = listed(60, None);
863        press(&mut state, Action::PageDown);
864        assert_eq!(
865            state.selected,
866            usize::from(State::list_rows(24)),
867            "a 24-line terminal pages by its list rows"
868        );
869        press(&mut state, Action::PageUp);
870        assert_eq!(state.selected, 0, "and back");
871    }
872
873    #[test]
874    fn down_in_the_detail_view_shows_the_next_vcon() {
875        let mut state = listed(3, None);
876        press(&mut state, Action::Open);
877        press(&mut state, Action::Down);
878        assert_eq!(
879            state.detail,
880            Some(row(1).uuid),
881            "the detail follows the selection"
882        );
883    }
884
885    #[test]
886    fn a_refresh_keeps_the_selection_on_the_same_vcon() {
887        let mut state = listed(3, None);
888        press(&mut state, Action::Bottom);
889        press(&mut state, Action::Open);
890        press(&mut state, Action::Refresh);
891        state.step(Event::Page(Ok(page(1..3, None))), NOW);
892        assert_eq!(
893            state.selected, 1,
894            "the vCon moved up one row and the selection with it"
895        );
896        assert_eq!(
897            state.detail,
898            Some(row(2).uuid),
899            "the detail is still that vCon"
900        );
901    }
902
903    // Failure.
904
905    #[test]
906    fn an_unreachable_server_fails_the_connection_and_the_list() {
907        let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
908        let effects = state.step(
909            Event::KeyInfo(Err(ApiError::Unreachable("connection refused".to_owned()))),
910            NOW,
911        );
912        assert_eq!(
913            effects,
914            [],
915            "nothing more is asked of a server that did not answer"
916        );
917        assert!(
918            matches!(&state.connection, Connection::Failed(why) if why.contains("connection refused")),
919            "the status line says why: {:?}",
920            state.connection
921        );
922        assert!(
923            matches!(state.listing, Listing::Failed(_)),
924            "the list says so too"
925        );
926    }
927
928    #[test]
929    fn a_refused_key_says_the_status() {
930        let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
931        state.step(Event::KeyInfo(Err(ApiError::Status(401, None))), NOW);
932        assert!(
933            matches!(&state.connection, Connection::Failed(why) if why.contains("401")),
934            "the refusal's status is shown: {:?}",
935            state.connection
936        );
937    }
938
939    #[test]
940    fn an_operator_key_connects_but_lists_nothing() {
941        let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
942        let operator = KeyInfo {
943            id: "0123456789abcdef".to_owned(),
944            tenant: None,
945            scopes: vec!["admin".to_owned()],
946        };
947        let effects = state.step(Event::KeyInfo(Ok(operator)), NOW);
948        assert_eq!(
949            effects,
950            [],
951            "an operator key reaches no vCon, so none is asked for"
952        );
953        assert!(
954            matches!(&state.listing, Listing::Failed(why) if why.contains("operator key")),
955            "the list says which key to use: {:?}",
956            state.listing
957        );
958    }
959
960    #[test]
961    fn a_key_without_read_lists_nothing() {
962        let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
963        let writer = KeyInfo {
964            scopes: vec!["write".to_owned()],
965            ..reader()
966        };
967        let effects = state.step(Event::KeyInfo(Ok(writer)), NOW);
968        assert_eq!(effects, [], "the list needs read, so it is not asked for");
969        assert!(
970            matches!(&state.listing, Listing::Failed(why) if why.contains("read scope")),
971            "the list names the scope: {:?}",
972            state.listing
973        );
974    }
975
976    #[test]
977    fn a_failed_first_page_is_an_error_state() {
978        let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
979        state.step(Event::KeyInfo(Ok(reader())), NOW);
980        state.step(
981            Event::Page(Err(ApiError::Status(503, Some("unavailable".to_owned())))),
982            NOW,
983        );
984        assert!(
985            matches!(&state.listing, Listing::Failed(why) if why.contains("503") && why.contains("unavailable")),
986            "the status and the problem's title are shown: {:?}",
987            state.listing
988        );
989        assert_eq!(state.as_of, None, "nothing was read, so no time is claimed");
990    }
991
992    #[test]
993    fn a_failed_next_page_keeps_the_rows_and_leaves_a_notice() {
994        let mut state = listed(2, Some("cursor-1"));
995        press(&mut state, Action::More);
996        state.step(
997            Event::Page(Err(ApiError::Unreachable("timed out".to_owned()))),
998            NOW,
999        );
1000        assert_eq!(state.rows.len(), 2, "the rows already read stay");
1001        assert_eq!(state.listing, Listing::Ready, "the list is still usable");
1002        assert_eq!(
1003            state.next.as_deref(),
1004            Some("cursor-1"),
1005            "the cursor is kept to try again"
1006        );
1007        assert!(
1008            state
1009                .notice
1010                .as_deref()
1011                .is_some_and(|n| n.contains("timed out")),
1012            "a notice says why: {:?}",
1013            state.notice
1014        );
1015    }
1016
1017    #[test]
1018    fn a_failed_refresh_drops_the_old_rows() {
1019        let mut state = listed(2, None);
1020        press(&mut state, Action::Refresh);
1021        state.step(Event::Page(Err(ApiError::Status(500, None))), NOW);
1022        assert!(
1023            matches!(state.listing, Listing::Failed(_)),
1024            "the error is shown"
1025        );
1026        assert_eq!(
1027            state.rows,
1028            [],
1029            "rows that may be out of date are not shown as current"
1030        );
1031    }
1032
1033    #[test]
1034    fn a_malformed_answer_is_an_error_state() {
1035        let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
1036        state.step(Event::KeyInfo(Ok(reader())), NOW);
1037        state.step(
1038            Event::Page(Err(ApiError::Malformed("expected value".to_owned()))),
1039            NOW,
1040        );
1041        assert!(
1042            matches!(&state.listing, Listing::Failed(why) if why.contains("expected value")),
1043            "what could not be read is shown: {:?}",
1044            state.listing
1045        );
1046    }
1047
1048    #[test]
1049    fn refresh_after_a_failed_connection_asks_for_the_key_again() {
1050        let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
1051        state.step(
1052            Event::KeyInfo(Err(ApiError::Unreachable("refused".to_owned()))),
1053            NOW,
1054        );
1055        let effects = press(&mut state, Action::Refresh);
1056        assert_eq!(
1057            effects,
1058            [Effect::FetchKey],
1059            "the connection is made again from the start"
1060        );
1061        assert_eq!(
1062            state.connection,
1063            Connection::Connecting,
1064            "and shown as such"
1065        );
1066    }
1067
1068    #[test]
1069    fn a_server_that_stops_answering_is_shown_as_not_connected() {
1070        let mut state = listed(2, None);
1071        press(&mut state, Action::Refresh);
1072        state.step(
1073            Event::Page(Err(ApiError::Unreachable("connection reset".to_owned()))),
1074            NOW,
1075        );
1076        assert!(
1077            matches!(state.connection, Connection::Failed(_)),
1078            "the status line no longer says connected"
1079        );
1080    }
1081
1082    #[test]
1083    fn a_vcon_gone_after_a_refresh_leaves_the_detail_without_a_row() {
1084        let mut state = listed(2, None);
1085        press(&mut state, Action::Open);
1086        press(&mut state, Action::Refresh);
1087        state.step(Event::Page(Ok(page(1..2, None))), NOW);
1088        assert_eq!(
1089            state.detail,
1090            Some(row(0).uuid),
1091            "the detail still names what was open"
1092        );
1093        assert_eq!(state.detail_row(), None, "and has no row to draw");
1094    }
1095
1096    #[test]
1097    fn each_api_error_says_what_failed() {
1098        for (error, text) in [
1099            (
1100                ApiError::Unreachable("refused".to_owned()),
1101                "the server did not answer: refused",
1102            ),
1103            (
1104                ApiError::Status(401, None),
1105                "the server refused the key (401)",
1106            ),
1107            (
1108                ApiError::Status(403, Some("forbidden".to_owned())),
1109                "the server answered 403 (forbidden)",
1110            ),
1111            (ApiError::Status(500, None), "the server answered 500"),
1112            (
1113                ApiError::Malformed("eof".to_owned()),
1114                "the server's answer could not be read: eof",
1115            ),
1116        ] {
1117            assert_eq!(error.to_string(), text, "{error:?}");
1118        }
1119    }
1120
1121    // Edge.
1122
1123    #[test]
1124    fn up_at_the_top_and_down_at_the_bottom_stay() {
1125        let mut state = listed(2, None);
1126        press(&mut state, Action::Up);
1127        assert_eq!(state.selected, 0, "no row above the first");
1128        press(&mut state, Action::Bottom);
1129        press(&mut state, Action::Down);
1130        assert_eq!(state.selected, 1, "no row below the last");
1131    }
1132
1133    #[test]
1134    fn open_on_an_empty_list_does_nothing() {
1135        let mut state = listed(0, None);
1136        press(&mut state, Action::Open);
1137        assert_eq!(state.view, View::List, "there is nothing to open");
1138        assert_eq!(state.detail, None, "and no vCon is named");
1139    }
1140
1141    #[test]
1142    fn movement_on_an_empty_list_stays_at_zero() {
1143        let mut state = listed(0, None);
1144        for action in [Action::Down, Action::Bottom, Action::PageDown, Action::Up] {
1145            press(&mut state, action);
1146            assert_eq!(state.selected, 0, "{action:?} on no rows");
1147        }
1148    }
1149
1150    #[test]
1151    fn more_on_the_last_page_asks_for_nothing() {
1152        let mut state = listed(2, None);
1153        assert_eq!(press(&mut state, Action::More), [], "there is no next page");
1154    }
1155
1156    #[test]
1157    fn a_second_refresh_while_loading_asks_for_nothing() {
1158        let mut state = listed(2, None);
1159        press(&mut state, Action::Refresh);
1160        assert_eq!(
1161            press(&mut state, Action::Refresh),
1162            [],
1163            "one request is in flight; a second would race it"
1164        );
1165    }
1166
1167    #[test]
1168    fn more_while_more_is_loading_asks_for_nothing() {
1169        let mut state = listed(2, Some("cursor-1"));
1170        press(&mut state, Action::More);
1171        assert_eq!(
1172            press(&mut state, Action::More),
1173            [],
1174            "the page is already on its way"
1175        );
1176        assert_eq!(
1177            press(&mut state, Action::Refresh),
1178            [],
1179            "and a refresh would race it"
1180        );
1181    }
1182
1183    #[test]
1184    fn refresh_while_connecting_asks_for_nothing() {
1185        let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
1186        assert_eq!(
1187            press(&mut state, Action::Refresh),
1188            [],
1189            "the key request is in flight"
1190        );
1191    }
1192
1193    #[test]
1194    fn a_resize_changes_only_the_size() {
1195        let mut state = listed(3, None);
1196        press(&mut state, Action::Down);
1197        let before = state.clone();
1198        let effects = state.step(Event::Resize(132, 43), NOW);
1199        assert_eq!(effects, [], "a resize asks the server nothing");
1200        assert_eq!(state.size, (132, 43), "the new size is kept");
1201        assert_eq!(
1202            State {
1203                size: before.size,
1204                ..state
1205            },
1206            before,
1207            "nothing else changed"
1208        );
1209    }
1210
1211    #[test]
1212    fn a_shorter_page_after_refresh_clamps_the_selection() {
1213        let mut state = listed(5, None);
1214        press(&mut state, Action::Bottom);
1215        press(&mut state, Action::Refresh);
1216        state.step(Event::Page(Ok(page(10..12, None))), NOW);
1217        assert_eq!(
1218            state.selected, 1,
1219            "the selection is the last row that exists"
1220        );
1221    }
1222
1223    #[test]
1224    fn page_down_past_the_end_stops_at_the_last_row() {
1225        let mut state = listed(3, None);
1226        press(&mut state, Action::PageDown);
1227        assert_eq!(state.selected, 2, "the last row, not past it");
1228    }
1229
1230    #[test]
1231    fn a_terminal_too_short_for_a_list_still_pages_by_one() {
1232        assert_eq!(State::list_rows(0), 1, "never zero: paging would not move");
1233        assert_eq!(State::list_rows(5), 1, "the frame takes five lines");
1234        assert_eq!(State::list_rows(24), 19, "24 lines leave 19 for rows");
1235    }
1236
1237    #[test]
1238    fn help_from_help_closes_it() {
1239        let mut state = listed(1, None);
1240        press(&mut state, Action::Help);
1241        press(&mut state, Action::Help);
1242        assert_eq!(state.view, View::List, "the same key closes help");
1243    }
1244
1245    #[test]
1246    fn a_key_press_clears_the_notice() {
1247        let mut state = listed(2, Some("cursor-1"));
1248        press(&mut state, Action::More);
1249        state.step(
1250            Event::Page(Err(ApiError::Unreachable("timed out".to_owned()))),
1251            NOW,
1252        );
1253        press(&mut state, Action::Down);
1254        assert_eq!(
1255            state.notice, None,
1256            "the notice is about the last request only"
1257        );
1258    }
1259
1260    #[test]
1261    fn back_in_the_list_view_does_not_quit() {
1262        let mut state = listed(1, None);
1263        press(&mut state, Action::Back);
1264        assert!(!state.quit, "only the quit keys end the program");
1265        assert_eq!(state.view, View::List, "and the view stays");
1266    }
1267
1268    // A key the server stops accepting while the UI runs.
1269
1270    #[test]
1271    fn a_key_refused_at_a_refresh_is_not_connected_as_at_start() {
1272        let mut state = listed(3, None);
1273        press(&mut state, Action::Refresh);
1274        state.step(Event::Page(Err(ApiError::Status(401, None))), NOW);
1275        assert_eq!(
1276            state.connection,
1277            Connection::Failed("the server refused the key (401)".to_owned()),
1278            "a revoked key is shown as it is when the UI starts with one"
1279        );
1280        assert_eq!(
1281            state.listing,
1282            Listing::Failed("the server refused the key (401)".to_owned()),
1283            "and the list says why"
1284        );
1285    }
1286
1287    #[test]
1288    fn a_refresh_after_a_refused_key_asks_for_the_key_again() {
1289        let mut state = listed(3, None);
1290        press(&mut state, Action::Refresh);
1291        state.step(Event::Page(Err(ApiError::Status(401, None))), NOW);
1292        assert_eq!(
1293            press(&mut state, Action::Refresh),
1294            vec![Effect::FetchKey],
1295            "the tenant and scopes are read again, not taken from before the refusal"
1296        );
1297    }
1298
1299    #[test]
1300    fn a_key_refused_at_a_next_page_is_not_connected_and_the_rows_stay() {
1301        let mut state = listed(3, Some("cursor-1"));
1302        press(&mut state, Action::More);
1303        state.step(Event::Page(Err(ApiError::Status(401, None))), NOW);
1304        assert_eq!(
1305            state.connection,
1306            Connection::Failed("the server refused the key (401)".to_owned()),
1307            "the status line stops saying connected"
1308        );
1309        assert_eq!(state.rows.len(), 3, "the rows read before stay");
1310        assert_eq!(
1311            state.notice.as_deref(),
1312            Some("The next page was not read: the server refused the key (401)."),
1313            "and the notice says why"
1314        );
1315    }
1316
1317    #[test]
1318    fn a_503_at_a_refresh_leaves_the_connection_as_it_was() {
1319        let mut state = listed(3, None);
1320        press(&mut state, Action::Refresh);
1321        state.step(
1322            Event::Page(Err(ApiError::Status(503, Some("unavailable".to_owned())))),
1323            NOW,
1324        );
1325        assert!(
1326            matches!(state.connection, Connection::Connected(_)),
1327            "the server answered for the key, and may answer the next request"
1328        );
1329        assert_eq!(
1330            press(&mut state, Action::Refresh),
1331            vec![Effect::FetchPage(None)],
1332            "so r reads the first page, not the key"
1333        );
1334    }
1335
1336    // Which keys act in a state: `acts` against what a press does.
1337
1338    const ACTIONS: [Action; 12] = [
1339        Action::Up,
1340        Action::Down,
1341        Action::Top,
1342        Action::Bottom,
1343        Action::PageUp,
1344        Action::PageDown,
1345        Action::Open,
1346        Action::Back,
1347        Action::Refresh,
1348        Action::More,
1349        Action::Help,
1350        Action::Quit,
1351    ];
1352
1353    const TRAVEL: [Action; 6] = [
1354        Action::Up,
1355        Action::Down,
1356        Action::Top,
1357        Action::Bottom,
1358        Action::PageUp,
1359        Action::PageDown,
1360    ];
1361
1362    fn after(mut state: State, events: Vec<Event>) -> State {
1363        for event in events {
1364            state.step(event, NOW);
1365        }
1366        state
1367    }
1368
1369    fn new() -> State {
1370        State::new("https://vcon.example.com:8443", (80, 24)).0
1371    }
1372
1373    fn key(tenant: Option<&str>, scope: &str) -> Event {
1374        Event::KeyInfo(Ok(KeyInfo {
1375            id: "0123456789abcdef".to_owned(),
1376            tenant: tenant.map(str::to_owned),
1377            scopes: vec![scope.to_owned()],
1378        }))
1379    }
1380
1381    fn no_answer() -> ApiError {
1382        ApiError::Unreachable("no answer within 15 seconds".to_owned())
1383    }
1384
1385    /// States of every kind the screen can be in, each with a name, in the
1386    /// list view, the detail view where a row can be opened, and help.
1387    fn states() -> Vec<(String, State)> {
1388        let act = Event::Action;
1389        let mut base: Vec<(&str, State)> = vec![
1390            ("connecting", new()),
1391            ("loading", after(new(), vec![Event::KeyInfo(Ok(reader()))])),
1392            (
1393                "no answer",
1394                after(new(), vec![Event::KeyInfo(Err(no_answer()))]),
1395            ),
1396            (
1397                "refused key",
1398                after(
1399                    new(),
1400                    vec![Event::KeyInfo(Err(ApiError::Status(401, None)))],
1401                ),
1402            ),
1403            ("operator key", after(new(), vec![key(None, "admin")])),
1404            (
1405                "write key",
1406                after(new(), vec![key(Some("t_example"), "write")]),
1407            ),
1408            (
1409                "first page failed",
1410                after(
1411                    new(),
1412                    vec![
1413                        Event::KeyInfo(Ok(reader())),
1414                        Event::Page(Err(ApiError::Status(503, None))),
1415                    ],
1416                ),
1417            ),
1418            ("empty", listed(0, None)),
1419            ("one row", listed(1, None)),
1420            ("one row, more", listed(1, Some("c"))),
1421            ("three rows", listed(3, None)),
1422            ("three rows, more", listed(3, Some("c"))),
1423            (
1424                "three rows, second",
1425                after(listed(3, None), vec![act(Action::Down)]),
1426            ),
1427            (
1428                "three rows, last",
1429                after(listed(3, Some("c")), vec![act(Action::Bottom)]),
1430            ),
1431            (
1432                "next page out",
1433                after(listed(3, Some("c")), vec![act(Action::More)]),
1434            ),
1435            (
1436                "next page failed",
1437                after(
1438                    listed(3, Some("c")),
1439                    vec![act(Action::More), Event::Page(Err(no_answer()))],
1440                ),
1441            ),
1442            (
1443                "refresh out",
1444                after(listed(3, Some("c")), vec![act(Action::Refresh)]),
1445            ),
1446            (
1447                "refresh failed",
1448                after(
1449                    listed(3, None),
1450                    vec![
1451                        act(Action::Refresh),
1452                        Event::Page(Err(ApiError::Status(503, None))),
1453                    ],
1454                ),
1455            ),
1456            (
1457                "reconnecting",
1458                after(
1459                    listed(3, None),
1460                    vec![
1461                        act(Action::Refresh),
1462                        Event::Page(Err(no_answer())),
1463                        act(Action::Refresh),
1464                    ],
1465                ),
1466            ),
1467        ];
1468        // The vCon open in the detail view leaves the list: three, one and
1469        // no rows are left.
1470        for (name, left) in [
1471            ("gone, three left", 3),
1472            ("gone, one left", 1),
1473            ("gone, none left", 0),
1474        ] {
1475            let mut state = after(
1476                listed(5, None),
1477                vec![act(Action::Bottom), act(Action::Open), act(Action::Refresh)],
1478            );
1479            state.step(Event::Page(Ok(page(0..left, None))), NOW);
1480            assert_eq!(
1481                state.view,
1482                View::Detail,
1483                "{name}: the detail view stays open"
1484            );
1485            assert!(
1486                state.detail_row().is_none(),
1487                "{name}: its vCon is not listed"
1488            );
1489            base.push((name, state));
1490        }
1491        let mut all = Vec::new();
1492        for (name, state) in base {
1493            let opened = after(state.clone(), vec![act(Action::Open)]);
1494            if opened.view == View::Detail && state.view != View::Detail {
1495                let refreshing = after(opened.clone(), vec![act(Action::Refresh)]);
1496                all.push((
1497                    format!("{name}, detail, help"),
1498                    after(opened.clone(), vec![act(Action::Help)]),
1499                ));
1500                all.push((format!("{name}, detail, r pressed"), refreshing));
1501                all.push((format!("{name}, detail"), opened));
1502            }
1503            all.push((
1504                format!("{name}, help"),
1505                after(state.clone(), vec![act(Action::Help)]),
1506            ));
1507            all.push((name.to_owned(), state));
1508        }
1509        all
1510    }
1511
1512    /// The state after `action`, and the requests it made.
1513    fn acted(state: &State, action: Action) -> (State, Vec<Effect>) {
1514        let mut next = state.clone();
1515        let effects = next.act(action);
1516        (next, effects)
1517    }
1518
1519    #[test]
1520    fn the_states_tried_cover_every_view_and_kind() {
1521        let all = states();
1522        assert!(all.len() >= 50, "{} states are tried", all.len());
1523        for view in [View::List, View::Detail, View::Help] {
1524            assert!(
1525                all.iter().any(|(_, state)| state.view == view),
1526                "a state in {view:?} is tried"
1527            );
1528        }
1529        let mut names: Vec<&String> = all.iter().map(|(name, _)| name).collect();
1530        names.sort();
1531        names.dedup();
1532        assert_eq!(names.len(), all.len(), "each state has its own name");
1533    }
1534
1535    #[test]
1536    fn a_key_that_does_not_act_changes_nothing() {
1537        for (name, state) in states() {
1538            for action in ACTIONS {
1539                if state.acts(action) {
1540                    continue;
1541                }
1542                let (next, effects) = acted(&state, action);
1543                assert!(
1544                    next == state && effects.is_empty(),
1545                    "{name}: {action:?} is said not to act, and a press changed the state or asked the server"
1546                );
1547            }
1548        }
1549    }
1550
1551    #[test]
1552    fn a_key_that_acts_changes_the_state_or_asks_the_server() {
1553        for (name, state) in states() {
1554            for action in ACTIONS {
1555                if !state.acts(action) || TRAVEL.contains(&action) {
1556                    continue;
1557                }
1558                let (next, effects) = acted(&state, action);
1559                assert!(
1560                    next != state || !effects.is_empty(),
1561                    "{name}: {action:?} is said to act, and a press did nothing"
1562                );
1563            }
1564        }
1565    }
1566
1567    #[test]
1568    fn the_keys_that_move_act_when_one_of_them_can_move() {
1569        for (name, state) in states() {
1570            // In the detail view the page keys move its text, not the
1571            // selection (page_down_in_the_detail_view_scrolls_...).
1572            let travel: Vec<Action> = TRAVEL
1573                .into_iter()
1574                .filter(|action| {
1575                    state.view != View::Detail
1576                        || !matches!(action, Action::PageUp | Action::PageDown)
1577                })
1578                .collect();
1579            let moves = travel
1580                .iter()
1581                .any(|action| acted(&state, *action).0 != state);
1582            for action in travel {
1583                assert_eq!(
1584                    state.acts(action),
1585                    moves,
1586                    "{name}: {action:?} acts when the selection can move ({moves})"
1587                );
1588            }
1589        }
1590    }
1591
1592    #[test]
1593    fn quit_and_help_act_in_every_state() {
1594        for (name, state) in states() {
1595            assert!(state.acts(Action::Quit), "{name}: q quits");
1596            assert!(state.acts(Action::Help), "{name}: ? opens or closes help");
1597        }
1598    }
1599
1600    #[test]
1601    fn nothing_but_help_back_and_quit_acts_in_the_help_view() {
1602        for (name, state) in states() {
1603            if state.view != View::Help {
1604                continue;
1605            }
1606            for action in ACTIONS {
1607                assert_eq!(
1608                    state.acts(action),
1609                    matches!(action, Action::Help | Action::Back | Action::Quit),
1610                    "{name}: {action:?}"
1611                );
1612            }
1613        }
1614    }
1615
1616    #[test]
1617    fn refresh_does_not_act_while_a_request_is_out() {
1618        for state in [
1619            new(),
1620            after(new(), vec![Event::KeyInfo(Ok(reader()))]),
1621            after(listed(3, Some("c")), vec![Event::Action(Action::More)]),
1622            after(listed(3, None), vec![Event::Action(Action::Refresh)]),
1623        ] {
1624            assert!(
1625                !state.acts(Action::Refresh),
1626                "a second request would race the first: {:?} {:?}",
1627                state.connection,
1628                state.listing
1629            );
1630        }
1631    }
1632
1633    #[test]
1634    fn refresh_acts_after_a_failure_the_server_made() {
1635        for state in [
1636            after(new(), vec![Event::KeyInfo(Err(no_answer()))]),
1637            after(
1638                new(),
1639                vec![Event::KeyInfo(Err(ApiError::Status(401, None)))],
1640            ),
1641            after(
1642                new(),
1643                vec![
1644                    Event::KeyInfo(Ok(reader())),
1645                    Event::Page(Err(ApiError::Status(503, None))),
1646                ],
1647            ),
1648        ] {
1649            assert!(
1650                state.acts(Action::Refresh),
1651                "the server may answer the next request: {:?}",
1652                state.listing
1653            );
1654        }
1655    }
1656
1657    #[test]
1658    fn refresh_does_not_act_for_a_key_that_may_not_list() {
1659        for event in [key(None, "admin"), key(Some("t_example"), "write")] {
1660            let mut state = after(new(), vec![event]);
1661            assert!(
1662                !state.acts(Action::Refresh),
1663                "the key is read once, at start: {:?}",
1664                state.listing
1665            );
1666            let before = state.clone();
1667            assert_eq!(
1668                press(&mut state, Action::Refresh),
1669                Vec::new(),
1670                "nothing is asked of the server"
1671            );
1672            assert_eq!(state, before, "and the refusal stays on the screen");
1673        }
1674    }
1675
1676    #[test]
1677    fn more_acts_only_when_the_server_holds_more_and_nothing_is_out() {
1678        assert!(listed(3, Some("c")).acts(Action::More), "a cursor is held");
1679        assert!(!listed(3, None).acts(Action::More), "every vCon is read");
1680        assert!(
1681            !after(listed(3, Some("c")), vec![Event::Action(Action::More)]).acts(Action::More),
1682            "the next page is on its way"
1683        );
1684        assert!(
1685            !after(listed(3, Some("c")), vec![Event::Action(Action::Refresh)]).acts(Action::More),
1686            "the list is being read again"
1687        );
1688        assert!(!new().acts(Action::More), "nothing is read yet");
1689    }
1690
1691    #[test]
1692    fn open_acts_only_in_a_list_that_shows_a_row() {
1693        assert!(listed(1, None).acts(Action::Open), "one row can be opened");
1694        assert!(
1695            !listed(0, None).acts(Action::Open),
1696            "an empty tenant has none"
1697        );
1698        assert!(!new().acts(Action::Open), "nothing is listed yet");
1699        let detail = after(listed(2, None), vec![Event::Action(Action::Open)]);
1700        assert!(
1701            !detail.acts(Action::Open),
1702            "the detail view is open already"
1703        );
1704    }
1705
1706    #[test]
1707    fn a_list_of_one_row_has_nowhere_to_move() {
1708        let state = listed(1, None);
1709        for action in TRAVEL {
1710            assert!(!state.acts(action), "{action:?} has no other row to select");
1711        }
1712    }
1713
1714    #[test]
1715    fn the_selection_does_not_move_while_the_list_is_not_shown() {
1716        let mut state = after(listed(3, None), vec![Event::Action(Action::Refresh)]);
1717        assert_eq!(state.listing, Listing::Loading, "the list is being read");
1718        press(&mut state, Action::Down);
1719        assert_eq!(state.selected, 0, "the screen shows no row to move from");
1720        press(&mut state, Action::Open);
1721        assert_eq!(state.view, View::List, "and none to open");
1722    }
1723
1724    #[test]
1725    fn back_acts_in_the_detail_and_help_views_only() {
1726        let list = listed(2, None);
1727        assert!(!list.acts(Action::Back), "the list is the first view");
1728        let detail = after(list.clone(), vec![Event::Action(Action::Open)]);
1729        assert!(detail.acts(Action::Back), "Esc returns to the list");
1730        let help = after(list, vec![Event::Action(Action::Help)]);
1731        assert!(help.acts(Action::Back), "Esc closes help");
1732    }
1733
1734    #[test]
1735    fn in_a_detail_view_whose_vcon_is_gone_the_keys_that_move_select_a_listed_one() {
1736        let mut state = after(
1737            listed(5, None),
1738            vec![
1739                Event::Action(Action::Bottom),
1740                Event::Action(Action::Open),
1741                Event::Action(Action::Refresh),
1742            ],
1743        );
1744        state.step(Event::Page(Ok(page(0..1, None))), NOW);
1745        assert!(
1746            state.acts(Action::Down),
1747            "one row is left, and j shows it in place of the message"
1748        );
1749        press(&mut state, Action::Down);
1750        assert_eq!(
1751            state.detail_row().map(|row| row.uuid.clone()),
1752            Some(row(0).uuid),
1753            "the detail view shows the row that is left"
1754        );
1755        assert!(!state.acts(Action::Down), "then there is nowhere to move");
1756    }
1757
1758    // The masked view and the reveals.
1759
1760    use super::{Content, Revealed};
1761    use crate::reveal::Part;
1762
1763    /// The parts a key reveals, in the order of the keys.
1764    const PARTS: [Part; 6] = [
1765        Part::Parties,
1766        Part::Subject,
1767        Part::Dialog,
1768        Part::Analysis,
1769        Part::Links,
1770        Part::All,
1771    ];
1772
1773    fn summary() -> Vec<String> {
1774        vec!["Form          unsigned".to_owned()]
1775    }
1776
1777    /// A list of three, the second vCon open and its masked view read.
1778    fn opened() -> State {
1779        let mut state = listed(3, None);
1780        press(&mut state, Action::Down);
1781        press(&mut state, Action::Open);
1782        state.step(Event::Masked(row(1).uuid, Ok(summary())), NOW);
1783        state
1784    }
1785
1786    /// `state` with `part` revealed as `text`.
1787    fn revealed(mut state: State, part: Part, text: &str) -> State {
1788        press(&mut state, Action::Reveal(part));
1789        state.step(Event::Revealed(row(1).uuid, part, Ok(text.to_owned())), NOW);
1790        state
1791    }
1792
1793    #[test]
1794    fn open_asks_for_the_masked_view_and_reads_it_until_it_arrives() {
1795        let mut state = listed(3, None);
1796        let effects = press(&mut state, Action::Open);
1797        assert_eq!(effects, [Effect::FetchMasked(row(0).uuid)], "one request");
1798        assert_eq!(state.content, Content::Reading, "being read");
1799        assert_eq!(state.revealed, None, "nothing revealed");
1800    }
1801
1802    #[test]
1803    fn the_masked_view_that_arrives_is_shown() {
1804        assert_eq!(opened().content, Content::Ready(summary()), "the summary");
1805    }
1806
1807    #[test]
1808    fn a_reveal_key_asks_for_that_part_of_the_vcon_open() {
1809        let mut state = opened();
1810        let effects = press(&mut state, Action::Reveal(Part::Parties));
1811        assert_eq!(
1812            effects,
1813            [Effect::FetchReveal(row(1).uuid, Part::Parties)],
1814            "a reveal of the parties"
1815        );
1816        assert_eq!(
1817            state.revealed,
1818            Some(Revealed::Reading(Part::Parties)),
1819            "being read"
1820        );
1821    }
1822
1823    #[test]
1824    fn each_reveal_key_asks_for_its_own_part() {
1825        for part in PARTS {
1826            let mut state = opened();
1827            assert!(state.acts(Action::Reveal(part)), "{part:?} acts");
1828            assert_eq!(
1829                press(&mut state, Action::Reveal(part)),
1830                [Effect::FetchReveal(row(1).uuid, part)],
1831                "{part:?}"
1832            );
1833        }
1834    }
1835
1836    #[test]
1837    fn the_revealed_text_is_shown_once_its_answer_arrives() {
1838        let state = revealed(opened(), Part::Subject, "Renewal call");
1839        assert_eq!(
1840            state.revealed,
1841            Some(Revealed::Shown(Part::Subject, "Renewal call".to_owned())),
1842            "shown"
1843        );
1844        assert_eq!(
1845            state.content,
1846            Content::Ready(summary()),
1847            "the summary stays"
1848        );
1849    }
1850
1851    #[test]
1852    fn page_down_in_the_detail_view_scrolls_a_long_text_and_page_up_returns() {
1853        let long: String = (0..200).map(|n| format!("line {n}\n")).collect();
1854        let mut state = revealed(opened(), Part::All, &long);
1855        let at = state.scroll;
1856        assert!(state.acts(Action::PageDown), "there is more below");
1857        press(&mut state, Action::PageDown);
1858        assert_eq!(state.scroll, at + State::page_lines(24), "one screen down");
1859        assert_eq!(state.detail, Some(row(1).uuid), "on the same vCon");
1860        press(&mut state, Action::PageUp);
1861        assert_eq!(state.scroll, at, "one screen up");
1862        while state.acts(Action::PageUp) {
1863            press(&mut state, Action::PageUp);
1864        }
1865        assert_eq!(state.scroll, 0, "at the top");
1866    }
1867
1868    /// The part revealed is below the masked view: the view moves to it,
1869    /// so it is on the screen when it arrives.
1870    #[test]
1871    fn a_reveal_moves_the_view_to_the_part_revealed() {
1872        let long: String = (0..200).map(|n| format!("line {n}\n")).collect();
1873        let state = revealed(opened(), Part::All, &long);
1874        let lines = crate::tui::view::detail_lines(&state, 80);
1875        let title = lines
1876            .iter()
1877            .position(|line| line == "The whole vCon, revealed:")
1878            .expect("the part's title");
1879        assert_eq!(
1880            state.scroll,
1881            title - 1,
1882            "the view starts above the part's title"
1883        );
1884        assert!(state.acts(Action::PageUp), "the masked view is above");
1885    }
1886
1887    #[test]
1888    fn a_masked_view_that_failed_says_why() {
1889        let mut state = listed(3, None);
1890        press(&mut state, Action::Open);
1891        let error = ApiError::Status(503, Some("The service cannot answer now".to_owned()));
1892        state.step(Event::Masked(row(0).uuid, Err(error.clone())), NOW);
1893        assert_eq!(
1894            state.content,
1895            Content::Failed(error.to_string()),
1896            "the reason"
1897        );
1898    }
1899
1900    #[test]
1901    fn a_reveal_that_failed_says_why_and_shows_no_text() {
1902        let mut state = opened();
1903        press(&mut state, Action::Reveal(Part::Dialog));
1904        let error = ApiError::Status(403, Some("Forbidden".to_owned()));
1905        state.step(
1906            Event::Revealed(row(1).uuid, Part::Dialog, Err(error.clone())),
1907            NOW,
1908        );
1909        assert_eq!(
1910            state.revealed,
1911            Some(Revealed::Failed(Part::Dialog, error.to_string())),
1912            "the reason"
1913        );
1914    }
1915
1916    #[test]
1917    fn a_reveal_key_in_the_list_does_nothing() {
1918        let mut state = listed(3, None);
1919        for part in PARTS {
1920            assert!(!state.acts(Action::Reveal(part)), "{part:?} does not act");
1921            assert_eq!(press(&mut state, Action::Reveal(part)), [], "{part:?}");
1922            assert_eq!(state.revealed, None, "{part:?}");
1923        }
1924    }
1925
1926    #[test]
1927    fn a_reveal_key_before_the_masked_view_arrived_does_nothing() {
1928        let mut state = listed(3, None);
1929        press(&mut state, Action::Open);
1930        assert!(!state.acts(Action::Reveal(Part::All)), "not yet");
1931        assert_eq!(
1932            press(&mut state, Action::Reveal(Part::All)),
1933            [],
1934            "no request"
1935        );
1936    }
1937
1938    #[test]
1939    fn a_reveal_key_after_a_failed_masked_view_does_nothing() {
1940        let mut state = listed(3, None);
1941        press(&mut state, Action::Open);
1942        state.step(
1943            Event::Masked(row(0).uuid, Err(ApiError::Status(404, None))),
1944            NOW,
1945        );
1946        assert!(
1947            !state.acts(Action::Reveal(Part::Parties)),
1948            "nothing to reveal"
1949        );
1950        assert_eq!(
1951            press(&mut state, Action::Reveal(Part::Parties)),
1952            [],
1953            "no request"
1954        );
1955    }
1956
1957    #[test]
1958    fn a_reveal_key_in_help_does_nothing() {
1959        let mut state = opened();
1960        press(&mut state, Action::Help);
1961        assert_eq!(
1962            press(&mut state, Action::Reveal(Part::Links)),
1963            [],
1964            "no request"
1965        );
1966        assert_eq!(state.view, View::Help, "help stays open");
1967    }
1968
1969    #[test]
1970    fn esc_drops_the_revealed_text() {
1971        let mut state = revealed(opened(), Part::Parties, "Ada Example");
1972        press(&mut state, Action::Back);
1973        assert_eq!(state.revealed, None, "dropped");
1974        assert_eq!(
1975            state.content,
1976            Content::None,
1977            "the masked view is dropped too"
1978        );
1979    }
1980
1981    #[test]
1982    fn r_drops_the_revealed_text_and_reads_the_masked_view_again() {
1983        let mut state = revealed(opened(), Part::Parties, "Ada Example");
1984        let effects = press(&mut state, Action::Refresh);
1985        assert_eq!(state.revealed, None, "dropped");
1986        assert!(
1987            effects.contains(&Effect::FetchMasked(row(1).uuid)),
1988            "{effects:?}"
1989        );
1990        assert!(effects.contains(&Effect::FetchPage(None)), "{effects:?}");
1991        assert_eq!(state.content, Content::Reading, "read again");
1992    }
1993
1994    #[test]
1995    fn moving_to_another_vcon_drops_the_text_and_asks_for_its_masked_view() {
1996        let mut state = revealed(opened(), Part::Parties, "Ada Example");
1997        let effects = press(&mut state, Action::Down);
1998        assert_eq!(state.detail, Some(row(2).uuid), "the next vCon");
1999        assert_eq!(
2000            effects,
2001            [Effect::FetchMasked(row(2).uuid)],
2002            "its masked view"
2003        );
2004        assert_eq!(state.revealed, None, "dropped");
2005        assert_eq!(state.scroll, 0, "at the top");
2006    }
2007
2008    #[test]
2009    fn a_reveal_that_arrives_after_esc_is_not_shown() {
2010        let mut state = opened();
2011        press(&mut state, Action::Reveal(Part::Parties));
2012        press(&mut state, Action::Back);
2013        press(&mut state, Action::Open);
2014        state.step(
2015            Event::Revealed(row(1).uuid, Part::Parties, Ok("Ada Example".to_owned())),
2016            NOW,
2017        );
2018        assert_eq!(state.revealed, None, "the late answer is dropped");
2019    }
2020
2021    #[test]
2022    fn a_masked_view_of_a_vcon_no_longer_open_is_not_shown() {
2023        let mut state = listed(3, None);
2024        press(&mut state, Action::Open);
2025        press(&mut state, Action::Down);
2026        state.step(Event::Masked(row(0).uuid, Ok(summary())), NOW);
2027        assert_eq!(
2028            state.content,
2029            Content::Reading,
2030            "still reading the open vCon's"
2031        );
2032    }
2033
2034    #[test]
2035    fn a_reveal_of_another_part_than_the_last_asked_is_not_shown() {
2036        let mut state = opened();
2037        press(&mut state, Action::Reveal(Part::Parties));
2038        press(&mut state, Action::Reveal(Part::Subject));
2039        state.step(
2040            Event::Revealed(row(1).uuid, Part::Parties, Ok("Ada Example".to_owned())),
2041            NOW,
2042        );
2043        assert_eq!(
2044            state.revealed,
2045            Some(Revealed::Reading(Part::Subject)),
2046            "the subject is awaited"
2047        );
2048    }
2049
2050    #[test]
2051    fn an_answer_that_arrives_while_help_is_open_is_kept() {
2052        let mut state = listed(3, None);
2053        press(&mut state, Action::Open);
2054        press(&mut state, Action::Help);
2055        state.step(Event::Masked(row(0).uuid, Ok(summary())), NOW);
2056        press(&mut state, Action::Help);
2057        assert_eq!(
2058            state.content,
2059            Content::Ready(summary()),
2060            "kept for the detail view"
2061        );
2062    }
2063
2064    #[test]
2065    fn page_keys_in_a_detail_view_that_fits_do_nothing() {
2066        let mut state = opened();
2067        assert!(!state.acts(Action::PageDown), "nothing below");
2068        assert!(!state.acts(Action::PageUp), "nothing above");
2069        press(&mut state, Action::PageDown);
2070        assert_eq!(
2071            (state.scroll, state.detail.clone()),
2072            (0, Some(row(1).uuid)),
2073            "unmoved"
2074        );
2075    }
2076}