Removing unused code. Updating comments.

Removing timeout.  Updating tests now that downloads work.

Bumping version for async downloads.

Downloads run asynchronously.  Using aiohttp to make archive http request so ArchiveDownloader.do_download can be asynchronous.

Removing session for create_download(s) usages.

Reworkingk create_downloads to use optional_session.

Canceling download workers after tests and when stopping the manager.

All tests passing.

Tests pass!

Downloader tests pass.

DownloadManager uses multiple workers to download domains in parallel.
This commit is contained in:
Roland 2022-07-09 18:51:45 -06:00
parent 4cc7ef907f
commit b6b04f2739
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
23 changed files with 650 additions and 663 deletions

View file

@ -30,17 +30,16 @@ class ArchiveDownloader(Downloader, ABC):
"""
return True, None
def do_download(self, download: Download) -> DownloadResult:
async def do_download(self, download: Download) -> DownloadResult:
if download.attempts > 3:
raise UnrecoverableDownloadError(f'Max download attempts reached for {download.url}')
archive = lib.do_archive(download.url)
archive = await lib.do_archive(download.url)
return DownloadResult(success=True, location=f'/archive/{archive.id}')
@optional_session
def already_downloaded(self, url: str, session: Session = None) -> Optional[Archive]:
archive = session.query(Archive).filter_by(url=url).one_or_none()
return archive
def already_downloaded(self, url: str, session: Session = None) -> bool:
return bool(session.query(Archive).filter_by(url=url).count())
# Archive downloader is the last downloader which should be used.

View file

@ -1,8 +1,7 @@
import asyncio
from http import HTTPStatus
from requests import Request
from sanic import response
from sanic import response, Request
from sanic_ext import validate
from sanic_ext.extensions.openapi import openapi

View file

@ -10,14 +10,15 @@ from datetime import datetime
from itertools import groupby
from typing import Iterator, Optional, Tuple, List
import requests
import aiohttp
from bs4 import BeautifulSoup
from selenium import webdriver
from sqlalchemy.orm import Session
from modules.archive.models import Domain, Archive
from wrolpi.cmd import which
from wrolpi.common import get_media_directory, logger, chunks, extract_domain, chdir, escape_file_name, walk
from wrolpi.common import get_media_directory, logger, chunks, extract_domain, chdir, escape_file_name, walk, \
aiohttp_post
from wrolpi.dates import now, Seconds, local_timezone
from wrolpi.db import get_db_session, get_db_curs, get_ranked_models, optional_session
from wrolpi.errors import InvalidDomain, UnknownURL, InvalidArchive
@ -102,7 +103,7 @@ def get_new_archive_files(url: str, title: Optional[str]) -> ArchiveFiles:
ARCHIVE_TIMEOUT = Seconds.minute * 10 # Wait at most 10 minutes for response.
def request_archive(url: str):
async def request_archive(url: str):
"""
Send a request to the archive service to archive the URL.
"""
@ -110,18 +111,17 @@ def request_archive(url: str):
data = {'url': url}
try:
resp = requests.post(f'{ARCHIVE_SERVICE}/json', json=data, timeout=ARCHIVE_TIMEOUT)
contents, status = await aiohttp_post(f'{ARCHIVE_SERVICE}/json', json_=data, timeout=ARCHIVE_TIMEOUT)
readability = contents['readability']
# Compressed base64
singlefile = contents['singlefile']
screenshot = contents['screenshot']
logger.debug(f'archive request status code {status}')
except Exception as e:
logger.error('Error when requesting archive', exc_info=e)
raise
logger.debug(f'archive request status {resp.status_code=}')
readability = resp.json()['readability']
# Compressed base64
singlefile = resp.json()['singlefile']
screenshot = resp.json()['screenshot']
if not (screenshot or singlefile or readability):
raise Exception('singlefile response was empty!')
@ -147,8 +147,8 @@ def request_archive(url: str):
SINGLE_FILE_BIN = which('single-file',
'/usr/bin/single-file', # rpi ubuntu
'/usr/local/bin/single-file', # debian
'/usr/bin/single-file', # rpi ubuntu
'/usr/local/bin/single-file', # debian
warn=True)
CHROMIUM = which('chromium-browser', 'chromium',
'/usr/bin/chromium-browser', # rpi ubuntu
@ -194,8 +194,8 @@ def local_screenshot(url: str) -> bytes:
READABILITY_BIN = which('readability-extractor',
'/usr/bin/readability-extractor', # rpi ubuntu
'/usr/local/bin/readability-extractor', # debian
'/usr/bin/readability-extractor', # rpi ubuntu
'/usr/local/bin/readability-extractor', # debian
warn=True)
@ -227,7 +227,7 @@ def local_archive(url: str):
return singlefile, readability, screenshot
def do_archive(url: str) -> Archive:
async def do_archive(url: str) -> Archive:
"""
Perform the real archive request to the archiving service. Store the resulting data into files. Create an Archive
record in the DB. Create Domain/URL if missing.
@ -236,7 +236,7 @@ def do_archive(url: str) -> Archive:
if DOCKERIZED or PYTEST:
# Perform the archive in the Archive docker container. (Typically in the development environment).
singlefile, readability, screenshot = request_archive(url)
singlefile, readability, screenshot = await request_archive(url)
else:
# Perform the archive using locally installed executables.
singlefile, readability, screenshot = local_archive(url)

