Skip to content

Commit

Permalink
chore: avoid using exception strings
Browse files Browse the repository at this point in the history
  • Loading branch information
nijel committed Nov 8, 2024
1 parent 89f1e17 commit 9f6381e
Show file tree
Hide file tree
Showing 87 changed files with 505 additions and 345 deletions.
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,6 @@ ignore = [
'Q003', # CONFIG: formatter
'W191', # CONFIG: formatter
"E203", # CONFIG: formatter
"EM", # TODO: Exception strings
"PTH", # TODO: Not using pathlib
"FBT", # TODO: Boolean in function definition
"BLE001", # WONTFIX: Do not catch blind exception: `Exception`, third-party modules do not have defined exceptions
Expand Down
3 changes: 2 additions & 1 deletion weblate/accounts/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,5 @@ def get_user(self, user_id):
def disable_anon_user_password_save(sender, instance, **kwargs) -> None:
"""Block setting password for anonymous user."""
if instance.is_anonymous and instance.has_usable_password():
raise ValueError("Anonymous user can not have usable password!")
msg = "Anonymous user can not have usable password!"
raise ValueError(msg)
5 changes: 2 additions & 3 deletions weblate/accounts/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -600,9 +600,8 @@ def clean_password(self) -> None:
class ResetForm(EmailForm):
def clean_email(self):
if self.cleaned_data["email"] == "[email protected]":
raise forms.ValidationError(
"No password reset for deleted or anonymous user."
)
msg = "No password reset for deleted or anonymous user."
raise forms.ValidationError(msg)
return super().clean_email()


Expand Down
3 changes: 2 additions & 1 deletion weblate/accounts/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -950,7 +950,8 @@ def get_second_factor_type(self) -> Literal["totp", "webauthn"]:
for tested in ("webauthn", "totp"):
if tested in self.second_factor_types:
return tested
raise ValueError("No second factor available!")
msg = "No second factor available!"
raise ValueError(msg)


def set_lang_cookie(response, profile) -> None:
Expand Down
3 changes: 2 additions & 1 deletion weblate/accounts/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,8 @@ def get_key_type(device: Device) -> DeviceType:
return "totp"
if isinstance(device, StaticDevice):
return "recovery"
raise TypeError(f"Unsupported device: {device}")
msg = f"Unsupported device: {device}"
raise TypeError(msg)


class WeblateWebAuthnHelper(WebAuthnHelper):
Expand Down
6 changes: 4 additions & 2 deletions weblate/accounts/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -762,7 +762,8 @@ def user_avatar(request: AuthenticatedHttpRequest, user: str, size: int):
128,
)
if size not in allowed_sizes:
raise Http404(f"Not supported size: {size}")
msg = f"Not supported size: {size}"
raise Http404(msg)

avatar_user = get_object_or_404(User, username=user)

Expand Down Expand Up @@ -1319,7 +1320,8 @@ def social_auth(request: AuthenticatedHttpRequest, backend: str):
try:
request.backend = load_backend(request.social_strategy, backend, uri)
except MissingBackend:
raise Http404("Backend not found") from None
msg = "Backend not found"
raise Http404(msg) from None
# Store session ID for OpenID based auth. The session cookies will not be sent
# on returning POST request due to SameSite cookie policy
if isinstance(request.backend, OpenIdAuth):
Expand Down
5 changes: 2 additions & 3 deletions weblate/addons/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,9 +406,8 @@ def user(self):
from weblate.auth.models import User

if not self.user_name or not self.user_verbose:
raise ValueError(
f"{self.__class__.__name__} is missing user_name and user_verbose!"
)
msg = f"{self.__class__.__name__} is missing user_name and user_verbose!"
raise ValueError(msg)

