Skip to content

Commit

Permalink
token_expires_at as datetime obj
Browse files Browse the repository at this point in the history
  • Loading branch information
klinga committed Feb 8, 2024
1 parent ed63808 commit 535f44b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 21 deletions.
22 changes: 9 additions & 13 deletions bookops_worldcat/authorize.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def __init__(
self.secret = secret
self.server_response: Optional[requests.Response] = None
self.timeout = timeout
self.token_expires_at = ""
self.token_expires_at: Optional[datetime.datetime] = None
self.token_str = ""
self.token_type = ""

Expand Down Expand Up @@ -146,7 +146,7 @@ def __init__(
def _auth(self) -> Tuple[str, str]:
return (self.key, self.secret)

def _hasten_expiration_time(self, utc_stamp_str: str) -> str:
def _hasten_expiration_time(self, utc_stamp_str: str) -> datetime.datetime:
"""
Resets expiration time one second earlier to account
for any delays between expiration check and request for
Expand All @@ -161,7 +161,7 @@ def _hasten_expiration_time(self, utc_stamp_str: str) -> str:
utcstamp = datetime.datetime.strptime(
utc_stamp_str, "%Y-%m-%d %H:%M:%SZ"
) - datetime.timedelta(seconds=1)
return datetime.datetime.strftime(utcstamp, "%Y-%m-%d %H:%M:%SZ")
return utcstamp

def _parse_server_response(self, response: requests.Response) -> None:
"""Parses authorization server response"""
Expand Down Expand Up @@ -235,20 +235,16 @@ def is_expired(self) -> bool:
>>> token.is_expired()
False
"""
try:
if (
datetime.datetime.strptime(self.token_expires_at, "%Y-%m-%d %H:%M:%SZ")
< datetime.datetime.utcnow()
):
if isinstance(self.token_expires_at, datetime.datetime):
if self.token_expires_at < datetime.datetime.utcnow():
return True
else:
return False
except TypeError:
raise
except ValueError:
raise
else:
raise TypeError

def __repr__(self):
return (
f"access_token: '{self.token_str}', expires_at: '{self.token_expires_at}'"
f"access_token: '{self.token_str}', "
f"expires_at: '{self.token_expires_at:%Y-%m-%d %H:%M:%SZ}'"
)
15 changes: 7 additions & 8 deletions tests/test_authorize.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-

import datetime
from contextlib import nullcontext as does_not_raise
import os

import pytest
Expand Down Expand Up @@ -264,7 +263,9 @@ def test_auth(self, mock_successful_post_token_response):
def test_hasten_expiration_time(self, mock_token):
utc_stamp = "2020-01-01 17:19:59Z"
token = mock_token
assert token._hasten_expiration_time(utc_stamp) == "2020-01-01 17:19:58Z"
timestamp = token._hasten_expiration_time(utc_stamp)
assert isinstance(timestamp, datetime.datetime)
assert timestamp == datetime.datetime(2020, 1, 1, 17, 19, 58, 0)

def test_payload(self, mock_successful_post_token_response):
token = WorldcatAccessToken(
Expand Down Expand Up @@ -347,16 +348,15 @@ def test_is_expired_false(

def test_is_expired_true(self, mock_utcnow, mock_token):
mock_token.is_expired() is False
mock_token.token_expires_at = datetime.datetime.strftime(
datetime.datetime.utcnow() - datetime.timedelta(0, 1),
"%Y-%m-%d %H:%M:%SZ",
mock_token.token_expires_at = datetime.datetime.utcnow() - datetime.timedelta(
0, 1
)

assert mock_token.is_expired() is True

@pytest.mark.parametrize(
"arg,expectation",
[(None, pytest.raises(TypeError)), ("20-01-01", pytest.raises(ValueError))],
[(None, pytest.raises(TypeError))],
)
def test_is_expired_exception(self, arg, expectation, mock_token):
mock_token.token_expires_at = arg
Expand Down Expand Up @@ -439,5 +439,4 @@ def test_post_token_request_with_live_service(self, live_keys):
# test if token looks right
assert token.token_str.startswith("tk_")
assert token.is_expired() is False
with does_not_raise():
datetime.datetime.strptime(token.token_expires_at, "%Y-%m-%d %H:%M:%SZ")
assert isinstance(token.token_expires_at, datetime.datetime)

0 comments on commit 535f44b

Please sign in to comment.