Adding Download.is_new/etc. for code suggestions. Fixing async test warnings.

This commit is contained in:
Roland 2023-09-20 12:58:35 -06:00
parent 351351d90c
commit b817534c37
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
11 changed files with 48 additions and 67 deletions

View file

@ -224,7 +224,7 @@ def get_title_from_html(html: str, url: str = None) -> str:
try:
return soup.title.string
except Exception: # noqa
logger.info(f'Unable to extract title {url}')
logger.debug(f'Unable to extract title {url}')
@optional_session

View file

@ -169,7 +169,7 @@ def test_archive_refresh_deleted_archive(test_client, test_session, archive_dire
@pytest.mark.asyncio
async def test_fills_contents_with_refresh(test_client, test_session, archive_factory, singlefile_contents_factory):
async def test_fills_contents_with_refresh(test_session, archive_factory, singlefile_contents_factory):
"""Refreshing archives fills in any missing contents."""
archive1 = archive_factory('example.com', 'https://example.com/one')
archive2 = archive_factory('example.com', 'https://example.com/one')
@ -277,7 +277,7 @@ def test_get_domains(test_session, archive_factory):
assert [i['domain'] for i in get_domains()] == []
@pytest.mark.asycio
@pytest.mark.asyncio
async def test_new_archive(test_session, fake_now):
singlefile, readability, screenshot = make_fake_archive_result()
fake_now(datetime(2000, 1, 1))
@ -521,7 +521,7 @@ def test_refresh_archives(test_session, test_directory, test_client, make_files_
@pytest.mark.asyncio
async def test_refresh_archives_index(test_session, test_directory, test_client, make_files_structure):
async def test_refresh_archives_index(test_session, make_files_structure):
"""Archives are indexed using ArchiveIndexer and archive_modeler."""
# The start of a typical singlefile html file.
singlefile_contents = '''<!DOCTYPE html> <html lang="en"><!--

View file

@ -89,7 +89,7 @@ def test_channel_no_download_frequency(test_client, test_session, test_directory
@pytest.mark.asyncio
def test_channel_frequency_update(download_channel, test_client, test_session, test_download_manager):
async def test_channel_frequency_update(download_channel, test_async_client, test_session, test_download_manager):
"""
A Channel's Download record is updated when the Channel's frequency is updated.
"""
@ -102,7 +102,7 @@ def test_channel_frequency_update(download_channel, test_client, test_session, t
url=download_channel.url,
download_frequency=100,
)
request, response = test_client.put(f'/api/videos/channels/{download_channel.id}', json=data)
request, response = await test_async_client.put(f'/api/videos/channels/{download_channel.id}', json=data)
assert response.status_code == HTTPStatus.NO_CONTENT, response.json
download = download_channel.get_download()
@ -115,7 +115,7 @@ def test_channel_frequency_update(download_channel, test_client, test_session, t
@pytest.mark.asyncio
async def test_channel_download_crud(test_session, simple_channel, test_downloader_config):
"""Modifying a Channel modifies it's Download."""
"""Modifying a Channel modifies its Download."""
assert simple_channel.url
assert simple_channel.download_frequency is None

View file

@ -220,7 +220,6 @@ 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.

View file

@ -107,27 +107,42 @@ class Download(ModelHelper, Base): # noqa
if reset_attempts:
self.attempts = 0
def is_new(self) -> bool:
return self.status == 'new'
def defer(self):
"""Download should be tried again after a time."""
self.status = 'deferred'
def is_deferred(self) -> bool:
return self.status == 'deferred'
def fail(self):
"""Download should not be attempted again. A recurring Download will raise an error."""
if self.frequency:
raise ValueError('Recurring download should not be failed.')
self.status = 'failed'
def is_failed(self) -> bool:
return self.status == 'failed'
def started(self):
"""Mark this Download as in progress."""
self.attempts += 1
self.status = 'pending'
def is_pending(self) -> bool:
return self.status == 'pending'
def complete(self):
"""Mark this Download as successfully downloaded."""
self.status = 'complete'
self.error = None # clear any old errors
self.last_successful_download = now()
def is_complete(self) -> bool:
return self.status == 'complete'
def get_downloader(self):
if self.downloader:
return self.manager.get_downloader_by_name(self.downloader)
@ -813,7 +828,7 @@ class DownloadManager:
download = self.get_download(session, id_=download_id)
downloader = download.get_downloader()
self.log_warning(f'Killing download {download_id} in {downloader}')
if download.status == 'pending':
if download.is_pending():
downloader.kill()
download.fail()
@ -982,7 +997,7 @@ class DownloadManager:
If the download is "complete" and the download has a frequency, schedule the download in it's next iteration.
(Next week, month, etc.)
"""
if download.status == 'deferred':
if download.is_deferred():
# Increase next_download slowly at first, then by large gaps later. The largest gap is the download
# frequency.
hours = 3 ** (download.attempts or 1)

View file

@ -405,7 +405,7 @@ def test_post_upload_directory(test_session, test_client, test_directory, make_f
dict(name='chunk', value='foo', filename='chunk')
]
body = make_multipart_form(forms)
request, response = test_client.post('/api/files/upload', data=body,
request, response = test_client.post('/api/files/upload', content=body,
headers={
'Content-Type': 'multipart/form-data; name=upload; filename="file.txt";'
' boundary=-----sanic'})
@ -430,7 +430,7 @@ def test_post_upload(test_session, test_client, test_directory, make_files_struc
dict(name='chunk', value='foo', filename='chunk')
]
body = make_multipart_form(forms)
request, response = test_client.post('/api/files/upload', data=body,
request, response = test_client.post('/api/files/upload', content=body,
headers={
'Content-Type': 'multipart/form-data; name=upload; filename="file.txt";'
' boundary=-----sanic'})
@ -448,7 +448,7 @@ def test_post_upload(test_session, test_client, test_directory, make_files_struc
dict(name='chunk', value='bar', filename='chunk')
]
body = make_multipart_form(forms)
request, response = test_client.post('/api/files/upload', data=body,
request, response = test_client.post('/api/files/upload', content=body,
headers={
'Content-Type': 'multipart/form-data; name=upload; filename="file.txt";'
' boundary=-----sanic'})

View file

@ -5,7 +5,6 @@ from datetime import datetime
from http import HTTPStatus
from itertools import zip_longest
from unittest import mock
from unittest.mock import MagicMock
import pytest
import pytz
@ -13,9 +12,9 @@ import yaml
from wrolpi.dates import Seconds
from wrolpi.db import get_db_context
from wrolpi.downloader import Downloader, Download, DownloadFrequency, DownloadResult, import_downloads_config, \
from wrolpi.downloader import Downloader, Download, DownloadFrequency, import_downloads_config, \
RSSDownloader, get_download_manager_config
from wrolpi.errors import UnrecoverableDownloadError, InvalidDownload, WROLModeEnabled
from wrolpi.errors import InvalidDownload, WROLModeEnabled
from wrolpi.test.common import assert_dict_contains
@ -211,7 +210,7 @@ async def test_recurring_downloads(test_session, test_download_manager, fake_now
# Download is "new" but has not been downloaded a second time.
assert download.next_download == expected
assert download.last_successful_download == now_
assert download.status == 'new'
assert download.is_new()
# Try the download, but it fails.
test_downloader.do_download.reset_mock()
@ -220,7 +219,7 @@ async def test_recurring_downloads(test_session, test_download_manager, fake_now
test_downloader.do_download.assert_called_once()
download = test_session.query(Download).one()
# Download is deferred, last successful download remains the same.
assert download.status == 'deferred'
assert download.is_deferred()
assert download.last_successful_download == now_
# Download should be retried after the DEFAULT_RETRY_FREQUENCY.
expected = datetime(2020, 1, 1, 3, 0, 0, 997200, tzinfo=pytz.UTC)
@ -234,7 +233,7 @@ async def test_recurring_downloads(test_session, test_download_manager, fake_now
await test_download_manager.wait_for_all_downloads()
test_downloader.do_download.assert_called_once()
download = test_session.query(Download).one()
assert download.status == 'complete'
assert download.is_complete()
assert download.last_successful_download == now_
# Floats cause slightly wrong date.
assert download.next_download == datetime(2020, 1, 1, 5, 0, 0, 997200, tzinfo=pytz.UTC)
@ -263,11 +262,11 @@ async def test_max_attempts(test_session, test_download_manager, test_downloader
await test_download_manager.wait_for_all_downloads()
download = session.query(Download).one()
assert download.attempts == 3
assert download.status == 'failed'
assert download.is_failed()
@pytest.mark.asyncio
async def test_skip_urls(test_session, test_download_manager, test_client, assert_download_urls, test_downloader):
async def test_skip_urls(test_session, test_download_manager, assert_download_urls, test_downloader):
"""The DownloadManager will not create downloads for URLs in its skip list."""
_, session = get_db_context()
get_download_manager_config().skip_urls = ['https://example.com/skipme']
@ -354,9 +353,12 @@ async def test_crud_download(test_async_client, test_session, test_download_mana
assert response.status_code == HTTPStatus.NOT_FOUND
assert test_session.query(Download).count() == 0
# Let background tasks finish.
await asyncio.sleep(1)
@pytest.mark.asyncio
async def test_downloads_config(test_session, test_client, test_download_manager, test_download_manager_config,
async def test_downloads_config(test_session, test_download_manager, test_download_manager_config,
test_downloader, assert_downloads):
# Can import with an empty config.
await import_downloads_config()
@ -444,7 +446,7 @@ async def test_downloads_config(test_session, test_client, test_download_manager
@pytest.mark.asyncio
async def test_download_excluded_urls(test_client, test_session, test_download_manager, test_downloader):
async def test_download_excluded_urls(test_session, test_download_manager, test_downloader):
"""Test that URLs that have been excluded are ignored by the download worker."""
test_downloader.already_downloaded = lambda *i, **kw: []
test_downloader.set_test_success()

View file

@ -17,13 +17,14 @@ def assert_events(expected: List[Dict], after=None):
assert_dict_contains(event, expected)
def test_events_api_feed(test_session, test_client, example_pdf):
@pytest.mark.asyncio
async def test_events_api_feed(test_session, test_async_client, example_pdf):
"""Events can be gotten from the API."""
# refresh_files() creates a few events.
request, response = test_client.post('/api/files/refresh')
request, response = await test_async_client.post('/api/files/refresh')
assert response.status_code == HTTPStatus.NO_CONTENT
request, response = test_client.get('/api/events/feed')
request, response = await test_async_client.get('/api/events/feed')
assert response.status_code == HTTPStatus.OK
assert (result := response.json.get('events'))
@ -48,7 +49,7 @@ def test_events_history_limit():
@pytest.mark.asyncio
async def test_get_events(test_client):
async def test_get_events():
after = now()
Events.send_global_refresh_started()

View file

@ -1,36 +0,0 @@
import pytest
from sqlalchemy import Column
from sqlalchemy.exc import StatementError
from wrolpi.common import ModelHelper, Base
from wrolpi.media_path import MediaPathType
class TestTable(Base, ModelHelper):
__tablename__ = 'testtable'
path = Column(MediaPathType, primary_key=True)
def test_media_path_type(test_session, test_directory):
"""MediaPathType checks that paths are valid. They must be in the media directory, absolute, and not empty."""
# A NULL media path is ok.
foo = TestTable()
test_session.commit()
# The correct media path is in the media directory, and absolute.
foo.path = test_directory / 'foo'
test_session.add(foo)
test_session.commit()
# The path cannot be empty.
foo.path = ''
with pytest.raises(StatementError) as error:
test_session.commit()
assert 'cannot be empty' in str(error)
test_session.rollback()
# Paths must be strings or Path.
foo.path = 1
with pytest.raises(StatementError) as error:
test_session.commit()
assert 'Invalid MediaPath type' in str(error)

View file

@ -410,18 +410,18 @@ async def test_restart_download(test_session, test_async_client, test_download_m
download = test_download_manager.create_download('https://example.com', test_downloader.name)
download.fail()
test_session.commit()
assert test_session.query(Download).one().status == 'failed'
assert test_session.query(Download).one().is_failed()
test_downloader.set_test_failure()
# Download is now "new" again.
request, response = await test_async_client.post(f'/api/download/{download.id}/restart')
assert response.status_code == HTTPStatus.NO_CONTENT
assert test_session.query(Download).one().status == 'new'
assert test_session.query(Download).one().is_new()
# Wait for the background download to fail. It should be deferred.
await asyncio.sleep(0.5)
assert test_session.query(Download).one().status == 'deferred'
assert test_session.query(Download).one().is_deferred()
def test_get_global_statistics(test_session, test_client):

View file

@ -93,5 +93,5 @@ async def test_rss_no_entries(test_session, test_download_manager):
await test_download_manager.wait_for_all_downloads()
(download,) = test_download_manager.get_downloads(test_session)
assert download.status == 'deferred'
assert download.is_deferred()
assert 'entries' in download.error