Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dhcp commands and exception usage. #223

Merged
merged 3 commits into from
May 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 23 additions & 13 deletions mreg_cli/api/abstracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,14 @@

from mreg_cli.api.endpoints import Endpoint
from mreg_cli.api.history import HistoryItem, HistoryResource
from mreg_cli.exceptions import CliError
from mreg_cli.log import cli_error, cli_warning
from mreg_cli.exceptions import (
CreateFailure,
EntityAlreadyExists,
EntityNotFound,
GetFailure,
InternalError,
PatchFailure,
)
from mreg_cli.outputmanager import OutputManager
from mreg_cli.utilities.api import (
delete,
Expand Down Expand Up @@ -205,7 +211,7 @@ def get_by_field_or_raise(
cls,
field: str,
value: str,
exc_type: type[Exception] = CliError,
exc_type: type[Exception] = EntityNotFound,
exc_message: str | None = None,
) -> Self:
"""Get an object by a field and raise if not found.
Expand All @@ -231,7 +237,7 @@ def get_by_field_and_raise(
cls,
field: str,
value: str,
exc_type: type[Exception] = CliError,
exc_type: type[Exception] = EntityAlreadyExists,
exc_message: str | None = None,
) -> None:
"""Get an object by a field and raise if found.
Expand Down Expand Up @@ -294,7 +300,7 @@ def get_by_query_unique(cls, data: dict[str, str]) -> Self:
"""
obj_dict = get_list_unique(cls.endpoint(), params=data)
if not obj_dict:
cli_warning(f"{cls.__name__} record for {data} not found.")
raise EntityNotFound(f"{cls.__name__} record for {data} not found.")
return cls(**obj_dict)

def refetch(self) -> Self:
Expand All @@ -309,7 +315,9 @@ def refetch(self) -> Self:
identifier = getattr(self, id_field)

if not identifier:
cli_error(f"Could not get identifier for {self.__class__.__name__} via {id_field}.")
raise InternalError(
f"Could not get identifier for {self.__class__.__name__} via {id_field}."
)

lookup = None
# If we have and ID field, a refetch based on that is cleaner as a rename
Expand All @@ -318,13 +326,13 @@ def refetch(self) -> Self:
if hasattr(self, "id"):
lookup = getattr(self, "id", None)
if not lookup:
cli_error(f"Could not get ID for {self.__class__.__name__} via 'id'.")
raise InternalError(f"Could not get ID for {self.__class__.__name__} via 'id'.")
else:
lookup = getattr(self, identifier)

obj = self.__class__.get_by_id(lookup)
if not obj:
cli_warning(f"Could not refresh {self.__class__.__name__} with ID {identifier}.")
raise GetFailure(f"Could not refresh {self.__class__.__name__} with ID {identifier}.")

return obj

Expand Down Expand Up @@ -353,10 +361,12 @@ def patch(self, fields: dict[str, Any]) -> Self:
field_name = aliases[key]
try:
nval = getattr(new_object, field_name)
except AttributeError:
cli_warning(f"Could not get value for {field_name} in patched object.")
except AttributeError as e:
raise PatchFailure(
f"Could not get value for {field_name} in patched object."
) from e
if value and str(nval) != str(value):
cli_warning(
raise PatchFailure(
# Should this reference `field_name` instead of `key`?
f"Patch failure! Tried to set {key} to {value}, but server returned {nval}."
)
Expand Down Expand Up @@ -401,7 +411,7 @@ def create(cls, params: dict[str, str | None]) -> Self | None:
if obj:
return obj

cli_warning(f"Could not fetch object from location {location}.")
raise GetFailure(f"Could not fetch object from location {location}.")

# else:
# Lots of endpoints don't give locations on creation,
Expand All @@ -410,7 +420,7 @@ def create(cls, params: dict[str, str | None]) -> Self | None:
# cli_warning("No location header in response.")

else:
cli_warning(f"Failed to create {cls} with {params} @ {cls.endpoint()}.")
raise CreateFailure(f"Failed to create {cls} with {params} @ {cls.endpoint()}.")

return None

Expand Down
3 changes: 1 addition & 2 deletions mreg_cli/api/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@

import ipaddress
import re
from datetime import datetime, date
from typing import Annotated, Any

from pydantic import AliasChoices, BeforeValidator, Field, field_validator
from pydantic import BeforeValidator, field_validator

from mreg_cli.api.abstracts import FrozenModel
from mreg_cli.types import IP_AddressT
Expand Down
6 changes: 3 additions & 3 deletions mreg_cli/api/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from pydantic import BaseModel, Field, field_validator

from mreg_cli.api.endpoints import Endpoint
from mreg_cli.log import cli_warning
from mreg_cli.exceptions import EntityNotFound, InternalError
from mreg_cli.outputmanager import OutputManager
from mreg_cli.utilities.api import get_list

Expand Down Expand Up @@ -93,7 +93,7 @@ def msg(self, basename: str) -> str:
else:
msg = ", ".join(f"{k} = '{v}'" for k, v in self.data.items())
else:
cli_warning(f"Unhandled history entry: {action}")
raise InternalError(f"Unhandled history entry: {action}")

return msg

Expand All @@ -119,7 +119,7 @@ def get(cls, name: str, resource: HistoryResource) -> list[HistoryItem]:
ret = get_list(Endpoint.History, params=params)

if len(ret) == 0:
cli_warning(f"No history found for {name}")
raise EntityNotFound(f"No history found for {name}")

model_ids = ",".join({str(i["model_id"]) for i in ret})

Expand Down
Loading
Loading