Medlar/crates/app/tests/main.rs
2026-11-25 14:03:30 -06:00

550 lines
22 KiB
Rust

//! The daily screen: what the list shows, the pointer, the keyboard, commands, motion, and the engine behind it.
#[path = "main/fixture.rs"]
mod fixture;
use eframe::egui::{Event, Key, Modifiers, PointerButton, Pos2, Vec2, pos2, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use fixture::{all, failed, lists, many, shot, view};
use medlar_app::app::App;
use medlar_app::bridge::{Bridge, Opening};
use medlar_app::desktop::Sources;
use medlar_app::ui::shape::Kind;
use medlar_app::views::list::layout::Form;
use medlar_app::views::list::model::{Age, Filter, Group, Listing, Query, Sort, Status, places};
use medlar_core::manager::{Command, Files};
use medlar_core::model::{ErrorKind, State, Task, TaskId};
use medlar_core::net_state::Bus;
use medlar_core::paths::Paths;
use medlar_core::settings::{Motion, Settings};
use medlar_core::snapshot::{Snapshot, TaskView};
use std::sync::Arc;
use std::time::{Duration, Instant};
type H = Harness<'static, Option<App>>;
fn harness_at(size: Vec2, set: impl Fn(&mut App) + 'static) -> H {
let frame = move |ui: &mut eframe::egui::Ui, s: &mut Option<App>| {
let Some(app) = s else {
let nowhere = Sources { caelestia: "/nonexistent".into(), kde: "/nonexistent".into() };
let mut app = App::new(ui.ctx(), Settings { motion: Motion::Normal, ..Settings::default() }, nowhere);
set(&mut app);
*s = Some(app);
ui.ctx().request_repaint();
return;
};
app.show(ui);
};
let mut h = Harness::builder().with_size(size).with_step_dt(1.0 / 60.0).build_ui_state(frame, None);
h.run_steps(60);
h
}
fn harness(views: Vec<TaskView>) -> H {
let shot = std::cell::RefCell::new(Some(shot(views)));
harness_at(vec2(1280.0, 900.0), move |app| app.main.bridge = Bridge::still(shot.take().unwrap(), lists()))
}
fn app(h: &mut H) -> &mut App {
h.state_mut().as_mut().unwrap()
}
fn set(h: &mut H, views: Vec<TaskView>) {
thread_local!(static REV: std::cell::Cell<u64> = const { std::cell::Cell::new(1000) });
let mut shot = shot(views);
REV.set(REV.get() + 1);
shot.rev = REV.get();
app(h).main.bridge.set_still(shot);
}
fn simple(n: i64) -> Vec<TaskView> {
(1..=n).map(|id| view(id, &format!("file-{id:02}.zip"), "a.example.org", State::Paused, 1000, 0.5)).collect()
}
fn row(h: &H, name: &str) -> eframe::egui::Rect {
h.get_by_label(name).rect()
}
fn pointer(h: &mut H, pos: Pos2, button: PointerButton, pressed: bool, modifiers: Modifiers) {
h.input_mut().events.push(Event::ModifiersChanged(modifiers));
h.input_mut().events.push(Event::PointerMoved(pos));
h.input_mut().events.push(Event::PointerButton { pos, button, pressed, modifiers });
h.step();
}
fn click_with(h: &mut H, pos: Pos2, modifiers: Modifiers) {
pointer(h, pos, PointerButton::Primary, true, modifiers);
pointer(h, pos, PointerButton::Primary, false, modifiers);
h.input_mut().events.push(Event::ModifiersChanged(Modifiers::NONE));
// Two clicks must not make a double click.
h.run_steps(30);
}
fn click(h: &mut H, pos: Pos2) {
click_with(h, pos, Modifiers::NONE);
}
fn drag(h: &mut H, from: Pos2, to: Pos2) {
pointer(h, from, PointerButton::Primary, true, Modifiers::NONE);
for i in 1..=10 {
h.input_mut().events.push(Event::PointerMoved(from + (to - from) * (i as f32 / 10.0)));
h.step();
}
pointer(h, to, PointerButton::Primary, false, Modifiers::NONE);
h.step();
}
fn key(h: &mut H, modifiers: Modifiers, key: Key) {
h.key_press_modifiers(modifiers, key);
h.run_steps(3);
}
fn selected(h: &mut H) -> Vec<TaskId> {
app(h).main.list.chosen()
}
fn sent(h: &mut H) -> Vec<Command> {
app(h).main.bridge.take_sent()
}
/// The middle of a row's name, where nothing else answers.
fn name(h: &H, of: &str) -> Pos2 {
let r = row(h, of);
pos2(r.left() + 160.0, r.center().y)
}
fn listed(query: &Query, shot: &Snapshot) -> (Vec<TaskId>, Listing) {
let mut listing = Listing::default();
listing.update(&Arc::new(shot.clone()), query, &Arc::new(lists()), medlar_app::views::list::model::today(medlar_core::model::now()));
(listing.rows.iter().map(|v| v.id()).collect(), listing)
}
#[test]
fn filters_search_sort_and_groups() {
let mut views = all();
Arc::make_mut(&mut views[7].task).tags = vec![2];
Arc::make_mut(&mut views[4].task).queue = 2;
let s = shot(views);
let plain = Query { group: Group::None, ..Query::default() };
let ids = |q: &Query| listed(q, &s).0;
let with = |f: Filter| ids(&Query { filter: f, ..plain.clone() });
assert_eq!(with(Filter { status: Status::Failed, ..Filter::default() }), [9, 10]);
assert_eq!(with(Filter { kind: Some(Kind::Audio), ..Filter::default() }), [8, 5]);
assert_eq!(with(Filter { tag: Some(2), ..Filter::default() }), [8]);
assert_eq!(with(Filter { queue: Some(2), ..Filter::default() }), [5]);
assert_eq!(with(Filter { host: Some("share.example.org:443".into()), ..Filter::default() }), [4, 12]);
assert!(with(Filter { age: Some(Age::Older), ..Filter::default() }).is_empty());
assert_eq!(with(Filter { search: " Example.EDU mp3".into(), ..Filter::default() }), [5]);
// The second queue comes after the first.
assert_eq!(ids(&plain).last(), Some(&5));
let by = |sort, down| ids(&Query { sort, down, ..plain.clone() });
assert_eq!(by(Sort::Size, true)[0], 7);
assert_eq!(by(Sort::Speed, true)[..2], [1, 2]);
assert_eq!(by(Sort::Name, false)[0], 2);
assert_eq!(by(Sort::Added, true)[0], 1);
let (rows, listing) = listed(&Query::default(), &s);
let heads: Vec<_> = listing.heads.iter().map(|h| (h.label.as_str(), h.count)).collect();
assert_eq!(heads, [("Downloading", 3), ("Waiting", 4), ("Paused", 1), ("Failed", 2), ("Done", 3)]);
assert_eq!(rows[..3], [1, 2, 3]);
assert_eq!((listing.head_of(2), listing.head_of(3)), (Some(0), Some(1)));
for group in Group::ALL {
let (rows, listing) = listed(&Query { group, ..Query::default() }, &s);
assert_eq!(rows.len(), 13, "{group:?}");
assert_eq!(listing.heads.iter().map(|h| h.count).sum::<usize>(), if group == Group::None { 0 } else { 13 });
}
assert_eq!(listing.counts.offline, 1);
}
#[test]
fn new_places_are_between_the_neighbours() {
let (_, l) = listed(&Query { group: Group::None, ..Query::default() }, &shot(simple(6)));
assert_eq!(places(&l, &[5], 1), [(5, 1, 1.5)]);
assert_eq!(places(&l, &[1], 6), [(1, 1, 7.0)]);
assert_eq!(places(&l, &[6], 0), [(6, 1, 0.0)]);
let two = places(&l, &[1, 2], 4);
assert!(two[0].2 > 4.0 && two[0].2 < two[1].2 && two[1].2 < 5.0, "{two:?}");
assert!(places(&l, &[99], 2).is_empty());
}
#[test]
fn pointer_selects_one_some_and_ranges() {
let mut h = harness(simple(8));
let (a, b, c) = (name(&h, "file-01.zip"), name(&h, "file-03.zip"), name(&h, "file-05.zip"));
click(&mut h, a);
assert_eq!(selected(&mut h), [1]);
click_with(&mut h, b, Modifiers::COMMAND);
assert_eq!(selected(&mut h), [1, 3]);
click_with(&mut h, c, Modifiers::SHIFT);
assert_eq!(selected(&mut h), [3, 4, 5]);
click(&mut h, a);
assert_eq!(selected(&mut h), [1]);
let below = pos2(a.x, 860.0);
click(&mut h, below);
assert!(selected(&mut h).is_empty());
}
#[test]
fn lasso_selects_what_it_touches() {
let mut h = harness(simple(8));
let (from, to) = (name(&h, "file-02.zip"), name(&h, "file-05.zip"));
drag(&mut h, from, to + vec2(60.0, 0.0));
assert_eq!(selected(&mut h), [2, 3, 4, 5]);
// From the empty ground, too.
let start = pos2(900.0, 880.0);
let end = name(&h, "file-07.zip");
drag(&mut h, start, end);
assert_eq!(selected(&mut h), [7, 8]);
assert!(sent(&mut h).is_empty());
}
#[test]
fn the_handle_moves_a_row_to_another_place() {
let mut h = harness(simple(8));
let r = row(&h, "file-06.zip");
let target = row(&h, "file-02.zip");
drag(&mut h, r.left_center() + vec2(16.0, 0.0), target.left_top() + vec2(16.0, 6.0));
let sent = sent(&mut h);
assert_eq!(sent.len(), 1);
let Some(Command::Edit { id: 6, edit }) = sent.into_iter().next() else { panic!("no edit of 6") };
let mut t = Task::default();
edit(&mut t);
assert_eq!((t.queue, t.position), (1, 1.5));
// Sorted by anything else there is no handle: the same drag is a lasso.
app(&mut h).main.list.query.sort = Sort::Name;
h.run_steps(5);
drag(&mut h, r.left_center() + vec2(16.0, 0.0), target.left_top() + vec2(16.0, 6.0));
assert!(self::sent(&mut h).is_empty());
}
#[test]
fn keyboard_moves_selects_and_acts() {
let mut h = harness(simple(30));
key(&mut h, Modifiers::NONE, Key::ArrowDown);
assert_eq!(selected(&mut h), [1]);
key(&mut h, Modifiers::NONE, Key::ArrowDown);
key(&mut h, Modifiers::SHIFT, Key::ArrowDown);
assert_eq!(selected(&mut h), [2, 3]);
key(&mut h, Modifiers::NONE, Key::End);
assert_eq!(selected(&mut h), [30]);
// It was scrolled to.
assert!(row(&h, "file-30.zip").bottom() <= 900.0);
key(&mut h, Modifiers::NONE, Key::Home);
key(&mut h, Modifiers::NONE, Key::Space);
assert!(matches!(sent(&mut h)[..], [Command::Resume(1)]));
key(&mut h, Modifiers::ALT, Key::ArrowDown);
assert!(matches!(sent(&mut h)[..], [Command::Edit { id: 1, .. }]));
key(&mut h, Modifiers::COMMAND, Key::A);
assert_eq!(selected(&mut h).len(), 30);
key(&mut h, Modifiers::NONE, Key::Escape);
assert!(selected(&mut h).is_empty());
// In the search field the keys are its own.
key(&mut h, Modifiers::COMMAND, Key::F);
key(&mut h, Modifiers::COMMAND, Key::A);
key(&mut h, Modifiers::NONE, Key::Delete);
assert!(selected(&mut h).is_empty() && sent(&mut h).is_empty());
h.input_mut().events.push(Event::Text("file-07".into()));
h.run_steps(5);
assert_eq!(app(&mut h).main.list.listing().rows.len(), 1);
}
#[test]
fn removal_is_undone_from_the_message() {
let mut h = harness(simple(4));
let at = name(&h, "file-02.zip");
click(&mut h, at);
key(&mut h, Modifiers::NONE, Key::Delete);
assert!(matches!(sent(&mut h)[..], [Command::Remove { id: 2, files: Files::Keep }]));
// The keyboard goes on from the next row.
assert_eq!(selected(&mut h), [3]);
key(&mut h, Modifiers::SHIFT, Key::Delete);
assert!(matches!(sent(&mut h)[..], [Command::Remove { id: 3, files: Files::Bin }]));
h.run_steps(60);
let undo = h.get_all_by_label("Undo").map(|n| n.rect().center()).max_by(|a, b| a.y.total_cmp(&b.y)).unwrap();
click(&mut h, undo);
assert!(matches!(sent(&mut h)[..], [Command::Restore(3)]));
}
#[test]
fn context_menu_selects_its_row_and_acts() {
let mut h = harness(simple(4));
let at = name(&h, "file-03.zip");
pointer(&mut h, at, PointerButton::Secondary, true, Modifiers::NONE);
pointer(&mut h, at, PointerButton::Secondary, false, Modifiers::NONE);
h.run_steps(30);
assert_eq!(selected(&mut h), [3]);
let item = h.get_by_label("Start now").rect().center();
click(&mut h, item);
assert!(matches!(sent(&mut h)[..], [Command::Start(3)]));
// The same from the keyboard.
key(&mut h, Modifiers::SHIFT, Key::F10);
h.run_steps(30);
assert!(h.query_by_label("Start now").is_some());
}
#[test]
fn toolbar_acts_on_all_selected() {
let mut h = harness(simple(4));
let (a, b) = (name(&h, "file-01.zip"), name(&h, "file-03.zip"));
click(&mut h, a);
click_with(&mut h, b, Modifiers::SHIFT);
h.run_steps(60);
// The toolbar's is the lowest of that name.
let resume = h.get_all_by_label("Resume").map(|n| n.rect().center()).max_by(|a, b| a.y.total_cmp(&b.y)).unwrap();
click(&mut h, resume);
assert!(matches!(sent(&mut h)[..], [Command::Resume(1), Command::Resume(2), Command::Resume(3)]));
}
#[test]
fn problems_offer_their_fix() {
let mut h = harness(all());
// A grouped list is longer than the window.
app(&mut h).main.list.query.filter.status = Status::Failed;
h.run_steps(60);
let choose = h.get_by_label("Choose").rect().center();
click(&mut h, choose);
let keep = h.get_by_label("Keep both").rect().center();
click(&mut h, keep);
assert!(matches!(sent(&mut h)[..], [Command::KeepBoth(10)]));
let link = h.get_by_label("Get new link").rect().center();
click(&mut h, link);
h.run_steps(60);
// Nothing changes before the new link was compared, see tests/add.rs.
assert!(h.get_by_label("Check the link").accesskit_node().is_disabled());
assert!(sent(&mut h).is_empty());
}
#[test]
fn the_next_try_is_counted_down() {
let mut v = failed(view(1, "a.zip", "a.example.org", State::Waiting, 1000, 0.0), ErrorKind::Busy, "");
v.retry_at = Some(medlar_core::model::now() + 2500);
let mut h = harness(vec![v]);
// Asleep until the next second, not awake all the time.
let delay = h.output().viewport_output.values().map(|o| o.repaint_delay).min().unwrap();
assert!(delay > Duration::from_millis(20) && delay <= Duration::from_secs(1), "{delay:?}");
h.step();
}
#[test]
fn every_state_of_the_screen() {
let mut h = harness(vec![]);
let add = h.get_by_label("Add").rect().center();
click(&mut h, add);
h.run_steps(60);
assert!(h.get_all_by_label("Add downloads").count() > 0);
h.input_mut().events.push(Event::Text("https://a.example.org/x.zip nonsense".into()));
h.run_steps(5);
let go = h.get_by_label("Download").rect().center();
click(&mut h, go);
let sent = sent(&mut h);
let [Command::Add(task)] = &sent[..] else { panic!("not added") };
assert_eq!(task.url, "https://a.example.org/x.zip");
let mut h = harness(all());
app(&mut h).main.list.query.filter.search = "no such thing".into();
h.run_steps(60);
let clear = h.get_by_label("Clear filters").rect().center();
click(&mut h, clear);
assert_eq!(app(&mut h).main.list.listing().rows.len(), 13);
for why in [None, Some("The download list could not be read.")] {
let mut h = harness_at(vec2(480.0, 360.0), move |app| app.main.bridge = Bridge::stuck(why));
h.run_steps(5);
assert_eq!(h.query_by_label("Try again").is_some(), why.is_some());
}
}
#[test]
fn every_size_and_form_draws_inside_its_list() {
for size in [vec2(480.0, 360.0), vec2(640.0, 480.0), vec2(900.0, 700.0), vec2(3440.0, 1440.0)] {
for form in [Form::Compact, Form::Cards] {
let mut h = harness_at(size, move |app| {
app.main.bridge = Bridge::still(shot(all()), lists());
app.main.list.form = form;
});
h.run_steps(30);
let rows: Vec<_> = h.get_all_by_role(eframe::egui::accesskit::Role::ListBoxOption).map(|n| n.rect()).collect();
assert!(!rows.is_empty(), "{size} {form:?}");
for r in &rows {
assert!(r.left() >= 64.0 && r.right() <= size.x, "{size} {form:?} {r}");
}
for (i, a) in rows.iter().enumerate() {
assert!(rows[..i].iter().all(|b| !a.shrink(0.5).intersects(*b)), "{size} {form:?} {a}");
}
}
}
}
fn top(h: &H, of: &str) -> f32 {
row(h, of).top()
}
#[test]
fn a_few_changes_move_and_many_do_not() {
let mut h = harness(simple(10));
let home = top(&h, "file-01.zip");
// One more, above all.
let mut views = simple(10);
let mut new = view(11, "new.zip", "a.example.org", State::Paused, 1000, 0.0);
Arc::make_mut(&mut new.task).position = 0.5;
views.push(new);
set(&mut h, views.clone());
h.step();
h.step();
let mid = top(&h, "file-01.zip");
assert!(mid > home - 12.0 && mid < home + 56.0, "{home} {mid}");
h.run_steps(120);
assert_eq!(top(&h, "file-01.zip"), home + 56.0);
assert!(app(&mut h).main.list.is_still() && !h.ctx.has_requested_repaint(), "at rest");
// To another state, under another heading.
Arc::make_mut(&mut views[4].task).state = State::Done;
set(&mut h, views.clone());
h.run_steps(2);
assert!(!app(&mut h).main.list.is_still());
h.run_steps(120);
assert!(app(&mut h).main.list.is_still());
// Gone.
views.remove(2);
set(&mut h, views.clone());
h.run_steps(2);
assert!(!app(&mut h).main.list.is_still());
h.run_steps(120);
// 40 at once.
views.extend((20..60).map(|id| view(id, &format!("bulk-{id}.zip"), "a.example.org", State::Paused, 1000, 0.0)));
set(&mut h, views);
h.run_steps(2);
assert!(app(&mut h).main.list.is_still());
}
#[test]
fn the_keyboard_moves_nothing() {
let mut h = harness(simple(10));
let at = name(&h, "file-02.zip");
click(&mut h, at);
key(&mut h, Modifiers::NONE, Key::Delete);
let mut views = simple(10);
views.remove(1);
set(&mut h, views);
h.run_steps(2);
assert!(app(&mut h).main.list.is_still());
}
#[test]
fn nothing_is_drawn_at_rest() {
let mut h = harness(simple(10));
h.run_steps(120);
assert!(!h.ctx.has_requested_repaint());
}
/// Milliseconds this thread has been on a core: other programs don't count.
fn cpu() -> f64 {
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").unwrap();
stat.split(' ').next().unwrap().parse::<f64>().unwrap() / 1.0e6
}
/// The CPU time of one frame, without drawing it on the screen. Numbers count in release: `--release -- --nocapture frame`.
#[test]
fn frame_of_ten_thousand_rows_is_quick() {
for form in [Form::Compact, Form::Cards] {
let mut h = harness_at(vec2(1600.0, 900.0), move |app| {
app.main.bridge = Bridge::still(many(10_000, 1), lists());
app.main.list.form = form;
});
let at = pos2(900.0, 600.0);
h.input_mut().events.push(Event::PointerMoved(at));
h.run_steps(30);
let mut views: Vec<Arc<TaskView>> = many(10_000, 1).iter().cloned().collect();
h.run_steps(30);
let mut measure = |h: &mut H, change: bool, state: bool| {
let mut times = vec![];
for i in 0..120u64 {
// Ten times a second the running ones have new numbers.
if change && i % 6 == 0 {
for v in &mut views[..8] {
let v = Arc::make_mut(v);
(v.rev, v.downloaded) = (i + 2, v.downloaded + 100_000);
if state {
Arc::make_mut(&mut v.task).notes = i.to_string();
}
}
app(h).main.bridge.set_still(views.iter().cloned().collect());
}
h.input_mut().events.push(Event::MouseWheel {
unit: eframe::egui::MouseWheelUnit::Point,
delta: vec2(0.0, -230.0),
phase: eframe::egui::TouchPhase::Move,
source: eframe::egui::MouseWheelSource::Trackpad,
modifiers: Modifiers::NONE,
});
let begun = cpu();
h.step();
times.push(cpu() - begun);
}
times.sort_by(f64::total_cmp);
(times[60], times[113], times[119])
};
let scrolling = measure(&mut h, false, false);
let both = measure(&mut h, true, false);
let all = measure(&mut h, true, true);
println!("{form:?}: scrolling median {:.2}, 95 % {:.2}, worst {:.2} ms; with changes {:.2}, {:.2}, {:.2} ms; with changes of tasks {:.2}, {:.2}, {:.2} ms", scrolling.0, scrolling.1, scrolling.2, both.0, both.1, both.2, all.0, all.1, all.2);
if !cfg!(debug_assertions) {
assert!(scrolling.1 < 8.0 && both.1 < 8.0 && all.1 < 8.0);
}
}
}
#[test]
fn the_real_engine_downloads_and_closes() {
let runtime = tokio::runtime::Runtime::new().unwrap();
let server = runtime.block_on(medlar_testserver::TestServer::start());
let dir = tempfile::tempdir().unwrap();
let at = |n: &str| dir.path().join(n);
let paths = Paths { config: at("config"), data: at("data"), state: at("state"), cache: at("cache"), portable: false };
paths.create().unwrap();
let folder = at("downloads");
let mut h = harness_at(vec2(1000.0, 700.0), |_| {});
let ctx = h.ctx.clone();
let settings = Settings { download_folder: folder.to_string_lossy().into(), ..Settings::default() };
app(&mut h).settings.download_folder = settings.download_folder.clone();
app(&mut h).main.bridge = Bridge::open(Opening { paths: paths.clone(), settings, bus: Bus::Off }, &ctx);
let until = |h: &mut H, what: &str, f: &dyn Fn(&H) -> bool| {
let end = Instant::now() + Duration::from_secs(60);
while !f(h) {
assert!(Instant::now() < end, "{what}");
std::thread::sleep(Duration::from_millis(20));
h.step();
}
};
until(&mut h, "the engine", &|h| h.state().as_ref().unwrap().main.bridge.manager().is_some());
let url = server.url(&medlar_testserver::TestServer::data_path(5, 2_000_000));
let task = Task { url, folder: folder.clone(), ..Task::default() };
app(&mut h).main.bridge.send(Command::Add(Box::new(task)));
until(&mut h, "the download", &|h| h.state().as_ref().unwrap().main.list.listing().rows.first().is_some_and(|v| v.state() == State::Done));
assert_eq!(std::fs::read_dir(&folder).unwrap().count(), 1);
// An order that can't be followed says why.
let id = app(&mut h).main.list.listing().rows[0].id();
app(&mut h).main.bridge.send(Command::Rename { id, name: "..".into() });
until(&mut h, "the error", &|h| !h.state().as_ref().unwrap().main.toasts.is_empty());
let begun = Instant::now();
app(&mut h).main.bridge.close();
assert!(begun.elapsed() < Duration::from_secs(3));
h.step();
}
#[test]
fn a_list_that_cannot_be_opened_says_so() {
let dir = tempfile::tempdir().unwrap();
let bad = dir.path().join("a file");
std::fs::write(&bad, "x").unwrap();
let paths = Paths { config: bad.clone(), data: bad.clone(), state: bad.clone(), cache: bad, portable: false };
let mut h = harness_at(vec2(1000.0, 700.0), |_| {});
let ctx = h.ctx.clone();
app(&mut h).main.bridge = Bridge::open(Opening { paths, settings: Settings::default(), bus: Bus::Off }, &ctx);
let end = Instant::now() + Duration::from_secs(20);
while h.query_by_label("Try again").is_none() {
assert!(Instant::now() < end);
std::thread::sleep(Duration::from_millis(20));
h.step();
}
assert!(!h.get_by_label("Try again").accesskit_node().is_disabled());
}