Remove dependency on pytz (#5749)

This commit is contained in:
Daniel Roschka 2022-12-10 00:56:08 +01:00 committed by GitHub
parent 9e19d35ce8
commit 0588db704a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 106 additions and 116 deletions

View File

@ -6,7 +6,6 @@ import logging
import os import os
import re import re
import requests import requests
import pytz
import xmltodict import xmltodict
from collections import defaultdict, OrderedDict from collections import defaultdict, OrderedDict
@ -985,7 +984,7 @@ def to_str(value: Any, spec: Dict[str, Any]) -> str:
elif vtype == "timestamp": elif vtype == "timestamp":
return ( return (
datetime.datetime.utcfromtimestamp(value) datetime.datetime.utcfromtimestamp(value)
.replace(tzinfo=pytz.utc) .replace(tzinfo=datetime.timezone.utc)
.isoformat() .isoformat()
) )
elif vtype == "string": elif vtype == "string":

View File

@ -1,8 +1,7 @@
import re import re
from copy import copy from copy import copy
from datetime import datetime from datetime import datetime, timezone
from typing import Any from typing import Any
import pytz
from moto import settings from moto import settings
from moto.core import BaseBackend, BackendDict, BaseModel, CloudFormationModel from moto.core import BaseBackend, BackendDict, BaseModel, CloudFormationModel
@ -422,7 +421,7 @@ class Service(BaseObject, CloudFormationModel):
if self.deployment_controller["type"] == "ECS": if self.deployment_controller["type"] == "ECS":
self.deployments = [ self.deployments = [
{ {
"createdAt": datetime.now(pytz.utc), "createdAt": datetime.now(timezone.utc),
"desiredCount": self.desired_count, "desiredCount": self.desired_count,
"id": f"ecs-svc/{mock_random.randint(0, 32**12)}", "id": f"ecs-svc/{mock_random.randint(0, 32**12)}",
"launchType": self.launch_type, "launchType": self.launch_type,
@ -430,7 +429,7 @@ class Service(BaseObject, CloudFormationModel):
"runningCount": 0, "runningCount": 0,
"status": "PRIMARY", "status": "PRIMARY",
"taskDefinition": self.task_definition, "taskDefinition": self.task_definition,
"updatedAt": datetime.now(pytz.utc), "updatedAt": datetime.now(timezone.utc),
} }
] ]
else: else:
@ -651,7 +650,7 @@ class ContainerInstance(BaseObject):
if ec2_instance.platform == "windows" if ec2_instance.platform == "windows"
else "linux", # options are windows and linux, linux is default else "linux", # options are windows and linux, linux is default
} }
self.registered_at = datetime.now(pytz.utc) self.registered_at = datetime.now(timezone.utc)
self.region_name = region_name self.region_name = region_name
self.id = str(mock_random.uuid4()) self.id = str(mock_random.uuid4())
self.cluster_name = cluster_name self.cluster_name = cluster_name
@ -748,9 +747,9 @@ class TaskSet(BaseObject):
self.client_token = client_token or "" self.client_token = client_token or ""
self.tags = tags or [] self.tags = tags or []
self.stabilityStatus = "STEADY_STATE" self.stabilityStatus = "STEADY_STATE"
self.createdAt = datetime.now(pytz.utc) self.createdAt = datetime.now(timezone.utc)
self.updatedAt = datetime.now(pytz.utc) self.updatedAt = datetime.now(timezone.utc)
self.stabilityStatusAt = datetime.now(pytz.utc) self.stabilityStatusAt = datetime.now(timezone.utc)
self.id = f"ecs-svc/{mock_random.randint(0, 32**12)}" self.id = f"ecs-svc/{mock_random.randint(0, 32**12)}"
self.service_arn = "" self.service_arn = ""
self.cluster_arn = "" self.cluster_arn = ""

View File

@ -1,5 +1,4 @@
import datetime import datetime
import pytz
from collections import OrderedDict from collections import OrderedDict
from typing import List, Iterable from typing import List, Iterable
@ -75,7 +74,7 @@ class FakeLoadBalancer(CloudFormationModel):
self.zones = zones self.zones = zones
self.listeners = [] self.listeners = []
self.backends = [] self.backends = []
self.created_time = datetime.datetime.now(pytz.utc) self.created_time = datetime.datetime.now(datetime.timezone.utc)
self.scheme = scheme or "internet-facing" self.scheme = scheme or "internet-facing"
self.attributes = FakeLoadBalancer.get_default_attributes() self.attributes = FakeLoadBalancer.get_default_attributes()
self.policies = [] self.policies = []

View File

