Skip to content

Commit

Permalink
chore: migrate from deprecated datetime.datetime.utcnow()
Browse files Browse the repository at this point in the history
  • Loading branch information
aciba90 committed Nov 7, 2024
1 parent aeccf89 commit 9b240e4
Show file tree
Hide file tree
Showing 10 changed files with 43 additions and 20 deletions.
4 changes: 2 additions & 2 deletions cloudinit/sources/DataSourceGCE.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,14 +213,14 @@ def _has_expired(public_key):
return False

expire_str = json_obj["expireOn"]
format_str = "%Y-%m-%dT%H:%M:%S+0000"
format_str = "%Y-%m-%dT%H:%M:%S%z"
try:
expire_time = datetime.datetime.strptime(expire_str, format_str)
except ValueError:
return False

# Expire the key if and only if we have exceeded the expiration timestamp.
return datetime.datetime.utcnow() > expire_time
return datetime.datetime.now(datetime.timezone.utc) > expire_time


def _parse_public_keys(public_keys_data, default_user=None):
Expand Down
4 changes: 2 additions & 2 deletions cloudinit/sources/azure/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import csv
import logging
import traceback
from datetime import datetime
from datetime import datetime, timezone
from io import StringIO
from typing import Any, Dict, List, Optional, Tuple
from xml.etree import ElementTree as ET # nosec B405
Expand Down Expand Up @@ -52,7 +52,7 @@ def __init__(
else:
self.supporting_data = {}

self.timestamp = datetime.utcnow()
self.timestamp = datetime.now(timezone.utc)

try:
self.vm_id = identity.query_vm_id()
Expand Down
4 changes: 2 additions & 2 deletions cloudinit/sources/azure/kvp.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# This file is part of cloud-init. See LICENSE file for license information.

import logging
from datetime import datetime
from datetime import datetime, timezone
from typing import Optional

from cloudinit import version
Expand Down Expand Up @@ -49,7 +49,7 @@ def report_success_to_host() -> bool:
[
"result=success",
f"agent=Cloud-Init/{version.version_string()}",
f"timestamp={datetime.utcnow().isoformat()}",
f"timestamp={datetime.now(timezone.utc).isoformat()}",
f"vm_id={vm_id}",
]
)
Expand Down
4 changes: 3 additions & 1 deletion tests/integration_tests/clouds.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,9 @@ def _perform_launch(
except KeyError:
profile_list = self._get_or_set_profile_list(release)

prefix = datetime.datetime.utcnow().strftime("cloudinit-%m%d-%H%M%S")
prefix = datetime.datetime.now(datetime.timezone.utc).strftime(
"cloudinit-%m%d-%H%M%S"
)
default_name = prefix + "".join(
random.choices(string.ascii_lowercase + string.digits, k=8)
)
Expand Down
14 changes: 11 additions & 3 deletions tests/integration_tests/test_paths.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import os
from datetime import datetime
from datetime import datetime, timezone
from typing import Iterator

import pytest
Expand Down Expand Up @@ -66,7 +66,11 @@ def collect_logs(self, custom_client: IntegrationInstance):
found_logs = custom_client.execute(
"tar -tf cloud-init.tar.gz"
).stdout.splitlines()
dirname = datetime.utcnow().date().strftime("cloud-init-logs-%Y-%m-%d")
dirname = (
datetime.now(timezone.utc)
.date()
.strftime("cloud-init-logs-%Y-%m-%d")
)
expected_logs = [
f"{dirname}/",
f"{dirname}/dmesg.txt",
Expand Down Expand Up @@ -98,7 +102,11 @@ def collect_logs(self, custom_client: IntegrationInstance):
found_logs = custom_client.execute(
"tar -tf cloud-init.tar.gz"
).stdout.splitlines()
dirname = datetime.utcnow().date().strftime("cloud-init-logs-%Y-%m-%d")
dirname = (
datetime.now(timezone.utc)
.date()
.strftime("cloud-init-logs-%Y-%m-%d")
)
assert f"{dirname}/new-cloud-dir/data/result.json" in found_logs

# LXD inserts some agent setup code into VMs on Bionic under
Expand Down
4 changes: 2 additions & 2 deletions tests/unittests/sources/azure/test_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ def agent_string():

@pytest.fixture()
def fake_utcnow():
timestamp = datetime.datetime.utcnow()
timestamp = datetime.datetime.now(datetime.timezone.utc)
with mock.patch.object(errors, "datetime", autospec=True) as m:
m.utcnow.return_value = timestamp
m.now.return_value = timestamp
yield timestamp


Expand Down
6 changes: 3 additions & 3 deletions tests/unittests/sources/azure/test_kvp.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# This file is part of cloud-init. See LICENSE file for license information.

from datetime import datetime
from datetime import datetime, timezone
from unittest import mock

import pytest
Expand All @@ -11,9 +11,9 @@

@pytest.fixture()
def fake_utcnow():
timestamp = datetime.utcnow()
timestamp = datetime.now(timezone.utc)
with mock.patch.object(kvp, "datetime", autospec=True) as m:
m.utcnow.return_value = timestamp
m.now.return_value = timestamp
yield timestamp


Expand Down
2 changes: 1 addition & 1 deletion tests/unittests/sources/test_azure.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ def mock_subp_subp():

@pytest.fixture
def mock_timestamp():
timestamp = datetime.datetime.utcnow()
timestamp = datetime.datetime.now(datetime.timezone.utc)
with mock.patch.object(errors, "datetime", autospec=True) as m:
m.utcnow.return_value = timestamp
yield timestamp
Expand Down
4 changes: 2 additions & 2 deletions tests/unittests/sources/test_gce.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,8 +341,8 @@ def test_get_data_returns_false_if_not_on_gce(self, m_fetcher):

def test_has_expired(self):
def _get_timestamp(days):
format_str = "%Y-%m-%dT%H:%M:%S+0000"
today = datetime.datetime.now()
format_str = "%Y-%m-%dT%H:%M:%S%z"
today = datetime.datetime.now(datetime.timezone.utc)
timestamp = today + datetime.timedelta(days=days)
return timestamp.strftime(format_str)

Expand Down
17 changes: 15 additions & 2 deletions tests/unittests/test_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,22 @@ def test_logger_uses_gmtime(self):
# parsed dt : 2017-08-23 14:19:43.069000
# utc_after : 2017-08-23 14:19:43.570064

utc_before = datetime.datetime.utcnow() - datetime.timedelta(0, 0.5)
def remove_tz(_dt: datetime.datetime) -> datetime.datetime:
"""
Removes the timezone object from an aware datetime dt without
conversion of date and time data
"""
return _dt.replace(tzinfo=None)

utc_before = remove_tz(
datetime.datetime.now(datetime.timezone.utc)
- datetime.timedelta(0, 0.5)
)
self.LOG.error("Test message")
utc_after = datetime.datetime.utcnow() + datetime.timedelta(0, 0.5)
utc_after = remove_tz(
datetime.datetime.now(datetime.timezone.utc)
+ datetime.timedelta(0, 0.5)
)

# extract timestamp from log:
# 2017-08-23 14:19:43,069 - test_log.py[ERROR]: Test message
Expand Down

0 comments on commit 9b240e4

Please sign in to comment.