Files
SanctuaryCommander/test/youtube_download_job_test.py
T

350 lines
17 KiB
Python

from contextlib import closing
import json
from pathlib import Path
import sqlite3
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
from youtube_downloader import claim_next_job, download_video, main, process_next_job
GENERATOR = Path(__file__).resolve().parents[1] / "sc_database_generator.py"
class YouTubeDownloadJobTest(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
self.workdir = Path(self.directory.name)
(self.workdir / "config.json").write_text(json.dumps({
"database": {"type": "SQLite", "name": "test.db"}
}))
self.initialize_database()
self.db = sqlite3.connect(self.workdir / "test.db")
self.addCleanup(self.db.close)
def initialize_database(self):
subprocess.run(
[sys.executable, str(GENERATOR)],
cwd=self.workdir,
check=True,
capture_output=True,
text=True
)
def insert_job(self, url="https://www.youtube.com/watch?v=test"):
return self.db.execute(
"INSERT INTO youtube_download_job (youtube_download_job_url) VALUES (?)",
[url]
).lastrowid
def test_new_job_defaults_to_pending(self):
job_id = self.insert_job()
self.assertEqual(self.db.execute(
"SELECT youtube_download_job_id, youtube_download_job_url, youtube_download_job_status "
"FROM youtube_download_job WHERE youtube_download_job_id = ?",
[job_id]
).fetchone(), (job_id, "https://www.youtube.com/watch?v=test", "pending"))
def test_job_can_be_marked_downloading_and_downloaded(self):
job_id = self.insert_job()
for status in ("downloading", "downloaded"):
self.db.execute(
"UPDATE youtube_download_job SET youtube_download_job_status = ? "
"WHERE youtube_download_job_id = ?",
[status, job_id]
)
self.assertEqual(self.db.execute(
"SELECT youtube_download_job_status FROM youtube_download_job "
"WHERE youtube_download_job_id = ?", [job_id]
).fetchone()[0], status)
def test_invalid_or_null_status_is_rejected(self):
for status in ("unknown", None):
with self.subTest(status=status):
with self.assertRaises(sqlite3.IntegrityError):
self.db.execute(
"INSERT INTO youtube_download_job "
"(youtube_download_job_url, youtube_download_job_status) VALUES (?, ?)",
["https://www.youtube.com/watch?v=test", status]
)
def test_retry_count_defaults_to_zero_and_rejects_invalid_values(self):
job_id = self.insert_job()
self.assertEqual(self.db.execute(
'SELECT youtube_download_job_retry_count FROM youtube_download_job'
).fetchone(), (0,))
for count in (-1, None, 1.5):
with self.subTest(count=count):
with self.assertRaises(sqlite3.IntegrityError):
self.db.execute(
'UPDATE youtube_download_job SET youtube_download_job_retry_count = ? '
'WHERE youtube_download_job_id = ?', [count, job_id]
)
def test_retry_limit_marks_failed_and_moves_to_next_job(self):
first = self.insert_job()
second = self.insert_job()
self.db.commit()
for failure_count in range(1, 5):
with patch('youtube_downloader.download_video', side_effect=OSError('Unavailable')):
with self.assertLogs('youtube_downloader', level='ERROR'):
self.assertFalse(process_next_job(self.db, self.workdir, max_retries=3))
expected_status = 'pending' if failure_count <= 3 else 'failed'
self.assertEqual(self.db.execute(
'SELECT youtube_download_job_status, youtube_download_job_retry_count '
'FROM youtube_download_job WHERE youtube_download_job_id = ?', [first]
).fetchone(), (expected_status, failure_count))
self.assertEqual(claim_next_job(self.db)[0], second)
self.assertIsNone(claim_next_job(self.db))
self.assertEqual(self.db.execute('SELECT COUNT(*) FROM media').fetchone(), (0,))
def test_zero_retries_fails_after_first_attempt(self):
self.insert_job()
self.db.commit()
with patch('youtube_downloader.download_video', side_effect=OSError('Unavailable')):
with self.assertLogs('youtube_downloader', level='ERROR'):
self.assertFalse(process_next_job(self.db, self.workdir, max_retries=0))
self.assertEqual(self.db.execute(
'SELECT youtube_download_job_status, youtube_download_job_retry_count FROM youtube_download_job'
).fetchone(), ('failed', 1))
with patch('youtube_downloader.download_video') as download:
self.assertFalse(process_next_job(self.db, self.workdir, max_retries=0))
download.assert_not_called()
def test_pending_jobs_above_new_limit_are_skipped(self):
first = self.insert_job()
second = self.insert_job()
self.db.execute(
'UPDATE youtube_download_job SET youtube_download_job_retry_count = 3 '
'WHERE youtube_download_job_id = ?', [first]
)
self.db.commit()
self.assertEqual(claim_next_job(self.db, max_retries=1)[0], second)
self.assertEqual(self.db.execute(
'SELECT youtube_download_job_status FROM youtube_download_job '
'WHERE youtube_download_job_id = ?', [first]
).fetchone(), ('failed',))
def test_retry_count_persists_and_success_does_not_increment_it(self):
self.insert_job()
self.db.commit()
with patch('youtube_downloader.download_video', side_effect=OSError('Unavailable')):
with self.assertLogs('youtube_downloader', level='ERROR'):
process_next_job(self.db, self.workdir)
with closing(sqlite3.connect(self.workdir / 'test.db')) as restarted:
self.assertEqual(restarted.execute(
'SELECT youtube_download_job_retry_count FROM youtube_download_job'
).fetchone(), (1,))
with patch('youtube_downloader.download_video', return_value=(self.workdir / 'video.mp4', 'Title')):
self.assertTrue(process_next_job(restarted, self.workdir))
self.assertEqual(self.db.execute(
'SELECT youtube_download_job_status, youtube_download_job_retry_count FROM youtube_download_job'
).fetchone(), ('downloaded', 1))
def test_url_is_required(self):
with self.assertRaises(sqlite3.IntegrityError):
self.insert_job(url=None)
def test_initialization_preserves_existing_records(self):
self.insert_job()
self.db.execute(
"INSERT INTO media (media_name, media_uri) VALUES (?, ?)",
["Existing stream", "https://example.com/stream"]
)
self.db.execute(
"INSERT INTO media_playback_option "
"(media_id, media_playback_option, media_playback_option_weight) "
"VALUES (1, '-fs', 1)"
)
self.db.commit()
tables = ("media", "media_playback_option", "youtube_download_job")
before = {table: self.db.execute(f"SELECT * FROM {table}").fetchall() for table in tables}
self.initialize_database()
after = {table: self.db.execute(f"SELECT * FROM {table}").fetchall() for table in tables}
self.assertEqual(before, after)
self.assertEqual(self.db.execute(
"SELECT name FROM sqlite_master WHERE type='table' "
"AND name NOT LIKE 'sqlite_%' ORDER BY name"
).fetchall(), [(table,) for table in tables])
def test_old_schema_is_migrated_without_losing_jobs(self):
self.db.execute('DROP TABLE youtube_download_job')
self.db.execute("""
CREATE TABLE youtube_download_job (
youtube_download_job_id INTEGER PRIMARY KEY AUTOINCREMENT,
youtube_download_job_url TEXT NOT NULL,
youtube_download_job_status TEXT NOT NULL DEFAULT 'pending'
CHECK(youtube_download_job_status IN ('pending', 'downloading', 'downloaded'))
)
""")
job_id = self.insert_job()
self.db.commit()
self.initialize_database()
self.assertEqual(self.db.execute(
'SELECT youtube_download_job_media_name FROM youtube_download_job '
'WHERE youtube_download_job_id = ?', [job_id]
).fetchone(), ('',))
def test_previous_schema_migration_preserves_jobs_and_sequence(self):
self.db.execute('DROP TABLE youtube_download_job')
self.db.execute("""
CREATE TABLE youtube_download_job (
youtube_download_job_id INTEGER PRIMARY KEY AUTOINCREMENT,
youtube_download_job_url TEXT NOT NULL,
youtube_download_job_media_name TEXT NOT NULL DEFAULT '',
youtube_download_job_status TEXT NOT NULL DEFAULT 'pending'
CHECK(youtube_download_job_status IN ('pending', 'downloading', 'downloaded'))
)
""")
for status in ('pending', 'downloading', 'downloaded'):
self.db.execute(
'INSERT INTO youtube_download_job (youtube_download_job_url, '
'youtube_download_job_media_name, youtube_download_job_status) VALUES (?, ?, ?)',
['https://youtu.be/test', 'Saved name', status]
)
deleted_id = self.insert_job()
self.db.execute('DELETE FROM youtube_download_job WHERE youtube_download_job_id = ?', [deleted_id])
self.db.commit()
before = self.db.execute('SELECT * FROM youtube_download_job ORDER BY 1').fetchall()
self.initialize_database()
self.assertEqual(self.db.execute(
'SELECT youtube_download_job_id, youtube_download_job_url, youtube_download_job_media_name, '
'youtube_download_job_status FROM youtube_download_job ORDER BY 1'
).fetchall(), before)
self.assertEqual(self.db.execute(
'SELECT youtube_download_job_retry_count FROM youtube_download_job'
).fetchall(), [(0,), (0,), (0,)])
self.assertGreater(self.insert_job(), deleted_id)
self.db.execute("UPDATE youtube_download_job SET youtube_download_job_status = 'failed'")
self.db.commit()
self.initialize_database()
self.assertEqual(self.db.execute(
"SELECT COUNT(*) FROM youtube_download_job WHERE youtube_download_job_status = 'failed'"
).fetchone(), (4,))
def test_claims_oldest_pending_job_only_once(self):
first = self.insert_job()
second = self.insert_job()
self.db.commit()
self.assertEqual(claim_next_job(self.db)[0], first)
with closing(sqlite3.connect(self.workdir / 'test.db')) as other_worker:
self.assertEqual(claim_next_job(other_worker)[0], second)
self.assertIsNone(claim_next_job(other_worker))
def test_success_registers_local_file_and_requested_name(self):
job_id = self.insert_job()
self.db.execute(
'UPDATE youtube_download_job SET youtube_download_job_media_name = ?',
['My video']
)
self.db.commit()
storage = self.workdir / 'Videos'
def fake_download(command, **kwargs):
storage.mkdir(exist_ok=True)
path = storage / f'job-{job_id}.mkv'
path.touch()
return subprocess.CompletedProcess(command, 0, json.dumps({
'filepath': str(path), 'title': 'YouTube title'
}), '')
with patch('youtube_downloader.subprocess.run', side_effect=fake_download) as run:
self.assertTrue(process_next_job(self.db, storage))
self.assertEqual(run.call_args.args[0][-2:], ['--', 'https://www.youtube.com/watch?v=test'])
self.assertIn('--no-playlist', run.call_args.args[0])
self.assertEqual(self.db.execute('SELECT media_name, media_uri FROM media').fetchall(),
[('My video', str(storage / f'job-{job_id}.mkv'))])
self.assertEqual(self.db.execute(
'SELECT youtube_download_job_status FROM youtube_download_job'
).fetchone(), ('downloaded',))
with patch('youtube_downloader.subprocess.run') as run:
self.assertFalse(process_next_job(self.db, storage))
run.assert_not_called()
def test_blank_name_uses_video_title(self):
self.insert_job()
self.db.commit()
path = self.workdir / 'video.mp4'
with patch('youtube_downloader.download_video', return_value=(path, 'Video title')):
self.assertTrue(process_next_job(self.db, self.workdir))
self.assertEqual(self.db.execute('SELECT media_name FROM media').fetchone(), ('Video title',))
def test_failed_download_returns_to_pending_without_media(self):
self.insert_job()
self.db.commit()
errors = [FileNotFoundError('yt-dlp missing'),
subprocess.CalledProcessError(1, ['yt-dlp'], stderr='Download failed')]
for error in errors:
with self.subTest(error=error):
with patch('youtube_downloader.subprocess.run', side_effect=error):
with self.assertLogs('youtube_downloader', level='ERROR'):
self.assertFalse(process_next_job(self.db, self.workdir))
self.assertEqual(self.db.execute('SELECT COUNT(*) FROM media').fetchone(), (0,))
self.assertEqual(self.db.execute(
'SELECT youtube_download_job_status FROM youtube_download_job'
).fetchone(), ('pending',))
def test_missing_or_outside_download_file_is_rejected(self):
for path in (self.workdir / 'Videos' / 'missing.mp4', GENERATOR):
with self.subTest(path=path):
result = subprocess.CompletedProcess([], 0, json.dumps({
'filepath': str(path), 'title': 'Title'
}), '')
with patch('youtube_downloader.subprocess.run', return_value=result):
with self.assertRaises(ValueError):
download_video(1, 'https://youtu.be/test', self.workdir / 'Videos')
def test_interrupt_releases_job_without_registering_media(self):
self.insert_job()
self.db.commit()
with patch('youtube_downloader.download_video', side_effect=KeyboardInterrupt):
with self.assertRaises(KeyboardInterrupt):
process_next_job(self.db, self.workdir)
self.assertEqual(self.db.execute(
'SELECT youtube_download_job_status FROM youtube_download_job'
).fetchone(), ('pending',))
self.assertEqual(self.db.execute('SELECT COUNT(*) FROM media').fetchone(), (0,))
self.assertEqual(self.db.execute(
'SELECT youtube_download_job_retry_count FROM youtube_download_job'
).fetchone(), (0,))
@patch('youtube_downloader.logging.basicConfig')
def test_main_polls_with_paths_relative_to_config(self, configure_logging):
(self.workdir / 'config.json').write_text(json.dumps({
'database': {'type': 'SQLite', 'name': 'test.db'},
'youtube_download_location': 'CustomVideos',
'youtube_download_max_retries': 2
}))
with patch('sys.argv', ['youtube_downloader.py', '--config',
str(self.workdir / 'config.json'), '--poll-interval', '2']):
with patch('youtube_downloader.process_next_job', return_value=False) as process:
with patch('youtube_downloader.time.sleep', side_effect=KeyboardInterrupt) as sleep:
with self.assertLogs('youtube_downloader', level='INFO'):
main()
self.assertEqual(process.call_args.args[1], self.workdir / 'CustomVideos')
self.assertEqual(process.call_args.args[2], 2)
self.assertTrue((self.workdir / 'CustomVideos').is_dir())
sleep.assert_called_once_with(2.0)
def test_media_insert_is_rolled_back_if_job_update_fails(self):
self.insert_job()
self.db.execute("""
CREATE TRIGGER reject_completion BEFORE UPDATE ON youtube_download_job
WHEN NEW.youtube_download_job_status = 'downloaded'
BEGIN SELECT RAISE(ABORT, 'Simulated database failure'); END
""")
self.db.commit()
with patch('youtube_downloader.download_video', return_value=(self.workdir / 'file.mp4', 'Title')):
with self.assertLogs('youtube_downloader', level='ERROR'):
self.assertFalse(process_next_job(self.db, self.workdir))
self.assertEqual(self.db.execute('SELECT COUNT(*) FROM media').fetchone(), (0,))
self.assertEqual(self.db.execute(
'SELECT youtube_download_job_status FROM youtube_download_job'
).fetchone(), ('pending',))
if __name__ == "__main__":
unittest.main()