@ -1,9 +1,7 @@
from datetime import datetime from datetime import datetime, timedelta, timezone
from datetime import timedelta
import warnings import warnings
import pytz
from dateutil.parser import parse as dtparse from dateutil.parser import parse as dtparse
from moto.core import BaseBackend, BackendDict, BaseModel from moto.core import BaseBackend, BackendDict, BaseModel
from moto.emr.exceptions import ( from moto.emr.exceptions import (
@ -79,9 +77,9 @@ class FakeInstanceGroup(BaseModel):
self.type = instance_type self.type = instance_type
self.ebs_configuration = ebs_configuration self.ebs_configuration = ebs_configuration
self.auto_scaling_policy = auto_scaling_policy self.auto_scaling_policy = auto_scaling_policy
self.creation_datetime = datetime.now(pytz.utc) self.creation_datetime = datetime.now(timezone.utc)
self.start_datetime = datetime.now(pytz.utc) self.start_datetime = datetime.now(timezone.utc)
self.ready_datetime = datetime.now(pytz.utc) self.ready_datetime = datetime.now(timezone.utc)
self.end_datetime = None self.end_datetime = None
self.state = "RUNNING" self.state = "RUNNING"
@ -135,14 +133,14 @@ class FakeStep(BaseModel):
self.jar = jar self.jar = jar
self.properties = properties or {} self.properties = properties or {}
self.creation_datetime = datetime.now(pytz.utc) self.creation_datetime = datetime.now(timezone.utc)
self.end_datetime = None self.end_datetime = None
self.ready_datetime = None self.ready_datetime = None
self.start_datetime = None self.start_datetime = None
self.state = state self.state = state
def start(self): def start(self):
self.start_datetime = datetime.now(pytz.utc) self.start_datetime = datetime.now(timezone.utc)
class FakeCluster(BaseModel): class FakeCluster(BaseModel):
@ -260,7 +258,7 @@ class FakeCluster(BaseModel):
self.service_role = service_role self.service_role = service_role
self.step_concurrency_level = step_concurrency_level self.step_concurrency_level = step_concurrency_level
self.creation_datetime = datetime.now(pytz.utc) self.creation_datetime = datetime.now(timezone.utc)
self.start_datetime = None self.start_datetime = None
self.ready_datetime = None self.ready_datetime = None
self.end_datetime = None self.end_datetime = None
@ -298,11 +296,11 @@ class FakeCluster(BaseModel):
def start_cluster(self): def start_cluster(self):
self.state = "STARTING" self.state = "STARTING"
self.start_datetime = datetime.now(pytz.utc) self.start_datetime = datetime.now(timezone.utc)
def run_bootstrap_actions(self): def run_bootstrap_actions(self):
self.state = "BOOTSTRAPPING" self.state = "BOOTSTRAPPING"
self.ready_datetime = datetime.now(pytz.utc) self.ready_datetime = datetime.now(timezone.utc)
self.state = "WAITING" self.state = "WAITING"
if not self.steps: if not self.steps:
if not self.keep_job_flow_alive_when_no_steps: if not self.keep_job_flow_alive_when_no_steps:
@ -310,7 +308,7 @@ class FakeCluster(BaseModel):
def terminate(self): def terminate(self):
self.state = "TERMINATING" self.state = "TERMINATING"
self.end_datetime = datetime.now(pytz.utc) self.end_datetime = datetime.now(timezone.utc)
self.state = "TERMINATED" self.state = "TERMINATED"
def add_applications(self, applications): def add_applications(self, applications):
@ -383,7 +381,7 @@ class FakeSecurityConfiguration(BaseModel):
def __init__(self, name, security_configuration): def __init__(self, name, security_configuration):
self.name = name self.name = name
self.security_configuration = security_configuration self.security_configuration = security_configuration
self.creation_date_time = datetime.now(pytz.utc) self.creation_date_time = datetime.now(timezone.utc)
class ElasticMapReduceBackend(BaseBackend): class ElasticMapReduceBackend(BaseBackend):
@ -454,7 +452,7 @@ class ElasticMapReduceBackend(BaseBackend):
): ):
clusters = self.clusters.values() clusters = self.clusters.values()
within_two_month = datetime.now(pytz.utc) - timedelta(days=60) within_two_month = datetime.now(timezone.utc) - timedelta(days=60)
clusters = [c for c in clusters if c.creation_datetime >= within_two_month] clusters = [c for c in clusters if c.creation_datetime >= within_two_month]
if job_flow_ids: if job_flow_ids:

View File

@ -1,10 +1,8 @@
import json import json
import re import re
from datetime import datetime from datetime import datetime, timezone
from functools import wraps from functools import wraps
import pytz
from urllib.parse import urlparse from urllib.parse import urlparse
from moto.core.responses import AWSServiceSpec from moto.core.responses import AWSServiceSpec
from moto.core.responses import BaseResponse from moto.core.responses import BaseResponse
@ -29,7 +27,7 @@ def generate_boto3_response(operation):
self.response_headers.update( self.response_headers.update(
{ {
"x-amzn-requestid": "2690d7eb-ed86-11dd-9877-6fad448a8419", "x-amzn-requestid": "2690d7eb-ed86-11dd-9877-6fad448a8419",
"date": datetime.now(pytz.utc).strftime( "date": datetime.now(timezone.utc).strftime(
"%a, %d %b %Y %H:%M:%S %Z" "%a, %d %b %Y %H:%M:%S %Z"
), ),
"content-type": "application/x-amz-json-1.1", "content-type": "application/x-amz-json-1.1",

View File

@ -8,7 +8,6 @@ import codecs
import string import string
import tempfile import tempfile
import threading import threading
import pytz
import sys import sys
import urllib.parse import urllib.parse
@ -913,7 +912,7 @@ class FakeBucket(CloudFormationModel):
self.notification_configuration = None self.notification_configuration = None
self.accelerate_configuration = None self.accelerate_configuration = None
self.payer = "BucketOwner" self.payer = "BucketOwner"
self.creation_date = datetime.datetime.now(tz=pytz.utc) self.creation_date = datetime.datetime.now(tz=datetime.timezone.utc)
self.public_access_block = None self.public_access_block = None
self.encryption = None self.encryption = None
self.object_lock_enabled = False self.object_lock_enabled = False
@ -1517,7 +1516,7 @@ class S3Backend(BaseBackend, CloudWatchMetricProvider):
{"Name": "StorageType", "Value": "StandardStorage"}, {"Name": "StorageType", "Value": "StandardStorage"},
{"Name": "BucketName", "Value": name}, {"Name": "BucketName", "Value": name},
], ],
timestamp=datetime.datetime.now(tz=pytz.utc).replace( timestamp=datetime.datetime.now(tz=datetime.timezone.utc).replace(
hour=0, minute=0, second=0, microsecond=0 hour=0, minute=0, second=0, microsecond=0
), ),
unit="Bytes", unit="Bytes",
@ -1532,7 +1531,7 @@ class S3Backend(BaseBackend, CloudWatchMetricProvider):
{"Name": "StorageType", "Value": "AllStorageTypes"}, {"Name": "StorageType", "Value": "AllStorageTypes"},
{"Name": "BucketName", "Value": name}, {"Name": "BucketName", "Value": name},
], ],
timestamp=datetime.datetime.now(tz=pytz.utc).replace( timestamp=datetime.datetime.now(tz=datetime.timezone.utc).replace(
hour=0, minute=0, second=0, microsecond=0 hour=0, minute=0, second=0, microsecond=0
), ),
unit="Count", unit="Count",

