Splitting errors into their modules. Removing API_ERRORS dict in favor of storing error data on the class.

This commit is contained in:
Roland 2023-07-17 14:21:27 -06:00
parent b3068885b2
commit fdaaa510c4
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
33 changed files with 337 additions and 449 deletions

View file

@ -10,7 +10,8 @@ from wrolpi.common import logger, register_modeler, register_refresh_cleanup, li
slow_logger
from wrolpi.db import optional_session, get_db_session
from wrolpi.downloader import Downloader, Download, DownloadResult
from wrolpi.errors import UnrecoverableDownloadError, InvalidArchive
from wrolpi.errors import UnrecoverableDownloadError
from .errors import InvalidArchive
from wrolpi.files.models import FileGroup
from wrolpi.vars import PYTEST
from . import lib

View file

@ -0,0 +1,9 @@
from http import HTTPStatus
from wrolpi.errors import APIError
class InvalidArchive(APIError):
code = 'INVALID_ARCHIVE'
summary = 'The archive is invalid. See server logs.'
status = HTTPStatus.BAD_REQUEST

View file

@ -11,7 +11,7 @@ from sqlalchemy.orm.collections import InstrumentedList
from wrolpi.common import ModelHelper, Base, logger
from wrolpi.dates import TZDateTime
from wrolpi.errors import InvalidArchive
from modules.archive import InvalidArchive
from wrolpi.files.models import FileGroup
from wrolpi.media_path import MediaPathType
from wrolpi.tags import Tag, TagFile

View file

@ -8,7 +8,7 @@ from pint import Quantity
from wrolpi import before_startup
from wrolpi.common import logger, Base, ConfigFile
from wrolpi.db import get_db_session
from wrolpi.errors import NoInventories, InventoriesVersionMismatch
from .errors import NoInventories, InventoriesVersionMismatch
from .inventory import unit_registry, get_items, get_inventories, increment_inventories_version, \
get_inventories_version
from .models import Inventory, Item

View file

@ -0,0 +1,15 @@
from http import HTTPStatus
from wrolpi.errors import APIError
class NoInventories(APIError):
code = 'NO_INVENTORIES'
summary = 'No Inventories'
status = HTTPStatus.BAD_REQUEST
class InventoriesVersionMismatch(APIError):
code = 'INVENTORIES_VERSION_MISMATCH'
summary = 'Inventories version in the DB does not match the inventories config'
status = HTTPStatus.BAD_REQUEST

View file

@ -10,7 +10,7 @@ from pint import Quantity
from wrolpi.common import Base
from wrolpi.db import get_db_session
from wrolpi.errors import NoInventories, InventoriesVersionMismatch
from ..errors import NoInventories, InventoriesVersionMismatch
from wrolpi.test.common import PytestCase
from .. import init
from ..common import sum_by_key, get_inventory_by_category, get_inventory_by_subcategory, get_inventory_by_name, \

View file

@ -135,4 +135,4 @@ def test_empty_import(test_client, test_session, test_directory):
body = {'files': []}
request, response = test_client.post('/api/map/import', content=json.dumps(body))
assert response.status_code == HTTPStatus.BAD_REQUEST
assert 'validate' in response.json['error']
assert 'validate' in response.json['summary']

21
modules/otp/errors.py Normal file
View file

@ -0,0 +1,21 @@
from http import HTTPStatus
from wrolpi.errors import APIError
class InvalidOTP(APIError):
code = 'INVALID_OTP'
summary = 'OTP has invalid characters'
status = HTTPStatus.BAD_REQUEST
class InvalidPlaintext(APIError):
code = 'INVALID_PLAINTEXT'
summary = 'Plaintext has invalid characters'
status = HTTPStatus.BAD_REQUEST
class InvalidCiphertext(APIError):
code = 'INVALID_CIPHERTEXT'
summary = 'Ciphertext has invalid characters'
status = HTTPStatus.BAD_REQUEST

View file

@ -3,7 +3,7 @@ from functools import partial
from typing import Dict
from wrolpi.common import chunks, remove_whitespace, logger
from wrolpi.errors import InvalidOTP, InvalidPlaintext, InvalidCiphertext
from modules.otp.errors import InvalidOTP, InvalidPlaintext, InvalidCiphertext
# These are the only characters we support.

View file

@ -9,7 +9,7 @@ from sanic_ext.extensions.openapi import openapi
from wrolpi.common import logger, wrol_mode_check, make_media_directory, \
get_media_directory, run_after
from wrolpi.errors import UnknownChannel
from ..errors import UnknownChannel
from wrolpi.root_api import json_response
from wrolpi.schema import JSONErrorResponse
from wrolpi.vars import PYTEST

