Skip to content

Commit

Permalink
fix: migrate datetime.utcnow for python 3.12 (#1413)
Browse files Browse the repository at this point in the history
  • Loading branch information
arithmetic1728 committed Nov 11, 2023
1 parent 0caf175 commit e4d9c27
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 9 deletions.
9 changes: 8 additions & 1 deletion google/auth/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
6 changes: 2 additions & 4 deletions tests/test_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,17 +55,15 @@ 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
assert not credentials.expired

# 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
Expand Down
6 changes: 2 additions & 4 deletions tests_async/test_credentials_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,17 +46,15 @@ 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
assert not credentials.expired

# 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
Expand Down

0 comments on commit e4d9c27

Please sign in to comment.