View File

@ -33,7 +33,6 @@ install_requires = [
"requests>=2.5", "requests>=2.5",
"xmltodict", "xmltodict",
"werkzeug>=0.5,!=2.2.0,!=2.2.1", "werkzeug>=0.5,!=2.2.0,!=2.2.1",
"pytz",
"python-dateutil<3.0.0,>=2.1", "python-dateutil<3.0.0,>=2.1",
"responses>=0.13.0", "responses>=0.13.0",
"MarkupSafe!=2.0.0a1", # This is a Jinja2 dependency, 2.0.0a1 currently seems broken "MarkupSafe!=2.0.0a1", # This is a Jinja2 dependency, 2.0.0a1 currently seems broken

View File

@ -1,9 +1,8 @@
import copy import copy
import json import json
from collections import OrderedDict from collections import OrderedDict
from datetime import datetime, timedelta from datetime import datetime, timedelta, timezone
import os import os
import pytz
import pytest import pytest
from unittest import SkipTest from unittest import SkipTest
import boto3 import boto3
@ -1453,9 +1452,9 @@ def test_describe_change_set():
stack["StackName"].should.equal("NewStack") stack["StackName"].should.equal("NewStack")
stack["Status"].should.equal("CREATE_COMPLETE") stack["Status"].should.equal("CREATE_COMPLETE")
stack["ExecutionStatus"].should.equal("AVAILABLE") stack["ExecutionStatus"].should.equal("AVAILABLE")
two_secs_ago = datetime.now(tz=pytz.UTC) - timedelta(seconds=2) two_secs_ago = datetime.now(tz=timezone.utc) - timedelta(seconds=2)
assert ( assert (
two_secs_ago < stack["CreationTime"] < datetime.now(tz=pytz.UTC) two_secs_ago < stack["CreationTime"] < datetime.now(tz=timezone.utc)
), "Change set should have been created recently" ), "Change set should have been created recently"
stack["Changes"].should.have.length_of(1) stack["Changes"].should.have.length_of(1)
stack["Changes"][0].should.equal( stack["Changes"][0].should.equal(
@ -1616,9 +1615,9 @@ def test_describe_stack_by_name():
stack = cf_conn.describe_stacks(StackName="test_stack")["Stacks"][0] stack = cf_conn.describe_stacks(StackName="test_stack")["Stacks"][0]
stack["StackName"].should.equal("test_stack") stack["StackName"].should.equal("test_stack")
two_secs_ago = datetime.now(tz=pytz.UTC) - timedelta(seconds=2) two_secs_ago = datetime.now(tz=timezone.utc) - timedelta(seconds=2)
assert ( assert (
two_secs_ago < stack["CreationTime"] < datetime.now(tz=pytz.UTC) two_secs_ago < stack["CreationTime"] < datetime.now(tz=timezone.utc)
), "Stack should have been created recently" ), "Stack should have been created recently"

View File

@ -1,10 +1,9 @@
import boto3 import boto3
import pytest import pytest
import pytz
import sure # noqa # pylint: disable=unused-import import sure # noqa # pylint: disable=unused-import
from botocore.exceptions import ClientError from botocore.exceptions import ClientError
from datetime import datetime, timedelta from datetime import datetime, timedelta, timezone
from dateutil.tz import tzutc from dateutil.tz import tzutc
from decimal import Decimal from decimal import Decimal
from freezegun import freeze_time from freezegun import freeze_time
@ -32,7 +31,7 @@ def test_put_metric_data_no_dimensions():
@mock_cloudwatch @mock_cloudwatch
def test_put_metric_data_can_not_have_nan(): def test_put_metric_data_can_not_have_nan():
client = boto3.client("cloudwatch", region_name="us-west-2") client = boto3.client("cloudwatch", region_name="us-west-2")
utc_now = datetime.now(tz=pytz.utc) utc_now = datetime.now(tz=timezone.utc)
with pytest.raises(ClientError) as exc: with pytest.raises(ClientError) as exc:
client.put_metric_data( client.put_metric_data(
Namespace="mynamespace", Namespace="mynamespace",
@ -55,7 +54,7 @@ def test_put_metric_data_can_not_have_nan():
@mock_cloudwatch @mock_cloudwatch
def test_put_metric_data_can_not_have_value_and_values(): def test_put_metric_data_can_not_have_value_and_values():
client = boto3.client("cloudwatch", region_name="us-west-2") client = boto3.client("cloudwatch", region_name="us-west-2")
utc_now = datetime.now(tz=pytz.utc) utc_now = datetime.now(tz=timezone.utc)
with pytest.raises(ClientError) as exc: with pytest.raises(ClientError) as exc:
client.put_metric_data( client.put_metric_data(
Namespace="mynamespace", Namespace="mynamespace",
@ -79,7 +78,7 @@ def test_put_metric_data_can_not_have_value_and_values():
@mock_cloudwatch @mock_cloudwatch
def test_put_metric_data_can_not_have_and_values_mismatched_counts(): def test_put_metric_data_can_not_have_and_values_mismatched_counts():
client = boto3.client("cloudwatch", region_name="us-west-2") client = boto3.client("cloudwatch", region_name="us-west-2")
utc_now = datetime.now(tz=pytz.utc) utc_now = datetime.now(tz=timezone.utc)
with pytest.raises(ClientError) as exc: with pytest.raises(ClientError) as exc:
client.put_metric_data( client.put_metric_data(
Namespace="mynamespace", Namespace="mynamespace",
@ -103,7 +102,7 @@ def test_put_metric_data_can_not_have_and_values_mismatched_counts():
@mock_cloudwatch @mock_cloudwatch
def test_put_metric_data_values_and_counts(): def test_put_metric_data_values_and_counts():
client = boto3.client("cloudwatch", region_name="us-west-2") client = boto3.client("cloudwatch", region_name="us-west-2")
utc_now = datetime.now(tz=pytz.utc) utc_now = datetime.now(tz=timezone.utc)
namespace = "values" namespace = "values"
metric = "mymetric" metric = "mymetric"
client.put_metric_data( client.put_metric_data(
@ -134,7 +133,7 @@ def test_put_metric_data_values_and_counts():
@mock_cloudwatch @mock_cloudwatch
def test_put_metric_data_values_without_counts(): def test_put_metric_data_values_without_counts():
client = boto3.client("cloudwatch", region_name="us-west-2") client = boto3.client("cloudwatch", region_name="us-west-2")
utc_now = datetime.now(tz=pytz.utc) utc_now = datetime.now(tz=timezone.utc)
namespace = "values" namespace = "values"
metric = "mymetric" metric = "mymetric"
client.put_metric_data( client.put_metric_data(
@ -164,7 +163,7 @@ def test_put_metric_data_values_without_counts():
@mock_cloudwatch @mock_cloudwatch
def test_put_metric_data_with_statistics(): def test_put_metric_data_with_statistics():
conn = boto3.client("cloudwatch", region_name="us-east-1") conn = boto3.client("cloudwatch", region_name="us-east-1")
utc_now = datetime.now(tz=pytz.utc) utc_now = datetime.now(tz=timezone.utc)
conn.put_metric_data( conn.put_metric_data(
Namespace="tester", Namespace="tester",
@ -192,7 +191,7 @@ def test_put_metric_data_with_statistics():
@mock_cloudwatch @mock_cloudwatch
def test_get_metric_statistics(): def test_get_metric_statistics():
conn = boto3.client("cloudwatch", region_name="us-east-1") conn = boto3.client("cloudwatch", region_name="us-east-1")
utc_now = datetime.now(tz=pytz.utc) utc_now = datetime.now(tz=timezone.utc)
conn.put_metric_data( conn.put_metric_data(
Namespace="tester", Namespace="tester",
@ -217,7 +216,7 @@ def test_get_metric_statistics():
@mock_cloudwatch @mock_cloudwatch
def test_get_metric_invalid_parameter_combination(): def test_get_metric_invalid_parameter_combination():
conn = boto3.client("cloudwatch", region_name="us-east-1") conn = boto3.client("cloudwatch", region_name="us-east-1")
utc_now = datetime.now(tz=pytz.utc) utc_now = datetime.now(tz=timezone.utc)
conn.put_metric_data( conn.put_metric_data(
Namespace="tester", Namespace="tester",
@ -242,7 +241,7 @@ def test_get_metric_invalid_parameter_combination():
@mock_cloudwatch @mock_cloudwatch
def test_get_metric_statistics_dimensions(): def test_get_metric_statistics_dimensions():
conn = boto3.client("cloudwatch", region_name="us-east-1") conn = boto3.client("cloudwatch", region_name="us-east-1")
utc_now = datetime.now(tz=pytz.utc) utc_now = datetime.now(tz=timezone.utc)
# put metric data with different dimensions # put metric data with different dimensions
dimensions1 = [{"Name": "dim1", "Value": "v1"}] dimensions1 = [{"Name": "dim1", "Value": "v1"}]
@ -311,7 +310,7 @@ def test_get_metric_statistics_dimensions():
@mock_cloudwatch @mock_cloudwatch
def test_duplicate_put_metric_data(): def test_duplicate_put_metric_data():
conn = boto3.client("cloudwatch", region_name="us-east-1") conn = boto3.client("cloudwatch", region_name="us-east-1")
utc_now = datetime.now(tz=pytz.utc) utc_now = datetime.now(tz=timezone.utc)
conn.put_metric_data( conn.put_metric_data(
Namespace="tester", Namespace="tester",
@ -412,7 +411,7 @@ def test_duplicate_put_metric_data():
@mock_cloudwatch @mock_cloudwatch
@freeze_time("2020-02-10 18:44:05") @freeze_time("2020-02-10 18:44:05")
def test_custom_timestamp(): def test_custom_timestamp():
utc_now = datetime.now(tz=pytz.utc) utc_now = datetime.now(tz=timezone.utc)
time = "2020-02-10T18:44:09Z" time = "2020-02-10T18:44:09Z"
cw = boto3.client("cloudwatch", "eu-west-1") cw = boto3.client("cloudwatch", "eu-west-1")
@ -609,7 +608,7 @@ def create_metrics_with_dimensions(cloudwatch, namespace, data_points=5):
@mock_cloudwatch @mock_cloudwatch
def test_get_metric_data_for_multiple_metrics_w_same_dimensions(): def test_get_metric_data_for_multiple_metrics_w_same_dimensions():
utc_now = datetime.now(tz=pytz.utc) utc_now = datetime.now(tz=timezone.utc)
cloudwatch = boto3.client("cloudwatch", "eu-west-1") cloudwatch = boto3.client("cloudwatch", "eu-west-1")
namespace = "my_namespace/" namespace = "my_namespace/"
cloudwatch.put_metric_data( cloudwatch.put_metric_data(
@ -681,7 +680,7 @@ def test_get_metric_data_for_multiple_metrics_w_same_dimensions():
@mock_cloudwatch @mock_cloudwatch
def test_get_metric_data_within_timeframe(): def test_get_metric_data_within_timeframe():
utc_now = datetime.now(tz=pytz.utc) utc_now = datetime.now(tz=timezone.utc)
cloudwatch = boto3.client("cloudwatch", "eu-west-1") cloudwatch = boto3.client("cloudwatch", "eu-west-1")
namespace1 = "my_namespace/" namespace1 = "my_namespace/"
# put metric data # put metric data
@ -742,7 +741,7 @@ def test_get_metric_data_within_timeframe():
@mock_cloudwatch @mock_cloudwatch
def test_get_metric_data_partially_within_timeframe(): def test_get_metric_data_partially_within_timeframe():
utc_now = datetime.now(tz=pytz.utc) utc_now = datetime.now(tz=timezone.utc)
yesterday = utc_now - timedelta(days=1) yesterday = utc_now - timedelta(days=1)
last_week = utc_now - timedelta(days=7) last_week = utc_now - timedelta(days=7)
cloudwatch = boto3.client("cloudwatch", "eu-west-1") cloudwatch = boto3.client("cloudwatch", "eu-west-1")
@ -866,7 +865,7 @@ def test_get_metric_data_partially_within_timeframe():
@mock_cloudwatch @mock_cloudwatch
def test_get_metric_data_outside_timeframe(): def test_get_metric_data_outside_timeframe():
utc_now = datetime.now(tz=pytz.utc) utc_now = datetime.now(tz=timezone.utc)
last_week = utc_now - timedelta(days=7) last_week = utc_now - timedelta(days=7)
cloudwatch = boto3.client("cloudwatch", "eu-west-1") cloudwatch = boto3.client("cloudwatch", "eu-west-1")
namespace1 = "my_namespace/" namespace1 = "my_namespace/"
@ -907,7 +906,7 @@ def test_get_metric_data_outside_timeframe():
@mock_cloudwatch @mock_cloudwatch
def test_get_metric_data_for_multiple_metrics(): def test_get_metric_data_for_multiple_metrics():
utc_now = datetime.now(tz=pytz.utc) utc_now = datetime.now(tz=timezone.utc)
cloudwatch = boto3.client("cloudwatch", "eu-west-1") cloudwatch = boto3.client("cloudwatch", "eu-west-1")
namespace = "my_namespace/" namespace = "my_namespace/"
# put metric data # put metric data
@ -968,7 +967,7 @@ def test_get_metric_data_for_multiple_metrics():
@mock_cloudwatch @mock_cloudwatch
def test_get_metric_data_for_dimensions(): def test_get_metric_data_for_dimensions():
utc_now = datetime.now(tz=pytz.utc) utc_now = datetime.now(tz=timezone.utc)
cloudwatch = boto3.client("cloudwatch", "eu-west-1") cloudwatch = boto3.client("cloudwatch", "eu-west-1")
namespace = "my_namespace/" namespace = "my_namespace/"
@ -1076,7 +1075,7 @@ def test_get_metric_data_for_dimensions():
@mock_cloudwatch @mock_cloudwatch
def test_get_metric_data_for_unit(): def test_get_metric_data_for_unit():
utc_now = datetime.now(tz=pytz.utc) utc_now = datetime.now(tz=timezone.utc)
cloudwatch = boto3.client("cloudwatch", "eu-west-1") cloudwatch = boto3.client("cloudwatch", "eu-west-1")
namespace = "my_namespace/" namespace = "my_namespace/"
@ -1149,7 +1148,7 @@ def test_get_metric_data_for_unit():
@mock_cloudwatch @mock_cloudwatch
@mock_s3 @mock_s3
def test_cloudwatch_return_s3_metrics(): def test_cloudwatch_return_s3_metrics():
utc_now = datetime.now(tz=pytz.utc) utc_now = datetime.now(tz=timezone.utc)
bucket_name = "examplebucket" bucket_name = "examplebucket"
cloudwatch = boto3.client("cloudwatch", "eu-west-3") cloudwatch = boto3.client("cloudwatch", "eu-west-3")
@ -1517,7 +1516,7 @@ def test_put_metric_alarm_error_evaluate_low_sample_count_percentile():
@mock_cloudwatch @mock_cloudwatch
def test_get_metric_data_with_custom_label(): def test_get_metric_data_with_custom_label():
utc_now = datetime.now(tz=pytz.utc) utc_now = datetime.now(tz=timezone.utc)
cloudwatch = boto3.client("cloudwatch", "eu-west-1") cloudwatch = boto3.client("cloudwatch", "eu-west-1")
namespace = "my_namespace/" namespace = "my_namespace/"

View File

@ -3,7 +3,6 @@ import datetime
import boto3 import boto3
from botocore.exceptions import ClientError from botocore.exceptions import ClientError
import pytz
import sure # noqa # pylint: disable=unused-import import sure # noqa # pylint: disable=unused-import
from moto import mock_ec2, settings from moto import mock_ec2, settings
@ -27,8 +26,8 @@ def test_request_spot_instances():
conn.create_security_group(GroupName=sec_name_1, Description="description") conn.create_security_group(GroupName=sec_name_1, Description="description")
conn.create_security_group(GroupName=sec_name_2, Description="description") conn.create_security_group(GroupName=sec_name_2, Description="description")
start_dt = datetime.datetime(2013, 1, 1).replace(tzinfo=pytz.utc) start_dt = datetime.datetime(2013, 1, 1).replace(tzinfo=datetime.timezone.utc)
end_dt = datetime.datetime(2013, 1, 2).replace(tzinfo=pytz.utc) end_dt = datetime.datetime(2013, 1, 2).replace(tzinfo=datetime.timezone.utc)
start = iso_8601_datetime_with_milliseconds(start_dt) start = iso_8601_datetime_with_milliseconds(start_dt)
end = iso_8601_datetime_with_milliseconds(end_dt) end = iso_8601_datetime_with_milliseconds(end_dt)

View File

@ -1,11 +1,10 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import time import time
from copy import deepcopy from copy import deepcopy
from datetime import datetime from datetime import datetime, timezone
import boto3 import boto3
import json import json
import pytz
import sure # noqa # pylint: disable=unused-import import sure # noqa # pylint: disable=unused-import
from botocore.exceptions import ClientError from botocore.exceptions import ClientError
import pytest import pytest
@ -173,7 +172,7 @@ def test_describe_cluster():
status["State"].should.equal("TERMINATED") status["State"].should.equal("TERMINATED")
# cluster['Status']['StateChangeReason'] # cluster['Status']['StateChangeReason']
status["Timeline"]["CreationDateTime"].should.be.a("datetime.datetime") status["Timeline"]["CreationDateTime"].should.be.a("datetime.datetime")
# status['Timeline']['EndDateTime'].should.equal(datetime(2014, 1, 24, 2, 19, 46, tzinfo=pytz.utc)) # status['Timeline']['EndDateTime'].should.equal(datetime(2014, 1, 24, 2, 19, 46, tzinfo=timezone.utc))
status["Timeline"]["ReadyDateTime"].should.be.a("datetime.datetime") status["Timeline"]["ReadyDateTime"].should.be.a("datetime.datetime")
dict((t["Key"], t["Value"]) for t in cl["Tags"]).should.equal( dict((t["Key"], t["Value"]) for t in cl["Tags"]).should.equal(
@ -215,7 +214,7 @@ def test_describe_job_flows():
# need sleep since it appears the timestamp is always rounded to # need sleep since it appears the timestamp is always rounded to
# the nearest second internally # the nearest second internally
time.sleep(1) time.sleep(1)
timestamp = datetime.now(pytz.utc) timestamp = datetime.now(timezone.utc)
time.sleep(1) time.sleep(1)
for idx in range(4, 6): for idx in range(4, 6):
@ -338,7 +337,7 @@ def test_list_clusters():
# need sleep since it appears the timestamp is always rounded to # need sleep since it appears the timestamp is always rounded to
# the nearest second internally # the nearest second internally
time.sleep(1) time.sleep(1)
timestamp = datetime.now(pytz.utc) timestamp = datetime.now(timezone.utc)
time.sleep(1) time.sleep(1)
for idx in range(40, 70): for idx in range(40, 70):

View File

@ -1,11 +1,10 @@
import json import json
import random import random
import unittest import unittest
from datetime import datetime from datetime import datetime, timezone
import boto3 import boto3
import pytest import pytest
import pytz
import sure # noqa # pylint: disable=unused-import import sure # noqa # pylint: disable=unused-import
from botocore.exceptions import ClientError from botocore.exceptions import ClientError
@ -1825,8 +1824,8 @@ def test_describe_replay():
ReplayName=name, ReplayName=name,
Description="test replay", Description="test replay",
EventSourceArn=archive_arn, EventSourceArn=archive_arn,
EventStartTime=datetime(2021, 2, 1, tzinfo=pytz.utc), EventStartTime=datetime(2021, 2, 1, tzinfo=timezone.utc),
EventEndTime=datetime(2021, 2, 2, tzinfo=pytz.utc), EventEndTime=datetime(2021, 2, 2, tzinfo=timezone.utc),
Destination={"Arn": event_bus_arn}, Destination={"Arn": event_bus_arn},
) )
@ -1837,8 +1836,8 @@ def test_describe_replay():
response["Description"].should.equal("test replay") response["Description"].should.equal("test replay")
response["Destination"].should.equal({"Arn": event_bus_arn}) response["Destination"].should.equal({"Arn": event_bus_arn})
response["EventSourceArn"].should.equal(archive_arn) response["EventSourceArn"].should.equal(archive_arn)
response["EventStartTime"].should.equal(datetime(2021, 2, 1, tzinfo=pytz.utc)) response["EventStartTime"].should.equal(datetime(2021, 2, 1, tzinfo=timezone.utc))
response["EventEndTime"].should.equal(datetime(2021, 2, 2, tzinfo=pytz.utc)) response["EventEndTime"].should.equal(datetime(2021, 2, 2, tzinfo=timezone.utc))
response["ReplayArn"].should.equal( response["ReplayArn"].should.equal(
f"arn:aws:events:eu-central-1:{ACCOUNT_ID}:replay/{name}" f"arn:aws:events:eu-central-1:{ACCOUNT_ID}:replay/{name}"
) )
@ -1879,8 +1878,8 @@ def test_list_replays():
ReplayName=name, ReplayName=name,
Description="test replay", Description="test replay",
EventSourceArn=archive_arn, EventSourceArn=archive_arn,
EventStartTime=datetime(2021, 2, 1, tzinfo=pytz.utc), EventStartTime=datetime(2021, 2, 1, tzinfo=timezone.utc),
EventEndTime=datetime(2021, 2, 2, tzinfo=pytz.utc), EventEndTime=datetime(2021, 2, 2, tzinfo=timezone.utc),
Destination={"Arn": event_bus_arn}, Destination={"Arn": event_bus_arn},
) )
@ -1891,8 +1890,8 @@ def test_list_replays():
replays.should.have.length_of(1) replays.should.have.length_of(1)
replay = replays[0] replay = replays[0]
replay["EventSourceArn"].should.equal(archive_arn) replay["EventSourceArn"].should.equal(archive_arn)
replay["EventStartTime"].should.equal(datetime(2021, 2, 1, tzinfo=pytz.utc)) replay["EventStartTime"].should.equal(datetime(2021, 2, 1, tzinfo=timezone.utc))
replay["EventEndTime"].should.equal(datetime(2021, 2, 2, tzinfo=pytz.utc)) replay["EventEndTime"].should.equal(datetime(2021, 2, 2, tzinfo=timezone.utc))
replay["ReplayName"].should.equal(name) replay["ReplayName"].should.equal(name)
replay["ReplayStartTime"].should.be.a(datetime) replay["ReplayStartTime"].should.be.a(datetime)
replay["ReplayEndTime"].should.be.a(datetime) replay["ReplayEndTime"].should.be.a(datetime)
@ -1910,15 +1909,15 @@ def test_list_replays_with_name_prefix():
client.start_replay( client.start_replay(
ReplayName="test", ReplayName="test",
EventSourceArn=archive_arn, EventSourceArn=archive_arn,
EventStartTime=datetime(2021, 1, 1, tzinfo=pytz.utc), EventStartTime=datetime(2021, 1, 1, tzinfo=timezone.utc),
EventEndTime=datetime(2021, 1, 2, tzinfo=pytz.utc), EventEndTime=datetime(2021, 1, 2, tzinfo=timezone.utc),
Destination={"Arn": event_bus_arn}, Destination={"Arn": event_bus_arn},
) )
client.start_replay( client.start_replay(
ReplayName="test-replay", ReplayName="test-replay",
EventSourceArn=archive_arn, EventSourceArn=archive_arn,
EventStartTime=datetime(2021, 2, 1, tzinfo=pytz.utc), EventStartTime=datetime(2021, 2, 1, tzinfo=timezone.utc),
EventEndTime=datetime(2021, 2, 2, tzinfo=pytz.utc), EventEndTime=datetime(2021, 2, 2, tzinfo=timezone.utc),
Destination={"Arn": event_bus_arn}, Destination={"Arn": event_bus_arn},
) )
@ -1941,15 +1940,15 @@ def test_list_replays_with_source_arn():
client.start_replay( client.start_replay(
ReplayName="test", ReplayName="test",
EventSourceArn=archive_arn, EventSourceArn=archive_arn,
EventStartTime=datetime(2021, 1, 1, tzinfo=pytz.utc), EventStartTime=datetime(2021, 1, 1, tzinfo=timezone.utc),
EventEndTime=datetime(2021, 1, 2, tzinfo=pytz.utc), EventEndTime=datetime(2021, 1, 2, tzinfo=timezone.utc),
Destination={"Arn": event_bus_arn}, Destination={"Arn": event_bus_arn},
) )
client.start_replay( client.start_replay(
ReplayName="test-replay", ReplayName="test-replay",
EventSourceArn=archive_arn, EventSourceArn=archive_arn,
EventStartTime=datetime(2021, 2, 1, tzinfo=pytz.utc), EventStartTime=datetime(2021, 2, 1, tzinfo=timezone.utc),
EventEndTime=datetime(2021, 2, 2, tzinfo=pytz.utc), EventEndTime=datetime(2021, 2, 2, tzinfo=timezone.utc),
Destination={"Arn": event_bus_arn}, Destination={"Arn": event_bus_arn},
) )
@ -1971,15 +1970,15 @@ def test_list_replays_with_state():
client.start_replay( client.start_replay(
ReplayName="test", ReplayName="test",
EventSourceArn=archive_arn, EventSourceArn=archive_arn,
EventStartTime=datetime(2021, 1, 1, tzinfo=pytz.utc), EventStartTime=datetime(2021, 1, 1, tzinfo=timezone.utc),
EventEndTime=datetime(2021, 1, 2, tzinfo=pytz.utc), EventEndTime=datetime(2021, 1, 2, tzinfo=timezone.utc),
Destination={"Arn": event_bus_arn}, Destination={"Arn": event_bus_arn},
) )
client.start_replay( client.start_replay(
ReplayName="test-replay", ReplayName="test-replay",
EventSourceArn=archive_arn, EventSourceArn=archive_arn,
EventStartTime=datetime(2021, 2, 1, tzinfo=pytz.utc), EventStartTime=datetime(2021, 2, 1, tzinfo=timezone.utc),
EventEndTime=datetime(2021, 2, 2, tzinfo=pytz.utc), EventEndTime=datetime(2021, 2, 2, tzinfo=timezone.utc),
Destination={"Arn": event_bus_arn}, Destination={"Arn": event_bus_arn},
) )
@ -2045,8 +2044,8 @@ def test_cancel_replay():
ReplayName=name, ReplayName=name,
Description="test replay", Description="test replay",
EventSourceArn=archive_arn, EventSourceArn=archive_arn,
EventStartTime=datetime(2021, 2, 1, tzinfo=pytz.utc), EventStartTime=datetime(2021, 2, 1, tzinfo=timezone.utc),
EventEndTime=datetime(2021, 2, 2, tzinfo=pytz.utc), EventEndTime=datetime(2021, 2, 2, tzinfo=timezone.utc),
Destination={"Arn": event_bus_arn}, Destination={"Arn": event_bus_arn},
) )
@ -2094,8 +2093,8 @@ def test_cancel_replay_error_illegal_state():
ReplayName=name, ReplayName=name,
Description="test replay", Description="test replay",
EventSourceArn=archive_arn, EventSourceArn=archive_arn,
EventStartTime=datetime(2021, 2, 1, tzinfo=pytz.utc), EventStartTime=datetime(2021, 2, 1, tzinfo=timezone.utc),
EventEndTime=datetime(2021, 2, 2, tzinfo=pytz.utc), EventEndTime=datetime(2021, 2, 2, tzinfo=timezone.utc),
Destination={"Arn": event_bus_arn}, Destination={"Arn": event_bus_arn},
) )
client.cancel_replay(ReplayName=name) client.cancel_replay(ReplayName=name)

View File

@ -6,8 +6,7 @@ import boto3
from botocore.client import ClientError from botocore.client import ClientError
from datetime import datetime from datetime import datetime, timezone
import pytz
from freezegun import freeze_time from freezegun import freeze_time
from moto import mock_glue, settings from moto import mock_glue, settings
@ -480,14 +479,14 @@ def test_create_partition():
helpers.create_table(client, database_name, table_name) helpers.create_table(client, database_name, table_name)
before = datetime.now(pytz.utc) before = datetime.now(timezone.utc)
part_input = helpers.create_partition_input( part_input = helpers.create_partition_input(
database_name, table_name, values=values database_name, table_name, values=values
) )
helpers.create_partition(client, database_name, table_name, part_input) helpers.create_partition(client, database_name, table_name, part_input)
after = datetime.now(pytz.utc) after = datetime.now(timezone.utc)
response = client.get_partitions(DatabaseName=database_name, TableName=table_name) response = client.get_partitions(DatabaseName=database_name, TableName=table_name)
@ -548,7 +547,7 @@ def test_batch_create_partition():
helpers.create_table(client, database_name, table_name) helpers.create_table(client, database_name, table_name)
before = datetime.now(pytz.utc) before = datetime.now(timezone.utc)
partition_inputs = [] partition_inputs = []
for i in range(0, 20): for i in range(0, 20):
@ -564,7 +563,7 @@ def test_batch_create_partition():
PartitionInputList=partition_inputs, PartitionInputList=partition_inputs,
) )
after = datetime.now(pytz.utc) after = datetime.now(timezone.utc)
response = client.get_partitions(DatabaseName=database_name, TableName=table_name) response = client.get_partitions(DatabaseName=database_name, TableName=table_name)

View File

@ -8,9 +8,8 @@ from moto import mock_secretsmanager, mock_lambda, settings
from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID
from botocore.exceptions import ClientError, ParamValidationError from botocore.exceptions import ClientError, ParamValidationError
import string import string
import pytz
from freezegun import freeze_time from freezegun import freeze_time
from datetime import timedelta, datetime from datetime import datetime, timedelta, timezone
import sure # noqa # pylint: disable=unused-import import sure # noqa # pylint: disable=unused-import
from uuid import uuid4 from uuid import uuid4
import pytest import pytest
@ -259,13 +258,13 @@ def test_delete_secret():
assert deleted_secret["ARN"] assert deleted_secret["ARN"]
assert deleted_secret["Name"] == "test-secret" assert deleted_secret["Name"] == "test-secret"
assert deleted_secret["DeletionDate"] > datetime.fromtimestamp(1, pytz.utc) assert deleted_secret["DeletionDate"] > datetime.fromtimestamp(1, timezone.utc)
secret_details = conn.describe_secret(SecretId="test-secret") secret_details = conn.describe_secret(SecretId="test-secret")
assert secret_details["ARN"] assert secret_details["ARN"]
assert secret_details["Name"] == "test-secret" assert secret_details["Name"] == "test-secret"
assert secret_details["DeletedDate"] > datetime.fromtimestamp(1, pytz.utc) assert secret_details["DeletedDate"] > datetime.fromtimestamp(1, timezone.utc)
@mock_secretsmanager @mock_secretsmanager
@ -278,13 +277,13 @@ def test_delete_secret_by_arn():
assert deleted_secret["ARN"] == secret["ARN"] assert deleted_secret["ARN"] == secret["ARN"]
assert deleted_secret["Name"] == "test-secret" assert deleted_secret["Name"] == "test-secret"
assert deleted_secret["DeletionDate"] > datetime.fromtimestamp(1, pytz.utc) assert deleted_secret["DeletionDate"] > datetime.fromtimestamp(1, timezone.utc)
secret_details = conn.describe_secret(SecretId="test-secret") secret_details = conn.describe_secret(SecretId="test-secret")
assert secret_details["ARN"] == secret["ARN"] assert secret_details["ARN"] == secret["ARN"]
assert secret_details["Name"] == "test-secret" assert secret_details["Name"] == "test-secret"
assert secret_details["DeletedDate"] > datetime.fromtimestamp(1, pytz.utc) assert secret_details["DeletedDate"] > datetime.fromtimestamp(1, timezone.utc)
@mock_secretsmanager @mock_secretsmanager
@ -296,7 +295,7 @@ def test_delete_secret_force():
result = conn.delete_secret(SecretId="test-secret", ForceDeleteWithoutRecovery=True) result = conn.delete_secret(SecretId="test-secret", ForceDeleteWithoutRecovery=True)
assert result["ARN"] assert result["ARN"]
assert result["DeletionDate"] > datetime.fromtimestamp(1, pytz.utc) assert result["DeletionDate"] > datetime.fromtimestamp(1, timezone.utc)
assert result["Name"] == "test-secret" assert result["Name"] == "test-secret"
with pytest.raises(ClientError): with pytest.raises(ClientError):
@ -325,7 +324,7 @@ def test_delete_secret_force_with_arn():
) )
assert result["ARN"] assert result["ARN"]
assert result["DeletionDate"] > datetime.fromtimestamp(1, pytz.utc) assert result["DeletionDate"] > datetime.fromtimestamp(1, timezone.utc)
assert result["Name"] == "test-secret" assert result["Name"] == "test-secret"
with pytest.raises(ClientError): with pytest.raises(ClientError):
@ -533,13 +532,17 @@ def test_describe_secret():
assert secret_description_2["Name"] == ("test-secret-2") assert secret_description_2["Name"] == ("test-secret-2")
assert secret_description_2["ARN"] != "" # Test arn not empty assert secret_description_2["ARN"] != "" # Test arn not empty
assert secret_description["CreatedDate"] <= datetime.now(tz=tzlocal()) assert secret_description["CreatedDate"] <= datetime.now(tz=tzlocal())
assert secret_description["CreatedDate"] > datetime.fromtimestamp(1, pytz.utc) assert secret_description["CreatedDate"] > datetime.fromtimestamp(1, timezone.utc)
assert secret_description_2["CreatedDate"] <= datetime.now(tz=tzlocal()) assert secret_description_2["CreatedDate"] <= datetime.now(tz=tzlocal())
assert secret_description_2["CreatedDate"] > datetime.fromtimestamp(1, pytz.utc) assert secret_description_2["CreatedDate"] > datetime.fromtimestamp(1, timezone.utc)
assert secret_description["LastChangedDate"] <= datetime.now(tz=tzlocal()) assert secret_description["LastChangedDate"] <= datetime.now(tz=tzlocal())
assert secret_description["LastChangedDate"] > datetime.fromtimestamp(1, pytz.utc) assert secret_description["LastChangedDate"] > datetime.fromtimestamp(
1, timezone.utc
)
assert secret_description_2["LastChangedDate"] <= datetime.now(tz=tzlocal()) assert secret_description_2["LastChangedDate"] <= datetime.now(tz=tzlocal())
assert secret_description_2["LastChangedDate"] > datetime.fromtimestamp(1, pytz.utc) assert secret_description_2["LastChangedDate"] > datetime.fromtimestamp(
1, timezone.utc
)
@mock_secretsmanager @mock_secretsmanager
@ -596,7 +599,9 @@ def test_restore_secret():
conn.delete_secret(SecretId="test-secret") conn.delete_secret(SecretId="test-secret")
described_secret_before = conn.describe_secret(SecretId="test-secret") described_secret_before = conn.describe_secret(SecretId="test-secret")
assert described_secret_before["DeletedDate"] > datetime.fromtimestamp(1, pytz.utc) assert described_secret_before["DeletedDate"] > datetime.fromtimestamp(
1, timezone.utc
)
restored_secret = conn.restore_secret(SecretId="test-secret") restored_secret = conn.restore_secret(SecretId="test-secret")
assert restored_secret["ARN"] assert restored_secret["ARN"]