View file

@ -8,7 +8,8 @@ from sqlalchemy.orm.exc import NoResultFound
from wrolpi.common import run_after, logger, \
get_media_directory
from wrolpi.db import get_db_curs, optional_session
from wrolpi.errors import UnknownChannel, UnknownDirectory, APIError, ValidationError, InvalidDownload
from wrolpi.errors import UnknownDirectory, APIError, ValidationError, InvalidDownload
from ..errors import UnknownChannel
from .. import schema
from ..common import check_for_channel_conflicts
from ..lib import save_channels_config

View file

@ -37,7 +37,7 @@ def test_get_video(test_client, test_session, simple_channel, video_factory):
# Test that a 404 is returned when no video exists
_, response = test_client.get('/api/videos/video/10')
assert response.status_code == HTTPStatus.NOT_FOUND, response.json
assert response.json == {'code': 1, 'api_error': 'The video could not be found.', 'message': ''}
assert response.json == {'code': 'UNKNOWN_VIDEO', 'summary': 'The video could not be found.', 'error': ''}
# Get the video info we inserted
_, response = test_client.get('/api/videos/video/1')
@ -203,8 +203,12 @@ def test_channel_conflicts(test_client, test_session, test_directory):
)
request, response = _post_channel(new_channel)
assert response.status_code == HTTPStatus.BAD_REQUEST
assert response.json == {'error': 'Could not validate the contents of the request', 'code': 10,
'cause': {'error': 'The channel name is already taken.', 'code': 5}}
assert response.json == {'cause': {'code': 'CHANNEL_NAME_CONFLICT',
'error': '',
'summary': 'The channel name is already taken.'},
'code': 'VALIDATION_ERROR',
'error': '',
'summary': 'Could not validate the contents of the request'}
# Directory was already used
new_channel = dict(
@ -213,8 +217,12 @@ def test_channel_conflicts(test_client, test_session, test_directory):
)
request, response = _post_channel(new_channel)
assert response.status_code == HTTPStatus.BAD_REQUEST
assert response.json == {'error': 'Could not validate the contents of the request', 'code': 10,
'cause': {'code': 7, 'error': 'The directory is already used by another channel.'}}
assert response.json == {'cause': {'code': 'CHANNEL_DIRECTORY_CONFLICT',
'error': '',
'summary': 'The directory is already used by another channel.'},
'code': 'VALIDATION_ERROR',
'error': '',
'summary': 'Could not validate the contents of the request'}
# URL is already used
channel_directory3 = tempfile.TemporaryDirectory(dir=test_directory).name
@ -226,8 +234,12 @@ def test_channel_conflicts(test_client, test_session, test_directory):
)
request, response = _post_channel(new_channel)
assert response.status_code == HTTPStatus.BAD_REQUEST
assert response.json == {'error': 'Could not validate the contents of the request', 'code': 10,
'cause': {'code': 6, 'error': 'The URL is already used by another channel.'}}
assert response.json == {'cause': {'code': 'CHANNEL_URL_CONFLICT',
'error': '',
'summary': 'The URL is already used by another channel.'},
'code': 'VALIDATION_ERROR',
'error': '',
'summary': 'Could not validate the contents of the request'}
def test_channel_empty_url_doesnt_conflict(test_client, test_session, test_directory):

View file

