From e4d9c278375647e6c21754f42b81819827beb5e4 Mon Sep 17 00:00:00 2001 From: arithmetic1728 <58957152+arithmetic1728@users.noreply.github.com> Date: Fri, 10 Nov 2023 16:34:40 -0800 Subject: [PATCH] fix: migrate datetime.utcnow for python 3.12 (#1413) --- google/auth/_helpers.py | 9 ++++++++- tests/test_credentials.py | 6 ++---- tests_async/test_credentials_async.py | 6 ++---- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/google/auth/_helpers.py b/google/auth/_helpers.py index f321bc834..e7e5d97cf 100644 --- a/google/auth/_helpers.py +++ b/google/auth/_helpers.py @@ -92,7 +92,14 @@ def utcnow(): Returns: datetime: The current time in UTC. """ - return datetime.datetime.utcnow() + # We used datetime.utcnow() before, since it's deprecated from python 3.12, + # we are using datetime.now(timezone.utc) now. "utcnow()" is offset-native + # (no timezone info), but "now()" is offset-aware (with timezone info). + # This will cause datetime comparison problem. For backward compatibility, + # we need to remove the timezone info. + now = datetime.datetime.now(datetime.timezone.utc) + now = now.replace(tzinfo=None) + return now def datetime_to_secs(value): diff --git a/tests/test_credentials.py b/tests/test_credentials.py index 5eee35c98..d64f3abb5 100644 --- a/tests/test_credentials.py +++ b/tests/test_credentials.py @@ -55,9 +55,7 @@ def test_expired_and_valid(): # Set the expiration to one second more than now plus the clock skew # accomodation. These credentials should be valid. credentials.expiry = ( - datetime.datetime.utcnow() - + _helpers.REFRESH_THRESHOLD - + datetime.timedelta(seconds=1) + _helpers.utcnow() + _helpers.REFRESH_THRESHOLD + datetime.timedelta(seconds=1) ) assert credentials.valid @@ -65,7 +63,7 @@ def test_expired_and_valid(): # Set the credentials expiration to now. Because of the clock skew # accomodation, these credentials should report as expired. - credentials.expiry = datetime.datetime.utcnow() + credentials.expiry = _helpers.utcnow() assert not credentials.valid assert credentials.expired diff --git a/tests_async/test_credentials_async.py b/tests_async/test_credentials_async.py index 9db5fc9ae..7d82758c3 100644 --- a/tests_async/test_credentials_async.py +++ b/tests_async/test_credentials_async.py @@ -46,9 +46,7 @@ def test_expired_and_valid(): # Set the expiration to one second more than now plus the clock skew # accomodation. These credentials should be valid. credentials.expiry = ( - datetime.datetime.utcnow() - + _helpers.REFRESH_THRESHOLD - + datetime.timedelta(seconds=1) + _helpers.utcnow() + _helpers.REFRESH_THRESHOLD + datetime.timedelta(seconds=1) ) assert credentials.valid @@ -56,7 +54,7 @@ def test_expired_and_valid(): # Set the credentials expiration to now. Because of the clock skew # accomodation, these credentials should report as expired. - credentials.expiry = datetime.datetime.utcnow() + credentials.expiry = _helpers.utcnow() assert not credentials.valid assert credentials.expired