View file

@ -14,11 +14,11 @@ from wrolpi.dates import local_timezone
from wrolpi.db import get_db_session
from wrolpi.media_path import MediaPath
from wrolpi.root_api import CustomJSONEncoder
from wrolpi.test.common import TestAPI, wrap_test_db, skip_circleci
from wrolpi.test.common import skip_circleci
def make_fake_request_archive(readability=True, screenshot=True, title=True):
def fake_request_archive(_):
async def fake_request_archive(_):
singlefile = '<html>\ntest single-file\nジにてこちら\n<title>some title</title></html>'
r = dict(
content=f'<html>test readability content</html>',
@ -31,63 +31,61 @@ def make_fake_request_archive(readability=True, screenshot=True, title=True):
return fake_request_archive
class TestArchive(TestAPI):
@pytest.mark.asyncio
async def test_no_screenshot(test_session):
with mock.patch('modules.archive.lib.request_archive', make_fake_request_archive(screenshot=False)):
archive = await do_archive('https://example.com')
assert isinstance(archive.singlefile_path, MediaPath)
assert isinstance(archive.readability_path, MediaPath)
# Screenshot was empty
assert archive.screenshot_path is None
def setUp(self) -> None:
super().setUp()
(pathlib.Path(self.tmp_dir.name) / 'archive').mkdir(exist_ok=True)
@wrap_test_db
def test_no_screenshot(self):
with mock.patch('modules.archive.lib.request_archive', make_fake_request_archive(screenshot=False)):
archive = do_archive('https://example.com')
self.assertIsInstance(archive.singlefile_path, MediaPath)
self.assertIsInstance(archive.readability_path, MediaPath)
# Screenshot was empty
self.assertIsNone(archive.screenshot_path)
@pytest.mark.asyncio
async def test_no_readability(test_session):
with mock.patch('modules.archive.lib.request_archive', make_fake_request_archive(readability=False)):
archive = await do_archive('https://example.com')
assert isinstance(archive.singlefile_path, MediaPath)
assert isinstance(archive.screenshot_path, MediaPath)
# Readability empty
assert archive.readability_path is None
assert archive.readability_txt_path is None
@wrap_test_db
def test_no_readability(self):
with mock.patch('modules.archive.lib.request_archive', make_fake_request_archive(readability=False)):
archive = do_archive('https://example.com')
self.assertIsInstance(archive.singlefile_path, MediaPath)
self.assertIsInstance(archive.screenshot_path, MediaPath)
# Readability empty
self.assertIsNone(archive.readability_path)
self.assertIsNone(archive.readability_txt_path)
@wrap_test_db
def test_dict(self):
with mock.patch('modules.archive.lib.request_archive', make_fake_request_archive()):
d = do_archive('https://example.com').dict()
self.assertIsInstance(d, dict)
json.dumps(d, cls=CustomJSONEncoder)
@pytest.mark.asyncio
async def test_dict(test_session):
with mock.patch('modules.archive.lib.request_archive', make_fake_request_archive()):
d = (await do_archive('https://example.com')).dict()
assert isinstance(d, dict)
json.dumps(d, cls=CustomJSONEncoder)
@wrap_test_db
def test_relationships(self):
with get_db_session(commit=True) as session:
url = 'https://wrolpi.org:443'
domain = get_or_create_domain(session, url)
archive = Archive(
singlefile_path=f'{self.tmp_dir.name}/wrolpi.org:443/foo',
title='bar',
url=url,
domain_id=domain.id,
)
session.add(archive)
session.flush()
self.assertEqual(archive.domain, domain)
@pytest.mark.asyncio
async def test_relationships(test_session, test_directory):
with get_db_session(commit=True) as session:
url = 'https://wrolpi.org:443'
domain = get_or_create_domain(session, url)
archive = Archive(
singlefile_path=f'{test_directory.name}/wrolpi.org:443/foo',
title='bar',
url=url,
domain_id=domain.id,
)
session.add(archive)
session.flush()
@wrap_test_db
def test_validate_paths(self):
with mock.patch('modules.archive.lib.request_archive', make_fake_request_archive()):
archive = do_archive('https://example.com')
try:
with get_db_session(commit=True):
archive.singlefile_path = 'asdf'
except ValueError as e:
self.assertIn('relative', str(e), f'Relative path error was not raised')
assert archive.domain == domain
@pytest.mark.asyncio
async def test_validate_paths(test_session):
with mock.patch('modules.archive.lib.request_archive', make_fake_request_archive()):
archive = await do_archive('https://example.com')
try:
with get_db_session(commit=True):
archive.singlefile_path = 'asdf'
except ValueError as e:
assert 'relative' in str(e), f'Relative path error was not raised'
def test_archive_refresh_deleted_archive(test_session, archive_directory, archive_factory):
@ -225,10 +223,11 @@ def test_get_domains(test_session, archive_factory):
assert [i['domain'] for i in get_domains()] == []
def test_new_archive(test_session, fake_now):
@pytest.mark.asycio
async def test_new_archive(test_session, fake_now):
with mock.patch('modules.archive.lib.request_archive', make_fake_request_archive()):
fake_now(datetime(2000, 1, 1))
archive1 = do_archive('https://example.com')
archive1 = await do_archive('https://example.com')
# Everything is filled out.
assert isinstance(archive1, Archive)
assert archive1.archive_datetime is not None
@ -251,18 +250,19 @@ def test_new_archive(test_session, fake_now):
assert json.load(fh) == {'title': 'ジにてこちら', 'url': 'https://example.com'}
fake_now(datetime(2000, 1, 2))
archive2 = do_archive('https://example.com')
archive2 = await do_archive('https://example.com')
# Domain is reused.
assert archive1.domain == archive2.domain
def test_get_title_from_html(test_session, fake_now):
@pytest.mark.asyncio
async def test_get_title_from_html(test_session, fake_now):
fake_now(datetime(2000, 1, 1))
with mock.patch('modules.archive.lib.request_archive', make_fake_request_archive()):
archive = do_archive('example.com')
archive = await do_archive('example.com')
assert archive.title == 'ジにてこちら'
def fake_request_archive(_):
async def fake_request_archive(_):
singlefile = '<html>\ntest single-file\nジにてこちら\n<title>some title</title></html>'
r = dict(
content=f'<html>test readability content</html>',
@ -273,10 +273,10 @@ def test_get_title_from_html(test_session, fake_now):
fake_now(datetime(2000, 1, 2))
with mock.patch('modules.archive.lib.request_archive', fake_request_archive):
archive = do_archive('example.com')
archive = await do_archive('example.com')
assert archive.title == 'some title'
def fake_request_archive(_):
async def fake_request_archive(_):
singlefile = '<html></html>'
r = dict(
content=f'<html>missing a title</html>',
@ -287,7 +287,7 @@ def test_get_title_from_html(test_session, fake_now):
fake_now(datetime(2000, 1, 3))
with mock.patch('modules.archive.lib.request_archive', fake_request_archive):
archive = do_archive('example.com')
archive = await do_archive('example.com')
assert archive.title is None
@ -313,14 +313,15 @@ def test_get_new_archive_files(fake_now):
@skip_circleci
def test_title_in_filename(test_session, fake_now, test_directory):
@pytest.mark.asyncio
async def test_title_in_filename(test_session, fake_now, test_directory):
"""
The Archive files have the title in the path.
"""
fake_now(datetime(2000, 1, 1))
with mock.patch('modules.archive.lib.request_archive', make_fake_request_archive()):
archive1 = do_archive('example.com')
archive1 = await do_archive('example.com')
assert archive1.title == 'ジにてこちら'
@ -335,7 +336,7 @@ def test_title_in_filename(test_session, fake_now, test_directory):
assert str(archive1.screenshot_path.path.relative_to(test_directory)) == \
'archive/2000-01-01-00-00-00_ジにてこちら.png'
def fake_request_archive(_):
async def fake_request_archive(_):
singlefile = '<html>\ntest single-file\nジにてこちら\n</html>' # no title in HTML
r = dict(
# No Title from Readability.
@ -346,7 +347,7 @@ def test_title_in_filename(test_session, fake_now, test_directory):
return singlefile, r, s
with mock.patch('modules.archive.lib.request_archive', fake_request_archive):
archive2 = do_archive('example.com')
archive2 = await do_archive('example.com')
assert str(archive2.singlefile_path.path.relative_to(test_directory)) == \
'archive/2000-01-01-00-00-00_NA.html'
@ -359,7 +360,7 @@ def test_title_in_filename(test_session, fake_now, test_directory):
assert str(archive2.screenshot_path.path.relative_to(test_directory)) == \
'archive/2000-01-01-00-00-00_NA.png'
def fake_request_archive(_):
async def fake_request_archive(_):
singlefile = '<html>\ntest single-file\nジにてこちら\n<title>dangerous ;\\//_title</html></html>'
r = dict(
# No Title from Readability.
@ -370,7 +371,7 @@ def test_title_in_filename(test_session, fake_now, test_directory):
return singlefile, r, s
with mock.patch('modules.archive.lib.request_archive', fake_request_archive):
archive3 = do_archive('example.com')
archive3 = await do_archive('example.com')
assert str(archive3.singlefile_path.path.relative_to(test_directory)) == \
'archive/2000-01-01-00-00-00_dangerous ;_title.html'

View file

@ -199,4 +199,3 @@ def download_channel(id_: int):
raise InvalidDownload(f'Channel {channel.name} does not have a download!')
download.renew(reset_attempts=True)
session.commit()
download_manager.start_downloads()

View file

@ -6,6 +6,7 @@ from datetime import timedelta
from http import HTTPStatus
import mock
import pytest
from modules.videos.channel.lib import delete_channel
from modules.videos.common import get_no_channel_directory
@ -108,7 +109,8 @@ def test_channel_no_download_frequency(test_client, test_session, test_directory
assert response.status_code == HTTPStatus.NO_CONTENT, response.json
def test_channel_frequency_update(download_channel, test_client, test_session):
@pytest.mark.asyncio
def test_channel_frequency_update(download_channel, test_client, test_session, test_download_manager):
"""
A Channel's Download record is updated when the Channel's frequency is updated.
"""
@ -336,8 +338,12 @@ def test_channel_empty_url_doesnt_conflict(test_client, test_session, test_direc
assert location != response.headers['Location']
def test_download_channel_no_refresh(test_session, download_channel, video_download_manager):
@pytest.mark.asyncio
async def test_download_channel_no_refresh(test_session, download_channel, video_download_manager):
"""A Channel cannot be downloaded until it has been refreshed."""
d = download_channel.get_download()
d.next_download = video_download_manager.calculate_next_download(d)
test_session.commit()
def check_refreshed(expected: bool):
channel = test_session.query(Channel).one()
@ -349,7 +355,8 @@ def test_download_channel_no_refresh(test_session, download_channel, video_downl
with mock.patch('modules.videos.downloader.YDL.extract_info') as mock_extract_info:
mock_extract_info.return_value = {'entries': [], 'url': 'foo', 'uploader': 'some uploader',
'channel_id': 'the id', 'id': 'the id'}
video_download_manager.do_downloads_sync()
await video_download_manager.do_downloads()
await video_download_manager.wait_for_all_downloads()
check_refreshed(True)

View file

@ -140,9 +140,7 @@ def video_factory(test_session, test_directory):
@pytest.fixture
def video_download_manager(test_download_manager) -> DownloadManager:
"""
Get a DownloadManager ready to download Videos and Channels.
"""
"""Get a DownloadManager ready to download Videos and Channels."""
channel_downloader = ChannelDownloader()
video_downloader = VideoDownloader(priority=40)

View file

@ -81,7 +81,7 @@ class ChannelDownloader(Downloader, ABC):
# A playlist will have an id different from its channel.
return info['id'] != info['channel_id']
def do_download(self, download: Download) -> DownloadResult:
async def do_download(self, download: Download) -> DownloadResult:
"""Update a Channel's catalog, then schedule downloads of every missing video."""
info = extract_info(download.url, process=False)
# Resolve the entries generator.
@ -142,8 +142,9 @@ YT_DLP_BIN = which(
class VideoDownloader(Downloader, ABC):
"""
Download a single video. Store the video in its channel's directory, otherwise store it in `videos/NO CHANNEL`.
"""Downloads a single video.
Store the video in its channel's directory, otherwise store it in `videos/NO CHANNEL`.
"""
name = 'video'
pretty_name = 'Videos'
@ -152,13 +153,9 @@ class VideoDownloader(Downloader, ABC):
return f'<VideoDownloader>'
@optional_session
def already_downloaded(self, url: str, session: Session = None) -> Optional[Video]:
def already_downloaded(self, url: str, session: Session = None) -> bool:
# We only consider a video record with a video file as "downloaded".
video = session.query(Video).filter(
Video.url == url,
Video.video_path != None,
).one_or_none()
return video
return bool(session.query(Video).filter(Video.url == url, Video.video_path != None, ).count()) # noqa
@classmethod
def valid_url(cls, url) -> Tuple[bool, Optional[dict]]:
@ -177,7 +174,7 @@ class VideoDownloader(Downloader, ABC):
logger.debug(f'{cls.__name__} not suitable for {url}')
return False, None
def do_download(self, download: Download) -> DownloadResult:
async def do_download(self, download: Download) -> DownloadResult:
if download.attempts >= 10:
raise UnrecoverableDownloadError('Max download attempts reached')
@ -226,7 +223,7 @@ class VideoDownloader(Downloader, ABC):
'--compat-options', 'no-live-chat',
url,
)
return_code, logs = self.process_runner(url, cmd, out_dir)
return_code, logs = await self.process_runner(url, cmd, out_dir)
stdout = logs['stdout'].decode() if hasattr(logs['stdout'], 'decode') else logs['stdout']
stderr = logs['stderr'].decode() if hasattr(logs['stderr'], 'decode') else logs['stderr']
@ -293,6 +290,7 @@ class VideoDownloader(Downloader, ABC):
@staticmethod
def prepare_filename(url: str, out_dir: pathlib.Path) -> Tuple[pathlib.Path, dict]:
"""Get the full path of a video file from its URL."""
if not out_dir.is_dir():
raise ValueError(f'Output directory does not exist! {out_dir=}')
@ -300,7 +298,6 @@ class VideoDownloader(Downloader, ABC):
options = get_downloader_config().dict()
options['outtmpl'] = f'{out_dir}/{options["file_name_format"]}'
options['merge_output_format'] = PREFERRED_VIDEO_EXTENSION
logger.debug(f'Download video with options: {options}')
logger.debug(f'Downloading {url} to {out_dir}')

View file

@ -150,8 +150,9 @@ class TestVideosDownloaders(TestAPI):
self.assertEqual(self.mgr.get_downloader('https://www.youtube.com/watch?v=31jPEBiAC3c')[0], self.vd)
def test_video_download_no_channel(test_session, video_download_manager, video_factory, test_directory,
mock_video_extract_info, mock_video_process_runner):
@pytest.mark.asyncio
async def test_video_download_no_channel(test_session, video_download_manager, video_factory, test_directory,
mock_video_extract_info, mock_video_process_runner):
"""A video can be downloaded even if it does not have a Channel."""
channel_dir = test_directory / 'NO CHANNEL'
channel_dir.mkdir(parents=True)
@ -168,7 +169,8 @@ def test_video_download_no_channel(test_session, video_download_manager, video_f
mock_video_extract_info.return_value = info_json
with mock.patch('modules.videos.downloader.VideoDownloader.prepare_filename') as mock_prepare_filename:
mock_prepare_filename.return_value = (video_path, {'id': 'foo'})
video_download_manager.create_download(url, test_session)
video_download_manager.create_download(url)
await video_download_manager.wait_for_all_downloads()
mock_video_process_runner.assert_called_once()
@ -176,9 +178,10 @@ def test_video_download_no_channel(test_session, video_download_manager, video_f
assert str(video.video_path.path) == f'{channel_dir}/video.mp4'
def test_download_channel(test_session, simple_channel, video_download_manager, video_file,
mock_video_extract_info, mock_video_prepare_filename,
mock_video_process_runner):
@pytest.mark.asyncio
async def test_download_channel(test_session, simple_channel, video_download_manager, video_file,
mock_video_extract_info, mock_video_prepare_filename,
mock_video_process_runner):
"""Downloading (updating the catalog of) a Channel creates download records for all of it's missing videos."""
url = 'https://www.youtube.com/c/LearningSelfReliance/videos'
@ -186,7 +189,8 @@ def test_download_channel(test_session, simple_channel, video_download_manager,
mock_video_extract_info.return_value = example_channel_json
with mock.patch('modules.videos.downloader.get_channel') as mock_get_channel:
mock_get_channel.return_value = simple_channel
video_download_manager.create_download(url, test_session)
video_download_manager.create_download(url)
await video_download_manager.wait_for_all_downloads()
# Two videos are in the example channel.
downloads = video_download_manager.get_once_downloads(test_session)
@ -238,18 +242,22 @@ def test_get_or_create_channel(test_session):
assert get_or_create_channel(source_id='quux') == channel
def test_download_info_save(test_session, video_download_manager, mock_video_extract_info, mock_video_prepare_filename,
mock_video_process_runner):
@pytest.mark.asyncio
async def test_download_info_save(test_session, video_download_manager, mock_video_extract_info,
mock_video_prepare_filename,
mock_video_process_runner):
"""
An info dict from Downloader.valid_url is saved to the Downloader and can be used by the Downloader later.
"""
mock_video_extract_info.return_value = {'some': 'info'}
mock_video_prepare_filename.return_value = 'some path'
video_download_manager.create_download('https://www.youtube.com/watch?v=HQ_62YwcA80', test_session)
video_download_manager.create_download('https://www.youtube.com/watch?v=HQ_62YwcA80')
await video_download_manager.wait_for_all_downloads()
assert mock_video_extract_info.call_count == 2 # Only called twice. The "info" gathering call was skipped.
def test_selected_downloader(test_session, video_download_manager, successful_download):
@pytest.mark.asyncio
async def test_selected_downloader(test_session, video_download_manager, successful_download):
"""
A user can specify which Downloader to use, no other should ever be used (even if the Download fails).
"""
@ -267,7 +275,8 @@ def test_selected_downloader(test_session, video_download_manager, successful_do
# DownloadManager will attempt to choose the Downloader.
with mock.patch('modules.videos.downloader.YDL.extract_info') as mock_extract_info:
mock_extract_info.side_effect = UnsupportedError('not this one')
video_download_manager.create_download('https://example.com', test_session)
video_download_manager.create_download('https://example.com')
await video_download_manager.wait_for_all_downloads()
mock_http_valid_url.assert_called_once()
mock_extract_info.assert_called_once()
mock_do_download.assert_called_once()
@ -279,7 +288,8 @@ def test_selected_downloader(test_session, video_download_manager, successful_do
# DownloadManager will only use the HTTPDownloader.
with mock.patch('modules.videos.downloader.YDL.extract_info') as mock_extract_info:
video_download_manager.create_download('https://example.com', test_session, downloader='http')
video_download_manager.create_download('https://example.com', downloader='http')
await video_download_manager.wait_for_all_downloads()
# DownloadManager does not try to find the Download, it trusts the "downloader" param.
mock_extract_info.assert_not_called()
mock_http_valid_url.assert_not_called()
@ -294,7 +304,8 @@ def test_selected_downloader(test_session, video_download_manager, successful_do
# DownloadManager will only use the HTTPDownloader, even if the download fails.
with mock.patch('modules.videos.downloader.YDL.extract_info') as mock_extract_info:
mock_do_download.side_effect = Exception('oh no!')
video_download_manager.create_download('https://example.com', test_session, downloader='http')
video_download_manager.create_download('https://example.com', downloader='http')
await video_download_manager.wait_for_all_downloads()
# DownloadManager does not try to find the Download, it trusts the "downloader" param.
mock_extract_info.assert_not_called()
mock_http_valid_url.assert_not_called()
@ -312,12 +323,13 @@ def test_channel_downloader_hidden(video_download_manager):
assert [i.__json__() for i in downloaders] == [(dict(name='video', pretty_name='Videos')), ]
@pytest.mark.asyncio
def test_bad_downloader(test_session, video_download_manager):
"""
Attempting to use an unknown downloader should raise an error.
"""
with pytest.raises(InvalidDownload):
video_download_manager.create_download('https://example.com', test_session, 'bad downloader')
video_download_manager.create_download('https://example.com', downloader='bad downloader')
def test_channel_download_no_download(test_session, video_download_manager, simple_channel):
@ -332,22 +344,27 @@ def test_channel_download_no_download(test_session, video_download_manager, simp
download_channel(simple_channel.id)
def test_invalid_download_url(test_session, test_download_manager, mock_video_extract_info):
@pytest.mark.asyncio
async def test_invalid_download_url(test_session, test_download_manager, mock_video_extract_info):
"""An invalid url should not be attempted again."""
_, session = get_db_context()
with mock.patch('modules.videos.downloader.VideoDownloader.valid_url') as mock_valid_url, \
mock.patch('wrolpi.downloader.DownloadManager.get_downloader') as mock_get_downloader:
mock_get_downloader.return_value = (VideoDownloader(), None)
video_downloader = VideoDownloader()
test_download_manager.register_downloader(video_downloader)
mock_get_downloader.return_value = (video_downloader, None)
mock_valid_url.return_value = (True, {}) # url is valid, but is not a video URL.
mock_video_extract_info.side_effect = UnsupportedError('oops')
test_download_manager.create_download('invalid url', session)
test_download_manager.create_download('invalid url', downloader=VideoDownloader.name)
await test_download_manager.wait_for_all_downloads()
download = session.query(Download).one()
assert download.status == 'failed'
def test_video_download_1(test_session, test_directory, simple_channel, video_download_manager,
mock_video_process_runner):
@pytest.mark.asyncio
async def test_video_download_1(test_session, test_directory, simple_channel, video_download_manager,
mock_video_process_runner):
simple_channel.source_id = example_video_json['channel_id']
simple_channel.directory = test_directory / 'videos/channel name'
simple_channel.directory.mkdir(parents=True)
@ -361,7 +378,8 @@ def test_video_download_1(test_session, test_directory, simple_channel, video_do
mock_extract_info.return_value = example_video_json
mock_prepare_filename.return_value = (video_file, {'id': 'foo'})
video_download_manager.create_download(url, test_session)
video_download_manager.create_download(url)
await video_download_manager.wait_for_all_downloads()
mock_video_process_runner.assert_called_once()
video_url, _, out_dir = mock_video_process_runner.call_args[0]
@ -374,8 +392,9 @@ def test_video_download_1(test_session, test_directory, simple_channel, video_do
assert video.video_path.path.is_absolute()
def test_download_result(test_session, test_directory, video_download_manager, mock_video_process_runner,
mock_video_extract_info):
@pytest.mark.asyncio
async def test_download_result(test_session, test_directory, video_download_manager, mock_video_process_runner,
mock_video_extract_info):
"""VideoDownloader returns a DownloadResult when complete."""
channel_directory = test_directory / 'videos/channel name'
channel_directory.mkdir(parents=True)
@ -385,7 +404,8 @@ def test_download_result(test_session, test_directory, video_download_manager, m
mock_video_extract_info.return_value = example_video_json
with mock.patch('modules.videos.downloader.VideoDownloader.prepare_filename') as mock_prepare_filename:
mock_prepare_filename.return_value = [video_file, {'id': 'foo'}]
video_download_manager.create_download('https://example.com', test_session)
video_download_manager.create_download('https://example.com')
await video_download_manager.wait_for_all_downloads()
download: Download = test_session.query(Download).one()
assert download.url == 'https://example.com'
@ -451,7 +471,8 @@ example_playlist_json = {
}
def test_download_playlist(test_session, test_directory, mock_video_extract_info, video_download_manager):
@pytest.mark.asyncio
async def test_download_playlist(test_session, test_directory, mock_video_extract_info, video_download_manager):
"""
All videos in a playlist can be downloaded for it's Channel.
"""
@ -467,7 +488,7 @@ def test_download_playlist(test_session, test_directory, mock_video_extract_info
with mock.patch('modules.videos.downloader.VideoDownloader.do_download') as mock_video_do_download:
mock_video_do_download.return_value = DownloadResult(success=True) # Don't download the videos.
result = channel_downloader.do_download(download)
result = await channel_downloader.do_download(download)
assert result.success is True, 'Download was not successful'
assert set(result.downloads) == {
'https://youtube.com/watch?v=video_2_url',