@ -4,7 +4,7 @@ from modules.videos import schema
from modules.videos.channel import lib
from modules.videos.lib import save_channels_config, import_channels_config
from modules.videos.models import Channel
from wrolpi.errors import UnknownChannel
from modules.videos.errors import UnknownChannel
@pytest.mark.parametrize('params', [

View file

@ -55,7 +55,7 @@ async def test_nested_channel_directories(test_session, test_async_client, test_
request, response = await test_async_client.post('/api/videos/channels', content=json.dumps(content))
assert response.status == HTTPStatus.BAD_REQUEST
assert response.json['cause'] and \
response.json['cause']['error'] == 'The directory is already used by another channel.'
response.json['cause']['summary'] == 'The directory is already used by another channel.'
# Channel 3 cannot be above Channel 1's directory.
content = dict(
@ -65,4 +65,4 @@ async def test_nested_channel_directories(test_session, test_async_client, test_
request, response = await test_async_client.post('/api/videos/channels', content=json.dumps(content))
assert response.status == HTTPStatus.BAD_REQUEST
assert response.json['cause'] and \
response.json['cause']['error'] == 'The directory is already used by another channel.'
response.json['cause']['summary'] == 'The directory is already used by another channel.'

View file

@ -17,8 +17,7 @@ from wrolpi.captions import FFMPEG_BIN
from wrolpi.cmd import FFPROBE_BIN
from wrolpi.common import logger, get_media_directory
from wrolpi.db import get_db_session, get_db_curs
from wrolpi.errors import ChannelNameConflict, ChannelURLConflict, \
ChannelDirectoryConflict, ChannelSourceIdConflict
from .errors import ChannelNameConflict, ChannelURLConflict, ChannelDirectoryConflict, ChannelSourceIdConflict
from wrolpi.vars import DEFAULT_FILE_PERMISSIONS
from .models import Channel

View file

@ -18,7 +18,8 @@ from wrolpi.dates import now
from wrolpi.db import get_db_session
from wrolpi.db import optional_session
from wrolpi.downloader import Downloader, Download, DownloadResult
from wrolpi.errors import UnknownChannel, ChannelURLEmpty, UnrecoverableDownloadError
from wrolpi.errors import UnrecoverableDownloadError
from .errors import UnknownChannel, ChannelURLEmpty
from wrolpi.files.lib import glob_shared_stem
from wrolpi.vars import PYTEST
from .channel.lib import create_channel, get_channel

45
modules/videos/errors.py Normal file
View file

@ -0,0 +1,45 @@
from http import HTTPStatus
from wrolpi.errors import APIError
class UnknownVideo(APIError):
code = 'UNKNOWN_VIDEO'
summary = 'The video could not be found.'
status = HTTPStatus.NOT_FOUND
class UnknownChannel(APIError):
code = 'UNKNOWN_CHANNEL'
summary = 'The channel could not be found.'
status = HTTPStatus.NOT_FOUND
class ChannelNameConflict(APIError):
code = 'CHANNEL_NAME_CONFLICT'
summary = 'The channel name is already taken.'
status = HTTPStatus.BAD_REQUEST
class ChannelURLConflict(APIError):
code = 'CHANNEL_URL_CONFLICT'
summary = 'The URL is already used by another channel.'
status = HTTPStatus.BAD_REQUEST
class ChannelDirectoryConflict(APIError):
code = 'CHANNEL_DIRECTORY_CONFLICT'
summary = 'The directory is already used by another channel.'
status = HTTPStatus.BAD_REQUEST
class ChannelSourceIdConflict(APIError):
code = 'CHANNEL_SOURCE_ID_CONFLICT'
summary = 'Search is empty, search_str must have content.'
status = HTTPStatus.BAD_REQUEST
class ChannelURLEmpty(APIError):
code = 'CHANNEL_URL_EMPTY'
summary = 'This channel has no URL'
status = HTTPStatus.BAD_REQUEST

View file

@ -13,7 +13,7 @@ from wrolpi.common import Base, ModelHelper, logger, get_media_directory, backgr
from wrolpi.dates import now, TZDateTime
from wrolpi.db import get_db_curs, get_db_session, optional_session
from wrolpi.downloader import Download, download_manager
from wrolpi.errors import UnknownVideo
from modules.videos.errors import UnknownVideo
from wrolpi.files.lib import refresh_files, split_path_stem_and_suffix
from wrolpi.files.models import FileGroup
from wrolpi.media_path import MediaPathType

View file

@ -150,7 +150,7 @@ def test_api_download_channel(test_session, test_client, simple_channel):
# simple_channel does not have a download record.
request, response = test_client.post(f'/api/videos/channels/download/{simple_channel.id}')
assert response.status_code == HTTPStatus.BAD_REQUEST, response.json
assert 'not have a download' in response.json['message']
assert 'not have a download' in response.json['error']
# Add a download frequency to the channel, this should also create a download.
simple_channel.update(dict(download_frequency=DownloadFrequency.daily))

View file

@ -6,7 +6,7 @@ from sqlalchemy.orm.exc import NoResultFound
from modules.videos.models import Video
from wrolpi.common import run_after, logger
from wrolpi.db import get_db_session, optional_session
from wrolpi.errors import UnknownVideo
from ..errors import UnknownVideo
from wrolpi.files.lib import handle_file_group_search_results, tag_names_to_file_group_sub_select
from ..lib import save_channels_config

View file

@ -8,7 +8,7 @@ import pytest
from modules.videos.models import Video
from modules.videos.video.lib import get_video_for_app
from wrolpi.dates import now
from wrolpi.errors import API_ERRORS, WROLModeEnabled
from wrolpi.errors import WROLModeEnabled
def test_get_video_prev_next(test_session, channel_factory, video_factory):
@ -133,26 +133,26 @@ async def test_wrol_mode(test_async_client, test_directory, simple_channel, simp
# Can't create, update, or delete a channel.
_, resp = await test_async_client.post('/api/videos/channels', content=channel)
assert resp.status_code == HTTPStatus.FORBIDDEN
assert resp.json['code'] == API_ERRORS[WROLModeEnabled]['code']
assert resp.json['code'] == 'WROL_MODE_ENABLED'
_, resp = await test_async_client.put(f'/api/videos/channels/{simple_channel.id}', content=channel)
assert resp.status_code == HTTPStatus.FORBIDDEN
assert resp.json['code'] == API_ERRORS[WROLModeEnabled]['code']
assert resp.json['code'] == 'WROL_MODE_ENABLED'
_, resp = await test_async_client.delete(f'/api/videos/channels/{simple_channel.id}')
assert resp.status_code == HTTPStatus.FORBIDDEN
assert resp.json['code'] == API_ERRORS[WROLModeEnabled]['code']
assert resp.json['code'] == 'WROL_MODE_ENABLED'
# Can't delete a video
_, resp = await test_async_client.delete(f'/api/videos/video/{simple_video.id}')
assert resp.status_code == HTTPStatus.FORBIDDEN
assert resp.json['code'] == API_ERRORS[WROLModeEnabled]['code']
assert resp.json['code'] == 'WROL_MODE_ENABLED'
# Can't refresh or download
_, resp = await test_async_client.post('/api/files/refresh')
assert resp.status_code == HTTPStatus.FORBIDDEN
assert resp.json['code'] == API_ERRORS[WROLModeEnabled]['code']
assert resp.json['code'] == 'WROL_MODE_ENABLED'
_, resp = await test_async_client.post(f'/api/videos/channels/download/{simple_channel.id}')
assert resp.status_code == HTTPStatus.FORBIDDEN
assert resp.json['code'] == API_ERRORS[WROLModeEnabled]['code']
assert resp.json['code'] == 'WROL_MODE_ENABLED'
# THE REST OF THESE METHODS ARE ALLOWED
content = dict(video_id=simple_video.id, tag_name=tag.name)

27
modules/zim/errors.py Normal file
View file

@ -0,0 +1,27 @@
from http import HTTPStatus
from wrolpi.errors import APIError
class UnknownZim(APIError):
code = 'UNKNOWN_ZIM'
summary = 'Failed to find the Zim'
status = HTTPStatus.NOT_FOUND
class UnknownZimEntry(APIError):
code = 'UNKNOWN_ZIM_ENTRY'
summary = 'Failed to find the Zim entry at that path'
status = HTTPStatus.NOT_FOUND
class UnknownZimTagEntry(APIError):
code = 'UNKNOWN_ZIM_TAG_ENTRY'
summary = 'Failed to find the TagZimEntry'
status = HTTPStatus.NOT_FOUND
class UnknownZimSubscription(APIError):
code = 'UNKNOWN_ZIM_SUBSCRIPTION'
summary = 'Failed to find the ZimSubscription'
status = HTTPStatus.NOT_FOUND

View file

@ -17,7 +17,7 @@ from wrolpi.common import register_modeler, logger, extract_html_text, extract_h
register_refresh_cleanup, background_task
from wrolpi.db import get_db_session, optional_session, get_db_curs
from wrolpi.downloader import DownloadFrequency
from wrolpi.errors import UnknownZim, UnknownZimSubscription
from modules.zim.errors import UnknownZim, UnknownZimSubscription
from wrolpi.files.lib import refresh_files
from wrolpi.files.models import FileGroup
from wrolpi.vars import PYTEST, DOCKERIZED

View file

@ -15,7 +15,7 @@ from wrolpi.common import Base, extract_html_text, logger, get_relative_to_media
from wrolpi.dates import TZDateTime
from wrolpi.db import optional_session, get_db_curs
from wrolpi.downloader import Download, download_manager
from wrolpi.errors import UnknownZimEntry, UnknownZimTagEntry
from modules.zim.errors import UnknownZimEntry, UnknownZimTagEntry
from wrolpi.files.models import FileGroup
from wrolpi.media_path import MediaPathType
from wrolpi.tags import Tag, tag_names_to_zim_sub_select

View file

@ -9,7 +9,7 @@ from modules.zim.models import TagZimEntry, ZimSubscription
from wrolpi import tags, flags
from wrolpi.common import DownloadFileInfo
from wrolpi.downloader import Download, import_downloads_config, save_downloads_config
from wrolpi.errors import UnknownZim
from modules.zim.errors import UnknownZim
from wrolpi.files import lib as files_lib
from wrolpi.files.models import FileGroup