use std::fmt;
use serde::Deserialize;
use time::OffsetDateTime;
use crate::reveal::Part;
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct KeyInfo {
pub id: String,
pub tenant: Option<String>,
pub scopes: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct Row {
pub uuid: String,
pub stored_at: String,
pub updated_at: String,
pub version: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct Page {
pub vcons: Vec<Row>,
pub next: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ApiError {
Unreachable(String),
Untrusted(String),
Status(u16, Option<String>),
Malformed(String),
}
impl std::error::Error for ApiError {}
impl fmt::Display for ApiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ApiError::Unreachable(why) => write!(f, "the server did not answer: {why}"),
ApiError::Untrusted(why) => {
write!(f, "the server's certificate was refused: {why}")
}
ApiError::Status(401, _) => f.write_str("the server refused the key (401)"),
ApiError::Status(status, Some(title)) => {
write!(f, "the server answered {status} ({title})")
}
ApiError::Status(status, None) => write!(f, "the server answered {status}"),
ApiError::Malformed(why) => {
write!(f, "the server's answer could not be read: {why}")
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Connection {
Connecting,
Connected(KeyInfo),
Failed(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Listing {
Loading,
Ready,
Failed(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum View {
List,
Detail,
Help,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
Up,
Down,
Top,
Bottom,
PageUp,
PageDown,
Open,
Back,
Refresh,
More,
Help,
Quit,
Reveal(Part),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Content {
None,
Reading,
Ready(Vec<String>),
Failed(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Revealed {
Reading(Part),
Shown(Part, String),
Failed(Part, String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Event {
Action(Action),
Resize(u16, u16),
KeyInfo(Result<KeyInfo, ApiError>),
Page(Result<Page, ApiError>),
Masked(String, Result<Vec<String>, ApiError>),
Revealed(String, Part, Result<String, ApiError>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Effect {
FetchKey,
FetchPage(Option<String>),
FetchMasked(String),
FetchReveal(String, Part),
}
const FRAME_LINES: u16 = 5;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct State {
pub server: String,
pub connection: Connection,
pub listing: Listing,
pub rows: Vec<Row>,
pub next: Option<String>,
pub selected: usize,
pub view: View,
pub behind_help: View,
pub detail: Option<String>,
pub more: bool,
pub as_of: Option<OffsetDateTime>,
pub notice: Option<String>,
pub size: (u16, u16),
pub quit: bool,
pub content: Content,
pub revealed: Option<Revealed>,
pub scroll: usize,
}
impl State {
#[must_use]
pub fn new(server: &str, size: (u16, u16)) -> (Self, Vec<Effect>) {
let state = Self {
server: server.to_owned(),
connection: Connection::Connecting,
listing: Listing::Loading,
rows: Vec::new(),
next: None,
selected: 0,
view: View::List,
behind_help: View::List,
detail: None,
more: false,
as_of: None,
notice: None,
size,
quit: false,
content: Content::None,
revealed: None,
scroll: 0,
};
(state, vec![Effect::FetchKey])
}
#[must_use]
pub fn list_rows(lines: u16) -> u16 {
lines.saturating_sub(FRAME_LINES).max(1)
}
#[must_use]
pub fn detail_row(&self) -> Option<&Row> {
let uuid = self.detail.as_deref()?;
self.rows.iter().find(|row| row.uuid == uuid)
}
fn busy(&self) -> bool {
self.more
|| self.connection == Connection::Connecting
|| (self.listing == Listing::Loading
&& matches!(self.connection, Connection::Connected(_)))
}
#[must_use]
pub fn acts(&self, action: Action) -> bool {
match (self.view, action) {
(_, Action::Quit | Action::Help) | (View::Help | View::Detail, Action::Back) => true,
(View::Help, _)
| (View::List, Action::Back | Action::Reveal(_))
| (View::Detail, Action::Open) => false,
(View::Detail, Action::Reveal(_)) => {
matches!(self.content, Content::Ready(_)) && self.detail_row().is_some()
}
(View::Detail, Action::PageDown) => self.scroll < self.scroll_most(),
(View::Detail, Action::PageUp) => self.scroll > 0,
(_, Action::Refresh) => !self.busy() && self.key_refusal().is_none(),
(_, Action::More) => {
!self.busy() && self.listing == Listing::Ready && self.next.is_some()
}
(View::List, Action::Open) => self.rows_shown() && !self.rows.is_empty(),
(
view,
Action::Up
| Action::Down
| Action::Top
| Action::Bottom
| Action::PageUp
| Action::PageDown,
) => {
let reselects =
view == View::Detail && !self.rows.is_empty() && self.detail_row().is_none();
self.rows_shown() && (self.rows.len() > 1 || reselects)
}
}
}
#[must_use]
pub fn rows_shown(&self) -> bool {
self.listing == Listing::Ready
}
#[must_use]
pub fn key_refusal(&self) -> Option<&'static str> {
match &self.connection {
Connection::Connected(info) => refusal(info),
Connection::Connecting | Connection::Failed(_) => None,
}
}
pub fn step(&mut self, event: Event, now: OffsetDateTime) -> Vec<Effect> {
match event {
Event::Action(action) => {
self.notice = None;
self.act(action)
}
Event::Resize(columns, lines) => {
self.size = (columns, lines);
Vec::new()
}
Event::KeyInfo(Ok(info)) => self.connected(info),
Event::KeyInfo(Err(error)) => {
self.connection = Connection::Failed(error.to_string());
self.listing = Listing::Failed(error.to_string());
Vec::new()
}
Event::Page(Ok(page)) => {
self.page(page, now);
Vec::new()
}
Event::Page(Err(error)) => {
self.page_failed(&error);
Vec::new()
}
Event::Masked(uuid, answer) => {
self.masked_arrived(&uuid, answer);
Vec::new()
}
Event::Revealed(uuid, part, answer) => {
self.reveal_arrived(&uuid, part, answer);
Vec::new()
}
}
}
fn connected(&mut self, info: KeyInfo) -> Vec<Effect> {
let refusal = refusal(&info);
self.connection = Connection::Connected(info);
match refusal {
Some(why) => {
self.listing = Listing::Failed(why.to_owned());
Vec::new()
}
None => {
self.listing = Listing::Loading;
vec![Effect::FetchPage(None)]
}
}
}
fn page(&mut self, page: Page, now: OffsetDateTime) {
if self.more {
self.rows.extend(page.vcons);
} else {
let on = self
.detail
.clone()
.or_else(|| self.rows.get(self.selected).map(|row| row.uuid.clone()));
self.rows = page.vcons;
if let Some(index) =
on.and_then(|uuid| self.rows.iter().position(|row| row.uuid == uuid))
{
self.selected = index;
}
}
self.selected = self.selected.min(self.rows.len().saturating_sub(1));
self.next = page.next;
self.more = false;
self.listing = Listing::Ready;
self.as_of = Some(now);
}
fn page_failed(&mut self, error: &ApiError) {
if matches!(
error,
ApiError::Unreachable(_) | ApiError::Untrusted(_) | ApiError::Status(401, _)
) {
self.connection = Connection::Failed(error.to_string());
}
if self.more {
self.more = false;
self.notice = Some(format!("The next page was not read: {error}."));
} else {
self.rows.clear();
self.next = None;
self.selected = 0;
self.as_of = None;
self.listing = Listing::Failed(error.to_string());
}
}
fn act(&mut self, action: Action) -> Vec<Effect> {
match (self.view, action) {
(_, Action::Quit) => self.quit = true,
(View::Help, Action::Help | Action::Back) => self.view = self.behind_help,
(View::Help, _)
| (View::List, Action::Back | Action::Reveal(_))
| (View::Detail, Action::Open) => {}
(view, Action::Help) => {
self.behind_help = view;
self.view = View::Help;
}
(View::Detail, Action::Back) => {
self.view = View::List;
self.content = Content::None;
self.drop_revealed();
}
(View::Detail, Action::Reveal(part)) => return self.reveal(part),
(View::Detail, Action::PageDown) => {
let page = Self::page_lines(self.size.1);
self.scroll = self.scroll.saturating_add(page).min(self.scroll_most());
}
(View::Detail, Action::PageUp) => {
self.scroll = self.scroll.saturating_sub(Self::page_lines(self.size.1));
}
(view, Action::Refresh) => {
let mut effects = self.refresh();
if view == View::Detail {
self.drop_revealed();
if !effects.is_empty()
&& let Some(uuid) = self.detail.clone()
{
self.content = Content::Reading;
effects.push(Effect::FetchMasked(uuid));
}
}
return effects;
}
(_, Action::More) => return self.more(),
(
_,
Action::Open
| Action::Up
| Action::Down
| Action::Top
| Action::Bottom
| Action::PageUp
| Action::PageDown,
) if !self.rows_shown() => {}
(View::List, Action::Open) => {
if let Some(row) = self.rows.get(self.selected) {
let uuid = row.uuid.clone();
self.view = View::Detail;
return self.show(uuid);
}
}
(
view,
Action::Up
| Action::Down
| Action::Top
| Action::Bottom
| Action::PageUp
| Action::PageDown,
) => {
self.travel(action);
if view == View::Detail
&& let Some(row) = self.rows.get(self.selected)
&& self.detail.as_deref() != Some(row.uuid.as_str())
{
let uuid = row.uuid.clone();
return self.show(uuid);
}
}
}
Vec::new()
}
fn show(&mut self, uuid: String) -> Vec<Effect> {
self.detail = Some(uuid.clone());
self.content = Content::Reading;
self.drop_revealed();
vec![Effect::FetchMasked(uuid)]
}
fn reveal(&mut self, part: Part) -> Vec<Effect> {
if !self.acts(Action::Reveal(part)) {
return Vec::new();
}
let Some(uuid) = self.detail.clone() else {
return Vec::new();
};
self.revealed = Some(Revealed::Reading(part));
self.scroll_to_revealed();
vec![Effect::FetchReveal(uuid, part)]
}
fn scroll_to_revealed(&mut self) {
let kept = self.revealed.take();
let top = crate::tui::view::detail_lines(self, self.size.0).len();
self.revealed = kept;
self.scroll = top.min(self.scroll_most());
}
fn drop_revealed(&mut self) {
self.revealed = None;
self.scroll = 0;
}
fn showing(&self, uuid: &str) -> bool {
let detail = self.view == View::Detail
|| (self.view == View::Help && self.behind_help == View::Detail);
detail && self.detail.as_deref() == Some(uuid)
}
fn masked_arrived(&mut self, uuid: &str, answer: Result<Vec<String>, ApiError>) {
if self.showing(uuid) && self.content == Content::Reading {
self.content = match answer {
Ok(lines) => Content::Ready(lines),
Err(error) => Content::Failed(error.to_string()),
};
}
}
fn reveal_arrived(&mut self, uuid: &str, part: Part, answer: Result<String, ApiError>) {
if self.showing(uuid) && self.revealed == Some(Revealed::Reading(part)) {
self.revealed = Some(match answer {
Ok(text) => Revealed::Shown(part, text),
Err(error) => Revealed::Failed(part, error.to_string()),
});
self.scroll_to_revealed();
}
}
#[must_use]
pub fn page_lines(lines: u16) -> usize {
usize::from(Self::list_rows(lines))
}
fn scroll_most(&self) -> usize {
crate::tui::view::detail_lines(self, self.size.0)
.len()
.saturating_sub(Self::page_lines(self.size.1))
}
fn travel(&mut self, action: Action) {
let last = self.rows.len().saturating_sub(1);
let page = usize::from(Self::list_rows(self.size.1));
self.selected = match action {
Action::Up => self.selected.saturating_sub(1),
Action::Down => self.selected.saturating_add(1),
Action::Top => 0,
Action::Bottom => last,
Action::PageUp => self.selected.saturating_sub(page),
Action::PageDown => self.selected.saturating_add(page),
_ => self.selected,
}
.min(last);
}
fn refresh(&mut self) -> Vec<Effect> {
if self.busy() {
return Vec::new();
}
if let Connection::Connected(info) = &self.connection {
return self.connected(info.clone());
}
self.connection = Connection::Connecting;
self.listing = Listing::Loading;
vec![Effect::FetchKey]
}
fn more(&mut self) -> Vec<Effect> {
if self.busy() || self.listing != Listing::Ready {
return Vec::new();
}
let Some(cursor) = self.next.clone() else {
return Vec::new();
};
self.more = true;
vec![Effect::FetchPage(Some(cursor))]
}
}
fn refusal(info: &KeyInfo) -> Option<&'static str> {
if info.tenant.is_none() {
Some("this is an operator key, which reaches no vCon: use a tenant key with the read scope")
} else if info.scopes.iter().all(|scope| scope != "read") {
Some("this key lacks the read scope: use a tenant key that holds it")
} else {
None
}
}
#[cfg(test)]
mod tests {
use time::OffsetDateTime;
use time::macros::datetime;
use super::{
Action, ApiError, Connection, Effect, Event, KeyInfo, Listing, Page, Row, State, View,
};
const NOW: OffsetDateTime = datetime!(2026-11-10 01:20:00 UTC);
fn row(n: u8) -> Row {
Row {
uuid: format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc{n:02}"),
stored_at: "2026-10-25T12:00:00.123456789Z".to_owned(),
updated_at: "2026-10-25T12:30:00Z".to_owned(),
version: format!("4f0c4b0a1d2e3f405162738495a6b7{n:02}"),
}
}
fn reader() -> KeyInfo {
KeyInfo {
id: "0123456789abcdef".to_owned(),
tenant: Some("t_example".to_owned()),
scopes: vec!["read".to_owned()],
}
}
fn page(rows: std::ops::Range<u8>, next: Option<&str>) -> Page {
Page {
vcons: rows.map(row).collect(),
next: next.map(str::to_owned),
}
}
fn listed(rows: u8, next: Option<&str>) -> State {
let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
state.step(Event::KeyInfo(Ok(reader())), NOW);
state.step(Event::Page(Ok(page(0..rows, next))), NOW);
state
}
fn press(state: &mut State, action: Action) -> Vec<Effect> {
state.step(Event::Action(action), NOW)
}
#[test]
fn a_new_state_is_connecting_and_asks_for_the_key() {
let (state, effects) = State::new("https://vcon.example.com:8443", (80, 24));
assert_eq!(
state.connection,
Connection::Connecting,
"nothing has answered yet"
);
assert_eq!(
effects,
[Effect::FetchKey],
"the key's tenant and scopes come first"
);
}
#[test]
fn a_reader_key_connects_and_asks_for_the_first_page() {
let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
let effects = state.step(Event::KeyInfo(Ok(reader())), NOW);
assert_eq!(
state.connection,
Connection::Connected(reader()),
"the key answered"
);
assert_eq!(state.listing, Listing::Loading, "the page is on its way");
assert_eq!(
effects,
[Effect::FetchPage(None)],
"the first page has no cursor"
);
}
#[test]
fn a_page_fills_the_list_and_records_when() {
let state = listed(3, Some("cursor-1"));
assert_eq!(state.listing, Listing::Ready, "the page arrived");
assert_eq!(state.rows.len(), 3, "every row of the page is kept");
assert_eq!(
state.next.as_deref(),
Some("cursor-1"),
"the cursor is kept for more"
);
assert_eq!(
state.as_of,
Some(NOW),
"the clock passed in is when it was read"
);
}
#[test]
fn down_and_up_move_the_selection() {
let mut state = listed(3, None);
press(&mut state, Action::Down);
press(&mut state, Action::Down);
assert_eq!(state.selected, 2, "two rows down");
press(&mut state, Action::Up);
assert_eq!(state.selected, 1, "one row back up");
}
#[test]
fn bottom_and_top_jump_to_the_ends() {
let mut state = listed(5, None);
press(&mut state, Action::Bottom);
assert_eq!(state.selected, 4, "the last row");
press(&mut state, Action::Top);
assert_eq!(state.selected, 0, "the first row");
}
#[test]
fn open_shows_the_selected_vcon_and_back_returns() {
let mut state = listed(3, None);
press(&mut state, Action::Down);
let effects = press(&mut state, Action::Open);
assert_eq!(state.view, View::Detail, "the detail view is open");
assert_eq!(
state.detail,
Some(row(1).uuid),
"on the row that was selected"
);
assert_eq!(
effects,
[Effect::FetchMasked(row(1).uuid)],
"the metadata is the list row's; the content is asked for masked"
);
press(&mut state, Action::Back);
assert_eq!(state.view, View::List, "back at the list");
}
#[test]
fn more_asks_for_the_next_page_and_appends_it() {
let mut state = listed(2, Some("cursor-1"));
let effects = press(&mut state, Action::More);
assert_eq!(
effects,
[Effect::FetchPage(Some("cursor-1".to_owned()))],
"the cursor goes back unchanged"
);
state.step(Event::Page(Ok(page(2..4, None))), NOW);
assert_eq!(state.rows.len(), 4, "the second page follows the first");
assert_eq!(state.next, None, "the last page has no cursor");
}
#[test]
fn refresh_asks_for_the_first_page_again_and_replaces_the_rows() {
let mut state = listed(3, None);
let effects = press(&mut state, Action::Refresh);
assert_eq!(effects, [Effect::FetchPage(None)], "from the start");
assert_eq!(
state.listing,
Listing::Loading,
"loading is shown meanwhile"
);
state.step(Event::Page(Ok(page(0..1, None))), NOW);
assert_eq!(state.rows.len(), 1, "the new page replaces the old rows");
}
#[test]
fn help_opens_over_a_view_and_returns_to_it() {
let mut state = listed(3, None);
press(&mut state, Action::Open);
press(&mut state, Action::Help);
assert_eq!(state.view, View::Help, "help is open");
press(&mut state, Action::Back);
assert_eq!(
state.view,
View::Detail,
"back at the view help was opened from"
);
}
#[test]
fn quit_ends_from_every_view() {
for open in [None, Some(Action::Open), Some(Action::Help)] {
let mut state = listed(1, None);
if let Some(open) = open {
press(&mut state, open);
}
press(&mut state, Action::Quit);
assert!(state.quit, "quit ends from {:?}", state.view);
}
}
#[test]
fn page_down_moves_by_the_rows_the_terminal_shows() {
let mut state = listed(60, None);
press(&mut state, Action::PageDown);
assert_eq!(
state.selected,
usize::from(State::list_rows(24)),
"a 24-line terminal pages by its list rows"
);
press(&mut state, Action::PageUp);
assert_eq!(state.selected, 0, "and back");
}
#[test]
fn down_in_the_detail_view_shows_the_next_vcon() {
let mut state = listed(3, None);
press(&mut state, Action::Open);
press(&mut state, Action::Down);
assert_eq!(
state.detail,
Some(row(1).uuid),
"the detail follows the selection"
);
}
#[test]
fn a_refresh_keeps_the_selection_on_the_same_vcon() {
let mut state = listed(3, None);
press(&mut state, Action::Bottom);
press(&mut state, Action::Open);
press(&mut state, Action::Refresh);
state.step(Event::Page(Ok(page(1..3, None))), NOW);
assert_eq!(
state.selected, 1,
"the vCon moved up one row and the selection with it"
);
assert_eq!(
state.detail,
Some(row(2).uuid),
"the detail is still that vCon"
);
}
#[test]
fn an_unreachable_server_fails_the_connection_and_the_list() {
let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
let effects = state.step(
Event::KeyInfo(Err(ApiError::Unreachable("connection refused".to_owned()))),
NOW,
);
assert_eq!(
effects,
[],
"nothing more is asked of a server that did not answer"
);
assert!(
matches!(&state.connection, Connection::Failed(why) if why.contains("connection refused")),
"the status line says why: {:?}",
state.connection
);
assert!(
matches!(state.listing, Listing::Failed(_)),
"the list says so too"
);
}
#[test]
fn a_refused_key_says_the_status() {
let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
state.step(Event::KeyInfo(Err(ApiError::Status(401, None))), NOW);
assert!(
matches!(&state.connection, Connection::Failed(why) if why.contains("401")),
"the refusal's status is shown: {:?}",
state.connection
);
}
#[test]
fn an_operator_key_connects_but_lists_nothing() {
let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
let operator = KeyInfo {
id: "0123456789abcdef".to_owned(),
tenant: None,
scopes: vec!["admin".to_owned()],
};
let effects = state.step(Event::KeyInfo(Ok(operator)), NOW);
assert_eq!(
effects,
[],
"an operator key reaches no vCon, so none is asked for"
);
assert!(
matches!(&state.listing, Listing::Failed(why) if why.contains("operator key")),
"the list says which key to use: {:?}",
state.listing
);
}
#[test]
fn a_key_without_read_lists_nothing() {
let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
let writer = KeyInfo {
scopes: vec!["write".to_owned()],
..reader()
};
let effects = state.step(Event::KeyInfo(Ok(writer)), NOW);
assert_eq!(effects, [], "the list needs read, so it is not asked for");
assert!(
matches!(&state.listing, Listing::Failed(why) if why.contains("read scope")),
"the list names the scope: {:?}",
state.listing
);
}
#[test]
fn a_failed_first_page_is_an_error_state() {
let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
state.step(Event::KeyInfo(Ok(reader())), NOW);
state.step(
Event::Page(Err(ApiError::Status(503, Some("unavailable".to_owned())))),
NOW,
);
assert!(
matches!(&state.listing, Listing::Failed(why) if why.contains("503") && why.contains("unavailable")),
"the status and the problem's title are shown: {:?}",
state.listing
);
assert_eq!(state.as_of, None, "nothing was read, so no time is claimed");
}
#[test]
fn a_failed_next_page_keeps_the_rows_and_leaves_a_notice() {
let mut state = listed(2, Some("cursor-1"));
press(&mut state, Action::More);
state.step(
Event::Page(Err(ApiError::Unreachable("timed out".to_owned()))),
NOW,
);
assert_eq!(state.rows.len(), 2, "the rows already read stay");
assert_eq!(state.listing, Listing::Ready, "the list is still usable");
assert_eq!(
state.next.as_deref(),
Some("cursor-1"),
"the cursor is kept to try again"
);
assert!(
state
.notice
.as_deref()
.is_some_and(|n| n.contains("timed out")),
"a notice says why: {:?}",
state.notice
);
}
#[test]
fn a_failed_refresh_drops_the_old_rows() {
let mut state = listed(2, None);
press(&mut state, Action::Refresh);
state.step(Event::Page(Err(ApiError::Status(500, None))), NOW);
assert!(
matches!(state.listing, Listing::Failed(_)),
"the error is shown"
);
assert_eq!(
state.rows,
[],
"rows that may be out of date are not shown as current"
);
}
#[test]
fn a_malformed_answer_is_an_error_state() {
let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
state.step(Event::KeyInfo(Ok(reader())), NOW);
state.step(
Event::Page(Err(ApiError::Malformed("expected value".to_owned()))),
NOW,
);
assert!(
matches!(&state.listing, Listing::Failed(why) if why.contains("expected value")),
"what could not be read is shown: {:?}",
state.listing
);
}
#[test]
fn refresh_after_a_failed_connection_asks_for_the_key_again() {
let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
state.step(
Event::KeyInfo(Err(ApiError::Unreachable("refused".to_owned()))),
NOW,
);
let effects = press(&mut state, Action::Refresh);
assert_eq!(
effects,
[Effect::FetchKey],
"the connection is made again from the start"
);
assert_eq!(
state.connection,
Connection::Connecting,
"and shown as such"
);
}
#[test]
fn a_server_that_stops_answering_is_shown_as_not_connected() {
let mut state = listed(2, None);
press(&mut state, Action::Refresh);
state.step(
Event::Page(Err(ApiError::Unreachable("connection reset".to_owned()))),
NOW,
);
assert!(
matches!(state.connection, Connection::Failed(_)),
"the status line no longer says connected"
);
}
#[test]
fn a_vcon_gone_after_a_refresh_leaves_the_detail_without_a_row() {
let mut state = listed(2, None);
press(&mut state, Action::Open);
press(&mut state, Action::Refresh);
state.step(Event::Page(Ok(page(1..2, None))), NOW);
assert_eq!(
state.detail,
Some(row(0).uuid),
"the detail still names what was open"
);
assert_eq!(state.detail_row(), None, "and has no row to draw");
}
#[test]
fn each_api_error_says_what_failed() {
for (error, text) in [
(
ApiError::Unreachable("refused".to_owned()),
"the server did not answer: refused",
),
(
ApiError::Status(401, None),
"the server refused the key (401)",
),
(
ApiError::Status(403, Some("forbidden".to_owned())),
"the server answered 403 (forbidden)",
),
(ApiError::Status(500, None), "the server answered 500"),
(
ApiError::Malformed("eof".to_owned()),
"the server's answer could not be read: eof",
),
] {
assert_eq!(error.to_string(), text, "{error:?}");
}
}
#[test]
fn up_at_the_top_and_down_at_the_bottom_stay() {
let mut state = listed(2, None);
press(&mut state, Action::Up);
assert_eq!(state.selected, 0, "no row above the first");
press(&mut state, Action::Bottom);
press(&mut state, Action::Down);
assert_eq!(state.selected, 1, "no row below the last");
}
#[test]
fn open_on_an_empty_list_does_nothing() {
let mut state = listed(0, None);
press(&mut state, Action::Open);
assert_eq!(state.view, View::List, "there is nothing to open");
assert_eq!(state.detail, None, "and no vCon is named");
}
#[test]
fn movement_on_an_empty_list_stays_at_zero() {
let mut state = listed(0, None);
for action in [Action::Down, Action::Bottom, Action::PageDown, Action::Up] {
press(&mut state, action);
assert_eq!(state.selected, 0, "{action:?} on no rows");
}
}
#[test]
fn more_on_the_last_page_asks_for_nothing() {
let mut state = listed(2, None);
assert_eq!(press(&mut state, Action::More), [], "there is no next page");
}
#[test]
fn a_second_refresh_while_loading_asks_for_nothing() {
let mut state = listed(2, None);
press(&mut state, Action::Refresh);
assert_eq!(
press(&mut state, Action::Refresh),
[],
"one request is in flight; a second would race it"
);
}
#[test]
fn more_while_more_is_loading_asks_for_nothing() {
let mut state = listed(2, Some("cursor-1"));
press(&mut state, Action::More);
assert_eq!(
press(&mut state, Action::More),
[],
"the page is already on its way"
);
assert_eq!(
press(&mut state, Action::Refresh),
[],
"and a refresh would race it"
);
}
#[test]
fn refresh_while_connecting_asks_for_nothing() {
let (mut state, _) = State::new("https://vcon.example.com:8443", (80, 24));
assert_eq!(
press(&mut state, Action::Refresh),
[],
"the key request is in flight"
);
}
#[test]
fn a_resize_changes_only_the_size() {
let mut state = listed(3, None);
press(&mut state, Action::Down);
let before = state.clone();
let effects = state.step(Event::Resize(132, 43), NOW);
assert_eq!(effects, [], "a resize asks the server nothing");
assert_eq!(state.size, (132, 43), "the new size is kept");
assert_eq!(
State {
size: before.size,
..state
},
before,
"nothing else changed"
);
}
#[test]
fn a_shorter_page_after_refresh_clamps_the_selection() {
let mut state = listed(5, None);
press(&mut state, Action::Bottom);
press(&mut state, Action::Refresh);
state.step(Event::Page(Ok(page(10..12, None))), NOW);
assert_eq!(
state.selected, 1,
"the selection is the last row that exists"
);
}
#[test]
fn page_down_past_the_end_stops_at_the_last_row() {
let mut state = listed(3, None);
press(&mut state, Action::PageDown);
assert_eq!(state.selected, 2, "the last row, not past it");
}
#[test]
fn a_terminal_too_short_for_a_list_still_pages_by_one() {
assert_eq!(State::list_rows(0), 1, "never zero: paging would not move");
assert_eq!(State::list_rows(5), 1, "the frame takes five lines");
assert_eq!(State::list_rows(24), 19, "24 lines leave 19 for rows");
}
#[test]
fn help_from_help_closes_it() {
let mut state = listed(1, None);
press(&mut state, Action::Help);
press(&mut state, Action::Help);
assert_eq!(state.view, View::List, "the same key closes help");
}
#[test]
fn a_key_press_clears_the_notice() {
let mut state = listed(2, Some("cursor-1"));
press(&mut state, Action::More);
state.step(
Event::Page(Err(ApiError::Unreachable("timed out".to_owned()))),
NOW,
);
press(&mut state, Action::Down);
assert_eq!(
state.notice, None,
"the notice is about the last request only"
);
}
#[test]
fn back_in_the_list_view_does_not_quit() {
let mut state = listed(1, None);
press(&mut state, Action::Back);
assert!(!state.quit, "only the quit keys end the program");
assert_eq!(state.view, View::List, "and the view stays");
}
#[test]
fn a_key_refused_at_a_refresh_is_not_connected_as_at_start() {
let mut state = listed(3, None);
press(&mut state, Action::Refresh);
state.step(Event::Page(Err(ApiError::Status(401, None))), NOW);
assert_eq!(
state.connection,
Connection::Failed("the server refused the key (401)".to_owned()),
"a revoked key is shown as it is when the UI starts with one"
);
assert_eq!(
state.listing,
Listing::Failed("the server refused the key (401)".to_owned()),
"and the list says why"
);
}
#[test]
fn a_refresh_after_a_refused_key_asks_for_the_key_again() {
let mut state = listed(3, None);
press(&mut state, Action::Refresh);
state.step(Event::Page(Err(ApiError::Status(401, None))), NOW);
assert_eq!(
press(&mut state, Action::Refresh),
vec![Effect::FetchKey],
"the tenant and scopes are read again, not taken from before the refusal"
);
}
#[test]
fn a_key_refused_at_a_next_page_is_not_connected_and_the_rows_stay() {
let mut state = listed(3, Some("cursor-1"));
press(&mut state, Action::More);
state.step(Event::Page(Err(ApiError::Status(401, None))), NOW);
assert_eq!(
state.connection,
Connection::Failed("the server refused the key (401)".to_owned()),
"the status line stops saying connected"
);
assert_eq!(state.rows.len(), 3, "the rows read before stay");
assert_eq!(
state.notice.as_deref(),
Some("The next page was not read: the server refused the key (401)."),
"and the notice says why"
);
}
#[test]
fn a_503_at_a_refresh_leaves_the_connection_as_it_was() {
let mut state = listed(3, None);
press(&mut state, Action::Refresh);
state.step(
Event::Page(Err(ApiError::Status(503, Some("unavailable".to_owned())))),
NOW,
);
assert!(
matches!(state.connection, Connection::Connected(_)),
"the server answered for the key, and may answer the next request"
);
assert_eq!(
press(&mut state, Action::Refresh),
vec![Effect::FetchPage(None)],
"so r reads the first page, not the key"
);
}
const ACTIONS: [Action; 12] = [
Action::Up,
Action::Down,
Action::Top,
Action::Bottom,
Action::PageUp,
Action::PageDown,
Action::Open,
Action::Back,
Action::Refresh,
Action::More,
Action::Help,
Action::Quit,
];
const TRAVEL: [Action; 6] = [
Action::Up,
Action::Down,
Action::Top,
Action::Bottom,
Action::PageUp,
Action::PageDown,
];
fn after(mut state: State, events: Vec<Event>) -> State {
for event in events {
state.step(event, NOW);
}
state
}
fn new() -> State {
State::new("https://vcon.example.com:8443", (80, 24)).0
}
fn key(tenant: Option<&str>, scope: &str) -> Event {
Event::KeyInfo(Ok(KeyInfo {
id: "0123456789abcdef".to_owned(),
tenant: tenant.map(str::to_owned),
scopes: vec![scope.to_owned()],
}))
}
fn no_answer() -> ApiError {
ApiError::Unreachable("no answer within 15 seconds".to_owned())
}
fn states() -> Vec<(String, State)> {
let act = Event::Action;
let mut base: Vec<(&str, State)> = vec![
("connecting", new()),
("loading", after(new(), vec![Event::KeyInfo(Ok(reader()))])),
(
"no answer",
after(new(), vec![Event::KeyInfo(Err(no_answer()))]),
),
(
"refused key",
after(
new(),
vec![Event::KeyInfo(Err(ApiError::Status(401, None)))],
),
),
("operator key", after(new(), vec![key(None, "admin")])),
(
"write key",
after(new(), vec![key(Some("t_example"), "write")]),
),
(
"first page failed",
after(
new(),
vec![
Event::KeyInfo(Ok(reader())),
Event::Page(Err(ApiError::Status(503, None))),
],
),
),
("empty", listed(0, None)),
("one row", listed(1, None)),
("one row, more", listed(1, Some("c"))),
("three rows", listed(3, None)),
("three rows, more", listed(3, Some("c"))),
(
"three rows, second",
after(listed(3, None), vec![act(Action::Down)]),
),
(
"three rows, last",
after(listed(3, Some("c")), vec![act(Action::Bottom)]),
),
(
"next page out",
after(listed(3, Some("c")), vec![act(Action::More)]),
),
(
"next page failed",
after(
listed(3, Some("c")),
vec![act(Action::More), Event::Page(Err(no_answer()))],
),
),
(
"refresh out",
after(listed(3, Some("c")), vec![act(Action::Refresh)]),
),
(
"refresh failed",
after(
listed(3, None),
vec![
act(Action::Refresh),
Event::Page(Err(ApiError::Status(503, None))),
],
),
),
(
"reconnecting",
after(
listed(3, None),
vec![
act(Action::Refresh),
Event::Page(Err(no_answer())),
act(Action::Refresh),
],
),
),
];
for (name, left) in [
("gone, three left", 3),
("gone, one left", 1),
("gone, none left", 0),
] {
let mut state = after(
listed(5, None),
vec![act(Action::Bottom), act(Action::Open), act(Action::Refresh)],
);
state.step(Event::Page(Ok(page(0..left, None))), NOW);
assert_eq!(
state.view,
View::Detail,
"{name}: the detail view stays open"
);
assert!(
state.detail_row().is_none(),
"{name}: its vCon is not listed"
);
base.push((name, state));
}
let mut all = Vec::new();
for (name, state) in base {
let opened = after(state.clone(), vec![act(Action::Open)]);
if opened.view == View::Detail && state.view != View::Detail {
let refreshing = after(opened.clone(), vec![act(Action::Refresh)]);
all.push((
format!("{name}, detail, help"),
after(opened.clone(), vec![act(Action::Help)]),
));
all.push((format!("{name}, detail, r pressed"), refreshing));
all.push((format!("{name}, detail"), opened));
}
all.push((
format!("{name}, help"),
after(state.clone(), vec![act(Action::Help)]),
));
all.push((name.to_owned(), state));
}
all
}
fn acted(state: &State, action: Action) -> (State, Vec<Effect>) {
let mut next = state.clone();
let effects = next.act(action);
(next, effects)
}
#[test]
fn the_states_tried_cover_every_view_and_kind() {
let all = states();
assert!(all.len() >= 50, "{} states are tried", all.len());
for view in [View::List, View::Detail, View::Help] {
assert!(
all.iter().any(|(_, state)| state.view == view),
"a state in {view:?} is tried"
);
}
let mut names: Vec<&String> = all.iter().map(|(name, _)| name).collect();
names.sort();
names.dedup();
assert_eq!(names.len(), all.len(), "each state has its own name");
}
#[test]
fn a_key_that_does_not_act_changes_nothing() {
for (name, state) in states() {
for action in ACTIONS {
if state.acts(action) {
continue;
}
let (next, effects) = acted(&state, action);
assert!(
next == state && effects.is_empty(),
"{name}: {action:?} is said not to act, and a press changed the state or asked the server"
);
}
}
}
#[test]
fn a_key_that_acts_changes_the_state_or_asks_the_server() {
for (name, state) in states() {
for action in ACTIONS {
if !state.acts(action) || TRAVEL.contains(&action) {
continue;
}
let (next, effects) = acted(&state, action);
assert!(
next != state || !effects.is_empty(),
"{name}: {action:?} is said to act, and a press did nothing"
);
}
}
}
#[test]
fn the_keys_that_move_act_when_one_of_them_can_move() {
for (name, state) in states() {
let travel: Vec<Action> = TRAVEL
.into_iter()
.filter(|action| {
state.view != View::Detail
|| !matches!(action, Action::PageUp | Action::PageDown)
})
.collect();
let moves = travel
.iter()
.any(|action| acted(&state, *action).0 != state);
for action in travel {
assert_eq!(
state.acts(action),
moves,
"{name}: {action:?} acts when the selection can move ({moves})"
);
}
}
}
#[test]
fn quit_and_help_act_in_every_state() {
for (name, state) in states() {
assert!(state.acts(Action::Quit), "{name}: q quits");
assert!(state.acts(Action::Help), "{name}: ? opens or closes help");
}
}
#[test]
fn nothing_but_help_back_and_quit_acts_in_the_help_view() {
for (name, state) in states() {
if state.view != View::Help {
continue;
}
for action in ACTIONS {
assert_eq!(
state.acts(action),
matches!(action, Action::Help | Action::Back | Action::Quit),
"{name}: {action:?}"
);
}
}
}
#[test]
fn refresh_does_not_act_while_a_request_is_out() {
for state in [
new(),
after(new(), vec![Event::KeyInfo(Ok(reader()))]),
after(listed(3, Some("c")), vec![Event::Action(Action::More)]),
after(listed(3, None), vec![Event::Action(Action::Refresh)]),
] {
assert!(
!state.acts(Action::Refresh),
"a second request would race the first: {:?} {:?}",
state.connection,
state.listing
);
}
}
#[test]
fn refresh_acts_after_a_failure_the_server_made() {
for state in [
after(new(), vec![Event::KeyInfo(Err(no_answer()))]),
after(
new(),
vec![Event::KeyInfo(Err(ApiError::Status(401, None)))],
),
after(
new(),
vec![
Event::KeyInfo(Ok(reader())),
Event::Page(Err(ApiError::Status(503, None))),
],
),
] {
assert!(
state.acts(Action::Refresh),
"the server may answer the next request: {:?}",
state.listing
);
}
}
#[test]
fn refresh_does_not_act_for_a_key_that_may_not_list() {
for event in [key(None, "admin"), key(Some("t_example"), "write")] {
let mut state = after(new(), vec![event]);
assert!(
!state.acts(Action::Refresh),
"the key is read once, at start: {:?}",
state.listing
);
let before = state.clone();
assert_eq!(
press(&mut state, Action::Refresh),
Vec::new(),
"nothing is asked of the server"
);
assert_eq!(state, before, "and the refusal stays on the screen");
}
}
#[test]
fn more_acts_only_when_the_server_holds_more_and_nothing_is_out() {
assert!(listed(3, Some("c")).acts(Action::More), "a cursor is held");
assert!(!listed(3, None).acts(Action::More), "every vCon is read");
assert!(
!after(listed(3, Some("c")), vec![Event::Action(Action::More)]).acts(Action::More),
"the next page is on its way"
);
assert!(
!after(listed(3, Some("c")), vec![Event::Action(Action::Refresh)]).acts(Action::More),
"the list is being read again"
);
assert!(!new().acts(Action::More), "nothing is read yet");
}
#[test]
fn open_acts_only_in_a_list_that_shows_a_row() {
assert!(listed(1, None).acts(Action::Open), "one row can be opened");
assert!(
!listed(0, None).acts(Action::Open),
"an empty tenant has none"
);
assert!(!new().acts(Action::Open), "nothing is listed yet");
let detail = after(listed(2, None), vec![Event::Action(Action::Open)]);
assert!(
!detail.acts(Action::Open),
"the detail view is open already"
);
}
#[test]
fn a_list_of_one_row_has_nowhere_to_move() {
let state = listed(1, None);
for action in TRAVEL {
assert!(!state.acts(action), "{action:?} has no other row to select");
}
}
#[test]
fn the_selection_does_not_move_while_the_list_is_not_shown() {
let mut state = after(listed(3, None), vec![Event::Action(Action::Refresh)]);
assert_eq!(state.listing, Listing::Loading, "the list is being read");
press(&mut state, Action::Down);
assert_eq!(state.selected, 0, "the screen shows no row to move from");
press(&mut state, Action::Open);
assert_eq!(state.view, View::List, "and none to open");
}
#[test]
fn back_acts_in_the_detail_and_help_views_only() {
let list = listed(2, None);
assert!(!list.acts(Action::Back), "the list is the first view");
let detail = after(list.clone(), vec![Event::Action(Action::Open)]);
assert!(detail.acts(Action::Back), "Esc returns to the list");
let help = after(list, vec![Event::Action(Action::Help)]);
assert!(help.acts(Action::Back), "Esc closes help");
}
#[test]
fn in_a_detail_view_whose_vcon_is_gone_the_keys_that_move_select_a_listed_one() {
let mut state = after(
listed(5, None),
vec![
Event::Action(Action::Bottom),
Event::Action(Action::Open),
Event::Action(Action::Refresh),
],
);
state.step(Event::Page(Ok(page(0..1, None))), NOW);
assert!(
state.acts(Action::Down),
"one row is left, and j shows it in place of the message"
);
press(&mut state, Action::Down);
assert_eq!(
state.detail_row().map(|row| row.uuid.clone()),
Some(row(0).uuid),
"the detail view shows the row that is left"
);
assert!(!state.acts(Action::Down), "then there is nowhere to move");
}
use super::{Content, Revealed};
use crate::reveal::Part;
const PARTS: [Part; 6] = [
Part::Parties,
Part::Subject,
Part::Dialog,
Part::Analysis,
Part::Links,
Part::All,
];
fn summary() -> Vec<String> {
vec!["Form unsigned".to_owned()]
}
fn opened() -> State {
let mut state = listed(3, None);
press(&mut state, Action::Down);
press(&mut state, Action::Open);
state.step(Event::Masked(row(1).uuid, Ok(summary())), NOW);
state
}
fn revealed(mut state: State, part: Part, text: &str) -> State {
press(&mut state, Action::Reveal(part));
state.step(Event::Revealed(row(1).uuid, part, Ok(text.to_owned())), NOW);
state
}
#[test]
fn open_asks_for_the_masked_view_and_reads_it_until_it_arrives() {
let mut state = listed(3, None);
let effects = press(&mut state, Action::Open);
assert_eq!(effects, [Effect::FetchMasked(row(0).uuid)], "one request");
assert_eq!(state.content, Content::Reading, "being read");
assert_eq!(state.revealed, None, "nothing revealed");
}
#[test]
fn the_masked_view_that_arrives_is_shown() {
assert_eq!(opened().content, Content::Ready(summary()), "the summary");
}
#[test]
fn a_reveal_key_asks_for_that_part_of_the_vcon_open() {
let mut state = opened();
let effects = press(&mut state, Action::Reveal(Part::Parties));
assert_eq!(
effects,
[Effect::FetchReveal(row(1).uuid, Part::Parties)],
"a reveal of the parties"
);
assert_eq!(
state.revealed,
Some(Revealed::Reading(Part::Parties)),
"being read"
);
}
#[test]
fn each_reveal_key_asks_for_its_own_part() {
for part in PARTS {
let mut state = opened();
assert!(state.acts(Action::Reveal(part)), "{part:?} acts");
assert_eq!(
press(&mut state, Action::Reveal(part)),
[Effect::FetchReveal(row(1).uuid, part)],
"{part:?}"
);
}
}
#[test]
fn the_revealed_text_is_shown_once_its_answer_arrives() {
let state = revealed(opened(), Part::Subject, "Renewal call");
assert_eq!(
state.revealed,
Some(Revealed::Shown(Part::Subject, "Renewal call".to_owned())),
"shown"
);
assert_eq!(
state.content,
Content::Ready(summary()),
"the summary stays"
);
}
#[test]
fn page_down_in_the_detail_view_scrolls_a_long_text_and_page_up_returns() {
let long: String = (0..200).map(|n| format!("line {n}\n")).collect();
let mut state = revealed(opened(), Part::All, &long);
let at = state.scroll;
assert!(state.acts(Action::PageDown), "there is more below");
press(&mut state, Action::PageDown);
assert_eq!(state.scroll, at + State::page_lines(24), "one screen down");
assert_eq!(state.detail, Some(row(1).uuid), "on the same vCon");
press(&mut state, Action::PageUp);
assert_eq!(state.scroll, at, "one screen up");
while state.acts(Action::PageUp) {
press(&mut state, Action::PageUp);
}
assert_eq!(state.scroll, 0, "at the top");
}
#[test]
fn a_reveal_moves_the_view_to_the_part_revealed() {
let long: String = (0..200).map(|n| format!("line {n}\n")).collect();
let state = revealed(opened(), Part::All, &long);
let lines = crate::tui::view::detail_lines(&state, 80);
let title = lines
.iter()
.position(|line| line == "The whole vCon, revealed:")
.expect("the part's title");
assert_eq!(
state.scroll,
title - 1,
"the view starts above the part's title"
);
assert!(state.acts(Action::PageUp), "the masked view is above");
}
#[test]
fn a_masked_view_that_failed_says_why() {
let mut state = listed(3, None);
press(&mut state, Action::Open);
let error = ApiError::Status(503, Some("The service cannot answer now".to_owned()));
state.step(Event::Masked(row(0).uuid, Err(error.clone())), NOW);
assert_eq!(
state.content,
Content::Failed(error.to_string()),
"the reason"
);
}
#[test]
fn a_reveal_that_failed_says_why_and_shows_no_text() {
let mut state = opened();
press(&mut state, Action::Reveal(Part::Dialog));
let error = ApiError::Status(403, Some("Forbidden".to_owned()));
state.step(
Event::Revealed(row(1).uuid, Part::Dialog, Err(error.clone())),
NOW,
);
assert_eq!(
state.revealed,
Some(Revealed::Failed(Part::Dialog, error.to_string())),
"the reason"
);
}
#[test]
fn a_reveal_key_in_the_list_does_nothing() {
let mut state = listed(3, None);
for part in PARTS {
assert!(!state.acts(Action::Reveal(part)), "{part:?} does not act");
assert_eq!(press(&mut state, Action::Reveal(part)), [], "{part:?}");
assert_eq!(state.revealed, None, "{part:?}");
}
}
#[test]
fn a_reveal_key_before_the_masked_view_arrived_does_nothing() {
let mut state = listed(3, None);
press(&mut state, Action::Open);
assert!(!state.acts(Action::Reveal(Part::All)), "not yet");
assert_eq!(
press(&mut state, Action::Reveal(Part::All)),
[],
"no request"
);
}
#[test]
fn a_reveal_key_after_a_failed_masked_view_does_nothing() {
let mut state = listed(3, None);
press(&mut state, Action::Open);
state.step(
Event::Masked(row(0).uuid, Err(ApiError::Status(404, None))),
NOW,
);
assert!(
!state.acts(Action::Reveal(Part::Parties)),
"nothing to reveal"
);
assert_eq!(
press(&mut state, Action::Reveal(Part::Parties)),
[],
"no request"
);
}
#[test]
fn a_reveal_key_in_help_does_nothing() {
let mut state = opened();
press(&mut state, Action::Help);
assert_eq!(
press(&mut state, Action::Reveal(Part::Links)),
[],
"no request"
);
assert_eq!(state.view, View::Help, "help stays open");
}
#[test]
fn esc_drops_the_revealed_text() {
let mut state = revealed(opened(), Part::Parties, "Ada Example");
press(&mut state, Action::Back);
assert_eq!(state.revealed, None, "dropped");
assert_eq!(
state.content,
Content::None,
"the masked view is dropped too"
);
}
#[test]
fn r_drops_the_revealed_text_and_reads_the_masked_view_again() {
let mut state = revealed(opened(), Part::Parties, "Ada Example");
let effects = press(&mut state, Action::Refresh);
assert_eq!(state.revealed, None, "dropped");
assert!(
effects.contains(&Effect::FetchMasked(row(1).uuid)),
"{effects:?}"
);
assert!(effects.contains(&Effect::FetchPage(None)), "{effects:?}");
assert_eq!(state.content, Content::Reading, "read again");
}
#[test]
fn moving_to_another_vcon_drops_the_text_and_asks_for_its_masked_view() {
let mut state = revealed(opened(), Part::Parties, "Ada Example");
let effects = press(&mut state, Action::Down);
assert_eq!(state.detail, Some(row(2).uuid), "the next vCon");
assert_eq!(
effects,
[Effect::FetchMasked(row(2).uuid)],
"its masked view"
);
assert_eq!(state.revealed, None, "dropped");
assert_eq!(state.scroll, 0, "at the top");
}
#[test]
fn a_reveal_that_arrives_after_esc_is_not_shown() {
let mut state = opened();
press(&mut state, Action::Reveal(Part::Parties));
press(&mut state, Action::Back);
press(&mut state, Action::Open);
state.step(
Event::Revealed(row(1).uuid, Part::Parties, Ok("Ada Example".to_owned())),
NOW,
);
assert_eq!(state.revealed, None, "the late answer is dropped");
}
#[test]
fn a_masked_view_of_a_vcon_no_longer_open_is_not_shown() {
let mut state = listed(3, None);
press(&mut state, Action::Open);
press(&mut state, Action::Down);
state.step(Event::Masked(row(0).uuid, Ok(summary())), NOW);
assert_eq!(
state.content,
Content::Reading,
"still reading the open vCon's"
);
}
#[test]
fn a_reveal_of_another_part_than_the_last_asked_is_not_shown() {
let mut state = opened();
press(&mut state, Action::Reveal(Part::Parties));
press(&mut state, Action::Reveal(Part::Subject));
state.step(
Event::Revealed(row(1).uuid, Part::Parties, Ok("Ada Example".to_owned())),
NOW,
);
assert_eq!(
state.revealed,
Some(Revealed::Reading(Part::Subject)),
"the subject is awaited"
);
}
#[test]
fn an_answer_that_arrives_while_help_is_open_is_kept() {
let mut state = listed(3, None);
press(&mut state, Action::Open);
press(&mut state, Action::Help);
state.step(Event::Masked(row(0).uuid, Ok(summary())), NOW);
press(&mut state, Action::Help);
assert_eq!(
state.content,
Content::Ready(summary()),
"kept for the detail view"
);
}
#[test]
fn page_keys_in_a_detail_view_that_fits_do_nothing() {
let mut state = opened();
assert!(!state.acts(Action::PageDown), "nothing below");
assert!(!state.acts(Action::PageUp), "nothing above");
press(&mut state, Action::PageDown);
assert_eq!(
(state.scroll, state.detail.clone()),
(0, Some(row(1).uuid)),
"unmoved"
);
}
}