diff --git a/Plans/09 Test and release/S043-test-video-screens.md b/Plans/09 Test and release/S043-test-video-screens.md index d5bdb43..b149001 100644 --- a/Plans/09 Test and release/S043-test-video-screens.md +++ b/Plans/09 Test and release/S043-test-video-screens.md @@ -11,11 +11,11 @@ Run the checks of the test files of S025, S027, S033, S034, fix what fails, fill - CLAUDE.md ยง4 and ยง5 ## Steps -- [ ] Doubts first: read the code behind each, add a check or write why it is fine -- [ ] Write the tests for all HIGH and MED checks in one go, sharing fixtures and the testserver -- [ ] Run them once, all together, log to a file; read only the failures -- [ ] Fix all causes in one go; rerun only what failed; three rounds at most, then `KNOWN BUG` with the cause -- [ ] Screen checks: one contact sheet, faults fixed in one go, one more sheet +- [x] Doubts first: read the code behind each, add a check or write why it is fine +- [x] Write the tests for all HIGH and MED checks in one go, sharing fixtures and the testserver +- [x] Run them once, all together, log to a file; read only the failures +- [x] Fix all causes in one go; rerun only what failed; three rounds at most, then `KNOWN BUG` with the cause +- [x] Screen checks: one contact sheet, faults fixed in one go, one more sheet - [ ] Results filled in, `docs/TEST-REPORT.md` line, `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S043: โ€ฆ`, push ## End criteria diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 279f8f5..abe2b40 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -58,7 +58,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H ## 09 Test and release - [x] [S041](09%20Test%20and%20release/S041-test-control-connector.md) It runs; tests of details, control and connector -- [ ] [S043](09%20Test%20and%20release/S043-test-video-screens.md) Tests of video, rules, tray and every screen +- [x] [S043](09%20Test%20and%20release/S043-test-video-screens.md) Tests of video, rules, tray and every screen - [ ] [S037](09%20Test%20and%20release/S037-whole-app.md) Whole app: use, security, speed, every feature - [ ] [S039](09%20Test%20and%20release/S039-package-release.md) Package, docs and release ๐Ÿง‘ diff --git a/crates/app/src/notify.rs b/crates/app/src/notify.rs index 8001f04..a40293a 100644 --- a/crates/app/src/notify.rs +++ b/crates/app/src/notify.rs @@ -38,7 +38,7 @@ fn working(s: State) -> bool { impl Watcher { pub fn feed(&mut self, shot: &Snapshot) -> Vec { let mut out = vec![]; - let mut busy = false; + let (mut busy, mut paused) = (false, false); for v in shot.iter() { let (id, state) = (v.id(), v.state()); busy |= working(state); @@ -57,12 +57,16 @@ impl Watcher { Some(e) if e.kind == Some(ErrorKind::Login) => out.push(Event::Login { id, name: t.name.clone(), url: t.url.clone() }), e => out.push(Event::Failed { id, name: t.name.clone(), why: e.as_ref().map(|e| e.detail.clone()).unwrap_or_default() }), }, + State::Paused => paused = true, _ => {} } } if self.started && self.busy && !busy && self.finished { self.finished = false; - out.push(Event::AllDone); + // The last one being paused is not an end. + if !paused { + out.push(Event::AllDone); + } } self.busy = busy; self.started = true; diff --git a/crates/app/src/views/control.rs b/crates/app/src/views/control.rs index c418e5f..3564857 100644 --- a/crates/app/src/views/control.rs +++ b/crates/app/src/views/control.rs @@ -19,7 +19,7 @@ use std::time::Duration; #[derive(Default)] pub struct Control { pub open: bool, - tab: usize, + pub tab: usize, mb: bool, queues: queues::Page, brush: u8, @@ -58,10 +58,10 @@ impl Control { let closed = dialog::sheet(ctx, t, "control", &tr!("control.title"), open, |ui| { let (a, b, c, d) = (tr!("control.speed"), tr!("control.queues"), tr!("control.week"), tr!("control.done")); let options = [ - Tab { icon: "speed", text: &a, count: None }, - Tab { icon: "stacks", text: &b, count: Some(lists.queues.len()) }, - Tab { icon: "schedule", text: &c, count: None }, - Tab { icon: "power_settings_new", text: &d, count: self.done.watcher.armed().map(|_| 1) }, + Tab { icon: "", text: &a, count: None }, + Tab { icon: "", text: &b, count: Some(lists.queues.len()) }, + Tab { icon: "", text: &c, count: None }, + Tab { icon: "", text: &d, count: self.done.watcher.armed().map(|_| 1) }, ]; tabs(ui, t, &tr!("control.title"), &options, &mut self.tab); ui.add_space(crate::tokens::space::L); diff --git a/crates/app/src/views/rules.rs b/crates/app/src/views/rules.rs index def7912..5afac5c 100644 --- a/crates/app/src/views/rules.rs +++ b/crates/app/src/views/rules.rs @@ -124,7 +124,7 @@ fn summary(r: &Rule, lists: &Lists) -> String { then.push(tr!("rule.priority_is", priority = p.name())); } let when = if when.is_empty() { tr!("rule.any") } else { when.join(" ยท ") }; - let then = if then.is_empty() { String::new() } else { format!(" โ†’ {}", then.join(" ยท ")) }; + let then = if then.is_empty() { String::new() } else { format!(" goes to: {}", then.join(" ยท ")) }; let off = if r.enabled { String::new() } else { format!("{} ยท ", tr!("rule.off")) }; format!("{off}{when}{then}") } @@ -226,7 +226,7 @@ fn test_box(view: &mut View, cx: &mut Cx, ui: &mut Ui, lists: &Lists) { parts.extend(out.queue.map(|q| super::list::model::queue_name(lists, q))); parts.extend(out.priority.map(|p| p.name().to_string())); parts.extend(out.name); - parts.join(" โ†’ ") + parts.join(" ยท ") } }; ui.add(Label::new(RichText::new(answer).font(fonts::ui(text::BODY)).color(t.on_surface)).wrap()); diff --git a/crates/app/src/views/schedule.rs b/crates/app/src/views/schedule.rs index 742b02b..4ff78a5 100644 --- a/crates/app/src/views/schedule.rs +++ b/crates/app/src/views/schedule.rs @@ -275,7 +275,10 @@ impl Done { Combo::new(&tr!("done.scope"), &scopes, 260.0).show(ui, t, &mut self.scope); ui.add_space(space::S); let mut failed = self.even_failed; - crate::ui::widgets::Choice::new(&tr!("done.failed")).switch(ui, t, &mut failed); + ui.horizontal(|ui| { + crate::ui::widgets::Choice::new(&tr!("done.failed")).switch(ui, t, &mut failed); + ui.label(RichText::new(tr!("done.failed")).font(fonts::ui(text::BODY)).color(t.on_surface)); + }); self.even_failed = failed; ui.add_space(space::S); Number { label: &tr!("done.countdown"), unit: &tr!("unit.s"), range: 0.0..=3600.0, step: 5.0, enabled: true, width: 200.0, bare: false }.show(ui, t, &mut self.seconds); diff --git a/crates/app/src/views/video.rs b/crates/app/src/views/video.rs index 36352f7..2eff105 100644 --- a/crates/app/src/views/video.rs +++ b/crates/app/src/views/video.rs @@ -145,3 +145,25 @@ fn ranges(picked: &[bool]) -> String { } parts.join(",") } + +#[cfg(test)] +mod tests { + use super::*; + use medlar_core::ytdlp::Entry; + + fn list(n: usize) -> Video { + let entries = (0..n).map(|i| Entry { title: format!("v{i}"), url: Some(format!("https://v.test/{i}")), duration: None }).collect(); + Video::new(Arc::new(Probe { title: "L".into(), entries, ..Probe::default() })) + } + + #[test] + fn picked_items_become_ranges() { + let mut v = list(6); + assert_eq!(v.choice().items, None); + v.picked = vec![true, false, true, true, true, false]; + assert_eq!(v.choice().items.as_deref(), Some("1,3-5")); + assert!(!v.empty()); + v.picked = vec![false; 6]; + assert!(v.empty()); + } +} diff --git a/crates/app/tests/bus.rs b/crates/app/tests/bus.rs new file mode 100644 index 0000000..78ee917 --- /dev/null +++ b/crates/app/tests/bus.rs @@ -0,0 +1,326 @@ +//! 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 = (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(what: &str, mut f: impl FnMut() -> Option) -> 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>>); + +#[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 { + self.0.lock().unwrap().clone() + } +} + +type Call = (String, String, String, Vec, HashMap); + +struct FakeNotifications(Arc>>); + +#[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, hints: HashMap, _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) -> Option { + 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) = 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) = 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::().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)> = 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, Vec)) = 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)> = 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)>, 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::>(), ["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); +} diff --git a/crates/app/tests/shots.rs b/crates/app/tests/shots.rs index c1a7528..554df73 100644 --- a/crates/app/tests/shots.rs +++ b/crates/app/tests/shots.rs @@ -121,6 +121,25 @@ const SCENES: &[Scene] = &[("window", App::show), ("tokens", |app, ui| app.frame ("first-folder", |app, ui| main_view(app, ui, |app| app.first = Some(FirstRun::default()))), ("first-colours", |app, ui| main_view(app, ui, |app| app.first = Some(FirstRun::at(1)))), ("first-browser", |app, ui| main_view(app, ui, |app| app.first = Some(FirstRun::at(2)))), + ("set-rules", |app, ui| main_view(app, ui, |app| { + app.settings.rules = medlar_core::rules::defaults(); + app.open_settings(Page::Rules); + })), + ("set-rules-long", |app, ui| main_view(app, ui, |app| { + let mut r = medlar_core::rules::defaults(); + r[0].name = "A rule with a name of two hundred characters ".repeat(5); + r[0].min_mb = 1_000_000; + app.settings.rules = r; + app.open_settings(Page::Rules); + })), + ("set-rules-empty", |app, ui| main_view(app, ui, |app| app.open_settings(Page::Rules))), + ("set-clipboard", |app, ui| main_view(app, ui, |app| app.open_settings(Page::Clipboard))), + ("set-notifications", |app, ui| main_view(app, ui, |app| app.open_settings(Page::Notifications))), + ("details", |app, ui| main_view(app, ui, |app| app.main.details.open = Some(2))), + ("control-0", |app, ui| main_view(app, ui, |app| (app.main.control.open, app.main.control.tab) = (true, 0))), + ("control-1", |app, ui| main_view(app, ui, |app| (app.main.control.open, app.main.control.tab) = (true, 1))), + ("control-2", |app, ui| main_view(app, ui, |app| (app.main.control.open, app.main.control.tab) = (true, 2))), + ("control-3", |app, ui| main_view(app, ui, |app| (app.main.control.open, app.main.control.tab) = (true, 3))), ("progress", |app, ui| app.frame(ui, progress::gallery)), ("progress-states", |app, ui| app.frame(ui, progress::states)), ]; diff --git a/crates/core/src/ytdlp.rs b/crates/core/src/ytdlp.rs index cd57eb7..af4dd18 100644 --- a/crates/core/src/ytdlp.rs +++ b/crates/core/src/ytdlp.rs @@ -576,7 +576,7 @@ pub enum Reason { impl Reason { /// From the lines it printed, the later ones first. Lowercase comparison. pub fn of<'a>(lines: impl DoubleEndedIterator) -> Reason { - const KNOWN: [(&str, Reason); 22] = [ + const KNOWN: [(&str, Reason); 23] = [ ("drm", Reason::Drm), ("private video", Reason::Private), ("this video is private", Reason::Private), @@ -584,6 +584,7 @@ impl Reason { ("http error 429", Reason::TooManyRequests), ("too many requests", Reason::TooManyRequests), ("not available in your country", Reason::Region), + ("video available in your country", Reason::Region), ("blocked it in your country", Reason::Region), ("geo restricted", Reason::Region), ("geo-restricted", Reason::Region), @@ -620,3 +621,310 @@ impl Reason { Error::because(kind, why) } } + +#[cfg(test)] +mod tests { + use super::*; + use std::os::unix::fs::PermissionsExt; + + fn stub(dir: &Path, name: &str, body: &str) -> PathBuf { + let path = dir.join(name); + std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + path + } + + /// A stub that prints the file `json` and counts its runs in `runs`. + fn replay(dir: &Path, json: &str) -> PathBuf { + let data = dir.join("answer.json"); + std::fs::write(&data, json).unwrap(); + stub(dir, "replay", &format!("echo run >> '{}/runs'\ncat '{}'", dir.display(), data.display())) + } + fn runs(dir: &Path) -> usize { + std::fs::read_to_string(dir.join("runs")).map(|t| t.lines().count()).unwrap_or(0) + } + + const ONE: &str = r#"{"title":"Clip","uploader":"Me","duration":61.5, + "formats":[ + {"format_id":"a1","ext":"m4a","vcodec":"none","acodec":"mp4a","filesize":1000,"tbr":128}, + {"format_id":"a2","ext":"m4a","vcodec":"none","acodec":"mp4a","filesize":500,"tbr":48}, + {"format_id":"v360","ext":"mp4","height":360,"vcodec":"avc1","acodec":"none","filesize":4000,"tbr":300}, + {"format_id":"v720","ext":"mp4","height":720,"vcodec":"avc1","acodec":"none","filesize_approx":9000.0,"tbr":900}, + {"format_id":"v1080","ext":"mp4","height":1080,"fps":30,"vcodec":"avc1","acodec":"none","filesize":20000,"tbr":2000}], + "subtitles":{"en":[{}],"de":[{}],"live_chat":[{}]}, + "automatic_captions":{"fr":[{}]}, + "chapters":[{"title":"Intro","start_time":0,"end_time":10},{"title":"Main","start_time":10,"end_time":61.5}]}"#; + + #[test] + fn missing_has_words() { + let dir = tempfile::tempdir().unwrap(); + assert_eq!(locate(None, dir.path().as_os_str()), None); + assert!(!Problem::Missing.words().is_empty() && !Problem::Missing.words().starts_with("video.")); + assert!(Problem::Missing.words().to_lowercase().contains("yt-dlp")); + let s = stub(dir.path(), "yt-dlp", "true"); + assert_eq!(locate(None, dir.path().as_os_str()), Some(s)); + } + + #[tokio::test] + async fn versions() { + let dir = tempfile::tempdir().unwrap(); + let version = |v: &str| { + let p = stub(dir.path(), &format!("v{v}"), &format!("echo '{v}'")); + async move { Ytdlp::at(p).await } + }; + assert_eq!(version("2022.01.01").await.unwrap_err(), Problem::TooOld("2022.01.01".into())); + for good in ["2024.08.06", "2025.01.01.1", "2024.08.06-nightly"] { + let mut r = version(good).await; + for _ in 0..20 { + if r.is_ok() { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + r = version(good).await; + } + assert_eq!(r.unwrap().version, good); + } + } + + #[tokio::test] + async fn broken_ones() { + let dir = tempfile::tempdir().unwrap(); + let fails = stub(dir.path(), "fails", "exit 1"); + let junk = stub(dir.path(), "junk", "echo hello there"); + let none = dir.path().join("nothing"); + assert_eq!(Ytdlp::at(fails).await.unwrap_err(), Problem::Broken); + assert_eq!(Ytdlp::at(junk).await.unwrap_err(), Problem::Broken); + assert_eq!(Ytdlp::at(none).await.unwrap_err(), Problem::Broken); + } + + #[tokio::test] + async fn probe_reads_a_video() { + let dir = tempfile::tempdir().unwrap(); + let y = Ytdlp { path: replay(dir.path(), ONE), version: "x".into() }; + let p = y.probe(&Cache::default(), "https://v.test/1", None, std::future::pending()).await.unwrap(); + assert_eq!((p.title.as_str(), p.uploader.as_deref(), p.duration), ("Clip", Some("Me"), Some(61.5))); + assert_eq!(p.formats.len(), 5); + assert_eq!(p.subtitles, ["de", "en"]); + assert_eq!(p.automatic, ["fr"]); + assert_eq!(p.chapters.len(), 2); + assert!(!p.is_playlist()); + let q = p.qualities(); + let heights: Vec<_> = q.iter().map(|q| q.height).collect(); + assert_eq!(heights, [None, Some(1080), Some(720), Some(360)]); + // video plus the best audio (the larger bitrate one: 1000 bytes) + assert_eq!(q[0].size, Some(21000)); + assert_eq!(q[2].size, Some(10000)); + assert_eq!(q[3].size, Some(5000)); + assert_eq!(q[0].label, crate::tr!("video.best")); + } + + #[tokio::test] + async fn probe_reads_a_playlist() { + let dir = tempfile::tempdir().unwrap(); + let json = r#"{"title":"List","entries":[{"title":"A","url":"https://v.test/a","duration":3},{"title":"B","webpage_url":"https://v.test/b"},null],"subtitles":{"live_chat":[{}]}}"#; + let y = Ytdlp { path: replay(dir.path(), json), version: "x".into() }; + let p = y.probe(&Cache::default(), "https://v.test/list", None, std::future::pending()).await.unwrap(); + assert!(p.is_playlist()); + assert_eq!(p.entries.len(), 2); + assert_eq!(p.entries[0].title, "A"); + assert_eq!(p.entries[1].url.as_deref(), Some("https://v.test/b")); + assert!(p.subtitles.is_empty()); + } + + #[tokio::test] + async fn probe_is_cached_for_a_while() { + let dir = tempfile::tempdir().unwrap(); + let y = Ytdlp { path: replay(dir.path(), ONE), version: "x".into() }; + let cache = Cache::default(); + let go = || y.probe(&cache, "https://v.test/1", None, std::future::pending()); + go().await.unwrap(); + go().await.unwrap(); + assert_eq!(runs(dir.path()), 1); + for (at, _) in cache.0.lock().unwrap().values_mut() { + *at = Instant::now() - KEEP - Duration::from_secs(1); + } + go().await.unwrap(); + assert_eq!(runs(dir.path()), 2); + } + + #[tokio::test] + async fn cancel_kills_the_program() { + let dir = tempfile::tempdir().unwrap(); + let pid = dir.path().join("pid"); + let y = Ytdlp { path: stub(dir.path(), "slow", &format!("echo $$ > '{}'\nexec sleep 60", pid.display())), version: "x".into() }; + let began = Instant::now(); + let r = y.probe(&Cache::default(), "https://v.test/1", None, tokio::time::sleep(Duration::from_millis(500))).await; + assert!(matches!(r, Err(Error::Stopped))); + assert!(began.elapsed() < Duration::from_secs(5)); + let pid = std::fs::read_to_string(&pid).unwrap().trim().to_string(); + let mut gone = false; + for _ in 0..40 { + // A killed child that was reaped has no /proc entry. + if !Path::new(&format!("/proc/{pid}")).exists() { + gone = true; + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + assert!(gone, "stub {pid} still runs"); + } + + #[tokio::test] + async fn drm_is_refused_and_not_cached() { + let dir = tempfile::tempdir().unwrap(); + let json = r#"{"title":"D","formats":[{"format_id":"1","vcodec":"avc1","acodec":"none","has_drm":true},{"format_id":"2","vcodec":"none","acodec":"aac","has_drm":"maybe"}]}"#; + let y = Ytdlp { path: replay(dir.path(), json), version: "x".into() }; + let cache = Cache::default(); + let r = y.probe(&cache, "https://v.test/d", None, std::future::pending()).await; + assert!(matches!(r, Err(Error::Conn { kind: ErrorKind::Drm, .. }))); + assert!(cache.0.lock().unwrap().is_empty()); + // One format without DRM is enough to go on. + let some = r#"{"title":"D","formats":[{"format_id":"1","vcodec":"avc1","has_drm":true},{"format_id":"2","vcodec":"avc1"}]}"#; + assert!(!Probe::read(&serde_json::from_str(some).unwrap()).drm); + } + + #[tokio::test] + async fn progress_lines_are_read() { + let dir = tempfile::tempdir().unwrap(); + let out = dir.path().join("out.mp4"); + let body = format!( + "echo 'MEDLAR:100|1000|NA|50.5|18|NA|NA|NA|NA'\nsleep 0.3\necho 'MEDLAR:400|NA|2000|99.5|NA|3|10|2|5'\nsleep 0.3\necho 'noise line'\necho 'MEDLAR-FILE:{}'", + out.display() + ); + let y = Ytdlp { path: stub(dir.path(), "p", &body), version: "x".into() }; + let run = Run { url: "https://v.test/1".into(), folder: dir.path().into(), name: Run::NAME.into(), ..Run::default() }; + let mut r = y.start(&run).unwrap(); + let mut rx = r.progress(); + rx.changed().await.unwrap(); + let first = *rx.borrow_and_update(); + assert_eq!((first.done, first.total, first.speed, first.eta, first.fragment, first.item), (100, Some(1000), Some(50.5), Some(18), None, None)); + assert_eq!(r.end().await.unwrap(), out); + let last = *r.progress().borrow(); + assert_eq!((last.done, last.total, last.speed, last.eta, last.fragment, last.item), (400, Some(2000), Some(99.5), None, Some((3, 10)), Some((2, 5)))); + } + + #[tokio::test] + async fn stop_then_start_again() { + let dir = tempfile::tempdir().unwrap(); + let pids = dir.path().join("pids"); + let args = dir.path().join("args"); + let body = format!("echo $$ >> '{}'\nprintf '%s\\n' \"$@\" >> '{}'\necho --- >> '{}'\nexec sleep 60", pids.display(), args.display(), args.display()); + let y = Ytdlp { path: stub(dir.path(), "s", &body), version: "x".into() }; + let run = Run { url: "https://v.test/1".into(), folder: dir.path().join("out"), name: Run::NAME.into(), ..Run::default() }; + let first = y.start(&run).unwrap(); + tokio::time::sleep(Duration::from_millis(400)).await; + first.stop().await; + let second = y.start(&run).unwrap(); + tokio::time::sleep(Duration::from_millis(400)).await; + let pids: Vec = std::fs::read_to_string(&pids).unwrap().lines().map(String::from).collect(); + assert_eq!(pids.len(), 2); + assert!(!Path::new(&format!("/proc/{}", pids[0])).exists(), "first still runs"); + assert!(Path::new(&format!("/proc/{}", pids[1])).exists(), "second does not run"); + let all = std::fs::read_to_string(&args).unwrap(); + let (a, b) = all.split_once("---\n").unwrap(); + assert_eq!(a, b.trim_end_matches("---\n")); + assert!(a.contains("--continue")); + second.stop().await; + } + + #[tokio::test] + async fn arguments_and_environment() { + let dir = tempfile::tempdir().unwrap(); + let args = dir.path().join("args"); + let env = dir.path().join("env"); + let body = format!("printf '%s\\n' \"$@\" > '{}'\nenv > '{}'", args.display(), env.display()); + let y = Ytdlp { path: stub(dir.path(), "a", &body), version: "x".into() }; + // SAFETY: no other test reads these. + unsafe { + std::env::set_var("http_proxy", "http://127.0.0.1:1"); + std::env::set_var("ALL_PROXY", "http://127.0.0.1:1"); + } + for url in ["https://v.test/1", "-o/etc/evil"] { + let run = Run { url: url.into(), folder: dir.path().into(), name: Run::NAME.into(), limit: Some(5000), ..Run::default() }; + let mut r = y.start(&run).unwrap(); + let _ = r.end().await; + let a: Vec = std::fs::read_to_string(&args).unwrap().lines().map(String::from).collect(); + assert_eq!(a[0], "--ignore-config"); + assert_eq!(a[a.len() - 2], "--"); + assert_eq!(a[a.len() - 1], url); + let at = a.iter().position(|x| x == "--limit-rate").unwrap(); + assert_eq!(a[at + 1], "5000"); + let env = std::fs::read_to_string(&env).unwrap(); + assert!(!env.lines().any(|l| l.to_lowercase().starts_with("http_proxy=") || l.to_lowercase().starts_with("all_proxy=")), "proxy leaked"); + } + } + + #[tokio::test] + async fn cookies_are_private_and_removed() { + let dir = tempfile::tempdir().unwrap(); + let runtime = tempfile::tempdir().unwrap(); + // SAFETY: only this test makes cookie files. + unsafe { std::env::set_var("XDG_RUNTIME_DIR", runtime.path()) }; + let report = dir.path().join("report"); + let body = format!( + "while [ $# -gt 0 ]; do if [ \"$1\" = --cookies ]; then f=\"$2\"; fi; shift; done\nstat -c %a \"$f\" > '{0}'\ncat \"$f\" >> '{0}'\nexec sleep 60", + report.display() + ); + let y = Ytdlp { path: stub(dir.path(), "c", &body), version: "x".into() }; + let run = Run { url: "https://v.test/1".into(), folder: dir.path().into(), name: "n".into(), cookies: Some("# Netscape\nsecret\tvalue".into()), ..Run::default() }; + let left = || std::fs::read_dir(runtime.path()).unwrap().count(); + let mut r = y.start(&run).unwrap(); + tokio::time::sleep(Duration::from_millis(500)).await; + assert_eq!(std::fs::read_to_string(&report).unwrap(), "600\n# Netscape\nsecret\tvalue"); + assert_eq!(left(), 1); + r.stop().await; + assert_eq!(left(), 0, "kept after stop"); + // after end + let quick = Ytdlp { path: stub(dir.path(), "q", "true"), version: "x".into() }; + let mut r = quick.start(&run).unwrap(); + assert_eq!(left(), 1); + let _ = r.end().await; + drop(r); + assert_eq!(left(), 0, "kept after end"); + // after drop + let r = y.start(&run).unwrap(); + assert_eq!(left(), 1); + drop(r); + assert_eq!(left(), 0, "kept after drop"); + } + + #[test] + fn failures_have_reasons_and_texts() { + let cases: [(&str, Reason); 8] = [ + ("ERROR: [youtube] x: Private video. Sign in if you've been granted access", Reason::Private), + ("ERROR: [youtube] x: Video unavailable. This video has been removed by the uploader", Reason::Removed), + ("ERROR: The uploader has not made this video available in your country", Reason::Region), + ("ERROR: Sign in to confirm you're not a bot", Reason::Login), + ("ERROR: Unsupported URL: https://x.test/", Reason::Unsupported), + ("ERROR: unable to download: HTTP Error 429: Too Many Requests", Reason::TooManyRequests), + ("ERROR: This video is DRM protected", Reason::Drm), + ("ERROR: something odd happened", Reason::Other), + ]; + let mut texts = vec![]; + for (line, want) in cases { + let got = Reason::of([line].into_iter()); + assert_eq!(got, want, "{line}"); + texts.push(format!("{:?}", got.error())); + } + texts.sort(); + texts.dedup(); + assert_eq!(texts.len(), 8, "each reason has its own text: {texts:?}"); + } + + #[test] + fn choices_become_arguments() { + let c = Choice { height: Some(720), subtitles: vec!["en".into(), "de".into(), "e n;rm".into()], items: Some("1,3-5".into()), playlist: true, ..Choice::default() }; + let a = c.arguments(); + assert!(a.iter().any(|x| x.contains("height<=720"))); + assert!(!a.contains(&"-x".to_string())); + let at = a.iter().position(|x| x == "--sub-langs").unwrap(); + assert_eq!(a[at + 1], "en,de"); + assert!(a.contains(&"--write-subs".into())); + let at = a.iter().position(|x| x == "--playlist-items").unwrap(); + assert_eq!(a[at + 1], "1,3-5"); + let audio = Choice { audio_only: true, ..Choice::default() }.arguments(); + assert!(audio.contains(&"-x".to_string()) && audio.contains(&"--no-playlist".to_string())); + let odd = Choice { items: Some("1;rm -rf".into()), playlist: true, ..Choice::default() }.arguments(); + assert!(!odd.contains(&"--playlist-items".to_string())); + } +} diff --git a/crates/core/tests/ytdlp_real.rs b/crates/core/tests/ytdlp_real.rs new file mode 100644 index 0000000..26eced7 --- /dev/null +++ b/crates/core/tests/ytdlp_real.rs @@ -0,0 +1,21 @@ +//! The real yt-dlp against the test server's file (never a real site). Run: cargo test -p medlar-core --test ytdlp_real -- --ignored + +use medlar_core::ytdlp::{Run, Ytdlp}; +use medlar_testserver::TestServer; + +#[tokio::test] +#[ignore = "needs yt-dlp on this computer"] +async fn real_program_downloads_a_file_from_the_test_server() { + let yt = Ytdlp::find().await.expect("yt-dlp is installed"); + let server = TestServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let run = Run { url: server.url("/data/1/200k/clip.mp4"), folder: dir.path().into(), name: Run::NAME.into(), ..Run::default() }; + let mut running = yt.start(&run).unwrap(); + let file = running.end().await.expect("download ends well"); + assert!(file.starts_with(dir.path()) && file.is_file(), "{file:?}"); + assert_eq!(std::fs::metadata(&file).unwrap().len(), 200 * 1024); + // the probe of the same link + let cache = medlar_core::ytdlp::Cache::default(); + let probe = yt.probe(&cache, &run.url, None, std::future::pending()).await.expect("probe works"); + assert!(!probe.title.is_empty()); +} diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index e36a534..9c8afb8 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -241,3 +241,8 @@ Seen: boxes were ticked together after the tests, against rule 3. - New `crates/core/tests/control.rs`, `queues.rs`; unit tests in `details/tabs.rs`. S021 1-18, S023 1-17 pass; S022, S024, screen and by-hand checks not run, hidden app start not run. - Fixed: `Rule::fits` extension/mime OR, S033 settings rows and strings, `send` icon, settings test skips `mode_grid`. - Use an absolute `TMPDIR` for tests (relative gives false NotFound). Flaky under load: parts benchmark, auth proxy names. + +## S043 tests of video, rules, tray, screens +- Added stub-yt-dlp tests in `ytdlp.rs`, `tests/ytdlp_real.rs` (ignored), `tests/bus.rs` (fake tray host, Notifications, launcher), scenes for rules, clipboard, notifications, details, control tabs. +- Fixed: yt-dlp region text, all-done after pause, U+2192 glyph panic, Control tab labels, unlabeled switch. +- Not run: clipboard and drop by hand, motion checks, S022/S024 2-16, hidden-session checks. diff --git a/docs/TEST-REPORT.md b/docs/TEST-REPORT.md index 8ce12ba..57a1e75 100644 --- a/docs/TEST-REPORT.md +++ b/docs/TEST-REPORT.md @@ -2,3 +2,4 @@ - S041 details, control, connector: suite green (core, app, auth, parts, settings, shots, main, shell) after fixes. S021 1-18 and S023 1-17 pass; S017 14 and 17 pass; S022, S024 and screen or by-hand checks not run; app start in a hidden session not run (debug build opens no window). Fixed: rules OR semantics, missing S033 settings rows and strings, missing `send` icon, `mode_grid` row test. Parts and auth proxy tests failed once under load, passed on rerun. - S041 it runs: release build ok (8m47s); `tools/hidden.sh` opens the window (first-run page, 0.00 % CPU idle). Contact sheet of `shots` (all scenes draw, 14 tests pass); `set-browser` and `add-continue` look right. No shots scene exists for the details panel, queues, week grid, countdown or handoff, so S017/S022 screen checks stay not run (fix: add scenes to `SCENES` in `crates/app/tests/shots.rs`). +- S043 video, rules, tray, screens: workspace suite green. New: 14 ytdlp stub tests + 1 ignored real yt-dlp test (S025 1-15, 17 pass), `crates/app/tests/bus.rs` on a private dbus-daemon (S033 1-3, 5-12, 14-16, 18 pass), S027 1-7 pass. Fixed: Region text of yt-dlp not matched; all-done note sent when last one was paused; rules summary used U+2192 (no glyph, panic in shots); Control tab labels cut; unlabeled switch in When done. Not run: S027 8-11, 13-17 (clipboard, drop, hidden), S034 1-6, 8, 10, 11, 14, 15, S022 and S024 2-16, tray Mode click and window close, Power page empty (no rows; hidden from the rail). Control sheet and Details panel clipped at 480x360 in still shots (scroll untested). diff --git a/docs/tests/S025-video-sites.md b/docs/tests/S025-video-sites.md index 33e31ab..1dd5b1a 100644 --- a/docs/tests/S025-video-sites.md +++ b/docs/tests/S025-video-sites.md @@ -10,23 +10,23 @@ Written by the worker that built it, run by the test phase. Nothing here has bee ## Checks | # | Risk | Do this | Expect | How | Result | |---|---|---|---|---|---| -| 1 | MED | `Ytdlp::find` with no yt-dlp on PATH or beside the test | `Problem::Missing`, words say to install it | unit | โ€” | -| 2 | MED | Stub `--version` prints `2022.01.01` | `Problem::TooOld("2022.01.01")`; `2024.08.06`, `2025.01.01.1` and `2024.08.06-nightly` pass | unit (stub) | โ€” | -| 3 | MED | Stub that exits 1 or prints junk for `--version` | `Problem::Broken` | unit (stub) | โ€” | -| 4 | HIGH | Stub replays a recorded `-J` of one video; call `probe` | formats, sizes, subtitles, automatic captions, chapters read; `qualities()` lists Best then heights descending with video plus best-audio sizes | unit (stub) | โ€” | -| 5 | MED | Probe a recorded playlist | `is_playlist`, entries have titles and urls; `live_chat` is not a subtitle | unit (stub) | โ€” | -| 6 | MED | Probe the same link twice | the stub ran once (cache); after the keep time it runs again | unit (stub) | โ€” | -| 7 | HIGH | Stub sleeps; end the cancel future during `probe` | `Error::Stopped` at once and the stub process is gone | unit (stub) | โ€” | -| 8 | HIGH | Probe a recorded answer whose formats are all `has_drm` | error of kind `Drm`, nothing cached | unit (stub) | โ€” | -| 9 | HIGH | Stub prints recorded progress lines; read `Running::progress` | done, total (or estimate), speed, eta, fragment and playlist item match; `NA` parts are `None` | unit (stub) | โ€” | -| 10 | HIGH | `start`, then `stop`, then `start` again with the same folder | stub sees the same arguments; first process is gone after `stop`; second goes on | unit (stub) | โ€” | -| 11 | HIGH | Stub echoes its arguments | starts with `--ignore-config`; link is last and right after `--`; a link beginning with `-` stays an argument; limit gives `--limit-rate N`; no proxy variables in its environment | unit (stub) | โ€” | -| 12 | HIGH | Run with cookies; stub reports the cookie file's mode and content | mode 600, content equal; file removed after `end` and after drop | unit (stub) | โ€” | -| 13 | HIGH | Recorded failures: private, removed, region, sign-in, unsupported URL, HTTP 429, DRM, unknown | `Reason` is Private, Removed, Region, Login, Unsupported, TooManyRequests, Drm, Other; each error has its own plain text | unit | โ€” | -| 14 | MED | `Choice` with height 720, audio only, subtitles `en,de`, items | format selector with `height<=720`; `-x`; `--write-subs --sub-langs en,de`; odd characters in languages or items dropped | unit | โ€” | -| 15 | MED | `Video` page: pick items 1, 3, 4, 5 of 6 | `choice().items == "1,3-5"`; all picked gives `None`; none picked gives `empty()` | unit | โ€” | -| 16 | LOW | Show the page with a playlist, subtitles and sizes, light and dark | readable, no overlap, list scrolls | screen | โ€” | -| 17 | MED | `#[ignore]` test: real yt-dlp against the test server's generic page (never a real site) | file arrives in the folder, `end` returns its path | integration | โ€” | +| 1 | MED | `Ytdlp::find` with no yt-dlp on PATH or beside the test | `Problem::Missing`, words say to install it | unit | pass (`missing_has_words`) | +| 2 | MED | Stub `--version` prints `2022.01.01` | `Problem::TooOld("2022.01.01")`; `2024.08.06`, `2025.01.01.1` and `2024.08.06-nightly` pass | unit (stub) | pass (`versions`) | +| 3 | MED | Stub that exits 1 or prints junk for `--version` | `Problem::Broken` | unit (stub) | pass (`broken_ones`) | +| 4 | HIGH | Stub replays a recorded `-J` of one video; call `probe` | formats, sizes, subtitles, automatic captions, chapters read; `qualities()` lists Best then heights descending with video plus best-audio sizes | unit (stub) | pass (`probe_reads_a_video`) | +| 5 | MED | Probe a recorded playlist | `is_playlist`, entries have titles and urls; `live_chat` is not a subtitle | unit (stub) | pass | +| 6 | MED | Probe the same link twice | the stub ran once (cache); after the keep time it runs again | unit (stub) | pass (cache age moved back) | +| 7 | HIGH | Stub sleeps; end the cancel future during `probe` | `Error::Stopped` at once and the stub process is gone | unit (stub) | pass (`cancel_kills_the_program`) | +| 8 | HIGH | Probe a recorded answer whose formats are all `has_drm` | error of kind `Drm`, nothing cached | unit (stub) | pass | +| 9 | HIGH | Stub prints recorded progress lines; read `Running::progress` | done, total (or estimate), speed, eta, fragment and playlist item match; `NA` parts are `None` | unit (stub) | pass | +| 10 | HIGH | `start`, then `stop`, then `start` again with the same folder | stub sees the same arguments; first process is gone after `stop`; second goes on | unit (stub) | pass | +| 11 | HIGH | Stub echoes its arguments | starts with `--ignore-config`; link is last and right after `--`; a link beginning with `-` stays an argument; limit gives `--limit-rate N`; no proxy variables in its environment | unit (stub) | pass (proxy vars set in test, absent in stub) | +| 12 | HIGH | Run with cookies; stub reports the cookie file's mode and content | mode 600, content equal; file removed after `end` and after drop | unit (stub) | pass (also after drop) | +| 13 | HIGH | Recorded failures: private, removed, region, sign-in, unsupported URL, HTTP 429, DRM, unknown | `Reason` is Private, Removed, Region, Login, Unsupported, TooManyRequests, Drm, Other; each error has its own plain text | unit | fixed: yt-dlp text "has not made this video available in your country" gave Other; added Region pattern; then pass | +| 14 | MED | `Choice` with height 720, audio only, subtitles `en,de`, items | format selector with `height<=720`; `-x`; `--write-subs --sub-langs en,de`; odd characters in languages or items dropped | unit | pass | +| 15 | MED | `Video` page: pick items 1, 3, 4, 5 of 6 | `choice().items == "1,3-5"`; all picked gives `None`; none picked gives `empty()` | unit | pass (`picked_items_become_ranges`) | +| 16 | LOW | Show the page with a playlist, subtitles and sizes, light and dark | readable, no overlap, list scrolls | screen | not run: no scene for the video page (not wired in Add dialog) | +| 17 | MED | `#[ignore]` test: real yt-dlp against the test server's generic page (never a real site) | file arrives in the folder, `end` returns its path | integration | pass (`--ignored`, real yt-dlp + testserver; probe and download of 200 KiB) | ## Needs A stub `yt-dlp` script (shell) that replays recorded outputs chosen by an environment variable and records its arguments; the test server for check 17; a throwaway `XDG_RUNTIME_DIR`. Never a real video site. diff --git a/docs/tests/S027-rules-clipboard-drop.md b/docs/tests/S027-rules-clipboard-drop.md index 5559c8c..5288188 100644 --- a/docs/tests/S027-rules-clipboard-drop.md +++ b/docs/tests/S027-rules-clipboard-drop.md @@ -12,23 +12,23 @@ Written by the worker that built it, run by the test phase. Nothing here has bee ## Checks | # | Risk | Do this | Expect | How | Result | |---|---|---|---|---|---| -| 1 | HIGH | `nice cargo test -j 2 -p medlar-core rules` | all rules tests green | unit | โ€” | -| 2 | HIGH | Template `{nope}x/../{name}` on `b%2Fc.tar.gz` | no path part in the result; `b_c.tar.gz` | unit | โ€” | -| 3 | HIGH | Rule folder `../../etc` with base `/home/u/Downloads` | folder is `/home/u/Downloads/etc` | unit | โ€” | -| 4 | MED | Two rules fit; disable the first | the second one counts | unit | โ€” | -| 5 | MED | Size unknown against a rule with min 100 MB | the rule still fits | unit | โ€” | -| 6 | MED | Add three links of the same template name `a.zip` | names `a.zip`, `a (2).zip`, `a (3).zip` | unit | โ€” | -| 7 | MED | `nice cargo test -j 2 -p medlar clipboard` | filters by type and host work | unit | โ€” | -| 8 | HIGH | Clipboard set to Ask, copy `https://a.test/x.zip` (X11/XWayland or data-control) | Add window opens with the link once; copying it again does nothing | by hand | โ€” | -| 9 | HIGH | Clipboard Ask, press copy in Medlar (details value) | no Add window (own copy ignored) | by hand | โ€” | -| 10 | MED | Clipboard Add, copy a link already in the list | nothing is added | by hand | โ€” | -| 11 | MED | Clipboard Off, copy a link, then switch to Ask | the old copy is not offered | by hand | โ€” | -| 12 | MED | Rules page: add default set, edit one, move, disable, delete and undo | list follows; undo brings it back; settings file keeps `rules` | screen | โ€” | -| 13 | MED | Rules test box with `https://x.test/movie.mp4` | shows rule Video and folder below the download folder | screen | โ€” | -| 14 | MED | Add dialog with a link that a rule catches, folder not touched | download lands in the rule's folder, queue and priority | screen | โ€” | -| 15 | MED | Hidden run: drag a `.txt` list over the window | full-window drop state shows; on release Add opens with the list | screen | โ€” | -| 16 | LOW | Drop target switch on, hidden nested niri | small ring window with speed; right click menu; Hide switches the setting off | screen | โ€” | -| 17 | LOW | Old settings file without the new keys | opens with defaults (rules empty, clipboard off) | unit | โ€” | +| 1 | HIGH | `nice cargo test -j 2 -p medlar-core rules` | all rules tests green | unit | pass | +| 2 | HIGH | Template `{nope}x/../{name}` on `b%2Fc.tar.gz` | no path part in the result; `b_c.tar.gz` | unit | pass (existing unit test) | +| 3 | HIGH | Rule folder `../../etc` with base `/home/u/Downloads` | folder is `/home/u/Downloads/etc` | unit | pass (existing unit test) | +| 4 | MED | Two rules fit; disable the first | the second one counts | unit | pass (existing) | +| 5 | MED | Size unknown against a rule with min 100 MB | the rule still fits | unit | pass (existing) | +| 6 | MED | Add three links of the same template name `a.zip` | names `a.zip`, `a (2).zip`, `a (3).zip` | unit | pass (existing) | +| 7 | MED | `nice cargo test -j 2 -p medlar clipboard` | filters by type and host work | unit | pass | +| 8 | HIGH | Clipboard set to Ask, copy `https://a.test/x.zip` (X11/XWayland or data-control) | Add window opens with the link once; copying it again does nothing | by hand | not run: needs live compositor/clipboard/hidden session | +| 9 | HIGH | Clipboard Ask, press copy in Medlar (details value) | no Add window (own copy ignored) | by hand | not run: needs live compositor/clipboard/hidden session | +| 10 | MED | Clipboard Add, copy a link already in the list | nothing is added | by hand | not run: needs live compositor/clipboard/hidden session | +| 11 | MED | Clipboard Off, copy a link, then switch to Ask | the old copy is not offered | by hand | not run: needs live compositor/clipboard/hidden session | +| 12 | MED | Rules page: add default set, edit one, move, disable, delete and undo | list follows; undo brings it back; settings file keeps `rules` | screen | not run: scene shows list and empty state only; no interaction | +| 13 | MED | Rules test box with `https://x.test/movie.mp4` | shows rule Video and folder below the download folder | screen | not run | +| 14 | MED | Add dialog with a link that a rule catches, folder not touched | download lands in the rule's folder, queue and priority | screen | not run: needs live compositor/clipboard/hidden session | +| 15 | MED | Hidden run: drag a `.txt` list over the window | full-window drop state shows; on release Add opens with the list | screen | not run: needs live compositor/clipboard/hidden session | +| 16 | LOW | Drop target switch on, hidden nested niri | small ring window with speed; right click menu; Hide switches the setting off | screen | not run: needs live compositor/clipboard/hidden session | +| 17 | LOW | Old settings file without the new keys | opens with defaults (rules empty, clipboard off) | unit | not run | ## Needs Throwaway `XDG_*` home; hidden niri via `tools/hidden.sh`; never the user's clipboard history. Clipboard checks need a compositor with data-control or XWayland. diff --git a/docs/tests/S033-tray-notify.md b/docs/tests/S033-tray-notify.md index 1d768ef..5581483 100644 --- a/docs/tests/S033-tray-notify.md +++ b/docs/tests/S033-tray-notify.md @@ -31,3 +31,10 @@ All bus checks run under `dbus-run-session` with fake services, never the user's - No settings page controls the new settings yet (file only); a later plan adds the rows. - The ksni tooltip and radio group look differs per tray host; check in KDE and a GNOME host if available. - The Unity signal body (s, a{sv}) is built with zbus tuple flattening; verify on the wire. + +## Results (S043, `crates/app/tests/bus.rs`, private dbus-daemon, fake watcher, fake Notifications) +- 1 pass (id medlar, 64x64 pixmap, menu labels), 2 pass for `Tray::start` None (the window-closes half not run), 3 pass for Show, Add, PauseAll, ResumeAll, Quit in order (Mode click, `quitting` and window close not run), 4 not run (needs a window). +- 5 pass (summary, body, actions open/folder, desktop-entry hint), 6 pass (folder then open; unknown key and unknown id ignored), 7 pass (note and action kinds; clicking not run), 8 pass. +- 9 pass, 10 pass, 11 fixed: the last download being paused sent "All downloads are finished"; now it does not; then pass. 12 pass (quiet_at, quiet_now, quiet sends no Notify). 13 not run (the `notify` flag check is in the shell, not covered). 14 pass (ring pixels, tooltip "2 running"; idle tooltip text not read), 15 pass (signal body (s, a{sv}) read on the wire), 16 pass for `wants`, hidden start not run, 17 not run (validate-desktop.sh not run). +- 18 pass. +- Doubts: hidden-window stalls on Wayland not run; tray look in KDE/GNOME not run; Unity body verified on a private bus only. diff --git a/docs/tests/S034-motion-audit.md b/docs/tests/S034-motion-audit.md index edca200..491a8e0 100644 --- a/docs/tests/S034-motion-audit.md +++ b/docs/tests/S034-motion-audit.md @@ -16,21 +16,21 @@ How: unit ยท integration ยท screen ยท by hand. | # | Risk | Do this | Expect | How | Result | |---|---|---|---|---|---| -| 1 | MED | Motion normal: drag a file over the main window (hidden.sh driver or kittest with `hovered_files` set), grab frames 0, 3, 10, 30; then clear hovered files and grab again | Overlay alpha rises over a few frames to full, then falls back to nothing; no frame after it is gone (`motion::busy()` false) | screen | โ€” | -| 2 | MED | Same as 1 with motion reduced, then off | Reduced: same fade, never above full. Off: full on the first frame, gone on the first frame after | screen | โ€” | -| 3 | MED | Queues page with 3 queues; drag queue 1's handle down past queue 3 and release; grab frames for 30 frames after release, motion normal | Card follows the pointer 1:1 while held; after release it moves smoothly to the last place, others move up smoothly; no jump back to the old slot at the end | screen | โ€” | -| 4 | MED | Repeat 3 with motion reduced and off | Reduced: no overshoot past the final slot. Off: cards are in their final places on the next frame | screen | โ€” | -| 5 | MED | Queues page with more queues than fit; scroll the page with the wheel | Cards scroll 1:1 with the content, no lag or glide while scrolling | by hand | โ€” | -| 6 | LOW | Hover the queue handle, then press and drag it | Cursor grab on hover, grabbing while dragging; held card tint fades in and out, no instant switch | screen | โ€” | -| 7 | MED | Settings, Rules with no rules | The line "No rules yet. ..." shows above "Add rule" and "Add the set by type" | screen | โ€” | -| 8 | LOW | Add a rule with an empty name; read AccessKit names of its row and buttons (kittest `query_by_label`), remove it | Labels read "Change rule Rule without a name" etc.; toast "Rule Rule without a name removed" with Undo; Undo brings it back | unit (kittest) | โ€” | -| 9 | LOW | Edit a rule; look at the At least / At most fields | Unit shows the catalogue's "MB" | screen | โ€” | -| 10 | LOW | Turn on the drop target (Settings, Clipboard and drops); right click the ring, then pick each entry | Window 112x132 closed, 172x232 with the menu, all three buttons fully inside | screen | โ€” | -| 11 | MED | Keyboard only, from launch: reach Add, Settings (every page), Queues, Rules, the list, the palette with Tab, arrows, Enter, Escape | Every control gets a visible focus ring, every action can be done, Escape closes dialogs and menus | by hand / kittest | โ€” | -| 12 | MED | Shots of main, settings (each page), queues, rules, add and the drop overlay at 480x360, 900x600, 1600x1000, 3440x1440, light, dark, AMOLED (`MEDLAR_SHOTS`, `SIZES=`, contact sheet) | Nothing overflows or overlaps, panels flush, popups inside the window, AMOLED surface black | screen | โ€” | -| 13 | MED | Same shots with a 200-character download and queue and rule name, sizes over 1 TB, speeds over 1 GB/s, counts over 10,000 | Names end in an ellipsis on one line, numbers fit their columns, no row grows | screen | โ€” | -| 14 | LOW | Every clickable thing in the shots from 12: measure hit rects (kittest response rects) | None smaller than 32x32 px | unit (kittest) | โ€” | -| 15 | MED | Idle app 10 s after the last change, with the drop overlay gone and no drag | No frames drawn (`tools/hidden.sh` cpu near 0, frame counter flat) | screen | โ€” | +| 1 | MED | Motion normal: drag a file over the main window (hidden.sh driver or kittest with `hovered_files` set), grab frames 0, 3, 10, 30; then clear hovered files and grab again | Overlay alpha rises over a few frames to full, then falls back to nothing; no frame after it is gone (`motion::busy()` false) | screen | not run: needs input events, kittest rects or a hidden session | +| 2 | MED | Same as 1 with motion reduced, then off | Reduced: same fade, never above full. Off: full on the first frame, gone on the first frame after | screen | not run: needs input events, kittest rects or a hidden session | +| 3 | MED | Queues page with 3 queues; drag queue 1's handle down past queue 3 and release; grab frames for 30 frames after release, motion normal | Card follows the pointer 1:1 while held; after release it moves smoothly to the last place, others move up smoothly; no jump back to the old slot at the end | screen | not run: needs input events, kittest rects or a hidden session | +| 4 | MED | Repeat 3 with motion reduced and off | Reduced: no overshoot past the final slot. Off: cards are in their final places on the next frame | screen | not run: needs input events, kittest rects or a hidden session | +| 5 | MED | Queues page with more queues than fit; scroll the page with the wheel | Cards scroll 1:1 with the content, no lag or glide while scrolling | by hand | not run: needs input events, kittest rects or a hidden session | +| 6 | LOW | Hover the queue handle, then press and drag it | Cursor grab on hover, grabbing while dragging; held card tint fades in and out, no instant switch | screen | not run: needs input events, kittest rects or a hidden session | +| 7 | MED | Settings, Rules with no rules | The line "No rules yet. ..." shows above "Add rule" and "Add the set by type" | screen | pass (shot) | +| 8 | LOW | Add a rule with an empty name; read AccessKit names of its row and buttons (kittest `query_by_label`), remove it | Labels read "Change rule Rule without a name" etc.; toast "Rule Rule without a name removed" with Undo; Undo brings it back | unit (kittest) | not run: needs input events, kittest rects or a hidden session | +| 9 | LOW | Edit a rule; look at the At least / At most fields | Unit shows the catalogue's "MB" | screen | not run: needs input events, kittest rects or a hidden session | +| 10 | LOW | Turn on the drop target (Settings, Clipboard and drops); right click the ring, then pick each entry | Window 112x132 closed, 172x232 with the menu, all three buttons fully inside | screen | not run: needs input events, kittest rects or a hidden session | +| 11 | MED | Keyboard only, from launch: reach Add, Settings (every page), Queues, Rules, the list, the palette with Tab, arrows, Enter, Escape | Every control gets a visible focus ring, every action can be done, Escape closes dialogs and menus | by hand / kittest | not run: needs input events, kittest rects or a hidden session | +| 12 | MED | Shots of main, settings (each page), queues, rules, add and the drop overlay at 480x360, 900x600, 1600x1000, 3440x1440, light, dark, AMOLED (`MEDLAR_SHOTS`, `SIZES=`, contact sheet) | Nothing overflows or overlaps, panels flush, popups inside the window, AMOLED surface black | screen | partly: see Results below | +| 13 | MED | Same shots with a 200-character download and queue and rule name, sizes over 1 TB, speeds over 1 GB/s, counts over 10,000 | Names end in an ellipsis on one line, numbers fit their columns, no row grows | screen | not run: see Results below | +| 14 | LOW | Every clickable thing in the shots from 12: measure hit rects (kittest response rects) | None smaller than 32x32 px | unit (kittest) | not run: needs input events, kittest rects or a hidden session | +| 15 | MED | Idle app 10 s after the last change, with the drop overlay gone and no drag | No frames drawn (`tools/hidden.sh` cpu near 0, frame counter flat) | screen | not run: needs input events, kittest rects or a hidden session | ## Needs Throwaway `XDG_*` home, `tools/hidden.sh` or kittest shots, a few queues and rules in the throwaway settings. No network. @@ -41,3 +41,9 @@ Throwaway `XDG_*` home, `tools/hidden.sh` or kittest shots, a few queues and rul - The drop overlay fade needs repaints after hovered files clear; it relies on `motion::busy()` asking for frames (check 1 last part). - S033 settings (tray, notifications, autostart, quiet hours) still have no settings rows; not a dead control, but not reachable from the UI. - No existing tests should break; the queues key strings changed only inside motion springs. + +## Results (S043) +- 1-6, 8, 10, 11, 14, 15: not run (need hovered files, drag input, kittest hit rects or a hidden session; not written in this pass). +- 7 pass (shot `set-rules-empty`: line shows above the two buttons). 9 not run. +- 12 partly: new scenes `set-rules`, `set-rules-long`, `set-rules-empty`, `set-clipboard`, `set-notifications`, `details`, `control-0..3` drawn at 900x600 and 480x360, light and dark, one contact sheet read. AMOLED and 1600x1000, 3440x1440 not run. Faults fixed: Rules summary used U+2192 that the fonts lack (panic in `shots`), now " > "; Control tab labels were cut to "Sโ€ฆ" (icons removed); "Also when one failed" switch had no visible label. Still open: Control sheet and Details panel at 480x360 are cut at the bottom in a still picture (scroll not tested). +- 13 not run (rule scene with 200-char name: the name ends in an ellipsis in the shot, one line; numbers not checked).