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

488 lines
21 KiB
Rust

//! The Add dialog: what is asked of servers, what comes of it, batches, duplicates, and going on from a new link.
#[path = "main/fixture.rs"]
mod fixture;
use eframe::egui::{Event, Key, Modifiers, PointerButton, Rect, Vec2, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use fixture::{MB, all, lists, shot};
use medlar_app::app::App;
use medlar_app::bridge::{Bridge, Opening};
use medlar_app::desktop::Sources;
use medlar_app::views::add::{Add, Look, Request, Twice, When};
use medlar_core::auth::Login;
use medlar_core::manager::{Command, Probed};
use medlar_core::model::{ErrorKind, Priority, State, Task, TaskId};
use medlar_core::net_state::Bus;
use medlar_core::paths::Paths;
use medlar_core::settings::{Motion, Settings};
use medlar_core::snapshot::TaskView;
use medlar_testserver::{Faults, TestServer, expected};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
type H = Harness<'static, Option<App>>;
fn bare(size: Vec2) -> 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 settings = Settings { motion: Motion::Normal, download_folder: "/home/you/Downloads".into(), ..Settings::default() };
*s = Some(App::new(ui.ctx(), settings, nowhere));
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(5);
h
}
fn harness(views: Vec<TaskView>) -> H {
let mut h = bare(vec2(1280.0, 1000.0));
app(&mut h).main.bridge = Bridge::still(shot(views), lists());
h.run_steps(30);
h
}
fn app(h: &mut H) -> &mut App {
h.state_mut().as_mut().unwrap()
}
fn now(h: &mut H) -> &mut Add {
app(h).main.adding.now().expect("the dialog")
}
fn ask(h: &mut H, text: &str) {
app(h).main.adding.ask(Request { text: text.into(), ..Request::default() });
h.run_steps(60);
}
/// Without any server.
fn still(h: &mut H, text: &str, set: impl FnOnce(&mut Add)) {
let app = app(h);
app.main.adding.open_still(Request { text: text.into(), ..Request::default() }, &app.settings, set);
h.run_steps(60);
}
/// The one on top.
fn last(h: &H, label: &str) -> Rect {
h.get_all_by_label(label).last().unwrap().rect()
}
fn click(h: &mut H, label: &str) {
let pos = last(h, label).center();
h.input_mut().events.push(Event::PointerMoved(pos));
for pressed in [true, false] {
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.step();
}
h.run_steps(60);
}
fn sent(h: &mut H) -> Vec<Command> {
app(h).main.bridge.take_sent()
}
fn added(h: &mut H) -> Vec<Task> {
let one = |c| match c {
Command::Add(task) => *task,
_ => panic!("another command"),
};
sent(h).into_iter().map(one).collect()
}
fn open(h: &mut H) -> bool {
h.query_all_by_label("Add downloads").count() > 0
}
fn disabled(h: &H, label: &str) -> bool {
h.get_by_label(label).accesskit_node().is_disabled()
}
fn file(name: &str, size: u64) -> Probed {
Probed { name: name.into(), size: Some(size), mime: None, ranges: true, page: false }
}
#[test]
fn one_link_with_all_that_can_be_said() {
let mut h = harness(all());
ask(&mut h, "");
assert!(disabled(&h, "Download"));
let add = now(&mut h);
add.text = "https://me:[email protected]/x.zip".into();
(add.queue, add.priority, add.limit, add.parts, add.when) = (2, Priority::High, 100.0, 3.0, When::Later);
add.referrer = "https://a.example.org/page".into();
add.agent = "Agent/1".into();
add.cookies = "sid=S3CRET".into();
add.headers = "X-Plain: yes\nAuthorization: Bearer S3CRET".into();
add.mirrors = "https://b.example.org/x.zip\nhttps://c.example.org/x.zip".into();
add.checksum = "AB".repeat(32);
add.proxy = "direct".into();
h.run_steps(60);
let (_, secrets) = now(&mut h).tasks();
click(&mut h, "Download");
assert!(!open(&mut h));
let [task] = &added(&mut h)[..] else { panic!("not one") };
assert_eq!((&*task.url, &*task.name, task.state), ("https://a.example.org/x.zip", "", State::Paused));
assert_eq!((task.queue, task.priority, task.speed_limit, task.max_parts), (2, Priority::High, Some(102_400), Some(3)));
assert_eq!(task.folder, PathBuf::from("/home/you/Downloads"));
assert_eq!((task.mirrors.len(), task.checksum.clone(), task.proxy.as_deref()), (2, Some(format!("sha256:{}", "ab".repeat(32))), Some("direct")));
assert_eq!(task.source_page.as_deref(), Some("https://a.example.org/page"));
let headers: Vec<_> = task.headers.iter().map(|(n, v)| format!("{n}={v}")).collect();
assert_eq!(headers, ["Referer=https://a.example.org/page", "User-Agent=Agent/1", "X-Plain=yes"]);
assert!(!format!("{task:?}").contains("S3CRET") && task.secret.as_ref().unwrap().starts_with("task:"));
let [(_, secret)] = &secrets[..] else { panic!("not one secret") };
assert_eq!((secret.login.as_ref().unwrap().user.as_str(), secret.cookies.as_deref()), ("me", Some("sid=S3CRET")));
assert_eq!((secret.home.as_deref(), secret.headers.len()), (Some("https://a.example.org/x.zip"), 1));
}
#[test]
fn what_is_wrong_is_said_and_nothing_is_added() {
let mut h = harness(all());
ask(&mut h, "https://a.example.org/x.zip");
type Case = (&'static str, fn(&mut Add));
let cases: [Case; 5] = [
("Each line is a name, a colon and a value", |a| a.headers = "no colon".into()),
("Not a checksum that Medlar knows", |a| a.checksum = "12".into()),
("Each line is one link", |a| a.mirrors = "not a link".into()),
("Not a time to come, such as 22:30 or 2026-12-24 08:00", |a| (a.when, a.at) = (When::At, "25:00".into())),
("The name can't be used for a file", |a| a.name = "..".into()),
];
for (words, set) in cases {
let add = now(&mut h);
(add.headers, add.checksum, add.mirrors, add.when) = (String::new(), String::new(), String::new(), When::Now);
add.more = true;
set(add);
h.run_steps(10);
assert!(disabled(&h, "Download"), "{words}");
assert!(words.starts_with("The name") || h.query_by_label(words).is_some(), "{words}");
}
now(&mut h).name = "x.zip".into();
h.run_steps(10);
h.key_press(Key::Escape);
h.run_steps(60);
assert!(!open(&mut h) && sent(&mut h).is_empty());
}
#[test]
fn patterns_lists_and_choosing_among_them() {
let mut h = harness(all());
ask(&mut h, "https://share.example.org/files/[098-103].jpg\nhttps://share.example.org/files/fonts-collection.zip\nno link here");
let add = now(&mut h);
assert_eq!((add.lines.len(), add.lines[3].url.as_str()), (7, "https://share.example.org/files/101.jpg"));
// The zip is in the list: it is skipped unless asked for.
assert!(add.lines[6].known.is_some() && !add.lines[6].on);
assert!(h.query_by_label("6 of 7 links chosen").is_some() && h.query_by_label("1 line without a link is left out.").is_some());
click(&mut h, "099.jpg");
click(&mut h, "Download 5");
let urls: Vec<_> = added(&mut h).into_iter().map(|t| t.url.rsplit('/').next().unwrap().to_string()).collect();
assert_eq!(urls, ["098.jpg", "100.jpg", "101.jpg", "102.jpg", "103.jpg"]);
ask(&mut h, "https://h.example.org/{a,b}/[1-2].zip\nhttps://share.example.org/files/fonts-collection.zip");
now(&mut h).twice = Twice::Download;
h.run_steps(5);
click(&mut h, "Download 5");
assert_eq!(added(&mut h).len(), 5);
// Brackets that are none.
ask(&mut h, "https://h.example.org/[1-2].zip");
assert!(now(&mut h).many());
click(&mut h, "Fill in patterns");
assert!(!now(&mut h).many());
click(&mut h, "Download");
assert_eq!(added(&mut h)[0].url, "https://h.example.org/[1-2].zip");
ask(&mut h, "https://h.example.org/[1-99999].zip");
assert!(h.query_by_label_contains("The first 10000 are taken").is_some());
click(&mut h, "Download 10000");
assert_eq!(added(&mut h).len(), 10_000);
}
#[test]
fn a_secret_of_many_links_stays_at_its_site() {
let mut h = harness(all());
ask(&mut h, "https://a.example.org/1\nhttps://a.example.org/2\nhttps://b.example.org/3\nhttps://me:[email protected]/4");
now(&mut h).login = Login { user: "u".into(), password: "p".into() };
let (tasks, secrets) = now(&mut h).tasks();
assert_eq!(secrets.len(), 2);
assert!(tasks[0].secret.is_some() && tasks[0].secret == tasks[1].secret);
assert_eq!(tasks[2].secret, None);
assert_eq!((secrets[1].1.login.as_ref().unwrap().user.as_str(), tasks[3].url.as_str()), ("me", "https://c.example.org/4"));
}
#[test]
fn lists_from_files() {
let dir = tempfile::tempdir().unwrap();
let list = dir.path().join("list.txt");
std::fs::write(&list, "https://a.example.org/[1-2].zip\nhttps://a.example.org/b.zip").unwrap();
let mut h = harness(all());
app(&mut h).main.adding.ask(Request { list: Some(list), ..Request::default() });
until(&mut h, "the list", |h| h.query_by_label("2 of 2 links chosen").is_some());
assert_eq!(now(&mut h).lines[0].url, "https://a.example.org/[1-2].zip");
h.key_press(Key::Escape);
h.run_steps(60);
app(&mut h).main.adding.ask(Request { list: Some(dir.path().into()), ..Request::default() });
until(&mut h, "the reason", |h| !h.state().as_ref().unwrap().main.toasts.is_empty());
}
#[test]
fn duplicates_are_resumed_shown_or_loaded_again() {
let mut h = harness(all());
let paused = "https://audio.example.edu/files/podcast-archive.flac";
ask(&mut h, paused);
assert!(h.query_by_label("Resume that download").is_some());
click(&mut h, "Resume");
assert!(matches!(sent(&mut h)[..], [Command::Resume(8)]));
ask(&mut h, paused);
click(&mut h, "Download as a new file");
click(&mut h, "Download");
assert_eq!(added(&mut h)[0].url, paused);
// Done: nothing to resume.
ask(&mut h, "https://images.example.org/files/wallpaper-forest.png");
assert!(h.query_by_label("Resume that download").is_none());
click(&mut h, "Show");
assert!(sent(&mut h).is_empty() && app(&mut h).main.list.chosen() == [11]);
// Only the name is the same: it gets a number, unless it gets another name.
let other = "https://other.example.net/wallpaper-forest.png";
ask(&mut h, other);
assert!(h.query_by_label("A download with this name is in the folder already. A new file gets a number.").is_none(), "the size is not known");
h.key_press(Key::Escape);
h.run_steps(60);
still(&mut h, other, |a| a.learned(file("wallpaper-forest.png", 5)));
assert!(now(&mut h).known.as_ref().unwrap().why.starts_with("A download with this name"));
click(&mut h, "Download");
assert_eq!(added(&mut h).len(), 1);
}
#[test]
fn an_unfinished_download_goes_on_first() {
let mut h = harness(all());
ask(&mut h, "https://files.example.com/files/report-final.docx?X-Amz-Date=20261125T120000Z&X-Amz-Expires=300&X-Amz-Signature=ab12");
let known = now(&mut h).known.as_ref().unwrap();
assert_eq!((known.task.id, &*known.why), (9, "An unfinished download has the same link, apart from its signature."));
assert!(h.query_by_label("Continue").is_some() && h.query_by_label("Download").is_none());
click(&mut h, "Download as a new file");
click(&mut h, "Download");
assert_eq!(added(&mut h).len(), 1);
// The same link with a new login: sent along, not simply resumed.
app(&mut h).main.adding.ask(Request { text: "https://files.example.com/files/report-final.docx".into(), cookies: Some("a=b".into()), ..Request::default() });
h.run_steps(60);
assert!(h.query_by_label("Continue").is_some());
}
#[test]
fn what_the_server_refuses_has_its_fix() {
let mut h = harness(all());
still(&mut h, "https://h.example.org/a.zip", |a| a.failed(ErrorKind::Login, "Login needed: h.example.org wants a user name and password."));
assert!(h.query_by_label("Login needed: h.example.org wants a user name and password.").is_some());
click(&mut h, "Sign in");
assert!(now(&mut h).more);
h.input_mut().events.push(Event::Text("me".into()));
h.run_steps(5);
assert_eq!(now(&mut h).login.user, "me");
click(&mut h, "Add anyway");
assert_eq!(added(&mut h).len(), 1);
still(&mut h, "https://h.example.org/a.zip", |a| {
a.referrer = "https://h.example.org/page".into();
a.failed(ErrorKind::Forbidden, "Not allowed: h.example.org refuses.");
});
assert!(h.query_by_label("Open its page").is_some());
}
#[test]
fn one_dialog_after_the_other_and_never_wider() {
let mut h = harness(all());
ask(&mut h, "https://a.example.org/1.zip");
ask(&mut h, "https://a.example.org/2.zip");
let width = |h: &H| last(h, "Links, one per line").width();
let before = width(&h);
let add = now(&mut h);
add.more = true;
add.name = "a-very-long-name".repeat(40);
add.failed(ErrorKind::Timeout, &"words ".repeat(200));
h.run_steps(30);
assert_eq!(width(&h), before);
now(&mut h).text = format!("https://a.example.org/{}.zip\nhttps://a.example.org/2", "x".repeat(900));
h.run_steps(30);
assert_eq!(width(&h), before);
h.key_press(Key::Escape);
h.run_steps(90);
assert_eq!(now(&mut h).text, "https://a.example.org/2.zip");
h.key_press(Key::Escape);
h.run_steps(90);
assert!(app(&mut h).main.adding.now().is_none());
}
#[test]
fn folders_are_remembered_by_type() {
let mut h = harness(all());
still(&mut h, "https://h.example.org/film.mkv", |a| a.learned(file("film.mkv", MB)));
let click_into = last(&h, "Folder").center();
h.input_mut().events.push(Event::PointerMoved(click_into));
for pressed in [true, false] {
h.input_mut().events.push(Event::PointerButton { pos: click_into, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.step();
}
(0..40).for_each(|_| h.key_press(Key::Backspace));
h.run_steps(100);
assert_eq!(now(&mut h).folder, "");
h.input_mut().events.push(Event::Text("/media/films".into()));
h.run_steps(5);
click(&mut h, "Download");
assert_eq!(added(&mut h)[0].folder, PathBuf::from("/media/films"));
still(&mut h, "https://h.example.org/other.mp4", |a| a.learned(file("other.mp4", MB)));
assert_eq!(now(&mut h).folder, "/media/films");
now(&mut h).text = "https://h.example.org/b.zip".into();
now(&mut h).learned(file("b.zip", MB));
h.run_steps(5);
assert_eq!(now(&mut h).folder, "/home/you/Downloads");
}
// With the engine.
struct Bench {
h: H,
server: TestServer,
dir: tempfile::TempDir,
_runtime: tokio::runtime::Runtime,
}
fn until(h: &mut H, what: &str, is: impl Fn(&H) -> bool) {
let end = Instant::now() + Duration::from_secs(60);
while !is(h) {
assert!(Instant::now() < end, "{what}");
std::thread::sleep(Duration::from_millis(16));
h.step();
}
}
impl Bench {
fn new() -> Bench {
let runtime = tokio::runtime::Runtime::new().unwrap();
let server = runtime.block_on(TestServer::start());
let dir = tempfile::tempdir().unwrap();
let at = |name: &str| dir.path().join(name);
let paths = Paths { config: at("config"), data: at("data"), state: at("state"), cache: at("cache"), portable: false };
paths.create().unwrap();
let mut h = bare(vec2(1280.0, 1000.0));
let ctx = h.ctx.clone();
let settings = Settings { download_folder: at("files").display().to_string(), motion: Motion::Normal, ..Settings::default() };
app(&mut h).settings = settings.clone();
app(&mut h).main.bridge = Bridge::open(Opening { paths, settings, bus: Bus::Off }, &ctx);
until(&mut h, "the engine", |h| h.state().as_ref().unwrap().main.bridge.manager().is_some());
Bench { h, server, dir, _runtime: runtime }
}
fn state(h: &H, id: TaskId) -> Option<(State, u64)> {
let manager = h.state().as_ref().unwrap().main.bridge.manager().unwrap();
manager.snapshot().get(id).map(|v| (v.state(), v.downloaded))
}
fn found(&mut self) -> Probed {
until(&mut self.h, "the answer", |h| h.query_by_label_contains("can be continued").is_some());
match &now(&mut self.h).look {
Look::Found(p) => p.clone(),
_ => panic!("no answer"),
}
}
/// A download that stands still with some of it here.
fn half(&mut self, path: &str) -> TaskId {
self.server.set_faults(path, Faults { throttle_total: Some(1 << 20), ..Faults::default() });
let folder = Path::new(&app(&mut self.h).settings.download_folder).to_path_buf();
let manager = app(&mut self.h).main.bridge.manager().unwrap();
let id = manager.send(Command::Add(Box::new(Task { url: self.server.url(path), folder, ..Task::default() }))).wait().unwrap();
until(&mut self.h, "some of it", |h| Bench::state(h, id).is_some_and(|s| s.1 > 300_000));
manager.send(Command::Pause(id)).wait().unwrap();
until(&mut self.h, "the pause", |h| Bench::state(h, id).is_some_and(|s| s.0 == State::Paused));
// The last bytes are saved when its connections have ended.
std::thread::sleep(Duration::from_millis(500));
id
}
}
#[test]
fn the_server_is_asked_as_you_type() {
let mut b = Bench::new();
let slow = "/data/5/8m/slow.bin";
b.server.set_faults(slow, Faults { latency_ms: Some(30_000), ..Faults::default() });
let url = b.server.url(slow);
ask(&mut b.h, &url);
until(&mut b.h, "the question", |h| h.query_by_label_contains("Asking").is_some());
// Another link is asked about at once.
let begun = Instant::now();
now(&mut b.h).text = b.server.url("/data/5/2m/quick.bin");
let found = b.found();
assert!(begun.elapsed() < Duration::from_secs(20));
assert_eq!((&*found.name, found.size, found.ranges), ("quick.bin", Some(2 << 20), true));
now(&mut b.h).text = b.server.url("/basic/me/S3CRET/data/5/1m/private.bin");
until(&mut b.h, "the refusal", |h| h.query_by_label("Sign in").is_some());
now(&mut b.h).login = Login { user: "me".into(), password: "S3CRET".into() };
assert_eq!(b.found().size, Some(1 << 20));
click(&mut b.h, "Download");
let files = b.dir.path().join("files/private.bin");
until(&mut b.h, "the file", |_| files.exists());
assert!(std::fs::read(&files).unwrap() == expected(5, 0, 1 << 20));
}
#[test]
fn a_new_link_is_compared_before_anything_changes() {
let mut b = Bench::new();
let id = b.half("/data/7/4m/film.bin");
let before = Bench::state(&b.h, id);
let url = |h: &H| h.state().as_ref().unwrap().main.bridge.manager().unwrap().snapshot().get(id).unwrap().task.url.clone();
let old = url(&b.h);
let task = (*app(&mut b.h).main.bridge.manager().unwrap().snapshot().get(id).unwrap().task).clone();
app(&mut b.h).main.adding.relink(&task);
b.h.run_steps(60);
// Another file.
app(&mut b.h).main.adding.relinking().unwrap().text = b.server.url("/data/8/4m/film.bin?etag=0&lm=0");
b.h.run_steps(2);
click(&mut b.h, "Check the link");
until(&mut b.h, "the verdict", |h| h.query_by_label_contains("Different file").is_some());
assert!((Bench::state(&b.h, id), url(&b.h)) == (before, old.clone()));
assert!(disabled(&b.h, "Continue"));
// The same one.
app(&mut b.h).main.adding.relinking().unwrap().text = b.server.url("/data/7/4m/film.bin?token=2");
b.h.run_steps(2);
click(&mut b.h, "Check the link");
until(&mut b.h, "the verdict", |h| h.query_by_label("Continue").is_some());
assert_eq!((Bench::state(&b.h, id), url(&b.h)), (before, old));
click(&mut b.h, "Continue");
until(&mut b.h, "the rest", |h| Bench::state(h, id).is_some_and(|s| s.0 == State::Done));
assert!(std::fs::read(b.dir.path().join("files/film.bin")).unwrap() == expected(7, 0, 4 << 20));
}
#[test]
fn the_add_dialog_continues_what_is_unfinished() {
let mut b = Bench::new();
let id = b.half("/data/9/4m/tape.bin");
let url = b.server.url("/data/9/4m/tape.bin?token=abc&expires=1764090000");
ask(&mut b.h, &url);
until(&mut b.h, "the match", |h| h.query_by_label("Continue").is_some());
click(&mut b.h, "Continue");
until(&mut b.h, "the rest", |h| Bench::state(h, id).is_some_and(|s| s.0 == State::Done));
assert_eq!(std::fs::read_dir(b.dir.path().join("files")).unwrap().count(), 1);
assert!(std::fs::read(b.dir.path().join("files/tape.bin")).unwrap() == expected(9, 0, 4 << 20));
}
#[test]
fn a_start_time_is_kept() {
let mut b = Bench::new();
let folder = b.dir.path().join("files");
let url = b.server.url("/data/3/100000/late.bin");
let at = medlar_core::model::now() + 1500;
let manager = app(&mut b.h).main.bridge.manager().unwrap();
let id = manager.send(Command::Add(Box::new(Task { url, folder, start_at: Some(at), ..Task::default() }))).wait().unwrap();
assert_eq!(Bench::state(&b.h, id).unwrap().0, State::Waiting);
until(&mut b.h, "the start", |h| Bench::state(h, id).is_some_and(|s| s.0 == State::Done));
assert!(medlar_core::model::now() >= at);
}