return User.objects.get_or_create_bot(
"addon", self.user_name, self.user_verbose
Expand Down
11 changes: 6 additions & 5 deletions weblate/addons/management/commands/install_addon.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,20 @@ def validate_form(self, form) -> None:
for field in form:
for error in field.errors:
self.stderr.write(f"Error in {field.name}: {error}")
raise CommandError("Invalid add-on configuration!")
msg = "Invalid add-on configuration!"
raise CommandError(msg)

def handle(self, *args, **options) -> None:
try:
addon = ADDONS[options["addon"]]
except KeyError as error:
raise CommandError(
"Add-on not found: {}".format(options["addon"])
) from error
msg = "Add-on not found: {}".format(options["addon"])
raise CommandError(msg) from error
try:
configuration = json.loads(options["configuration"])
except ValueError as error:
raise CommandError(f"Invalid add-on configuration: {error}") from error
msg = f"Invalid add-on configuration: {error}"
raise CommandError(msg) from error
try:
user = User.objects.filter(is_superuser=True)[0]
except IndexError:
Expand Down
3 changes: 2 additions & 1 deletion weblate/addons/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,8 @@ def handle_addon_event(
component = translation.component

if component is None and not auto_scope:
raise ValueError("Missing event scope!")
msg = "Missing event scope!"
raise ValueError(msg)

# EVENT_DAILY uses custom queryset because it is not triggered from the
# object scope
Expand Down
3 changes: 2 additions & 1 deletion weblate/addons/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,8 @@ class CrashAddon(UpdateBaseAddon):

def update_translations(self, component: Component, previous_head: str) -> None:
if previous_head:
raise CrashAddonError("Test error")
msg = "Test error"
raise CrashAddonError(msg)

@classmethod
def can_install(cls, component: Component, user: User | None) -> bool: # noqa: ARG003
Expand Down
18 changes: 12 additions & 6 deletions weblate/addons/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,20 @@ class AddonList(PathViewMixin, ListView):
def get_queryset(self):
if isinstance(self.path_object, Component):
if not self.request.user.has_perm("component.edit", self.path_object):
raise PermissionDenied("Can not edit component")
msg = "Can not edit component"
raise PermissionDenied(msg)
self.kwargs["component_obj"] = self.path_object
return Addon.objects.filter_component(self.path_object)
if isinstance(self.path_object, Project):
if not self.request.user.has_perm("project.edit", self.path_object):
raise PermissionDenied("Can not edit project")
msg = "Can not edit project"
raise PermissionDenied(msg)
self.kwargs["project_obj"] = self.path_object
return Addon.objects.filter_project(self.path_object)

if not self.request.user.has_perm("management.addons"):
raise PermissionDenied("Can not manage add-ons")
msg = "Can not manage add-ons"
raise PermissionDenied(msg)
return Addon.objects.filter_sitewide()

def get_success_url(self):
Expand Down Expand Up @@ -174,15 +177,18 @@ def get_object(self): # type: ignore[override]
if obj.component and not self.request.user.has_perm(
"component.edit", obj.component
):
raise PermissionDenied("Can not edit component")
msg = "Can not edit component"
raise PermissionDenied(msg)
if obj.project and not self.request.user.has_perm("project.edit", obj.project):
raise PermissionDenied("Can not edit project")
msg = "Can not edit project"
raise PermissionDenied(msg)
if (
obj.project is None
and obj.component is None
and not self.request.user.has_perm("management.addons")
):
raise PermissionDenied("Can not manage add-ons")
msg = "Can not manage add-ons"
raise PermissionDenied(msg)
return obj


Expand Down
35 changes: 18 additions & 17 deletions weblate/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,31 +168,32 @@ def is_source_language(self):
def validate_code(self, value):
check_query = Language.objects.filter(code=value)
if not check_query.exists() and self.is_source_language:
raise serializers.ValidationError(
"Language with this language code was not found."
)
msg = "Language with this language code was not found."
raise serializers.ValidationError(msg)
return value

def validate_plural(self, value):
if not value and not self.is_source_language:
raise serializers.ValidationError("This field is required.")
msg = "This field is required."
raise serializers.ValidationError(msg)
return value

def validate_name(self, value):
if not value and not self.is_source_language:
raise serializers.ValidationError("This field is required.")
msg = "This field is required."
raise serializers.ValidationError(msg)
return value

def create(self, validated_data):
plural_validated = validated_data.pop("plural", None)
if not plural_validated:
raise serializers.ValidationError("No valid plural data was provided.")
msg = "No valid plural data was provided."
raise serializers.ValidationError(msg)

check_query = Language.objects.filter(code=validated_data.get("code"))
if check_query.exists():
raise serializers.ValidationError(
"Language with this Language code already exists."
)
msg = "Language with this Language code already exists."
raise serializers.ValidationError(msg)
language = super().create(validated_data)
plural = Plural(language=language, **plural_validated)
plural.save()
Expand Down Expand Up @@ -267,9 +268,8 @@ def get_queryset(self):
def to_internal_value(self, data):
check_query = Permission.objects.filter(codename=data)
if not check_query.exists():
raise serializers.ValidationError(
"Permission with this codename was not found."
)
msg = "Permission with this codename was not found."
raise serializers.ValidationError(msg)
return data


Expand Down Expand Up @@ -617,10 +617,12 @@ def __init__(self, *args, **kwargs) -> None:

def validate_enforced_checks(self, value):
if not isinstance(value, list):
raise serializers.ValidationError("Enforced checks has to be a list.")
msg = "Enforced checks has to be a list."
raise serializers.ValidationError(msg)
for item in value:
if item not in CHECKS:
raise serializers.ValidationError(f"Unsupported enforced check: {item}")
msg = f"Unsupported enforced check: {item}"
raise serializers.ValidationError(msg)
return value

def to_representation(self, instance):
Expand Down Expand Up @@ -1046,9 +1048,8 @@ def to_internal_value(self, data):
try:
label = self.get_queryset().get(id=data)
except Label.DoesNotExist as err:
raise serializers.ValidationError(
"Label with this ID was not found in this project."
) from err
msg = "Label with this ID was not found in this project."
raise serializers.ValidationError(msg) from err
return label


Expand Down
Loading

0 comments on commit 9f6381e

Please sign in to comment.