Files
VoelinClient/crates/voelin-ui-vm/src/events/tests.rs
T
faumarayandClaude Sonnet 5.5 03d1c3bd07 Move the state transition of every engine event that the AppState holds into voelin-ui-vm
events::apply(state, host, event) changes the AppState for an engine Event and
returns an Update: the parts to draw again (Refresh, each once), the status
line, the engine commands, what to keep (Persist), pictures to decode again,
the password dialog, notices for the bell, the chats that changed, a stream to
watch. Host is what a transition asks while it runs (is the chat on screen,
the store's read markers, the preview limit); the Slint client answers it in
host.rs and carries the update out there, so App::handle_event is
social_event, apply_event and social_refresh. The chat transitions (tabs,
messages, what is read, pins and topics, files), the pictures linked in
chats, the server's name, icon and gateway, joining again and the password
prompt, the last place of voice and the stored volumes moved with it; Spot,
the notice types, own_uids and peer_name moved to the view model crate.

Update::rest hands back the events whose state is not in the AppState yet
(the streams we share and watch, the studio's stream, a setting that
changed); the friends, pokes and offline messages are still looked at by
social.rs before and after. The vm tests replay tapes of events against a
fake Host.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:30:39 +03:00

794 lines
26 KiB
Rust

//! Tapes of engine events replayed through [`apply`] against a fake host:
//! the state they leave, and what each update asks of a front end.
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use voelin_core::gateway::Pin;
use voelin_core::stream::StreamInfo;
use voelin_core::{
AudioSettings, BackendInfo, Command, Event, GatewayRequest, GatewayUpdate, HistoryMessage,
HistorySource, JoinFailure, ObserveState, SessionState, Source, TransferState, VoiceState,
};
use voelin_gateway_proto::{UserRef, feature};
use voelin_model::{
Capabilities, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerDetails,
};
use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget, MessageSource};
use super::*;
use crate::bridge::ChatLine;
use crate::host::Refresh;
use crate::settings::{ClientPlayback, ClientPlaybackMap, LastVoice, UiSettings};
type State = AppState<Vec<ChatLine>>;
/// The front end of the tests: answers what the transitions ask and keeps
/// what they store.
#[derive(Default)]
struct Fake {
demo: bool,
shown: Cell<bool>,
watching: bool,
autowatch: bool,
limit: u64,
/// What the store has: server unique id, its chats' reads.
reads: HashMap<String, Vec<(StoredTarget, ChatRead)>>,
/// What was stored.
written: RefCell<Vec<(String, StoredTarget, ChatRead)>>,
}
impl Host for Fake {
fn demo_ui(&self) -> bool {
self.demo
}
fn chat_shown(&self) -> bool {
self.shown.get()
}
fn watching(&self) -> bool {
self.watching
}
fn autowatch(&self) -> bool {
self.autowatch
}
fn preview_limit(&self) -> u64 {
self.limit
}
fn fetch_images(&self) -> bool {
false
}
fn chat_reads(&self, server_uid: &str) -> Result<Vec<(StoredTarget, ChatRead)>, String> {
Ok(self.reads.get(server_uid).cloned().unwrap_or_default())
}
fn set_chat_read(
&self,
server_uid: &str,
target: &StoredTarget,
read: &ChatRead,
) -> Result<(), String> {
self.written.borrow_mut().push((server_uid.to_owned(), target.clone(), *read));
Ok(())
}
}
fn state() -> State {
let bookmark = Bookmark {
id: 1,
name: "ts.example".into(),
address: "ts.example".into(),
nickname: "Me".into(),
..Default::default()
};
AppState::new(
vec![bookmark],
UiSettings::default(),
AudioSettings::default(),
ClientPlaybackMap::new(),
)
}
fn session(voice: VoiceState, own_channel: Option<u64>) -> SessionState {
let connected = voice == VoiceState::Connected;
SessionState {
voice,
observe: ObserveState::Off,
presence_source: connected.then_some(Source::Voice),
own_channel,
own_client: connected.then_some(10),
server_uid: connected.then(|| "srv=".to_owned()),
..Default::default()
}
}
/// Lobby (1) and Games (2), with Me (10, in Games) and Alice (11, in
/// Games).
fn presence() -> Arc<Presence> {
let mut p = Presence { server_name: "Nightfall Guild".into(), ..Default::default() };
for (id, order, name) in [(1, 0, "Lobby"), (2, 1, "Games")] {
p.channels.insert(id, ChannelInfo { id, order, name: name.into(), ..Default::default() });
}
for (id, name, uid) in [(10, "Me", "me="), (11, "Alice", "alice=")] {
p.clients.insert(
id,
ClientInfo {
id,
channel: 2,
nickname: name.into(),
uid: Some(uid.into()),
..Default::default()
},
);
}
p.server = ServerDetails { welcome_message: "Welcome".into(), ..Default::default() };
Arc::new(p)
}
/// A message of Games, by Alice unless `mine`.
fn said(id: i64, ts_ms: i64, mine: bool, text: &str) -> HistoryMessage {
HistoryMessage {
id,
message: ChatMessage {
target: ChatTarget::Channel(2),
author_name: if mine { "Me" } else { "Alice" }.into(),
author_uid: Some(if mine { "me=" } else { "alice=" }.into()),
author_id: Some(if mine { 10 } else { 11 }),
text: text.into(),
ts_ms,
via_relay: false,
blocked: false,
},
source: MessageSource::Voice,
remote_id: Some(id + 1000),
topic_id: None,
reactions: Vec::new(),
pinned: false,
rev: 0,
}
}
fn games(messages: Vec<HistoryMessage>, source: HistorySource) -> Event {
Event::ChatHistory {
session: 1,
target: ChatTarget::Channel(2),
messages,
source,
complete: true,
}
}
fn run(state: &mut State, host: &Fake, tape: Vec<Event>) -> Vec<Update> {
tape.into_iter().map(|event| apply(state, host, event)).collect()
}
fn gateway(update: GatewayUpdate) -> Event {
Event::Gateway { session: 1, update }
}
fn open_chats(update: &Update) -> Vec<ChatTarget> {
update
.commands
.iter()
.filter_map(|c| match c {
Command::OpenChat { target, .. } => Some(target.clone()),
_ => None,
})
.collect()
}
/// A first connection to a server, event by event: what the session knows
/// after each, and what the front end is told to do.
#[test]
fn a_first_connection() {
let mut st = state();
let host = Fake {
reads: HashMap::from([(
"srv=".to_owned(),
vec![(StoredTarget::Channel(2), ChatRead { ts_ms: 200, id: 7, updated_ms: 1 })],
)]),
..Default::default()
};
let backend = BackendInfo { product: "TeamSpeak 6".into(), version: "6.0.0".into() };
let caps = Capabilities { streams: true, file_transfer: true, ..Default::default() };
// Connecting: the rail and the bar change, nothing is sent.
let ups = run(
&mut st,
&host,
vec![Event::State { session: 1, state: session(VoiceState::Connecting, None) }],
);
assert_eq!(st.sessions[&1].state.voice, VoiceState::Connecting);
assert!(ups[0].refresh.servers && ups[0].refresh.toolbar && ups[0].refresh.tree);
assert!(ups[0].commands.is_empty() && ups[0].status.is_none() && ups[0].autoshare);
// The server answers: it gives its name to a bookmark that has only the
// address, and says what it runs.
let ups = run(
&mut st,
&host,
vec![Event::ServerInfo {
session: 1,
name: " Nightfall Guild ".into(),
backend,
capabilities: caps,
}],
);
assert_eq!(st.bookmarks[0].name, "Nightfall Guild");
assert_eq!(ups[0].persist, [Persist::Bookmark { id: 1, what: "server named" }]);
assert_eq!(
ups[0].status.as_deref(),
Some("Connected to Nightfall Guild (TeamSpeak 6 6.0.0)")
);
assert_eq!(st.status, "Connected to Nightfall Guild (TeamSpeak 6 6.0.0)");
assert!(st.sessions[&1].capabilities.streams && ups[0].refresh.streams);
// Its presence: the bar, the tree and the chat are drawn; the stored
// volume of Alice is sent once voice is connected, not before.
st.playback.insert("alice=".into(), ClientPlayback { volume: 0.5, muted: true });
let ups = run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
assert_eq!(st.sessions[&1].presence.clients.len(), 2);
assert!(ups[0].refresh.tree && ups[0].refresh.chat && ups[0].first_client);
assert!(ups[0].commands.is_empty());
// Voice connected into Games: its chat opens and is shown, with the
// store's read marker; the place is remembered.
let ups = run(
&mut st,
&host,
vec![Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }],
);
let view = &st.sessions[&1];
assert_eq!(view.reads_of.as_deref(), Some("srv="));
assert_eq!(view.tabs[view.current_tab].target, ChatTarget::Channel(2));
assert_eq!(view.tabs[view.current_tab].read, Some((200, 7)));
assert_eq!(view.channel_tab, ChatTarget::Channel(2));
assert!(view.focused_own_channel);
assert_eq!(open_chats(&ups[0]), [ChatTarget::Channel(2)]);
assert_eq!(ups[0].status.as_deref(), Some("Connected"));
assert_eq!(
st.settings.last_voice,
Some(LastVoice {
bookmark: 1,
address: "ts.example".into(),
channel: vec!["Games".into()]
})
);
assert!(ups[0].persist.contains(&Persist::Settings));
assert!(ups[0].refresh.chat && ups[0].refresh.servers);
// The presence again, now that voice is connected: Alice's volume goes
// to the engine, once.
let ups = run(
&mut st,
&host,
vec![
Event::Presence { session: 1, presence: presence() },
Event::Presence { session: 1, presence: presence() },
],
);
assert!(matches!(
ups[0].commands.as_slice(),
[
Command::SetClientVolume { session: 1, client: 11, volume },
Command::SetClientMuted { session: 1, client: 11, muted: true },
] if *volume == 0.5
));
assert!(ups[1].commands.is_empty());
}
/// The messages of a chat: a stored page, then live ones, with the chat on
/// screen or not, and what is kept of how far it was read.
#[test]
fn messages_are_counted_read_and_kept() {
let mut st = state();
let host = Fake::default();
run(
&mut st,
&host,
vec![
Event::Presence { session: 1, presence: presence() },
Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) },
],
);
// The stored page: two read before, one new. (Its marker came from the
// store: nothing here, so what the tab held when the page came counts as
// read.)
let ups = run(
&mut st,
&host,
vec![games(
vec![said(6, 190, false, "hi"), said(7, 200, true, "hello"), said(8, 300, false, "x")],
HistorySource::Local,
)],
);
let tab = &st.sessions[&1].tabs[1];
assert_eq!(tab.messages.iter().map(|m| m.message.id).collect::<Vec<_>>(), [6, 7, 8]);
assert!(tab.complete && !tab.loading);
assert_eq!(tab.unread, 0, "a first page is what was read");
assert_eq!(ups[0].chats, [(1, ChatTarget::Channel(2))]);
assert!(ups[0].refresh.chat);
// A live message while the chat is not on screen is new.
let ups =
run(&mut st, &host, vec![games(vec![said(9, 400, false, "new")], HistorySource::Live)]);
assert_eq!(st.sessions[&1].tabs[1].unread, 1);
assert!(ups[0].refresh.servers, "the rail counts it");
// Our own is not.
st.own_uids.insert("me=".into());
run(&mut st, &host, vec![games(vec![said(10, 410, true, "mine")], HistorySource::Live)]);
assert_eq!(st.sessions[&1].tabs[1].unread, 1);
// The chat comes on screen: read up to its end, a divider over the new.
host.shown.set(true);
let mut cx = Cx::new(&host);
assert!(crate::chat::logic::track_reading(&mut st, &mut cx));
let tab = &st.sessions[&1].tabs[1];
assert_eq!((tab.unread, tab.divider, tab.read), (0, Some(9), Some((410, 10))));
assert_eq!(st.reading, Some((1, ChatTarget::Channel(2))));
// A live one now is read at once.
run(&mut st, &host, vec![games(vec![said(11, 500, false, "seen")], HistorySource::Live)]);
assert_eq!(st.sessions[&1].tabs[1].unread, 0);
assert_eq!(st.sessions[&1].tabs[1].read, Some((500, 11)));
// The session ends: where the chats were read is stored, and what the
// store has is what the tab then says it has.
let mut ended = session(VoiceState::Disconnected, None);
ended.server_uid = Some("srv=".into());
let ups = run(&mut st, &host, vec![Event::State { session: 1, state: ended }]);
let written = host.written.borrow();
assert_eq!(written.len(), 1, "{written:?}");
assert_eq!(written[0].0, "srv=");
assert_eq!(written[0].1, StoredTarget::Channel(2));
assert_eq!((written[0].2.ts_ms, written[0].2.id), (500, 11));
assert_eq!(st.sessions[&1].tabs[1].stored_read, Some((500, 11)));
assert!(ups[0].refresh.servers);
}
/// Where the chat lines go when the engine keeps no history (it does not
/// know the server yet): one row appended per message.
#[test]
fn a_session_without_history_appends_lines() {
let mut st = state();
let host = Fake::default();
let message = |text: &str| ChatMessage {
target: ChatTarget::Server,
author_name: "Alice".into(),
author_uid: Some("alice=".into()),
author_id: Some(11),
text: text.into(),
ts_ms: 1000,
via_relay: false,
blocked: false,
};
let ups = run(
&mut st,
&host,
vec![
Event::Chat { session: 1, message: message("one") },
Event::Chat { session: 1, message: message("two") },
],
);
let tab = &st.sessions[&1].tabs[0];
assert_eq!(tab.lines.len(), 2);
assert_eq!(tab.unread, 2);
assert_eq!(ups[1].chats, [(1, ChatTarget::Server)]);
assert!(ups[1].refresh.chat && ups[1].refresh.servers);
// With a server unique id the engine has the history, and the live
// message arrives as `ChatHistory`.
st.sessions.get_mut(&1).unwrap().state.server_uid = Some("srv=".into());
run(&mut st, &host, vec![Event::Chat { session: 1, message: message("three") }]);
assert_eq!(st.sessions[&1].tabs[0].lines.len(), 2);
}
/// What a gateway brings: capabilities, requests for what the screens
/// show, pins, the stream directory, reminders for the bell.
#[test]
fn a_gateway_connects_and_tells() {
let mut st = state();
let host = Fake::default();
run(
&mut st,
&host,
vec![
Event::Presence { session: 1, presence: presence() },
Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) },
],
);
let caps: Vec<String> = [feature::EVENTS, feature::PINS, feature::TOPICS, feature::STREAMS]
.map(String::from)
.into();
st.bookmarks[0].gateway_urls = vec!["wss://gw.example/v1".into()];
let ups = run(
&mut st,
&host,
vec![gateway(GatewayUpdate::Connected {
url: "wss://gw.example/v1".into(),
gateway_id: "g".into(),
server_uid: "srv=".into(),
server_name: "Nightfall Guild".into(),
uid: "me=".into(),
capabilities: caps,
})],
);
let view = &st.sessions[&1];
assert!(view.gateway_has(feature::PINS) && view.gateway_has(feature::EVENTS));
assert_eq!(view.extra.gateway_uid.as_deref(), Some("me="));
assert_eq!(
st.bookmarks[0].gateway_url.as_deref(),
Some("wss://gw.example/v1"),
"the gateway in use is kept"
);
assert!(ups[0].persist.contains(&Persist::Bookmark { id: 1, what: "gateway in use" }));
// The permissions, the events and the directory, then the current
// chat's pins and topics.
let asked: Vec<&GatewayRequest> = ups[0]
.commands
.iter()
.filter_map(|c| match c {
Command::Gateway { session: 1, request } => Some(request),
_ => None,
})
.collect();
assert!(matches!(
asked.as_slice(),
[
GatewayRequest::Permissions { channel: None },
GatewayRequest::Events { .. },
GatewayRequest::Streams,
GatewayRequest::Pins { target: ChatTarget::Channel(2) },
GatewayRequest::Topics { target: ChatTarget::Channel(2), .. },
]
));
assert!(ups[0].refresh.home && ups[0].refresh.events && ups[0].refresh.gateways);
// The answers: pins (newest first), the directory's viewer counts, a
// failed request of the user.
let pin = |id: i64, ts_ms: i64| Pin {
message: said(id, ts_ms, false, "pinned"),
by: UserRef { uid: "alice=".into(), name: "Alice".into() },
ts_ms,
};
let ups = run(
&mut st,
&host,
vec![
gateway(GatewayUpdate::Pins {
target: ChatTarget::Channel(2),
pins: vec![pin(3, 10), pin(4, 20)],
}),
gateway(GatewayUpdate::Failed {
request: "pin".into(),
code: Some(voelin_gateway_proto::ErrorCode::Forbidden),
message: "no".into(),
}),
],
);
let tab = &st.sessions[&1].tabs[1];
assert!(tab.pins_loaded);
assert_eq!(tab.pins.iter().map(|p| p.message.id).collect::<Vec<_>>(), [4, 3]);
assert!(ups[0].refresh.chat);
assert_eq!(ups[1].status.as_deref(), Some("Not allowed on this server."));
// Gone: nothing of the gateway stays.
run(&mut st, &host, vec![gateway(GatewayUpdate::Disconnected { reason: None })]);
let view = &st.sessions[&1];
assert!(view.gateway_caps.is_empty() && !view.tabs[1].pins_loaded);
}
/// A password that was refused asks again, and says so the second time.
#[test]
fn a_locked_channel_asks_for_its_password() {
let mut st = state();
let host = Fake::default();
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
let failed = || Event::JoinFailed { session: 1, channel: 1, reason: JoinFailure::Password };
let ups = run(&mut st, &host, vec![failed()]);
let prompt = ups[0].password.clone().unwrap();
assert_eq!((prompt.name.as_str(), prompt.wrong), ("Lobby", false));
assert_eq!(st.join_target, Some((1, 1)));
// A password was given and refused: it is forgotten, the prompt says so.
st.sessions.get_mut(&1).unwrap().channel_passwords.insert(1, "nope".into());
let ups = run(&mut st, &host, vec![failed()]);
assert!(ups[0].password.as_ref().unwrap().wrong);
assert!(st.sessions[&1].channel_passwords.is_empty());
// The others are a toast.
let ups = run(
&mut st,
&host,
vec![Event::JoinFailed { session: 1, channel: 1, reason: JoinFailure::Full }],
);
assert_eq!(ups[0].status.as_deref(), Some("The channel is full"));
}
/// Connected into another channel than the one asked for: joined again,
/// with the password given this connection.
#[test]
fn a_channel_asked_for_and_not_entered_is_joined_again() {
let mut st = state();
let host = Fake::default();
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
let view = st.sessions.get_mut(&1).unwrap();
view.join_after_connect = Some(1);
view.channel_passwords.insert(1, "pw".into());
// Connected into Games, not the Lobby that was asked for.
let ups = run(
&mut st,
&host,
vec![Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }],
);
assert!(ups[0].commands.iter().any(|c| matches!(
c,
Command::MoveToChannel { session: 1, channel: 1, password: Some(p) } if p == "pw"
)));
assert_eq!(st.sessions[&1].join_after_connect, None);
// The sample sessions send nothing to the engine.
let mut demo = state();
let host = Fake { demo: true, ..Default::default() };
run(&mut demo, &host, vec![Event::Presence { session: 1, presence: presence() }]);
demo.sessions.get_mut(&1).unwrap().join_after_connect = Some(1);
let ups = run(
&mut demo,
&host,
vec![Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }],
);
assert!(open_chats(&ups[0]).is_empty());
assert!(!ups[0].commands.iter().any(|c| matches!(c, Command::MoveToChannel { .. })));
}
/// Pictures and files: the engine's cache, an upload from the composer, a
/// download that runs, the contacts, errors.
#[test]
fn pictures_files_contacts_and_errors() {
let mut st = state();
let host = Fake::default();
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
let path = PathBuf::from("/cache/avatars/ab");
let ups = run(
&mut st,
&host,
vec![
Event::AvatarReady {
session: 1,
client_uid: "alice=".into(),
path: path.clone(),
hash: "ab".into(),
},
Event::IconReady { session: 1, icon: 5, path: "/cache/icons/5".into() },
Event::PictureReady {
session: 1,
url: "https://e.com/a.png".into(),
path: "/cache/pictures/a".into(),
},
],
);
let view = &st.sessions[&1];
assert_eq!(view.avatars.get("alice="), Some(&path));
assert!(view.icons.contains_key(&5) && view.pictures.contains_key("https://e.com/a.png"));
assert_eq!(ups[0].reloaded, [path]);
assert_eq!(
ups[0].refresh,
Refresh {
tree: true,
chat: true,
toolbar: true,
member_card: true,
streams: true,
..Refresh::default()
}
);
assert!(ups[1].refresh.servers && ups[1].refresh.tree && !ups[1].refresh.chat);
// An upload from the composer posts its link once it is up.
st.uploads.insert(7, (1, 2, "notes.txt".into()));
let done = TransferState::Done { size: 12, data: None, path: None };
let ups = run(&mut st, &host, vec![Event::Transfer { session: 1, transfer: 7, state: done }]);
assert!(st.uploads.is_empty());
assert_eq!(ups[0].status.as_deref(), Some("notes.txt shared"));
assert!(matches!(
ups[0].commands.as_slice(),
[Command::SendChat { session: 1, target: ChatTarget::Channel(2), text }] if text.contains("notes.txt")
));
st.uploads.insert(8, (1, 2, "big.iso".into()));
let failed = TransferState::Failed("full".into());
let ups = run(&mut st, &host, vec![Event::Transfer { session: 1, transfer: 8, state: failed }]);
assert_eq!(ups[0].status.as_deref(), Some("Could not upload big.iso: full"));
// Errors and rejected settings reach the status line, but not the sample
// sessions' (the engine does not know them).
let ups = run(
&mut st,
&host,
vec![
Event::Error { session: 1, message: "kicked".into() },
Event::SettingRejected { key: "audio".into(), message: "no".into() },
Event::MicrophoneTestError { message: "no device".into() },
],
);
assert_eq!(ups[0].status.as_deref(), Some("kicked"));
assert_eq!(ups[1].status.as_deref(), Some("Setting audio: no"));
assert_eq!(st.status, "Microphone test: no device");
let demo = Fake { demo: true, ..Default::default() };
let ups = run(&mut st, &demo, vec![Event::Error { session: 1, message: "kicked".into() }]);
assert!(ups[0].status.is_none());
}
/// A client that talks, the meter, the groups in the order TeamSpeak sorts
/// them.
#[test]
fn talking_the_meter_and_groups() {
let mut st = state();
let host = Fake::default();
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
let ups = run(
&mut st,
&host,
vec![
Event::Talking { session: 1, client: 11, talking: true },
Event::Talking { session: 1, client: 11, talking: false },
Event::InputLevel { session: Some(1), level_db: -20.0, sending: true },
Event::InputLevel { session: None, level_db: -30.0, sending: false },
Event::InputLevel { session: Some(2), level_db: -10.0, sending: true },
],
);
assert!(st.sessions[&1].talking.is_empty());
assert!(ups[0].refresh.tree);
assert_eq!(ups[2].input_level, Some((-20.0, true)));
assert_eq!(ups[3].input_level, None, "no microphone test is running");
assert_eq!(ups[4].input_level, None, "another server's");
st.mic_test = true;
let ups = run(
&mut st,
&host,
vec![Event::InputLevel { session: None, level_db: -30.0, sending: false }],
);
assert_eq!(ups[0].input_level, Some((-30.0, false)));
let group = |id, sort_id| voelin_model::GroupInfo { id, sort_id, ..Default::default() };
run(
&mut st,
&host,
vec![Event::Groups {
session: 1,
server_groups: Arc::new(vec![group(7, 20), group(6, 20), group(9, 10)]),
channel_groups: Arc::new(vec![group(5, 0)]),
}],
);
let ids: Vec<_> = st.sessions[&1].server_groups.iter().map(|g| g.id).collect();
assert_eq!(ids, [9, 6, 7]);
}
/// The streams the voice connection lists: the one a lookup waited for is
/// to be watched; the rest of the stream events are the front end's.
#[test]
fn streams_are_listed_and_the_rest_is_handed_back() {
let mut st = state();
let host = Fake::default();
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
let stream = |id: &str, streamer| StreamInfo {
id: id.into(),
streamer,
name: "screen".into(),
kind: voelin_core::stream::StreamKind::Screen,
bitrate: 0,
viewer_limit: 0,
audio: false,
viewers: Some(1),
};
let ups = run(
&mut st,
&host,
vec![Event::StreamsChanged { session: 1, streams: vec![stream("s1", 11)] }],
);
assert_eq!(st.sessions[&1].streams.len(), 1);
assert!(ups[0].refresh.streams && ups[0].refresh.servers && ups[0].watch.is_none());
// A client's stream was asked for before the list knew it.
st.pending_watch = Some((1, 11));
let ups = run(
&mut st,
&host,
vec![Event::StreamsChanged { session: 1, streams: vec![stream("s2", 11)] }],
);
assert_eq!(ups[0].watch.as_deref(), Some("s2"));
assert_eq!(st.pending_watch, None);
// The development switch watches the first stream that is not ours.
let host = Fake { autowatch: true, ..Default::default() };
let ups = run(
&mut st,
&host,
vec![Event::StreamsChanged { session: 1, streams: vec![stream("s3", 11)] }],
);
assert_eq!(ups[0].watch.as_deref(), Some("s3"));
// What watching and sharing make of the other stream events is the front
// end's (and so is a setting that changed).
let ups = run(
&mut st,
&host,
vec![
Event::StreamKeyframeRequest { session: 1, layer: 0 },
Event::SettingChanged { key: "audio".into() },
],
);
assert!(matches!(ups[0].rest, Some(Event::StreamKeyframeRequest { .. })));
assert!(matches!(&ups[1].rest, Some(Event::SettingChanged { key }) if key == "audio"));
assert!(ups[0].refresh.is_empty() && ups[0].commands.is_empty());
}
/// Pictures linked in a chat are downloaded once, up to the limit.
#[test]
fn linked_pictures_are_fetched_once() {
let mut st = state();
let host = Fake { limit: 100 * 1024, ..Default::default() };
let mut connected = session(VoiceState::Connected, Some(2));
connected.server_uid = Some("srv=".into());
run(
&mut st,
&host,
vec![
Event::ServerInfo {
session: 1,
name: "S".into(),
backend: BackendInfo::default(),
capabilities: Capabilities { file_transfer: true, ..Default::default() },
},
Event::Presence { session: 1, presence: presence() },
Event::State { session: 1, state: connected },
],
);
let link = "[URL=ts3file://ts.example?port=9987&channel=2&path=%2F&channelpassword=&filename=a.png&isDir=0&size=2048&fileSize=2048]a.png[/URL]";
let ups =
run(&mut st, &host, vec![games(vec![said(1, 100, false, link)], HistorySource::Live)]);
let downloads: Vec<_> =
ups[0].commands.iter().filter(|c| matches!(c, Command::DownloadChatFile { .. })).collect();
assert_eq!(downloads.len(), 1, "{:?}", ups[0].commands);
// Asked once: the same page again asks for nothing.
let ups =
run(&mut st, &host, vec![games(vec![said(1, 100, false, link)], HistorySource::Live)]);
assert!(!ups[0].commands.iter().any(|c| matches!(c, Command::DownloadChatFile { .. })));
}
#[test]
fn the_status_line_names_the_servers_software() {
let backend = |product: &str, version: &str| BackendInfo {
product: product.into(),
version: version.into(),
};
assert_eq!(
connected_status("Nightfall Guild", &backend("TeamSpeak 6", "6.0.0-beta13.1")),
"Connected to Nightfall Guild (TeamSpeak 6 6.0.0-beta13.1)"
);
assert_eq!(
connected_status("Pixel Lounge", &backend("TeamSpeak 3", "3.13.8")),
"Connected to Pixel Lounge (TeamSpeak 3 3.13.8)"
);
// Not recognised: the version string the server sent.
assert_eq!(connected_status("Home", &backend("", "custom 9")), "Connected to Home (custom 9)");
}
#[test]
fn a_server_icon_is_taken_from_the_bookmarks_own_address_only() {
let path = std::env::temp_dir()
.join(format!("voelin-server-icon-provenance-{}.svg", std::process::id()));
std::fs::write(
&path,
r#"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="4"><rect width="4" height="4" fill="red"/></svg>"#,
)
.unwrap();
let mut bookmark = Bookmark { address: "a.test".into(), ..Default::default() };
let mut view = SessionView::<()>::default();
view.icons.insert(1234, path.clone());
assert!(apply_server_icon(&mut bookmark, &mut view, "a.test", 1234));
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4);
// Details from another address, queued before an edit, change nothing.
assert!(!apply_server_icon(&mut bookmark, &mut view, "b.test", 77));
assert_eq!(view.server_icon, 1234);
std::fs::remove_file(path).unwrap();
}