Medlar/crates/core/tests/video.rs

180 lines
7.8 KiB
Rust

//! Video tasks in the manager, through a stub yt-dlp: progress, pause and resume, error kinds, what is kept. No real site.
use medlar_core::host::{Caps, Hosts};
use medlar_core::http::{ClientOptions, Shared, client};
use medlar_core::manager::*;
use medlar_core::model::*;
use medlar_core::settings::Limits;
use medlar_core::snapshot::{Snapshot, TaskView};
use medlar_core::store::Store;
use medlar_core::ytdlp::Choice;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::time::sleep;
const LIMITS: Limits = Limits { speed: 0, max_active: 2, max_connections: 32, parts_per_download: 4, connections_per_host: 16 };
/// Answers `--version`, `--dump-single-json` and downloads by the words in the link: `private`, `removed`, `slow` (the first
/// run hangs after some progress), `nothing` (no video site); anything else finishes. Its arguments go to `args`.
const STUB: &str = r#"#!/bin/sh
case "$*" in *--version*) echo 2024.08.06; exit 0;; esac
S='@DIR@'
prev=; dir=; url=
for a in "$@"; do [ "$prev" = "-P" ] && dir="$a"; prev="$a"; url="$a"; done
case "$*" in *--dump-single-json*)
case "$url" in *nothing*) echo "ERROR: Unsupported URL: $url" >&2; exit 1;; esac
echo '{"title":"Clip","formats":[{"format_id":"v","ext":"mp4","height":720,"vcodec":"avc1","acodec":"mp4a","filesize":1000}]}'
exit 0;;
esac
echo "$*" >> "$S/args"
n=$(wc -l < "$S/args")
case "$url" in
*private*) echo "ERROR: [site] x: Private video. Sign in if you've been granted access to this video" >&2; exit 1;;
*removed*) echo "ERROR: [site] x: Video unavailable. This video has been removed by the uploader" >&2; exit 1;;
*slow*) if [ "$n" = 1 ]; then echo 'MEDLAR:400|1000|NA|100|6|NA|NA|NA|NA'; echo $$ > "$S/pid"; exec sleep 60; fi;;
esac
echo 'MEDLAR:500|1000|NA|100|5|NA|NA|NA|NA'
sleep 0.2
mkdir -p "$dir"
head -c 1000 /dev/zero > "$dir/Clip [x].mp4"
echo "MEDLAR-FILE:$dir/Clip [x].mp4"
"#;
fn ms(n: u64) -> Duration {
Duration::from_millis(n)
}
struct Bench {
dir: tempfile::TempDir,
manager: Manager,
}
impl Bench {
fn new() -> Bench {
let dir = tempfile::tempdir().unwrap();
let stub = dir.path().join("yt-dlp");
std::fs::write(&stub, STUB.replace("@DIR@", &dir.path().display().to_string())).unwrap();
std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();
let manager = Manager::open(Bench::config(dir.path(), Some(stub))).unwrap();
Bench { dir, manager }
}
fn config(dir: &Path, ytdlp: Option<PathBuf>) -> Config {
let store = Arc::new(Store::open(&dir.join("medlar.db")).unwrap());
let client = client(&ClientOptions::default()).unwrap();
let hosts = Hosts::new(Caps::default());
let mut config = Config::new(Shared { client, store, hosts }, LIMITS);
(config.bin, config.tick, config.ytdlp) = (Bin::at(dir.join("Trash")), ms(20), ytdlp);
config
}
/// Ends the program and starts it again with `ytdlp`.
fn restart(self, ytdlp: Option<PathBuf>) -> Bench {
let Bench { dir, manager } = self;
drop(manager);
Bench { manager: Manager::open(Bench::config(dir.path(), ytdlp)).unwrap(), dir }
}
fn files(&self) -> PathBuf {
self.dir.path().join("files")
}
async fn add(&self, what: &str, choice: Choice) -> TaskId {
let task = Task { url: format!("https://video.test/{what}"), name: "Clip".into(), folder: self.files(), video: Some(choice), ..Task::default() };
self.manager.send(Command::Add(Box::new(task))).await.unwrap()
}
fn view(&self, id: TaskId) -> Arc<TaskView> {
self.manager.snapshot().get(id).unwrap().clone()
}
fn args(&self) -> Vec<String> {
std::fs::read_to_string(self.dir.path().join("args")).unwrap_or_default().lines().map(String::from).collect()
}
async fn until(&self, what: &str, is: impl Fn(&Snapshot) -> bool) {
let end = Instant::now() + Duration::from_secs(20);
while !is(&self.manager.snapshot()) {
let states: Vec<_> = self.manager.snapshot().iter().map(|v| (v.id(), v.state(), v.task.error.clone())).collect();
assert!(Instant::now() < end, "never {what}: {states:?}");
sleep(ms(5)).await;
}
}
async fn until_state(&self, id: TaskId, state: State) {
self.until(state.name(), |s| s.get(id).is_some_and(|v| v.state() == state)).await;
}
async fn kind(&self, id: TaskId) -> Option<ErrorKind> {
self.until_state(id, State::Failed).await;
self.view(id).task.error.as_ref().and_then(|e| e.kind)
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_video_is_downloaded_and_named_by_its_file() {
let b = Bench::new();
let choice = Choice { height: Some(720), subtitles: vec!["en".into()], ..Choice::default() };
let id = b.add("clip", choice.clone()).await;
b.until_state(id, State::Done).await;
let v = b.view(id);
assert_eq!((&*v.task.name, v.task.size, v.downloaded), ("Clip [x].mp4", Some(1000), 1000), "{:#?}", v.log);
assert_eq!(std::fs::metadata(b.files().join("Clip [x].mp4")).unwrap().len(), 1000);
let [args] = &b.args()[..] else { panic!("not one run: {:?}", b.args()) };
assert!(args.contains("height<=720") && args.contains("--sub-langs en") && args.contains("--no-playlist"), "{args}");
assert!(args.ends_with("-- https://video.test/clip"), "{args}");
// The choice is kept.
let b = b.restart(None);
let v = b.view(id);
assert_eq!((v.state(), v.task.video.as_ref()), (State::Done, Some(&choice)));
}
#[tokio::test(flavor = "multi_thread")]
async fn pause_ends_the_program_and_resume_goes_on() {
let b = Bench::new();
let id = b.add("slow", Choice::default()).await;
b.until("under way", |s| s.get(id).is_some_and(|v| v.downloaded == 400 && v.state() == State::Running)).await;
let pid = std::fs::read_to_string(b.dir.path().join("pid")).unwrap().trim().to_string();
b.manager.send(Command::Pause(id)).await.unwrap();
assert_eq!(b.view(id).state(), State::Paused);
let end = Instant::now() + Duration::from_secs(5);
while Path::new(&format!("/proc/{pid}")).exists() {
assert!(Instant::now() < end, "yt-dlp {pid} still runs after the pause");
sleep(ms(20)).await;
}
b.manager.send(Command::Resume(id)).await.unwrap();
b.until_state(id, State::Done).await;
let args = b.args();
assert_eq!(args.len(), 2, "{args:?}");
assert!(args.iter().all(|a| a.contains("--continue")), "{args:?}");
assert_eq!(b.view(id).counters.runs, 2);
}
#[tokio::test(flavor = "multi_thread")]
async fn failures_have_kinds() {
let b = Bench::new();
let private = b.add("private", Choice::default()).await;
let removed = b.add("removed", Choice::default()).await;
assert_eq!(b.kind(private).await, Some(ErrorKind::Login));
assert_eq!(b.kind(removed).await, Some(ErrorKind::NotFound));
let detail = b.view(private).task.error.clone().unwrap().detail;
assert!(!detail.is_empty() && !detail.starts_with("error."), "{detail}");
// Without a working yt-dlp it says so.
let b = b.restart(Some(PathBuf::from("/nonexistent/yt-dlp")));
b.manager.send(Command::Resume(removed)).await.unwrap();
assert_eq!(b.kind(removed).await, Some(ErrorKind::Tool));
}
#[tokio::test(flavor = "multi_thread")]
async fn the_page_is_asked_without_adding() {
let b = Bench::new();
let probe = b.manager.probe_video("https://video.test/clip".into(), None).await.unwrap();
assert_eq!((&*probe.title, probe.formats.len()), ("Clip", 1));
match b.manager.probe_video("https://video.test/nothing".into(), None).await {
Err(Error::Link(f)) => assert_eq!(f.kind, ErrorKind::BadLink),
other => panic!("{:?}", other.map(|p| p.title.clone())),
}
assert!(b.manager.snapshot().iter().next().is_none() && b.args().is_empty());
}