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

Errors-refactor #74

Merged
merged 10 commits into from
Feb 20, 2024
6 changes: 3 additions & 3 deletions bookops_worldcat/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .__version__ import __title__, __version__
from .__version__ import __title__, __version__ # noqa: F401

from .authorize import WorldcatAccessToken
from .metadata_api import MetadataSession
from .authorize import WorldcatAccessToken # noqa: F401
from .metadata_api import MetadataSession # noqa: F401
14 changes: 5 additions & 9 deletions bookops_worldcat/_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@

from . import __title__, __version__
from .authorize import WorldcatAccessToken
from .errors import WorldcatSessionError, WorldcatAuthorizationError


class WorldcatSession(requests.Session):
Expand All @@ -21,7 +20,7 @@ def __init__(
self,
authorization: WorldcatAccessToken,
agent: Optional[str] = None,
timeout: Union[int, float, Tuple[int, int], Tuple[float, float]] = (
timeout: Union[int, float, Tuple[int, int], Tuple[float, float], None] = (
5,
5,
),
Expand All @@ -39,7 +38,7 @@ def __init__(
self.authorization = authorization

if not isinstance(self.authorization, WorldcatAccessToken):
raise WorldcatSessionError(
raise TypeError(
"Argument 'authorization' must be 'WorldcatAccessToken' object."
)

Expand All @@ -48,7 +47,7 @@ def __init__(
elif agent and isinstance(agent, str):
self.headers.update({"User-Agent": agent})
else:
raise WorldcatSessionError("Argument 'agent' must be a string.")
raise ValueError("Argument 'agent' must be a string.")

self.timeout = timeout

Expand All @@ -59,11 +58,8 @@ def _get_new_access_token(self) -> None:
Allows to continue sending request with new access token after
the previous one expired
"""
try:
self.authorization._request_token()
self._update_authorization()
except WorldcatAuthorizationError as exc:
raise WorldcatSessionError(exc)
self.authorization._request_token()
self._update_authorization()

def _update_authorization(self) -> None:
self.headers.update({"Authorization": f"Bearer {self.authorization.token_str}"})
59 changes: 32 additions & 27 deletions bookops_worldcat/authorize.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,41 +99,43 @@ def __init__(
self.token_type = ""

# default bookops-worldcat request header
if not self.agent:
self.agent = f"{__title__}/{__version__}"
if isinstance(self.agent, str):
if not self.agent.strip():
self.agent = f"{__title__}/{__version__}"
else:
if not isinstance(self.agent, str):
raise WorldcatAuthorizationError("Argument 'agent' must be a string.")
raise TypeError("Argument 'agent' must be a string.")

# asure passed arguments are valid
if not self.key:
raise WorldcatAuthorizationError("Argument 'key' is required.")
if isinstance(self.key, str):
if not self.key.strip():
raise ValueError("Argument 'key' cannot be an empty string.")
else:
if not isinstance(self.key, str):
raise WorldcatAuthorizationError("Argument 'key' must be a string.")
raise TypeError("Argument 'key' must be a string.")

if not self.secret:
raise WorldcatAuthorizationError("Argument 'secret' is required.")
if isinstance(self.secret, str):
if not self.secret.strip():
raise ValueError("Argument 'secret' cannot be an empty string.")
else:
if not isinstance(self.secret, str):
raise WorldcatAuthorizationError("Argument 'secret' must be a string.")
raise TypeError("Argument 'secret' must be a string.")

if not self.principal_id:
raise WorldcatAuthorizationError(
"Argument 'principal_id' is required for read/write endpoint of "
"Metadata API."
)
if not self.principal_idns:
raise WorldcatAuthorizationError(
"Argument 'principal_idns' is required for read/write endpoint of "
"Metadata API."
)
if isinstance(self.principal_id, str):
if not self.principal_id.strip():
raise ValueError("Argument 'principal_id' cannot be an empty string.")
else:
raise TypeError("Argument 'principal_id' must be a string.")

if isinstance(self.principal_idns, str):
if not self.principal_idns.strip():
raise ValueError("Argument 'principal_idns' cannot be an empty string.")
else:
raise TypeError("Argument 'principal_idns' must be a string.")

# validate passed scopes
if not self.scopes:
raise WorldcatAuthorizationError("Argument 'scopes' is required.")
elif not isinstance(self.scopes, str):
raise WorldcatAuthorizationError("Argument 'scopes' must a string.")
if isinstance(self.scopes, str):
if not self.scopes.strip():
raise ValueError("Argument 'scopes' cannot be an empty string.")
else:
raise TypeError("Argument 'scopes' must a string.")
self.scopes = self.scopes.strip()

# assign default value for timout
Expand Down Expand Up @@ -242,7 +244,10 @@ def is_expired(self) -> bool:
else:
return False
else:
raise TypeError
raise TypeError(
"Attribue 'WorldcatAccessToken.token_expires_at' is of invalid type. "
"Expected `datetime.datetime` object."
)

def __repr__(self):
return (
Expand Down
10 changes: 1 addition & 9 deletions bookops_worldcat/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,7 @@ class WorldcatAuthorizationError(BookopsWorldcatError):
pass


class WorldcatSessionError(BookopsWorldcatError):
"""
Exception raised during WorlCat session
"""

pass


class WorldcatRequestError(WorldcatSessionError):
class WorldcatRequestError(BookopsWorldcatError):
"""
Exceptions raised on HTTP errors returned by web service
"""
Expand Down
Loading