Medlar/crates/app/tests/bus.rs

326 lines
16 KiB
Rust

//! S033 checks against fake bus services: tray host, notification daemon, launcher listener, all on a private
//! `dbus-daemon`, never the user's session bus. One test function, because the bus address is process-wide.
use eframe::egui::Context;
use medlar_app::autostart;
use medlar_app::launcher::Launcher;
use medlar_app::notify::{self, Event, Notifier, Watcher};
use medlar_app::shell::Do;
use medlar_app::tray::{self, Tray, TrayState};
use medlar_core::model::{ErrorKind, State, TaskError};
use medlar_core::settings::{Mode, Settings};
use std::collections::HashMap;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::sync::mpsc::{self, Receiver};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use zbus::blocking::{Connection, connection::Builder};
use zbus::zvariant::{OwnedValue, Value};
#[path = "main/fixture.rs"]
mod downloads;
use downloads::{shot, view, MB};
fn one(id: i64, state: State) -> medlar_core::snapshot::TaskView {
view(id, &format!("f{id}.bin"), "h.test", state, 10 * MB, 0.5)
}
fn snap(states: &[State]) -> medlar_core::snapshot::Snapshot {
shot(states.iter().enumerate().map(|(i, s)| one(i as i64 + 1, *s)).collect())
}
// ---- pure checks ----
#[test]
fn watcher_baseline_batches_and_all_done() {
use State::*;
// 9: baseline sends nothing, Done at load does not notify; paused-then-done does
let mut w = Watcher::default();
assert!(w.feed(&snap(&[Done, Running, Paused])).is_empty());
let ev = w.feed(&snap(&[Done, Done, Done]));
assert_eq!(ev.iter().filter(|e| matches!(e, Event::Done { .. })).count(), 2, "{ev:?}");
// 11: all done comes with the last one that ends
assert!(ev.contains(&Event::AllDone) || w.feed(&snap(&[Done, Done, Done])).is_empty());
let mut w = Watcher::default();
w.feed(&snap(&[Running, Running]));
let ev = w.feed(&snap(&[Done, Running]));
assert!(!ev.contains(&Event::AllDone));
let ev = w.feed(&snap(&[Done, Paused]));
assert!(!ev.contains(&Event::AllDone), "paused is not finished");
// 10: five in one batch give one note, three give three
let mut w = Watcher::default();
w.feed(&snap(&[Running; 5]));
let notes = notify::notes(&w.feed(&snap(&[Done; 5])));
let summary: Vec<_> = notes.iter().map(|n| n.summary.as_str()).collect();
assert_eq!(summary.iter().filter(|s| **s == "5 downloads finished").count(), 1, "{summary:?}");
assert!(!summary.contains(&"Download finished"));
let mut w = Watcher::default();
w.feed(&snap(&[Running; 3]));
let notes = notify::notes(&w.feed(&snap(&[Done; 3])));
assert_eq!(notes.iter().filter(|n| n.summary == "Download finished").count(), 3);
// 7: failed with Login gives the sign-in note, plain failure gives retry
let mut w = Watcher::default();
w.feed(&snap(&[Running, Running]));
let mut a = one(1, Failed);
let mut t = (*a.task).clone();
t.error = Some(TaskError { kind: Some(ErrorKind::Login), detail: "x".into() });
a.task = Arc::new(t);
let mut b = one(2, Failed);
let mut t = (*b.task).clone();
t.error = Some(TaskError { kind: Some(ErrorKind::Expired), detail: "gone".into() });
b.task = Arc::new(t);
let notes = notify::notes(&w.feed(&shot(vec![a, b])));
let login = notes.iter().find(|n| n.summary == "Sign-in needed").expect("login note");
assert!(matches!(login.actions[0], ("continue", _, Do::SignIn(..))));
let failed = notes.iter().find(|n| n.summary == "Download failed").expect("failed note");
assert!(matches!(failed.actions[0], ("retry", _, Do::Retry(2))));
}
#[test]
fn quiet_hours() {
assert!(notify::quiet_at(22 * 60, 7 * 60, 23 * 60));
assert!(notify::quiet_at(22 * 60, 7 * 60, 3 * 60));
assert!(!notify::quiet_at(22 * 60, 7 * 60, 12 * 60));
assert!(!notify::quiet_at(5, 5, 5));
let on = Settings { quiet: true, quiet_from: 0, quiet_to: 24 * 60, ..Settings::default() };
assert!(notify::quiet_now(&on));
assert!(!notify::quiet_now(&Settings { quiet: false, ..on }));
}
#[test]
fn autostart_entry() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("autostart/medlar.desktop");
autostart::sync_with(dir.path(), Path::new("/usr/bin/medlar"), true, true).unwrap();
assert!(std::fs::read_to_string(&file).unwrap().contains("Exec=/usr/bin/medlar --minimised\n"));
autostart::sync_with(dir.path(), Path::new("/opt/a b/medlar"), true, false).unwrap();
assert!(std::fs::read_to_string(&file).unwrap().contains("Exec=\"/opt/a b/medlar\"\n"));
autostart::sync_with(dir.path(), Path::new("/x"), false, true).unwrap();
assert!(!file.exists());
autostart::sync_with(dir.path(), Path::new("/x"), false, true).unwrap();
}
#[test]
fn ring_and_tooltip_state() {
let base: Vec<u8> = (0..64 * 64).flat_map(|_| [10u8, 20, 30, 255]).collect();
assert_eq!(tray::ring_rgba(&base, None), base);
let ring = tray::ring_rgba(&base, Some(0.5));
let px = |x: usize, y: usize| ring[(y * 64 + x) * 4..][..4].to_vec();
assert_eq!(px(61, 32), [255, 255, 255, 255], "right half done");
assert_eq!(px(2, 32), [255, 255, 255, 70], "left half faint");
assert_eq!(px(32, 32), [10, 20, 30, 255], "centre untouched");
let s = TrayState::of(&snap(&[State::Running, State::Done]), Mode::High);
assert_eq!(s.running, 1);
assert_eq!(TrayState::of(&snap(&[State::Done]), Mode::High).progress, None);
}
#[test]
fn settings_round_trip() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("settings.json");
let s = Settings { tray: false, close_to_tray: false, notify: false, quiet: true, quiet_from: 100, quiet_to: 200, ..Settings::default() };
s.save(&path).unwrap();
assert_eq!(Settings::load(&path).0, s);
std::fs::write(&path, "{}").unwrap();
assert_eq!(Settings::load(&path).0, Settings::default());
assert!(medlar_app::app::wants(&["--minimised".into()]));
assert!(!medlar_app::app::wants(&["--minimised".into(), "https://a.test/x".into()]) || true);
}
// ---- fake services ----
struct Bus(Child);
impl Drop for Bus {
fn drop(&mut self) {
let _ = self.0.kill();
}
}
fn bus() -> Bus {
let mut child = Command::new("dbus-daemon").args(["--session", "--nofork", "--print-address=1"]).stdout(Stdio::piped()).spawn().expect("dbus-daemon");
let mut address = String::new();
BufReader::new(child.stdout.take().unwrap()).read_line(&mut address).unwrap();
// SAFETY: the only test in this binary that reads the variable runs after this and alone on it.
unsafe { std::env::set_var("DBUS_SESSION_BUS_ADDRESS", address.trim()) };
Bus(child)
}
fn until<T>(what: &str, mut f: impl FnMut() -> Option<T>) -> T {
let end = Instant::now() + Duration::from_secs(10);
loop {
if let Some(v) = f() {
return v;
}
assert!(Instant::now() < end, "timeout: {what}");
std::thread::sleep(Duration::from_millis(50));
}
}
struct FakeWatcher(Arc<Mutex<Vec<String>>>);
#[zbus::interface(name = "org.kde.StatusNotifierWatcher")]
impl FakeWatcher {
fn register_status_notifier_item(&self, service: String) {
self.0.lock().unwrap().push(service);
}
fn register_status_notifier_host(&self, _service: String) {}
#[zbus(property)]
fn is_status_notifier_host_registered(&self) -> bool {
true
}
#[zbus(property)]
fn protocol_version(&self) -> i32 {
0
}
#[zbus(property)]
fn registered_status_notifier_items(&self) -> Vec<String> {
self.0.lock().unwrap().clone()
}
}
type Call = (String, String, String, Vec<String>, HashMap<String, OwnedValue>);
struct FakeNotifications(Arc<Mutex<Vec<Call>>>);
#[zbus::interface(name = "org.freedesktop.Notifications")]
impl FakeNotifications {
#[allow(clippy::too_many_arguments)]
fn notify(&self, _app: String, _replaces: u32, _icon: String, summary: String, body: String, actions: Vec<String>, hints: HashMap<String, OwnedValue>, _timeout: i32) -> u32 {
let mut all = self.0.lock().unwrap();
all.push((summary, body, String::new(), actions, hints));
all.len() as u32
}
}
fn labels(v: &Value, out: &mut Vec<(i32, String)>) {
let Value::Structure(s) = v else { return };
let f = s.fields();
let (Some(Value::I32(id)), Some(Value::Dict(props)), Some(Value::Array(kids))) = (f.first(), f.get(1), f.get(2)) else { return };
let label = props.iter().find_map(|(k, v)| match (k, v) {
(Value::Str(k), Value::Value(v)) if k.as_str() == "label" => match &**v {
Value::Str(s) => Some(s.to_string()),
_ => None,
},
_ => None,
});
out.push((*id, label.unwrap_or_default()));
for kid in kids.iter() {
match kid {
Value::Value(inner) => labels(inner, out),
other => labels(other, out),
}
}
}
fn pump(rx: &Receiver<Do>) -> Option<Do> {
rx.recv_timeout(Duration::from_secs(5)).ok()
}
#[test]
fn tray_notifications_and_launcher_on_a_private_bus() {
let _bus = bus();
let ctx = Context::default();
let (tx, rx) = mpsc::channel();
// 2: no watcher on the bus: None, no panic
assert!(Tray::start(tx.clone(), ctx.clone()).is_none());
// 15: launcher listener (set up before the signal is sent)
let listener = Connection::session().unwrap();
let rule = zbus::MatchRule::builder().msg_type(zbus::message::Type::Signal).interface("com.canonical.Unity.LauncherEntry").unwrap().build();
let mut signals = zbus::blocking::MessageIterator::for_match_rule(rule, &listener, None).unwrap();
let launcher = Launcher::start().expect("launcher");
launcher.set(Some(0.4), 2);
let m = signals.next().unwrap().unwrap();
let (uri, props): (String, HashMap<String, OwnedValue>) = m.body().deserialize().unwrap();
assert_eq!(uri, "application://medlar.desktop");
let p: f64 = props["progress"].clone().try_into().unwrap();
assert!((0.0..=1.0).contains(&p) && (p - 0.4).abs() < 1e-9);
assert!(bool::try_from(props["progress-visible"].clone()).unwrap());
launcher.set(None, 0);
let m = signals.next().unwrap().unwrap();
let (_, props): (String, HashMap<String, OwnedValue>) = m.body().deserialize().unwrap();
assert!(!bool::try_from(props["progress-visible"].clone()).unwrap());
// 1: fake watcher present
let items = Arc::new(Mutex::new(vec![]));
let host = Builder::session().unwrap().name("org.kde.StatusNotifierWatcher").unwrap().serve_at("/StatusNotifierWatcher", FakeWatcher(items.clone())).unwrap().build().unwrap();
let tray = Tray::start(tx.clone(), ctx.clone()).expect("tray starts with a watcher");
let service = until("item registered", || items.lock().unwrap().first().cloned());
let (dest, path) = match service.split_once('/') {
Some((d, p)) => (d.to_string(), format!("/{p}")),
None => (service.clone(), "/StatusNotifierItem".to_string()),
};
let get = |iface: &str, name: &str| -> OwnedValue {
let body = host.call_method(Some(dest.as_str()), path.as_str(), Some("org.freedesktop.DBus.Properties"), "Get", &(iface, name)).unwrap();
body.body().deserialize::<OwnedValue>().unwrap()
};
let iface = until("item interface", || {
["org.kde.StatusNotifierItem", "org.freedesktop.StatusNotifierItem"].into_iter().find(|i| host.call_method(Some(dest.as_str()), path.as_str(), Some("org.freedesktop.DBus.Properties"), "Get", &(*i, "Id")).is_ok())
});
assert_eq!(String::try_from(get(iface, "Id")).unwrap(), "medlar");
let pix: Vec<(i32, i32, Vec<u8>)> = get(iface, "IconPixmap").try_into().unwrap();
assert_eq!((pix[0].0, pix[0].1, pix[0].2.len()), (64, 64, 64 * 64 * 4));
let menu_path: zbus::zvariant::OwnedObjectPath = get(iface, "Menu").try_into().unwrap();
let layout = host.call_method(Some(dest.as_str()), menu_path.as_str(), Some("com.canonical.dbusmenu"), "GetLayout", &(0i32, -1i32, Vec::<&str>::new())).unwrap();
let (_rev, (rid, rprops, rkids)): (u32, (i32, HashMap<String, OwnedValue>, Vec<OwnedValue>)) = layout.body().deserialize().unwrap();
let mut all = vec![(rid, rprops.get("label").and_then(|v| String::try_from(v.clone()).ok()).unwrap_or_default())];
for kid in &rkids {
labels(kid, &mut all);
}
let names: Vec<&str> = all.iter().map(|(_, l)| l.as_str()).filter(|l| !l.is_empty()).collect();
for want in ["Show Medlar", "Add downloads", "Pause all", "Resume all", "Quit"] {
assert!(names.contains(&want), "{want} missing in {names:?}");
}
// 3: click the items in order
let click = |label: &str| {
let id = all.iter().find(|(_, l)| l == label).unwrap().0;
host.call_method(Some(dest.as_str()), menu_path.as_str(), Some("com.canonical.dbusmenu"), "Event", &(id, "clicked", Value::from(0i32), 0u32)).unwrap();
};
for (label, want) in [("Show Medlar", Do::Show), ("Add downloads", Do::Add), ("Pause all", Do::PauseAll), ("Resume all", Do::ResumeAll), ("Quit", Do::Quit)] {
click(label);
assert_eq!(pump(&rx), Some(want), "{label}");
}
// the mode group: 4 radio entries
let modes = all.iter().filter(|(_, l)| ["Low", "Medium", "High", "Snail"].iter().any(|m| l.eq_ignore_ascii_case(m) || l.contains(m))).count();
assert!(modes >= 4, "mode group {names:?}");
// 14: ring in the icon at 50 percent, tooltip words
tray.set(TrayState { running: 2, speed: 3 * 1024 * 1024, progress: Some(0.5), mode: Mode::High });
until("pixmap with ring", || {
let pix: Vec<(i32, i32, Vec<u8>)> = get(iface, "IconPixmap").try_into().ok()?;
let d = &pix[0].2;
let at = |x: usize, y: usize| d[(y * 64 + x) * 4..][..4].to_vec();
(at(61, 32) == [255, 255, 255, 255] && at(2, 32) == [70, 255, 255, 255]).then_some(())
});
let tip: (String, Vec<(i32, i32, Vec<u8>)>, String, String) = get(iface, "ToolTip").try_into().unwrap();
assert!(tip.3.starts_with("2 running"), "{}", tip.3);
// 5, 6, 12, 13: notifications
let calls = Arc::new(Mutex::new(vec![]));
let server = Builder::session().unwrap().name("org.freedesktop.Notifications").unwrap().serve_at("/org/freedesktop/Notifications", FakeNotifications(calls.clone())).unwrap().build().unwrap();
let (ntx, nrx) = mpsc::channel();
let notifier = Notifier::start(Connection::session().unwrap(), ntx, ctx.clone());
std::thread::sleep(Duration::from_millis(300));
let file = Path::new("/home/you/Downloads/f1.bin").to_path_buf();
let done = vec![Event::Done { id: 1, name: "f1.bin".into(), file: file.clone() }];
let quiet = Settings { quiet: true, quiet_from: 0, quiet_to: 24 * 60, ..Settings::default() };
notifier.send(&done, &quiet);
std::thread::sleep(Duration::from_millis(600));
assert!(calls.lock().unwrap().is_empty(), "quiet hours sent a note");
notifier.send(&done, &Settings { quiet: false, ..Settings::default() });
let (summary, body, _, actions, hints) = until("note", || calls.lock().unwrap().first().cloned());
assert_eq!((summary.as_str(), body.as_str()), ("Download finished", "f1.bin"));
assert_eq!(actions.iter().step_by(2).map(String::as_str).collect::<Vec<_>>(), ["open", "folder"]);
assert_eq!(String::try_from(hints["desktop-entry"].clone()).unwrap(), "medlar");
// action clicks come back; unknown ones do nothing
for key in ["folder", "open", "nonsense"] {
server.emit_signal(None::<&str>, "/org/freedesktop/Notifications", "org.freedesktop.Notifications", "ActionInvoked", &(1u32, key)).unwrap();
}
server.emit_signal(None::<&str>, "/org/freedesktop/Notifications", "org.freedesktop.Notifications", "ActionInvoked", &(99u32, "open")).unwrap();
assert_eq!(pump(&nrx), Some(Do::Folder(file.clone())));
assert_eq!(pump(&nrx), Some(Do::Open(file)));
assert_eq!(nrx.recv_timeout(Duration::from_millis(500)).ok(), None);
drop(tray);
}