From cb74490ca4e841b7cff27a8bc81e0f70864a493f Mon Sep 17 00:00:00 2001 From: jackwotherspoon Date: Wed, 8 Nov 2023 14:14:45 +0000 Subject: [PATCH] fix: use utcnow() for refresh calculation --- google/cloud/alloydb/connector/refresh.py | 8 +++++--- tests/unit/mocks.py | 8 ++++---- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/google/cloud/alloydb/connector/refresh.py b/google/cloud/alloydb/connector/refresh.py index 5baab41f..4143f10f 100644 --- a/google/cloud/alloydb/connector/refresh.py +++ b/google/cloud/alloydb/connector/refresh.py @@ -35,7 +35,9 @@ _refresh_buffer: int = 4 * 60 # 4 minutes -def _seconds_until_refresh(expiration: datetime, now: datetime = datetime.now()) -> int: +def _seconds_until_refresh( + expiration: datetime, now: datetime = datetime.utcnow() +) -> int: """ Calculates the duration to wait before starting the next refresh. Usually the duration will be half of the time until certificate @@ -43,7 +45,7 @@ def _seconds_until_refresh(expiration: datetime, now: datetime = datetime.now()) Args: expiration (datetime.datetime): Time of certificate expiration. - now (datetime.datetime): Current time. Defaults to datetime.now() + now (datetime.datetime): Current time. Defaults to datetime.utcnow() Returns: int: Time in seconds to wait before performing next refresh. """ @@ -107,7 +109,7 @@ async def _is_valid(task: asyncio.Task) -> bool: try: result = await task # valid if current time is before cert expiration - if datetime.now() < result.expiration: + if datetime.utcnow() < result.expiration: return True except Exception: # suppress any errors from task diff --git a/tests/unit/mocks.py b/tests/unit/mocks.py index 7ef94ce3..f01b2989 100644 --- a/tests/unit/mocks.py +++ b/tests/unit/mocks.py @@ -29,7 +29,7 @@ def __init__(self) -> None: def refresh(self, request: Callable) -> None: """Refreshes the access token.""" self.token = "12345" - self.expiry = datetime.now() + timedelta(minutes=60) + self.expiry = datetime.utcnow() + timedelta(minutes=60) @property def expired(self) -> bool: @@ -67,7 +67,7 @@ def generate_cert( # generate private key key = rsa.generate_private_key(public_exponent=65537, key_size=2048) # calculate expiry time - now = datetime.now() + now = datetime.utcnow() expiration = now + timedelta(minutes=expires_in) # configure cert subject subject = issuer = x509.Name( @@ -103,8 +103,8 @@ def __init__( name: str = "test-instance", ip_address: str = "127.0.0.1", server_name: str = "00000000-0000-0000-0000-000000000000.server.alloydb", - cert_before: datetime = datetime.now(), - cert_expiry: datetime = datetime.now() + timedelta(hours=1), + cert_before: datetime = datetime.utcnow(), + cert_expiry: datetime = datetime.utcnow() + timedelta(hours=1), ) -> None: self.project = project self.region = region