internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: getmoto/moto

Issue:
S3 CreationDate not correctly formatted
I think there's a small regression in version 1.3.15.3 of the library, as used by Localstack.

This appears to be generating incorrectly formatted `CreationDate` fields in S3 ListBucket responses, which breaks some clients (AWS Java SDK chokes on the formatting; AWS CLI does not).

More background is captured in this Localstack issue: https://github.com/localstack/localstack/issues/1899

I suspect this issue can be simply fixed by amending this line to format the creation date according to ISO8601: https://github.com/spulec/moto/commit/ab0853cddc6bf9a0789999751a5d698186b8ebd0#diff-f28b3d402b1d050e247f518f3b94865bR1313


Discussion:
I think this should be fixed with https://github.com/spulec/moto/commit/19bf8bf76207a01a168ec842c2e4e917adc466dd

Let me know if that isn't sufficient.

Resolving patch:
diff --git a/moto/s3/models.py b/moto/s3/models.py
--- a/moto/s3/models.py
+++ b/moto/s3/models.py
@@ -5,6 +5,7 @@
 import os
 import base64
 import datetime
+import pytz
 import hashlib
 import copy
 import itertools
@@ -776,7 +777,7 @@ def __init__(self, name, region_name):
         self.notification_configuration = None
         self.accelerate_configuration = None
         self.payer = "BucketOwner"
-        self.creation_date = datetime.datetime.utcnow()
+        self.creation_date = datetime.datetime.now(tz=pytz.utc)
         self.public_access_block = None
         self.encryption = None
 


Test patch:
Repository: getmoto/moto

Issue:
EventsRule Cloudformation's update
Hey guys ! Happy to be here again :)

Right now I'm facing a issue related with the update of my stack. This issue was detected during a serverless deployment and after further investigation I'd figured out there's no implementation for `update_from_cloudformation_json` in Rule's model.


Discussion:

Resolving patch:
diff --git a/moto/events/models.py b/moto/events/models.py
--- a/moto/events/models.py
+++ b/moto/events/models.py
@@ -80,6 +80,15 @@ def create_from_cloudformation_json(
         event_name = properties.get("Name") or resource_name
         return event_backend.put_rule(name=event_name, **properties)
 
+    @classmethod
+    def update_from_cloudformation_json(
+        cls, original_resource, new_resource_name, cloudformation_json, region_name
+    ):
+        original_resource.delete(region_name)
+        return cls.create_from_cloudformation_json(
+            new_resource_name, cloudformation_json, region_name
+        )
+
     @classmethod
     def delete_from_cloudformation_json(
         cls, resource_name, cloudformation_json, region_name


Test patch:
diff --git a/tests/test_cloudformation/test_cloudformation_stack_integration.py b/tests/test_cloudformation/test_cloudformation_stack_integration.py
--- a/tests/test_cloudformation/test_cloudformation_stack_integration.py
+++ b/tests/test_cloudformation/test_cloudformation_stack_integration.py
@@ -18,6 +18,7 @@
 import boto.vpc
 import boto3
 import sure  # noqa
+from string import Template
 
 from moto import (
     mock_autoscaling_deprecated,
@@ -2499,6 +2500,45 @@ def test_stack_events_create_rule_as_target():
     log_groups["logGroups"][0]["retentionInDays"].should.equal(3)
 
 
+@mock_cloudformation
+@mock_events
+def test_stack_events_update_rule_integration():
+    events_template = Template(
+        """{
+        "AWSTemplateFormatVersion": "2010-09-09",
+        "Resources": {
+            "Event": {
+                "Type": "AWS::Events::Rule",
+                "Properties": {
+                    "Name": "$Name",
+                    "State": "$State",
+                    "ScheduleExpression": "rate(5 minutes)",
+                },
+            }
+        },
+    } """
+    )
+
+    cf_conn = boto3.client("cloudformation", "us-west-2")
+
+    original_template = events_template.substitute(Name="Foo", State="ENABLED")
+    cf_conn.create_stack(StackName="test_stack", TemplateBody=original_template)
+
+    rules = boto3.client("events", "us-west-2").list_rules()
+    rules["Rules"].should.have.length_of(1)
+    rules["Rules"][0]["Name"].should.equal("Foo")
+    rules["Rules"][0]["State"].should.equal("ENABLED")
+
+    update_template = events_template.substitute(Name="Bar", State="DISABLED")
+    cf_conn.update_stack(StackName="test_stack", TemplateBody=update_template)
+
+    rules = boto3.client("events", "us-west-2").list_rules()
+
+    rules["Rules"].should.have.length_of(1)
+    rules["Rules"][0]["Name"].should.equal("Bar")
+    rules["Rules"][0]["State"].should.equal("DISABLED")
+
+
 @mock_cloudformation
 @mock_autoscaling
 def test_autoscaling_propagate_tags():
Repository: getmoto/moto

Issue:
API Gateway create_api_key default value is wrong
API Gateway create_api_key wiill generate some  wrong default value.
For example, `enabled` should be False, but moto will return True.



### Use boto3

```
>>> import moto
>>> import boto3
>>> from pprint import pprint
>>> client = boto3.client('apigateway')
>>> res = client.create_api_key(name='test')
>>> pprint(res)
{'ResponseMetadata': {'HTTPHeaders': {'connection': 'keep-alive',
                                      'content-length': '170',
                                      'content-type': 'application/json',
                                      'date': 'Wed, 15 Jul 2020 02:09:07 GMT',
                                      'x-amz-apigw-id': 'PsTCmK_etjMEbCQ=',
                                      'x-amzn-requestid': '2743161b-503f-40ce-8f3d-b7f9d94ffc11'},
                      'HTTPStatusCode': 201,
                      'RequestId': '2743161b-503f-40ce-8f3d-b7f9d94ffc11',
                      'RetryAttempts': 0},
 'createdDate': datetime.datetime(2020, 7, 15, 11, 9, 7, tzinfo=tzlocal()),
 'enabled': False,
 'id': 'xxxxxxxxxx',
 'lastUpdatedDate': datetime.datetime(2020, 7, 15, 11, 9, 7, tzinfo=tzlocal()),
 'name': 'test',
 'stageKeys': [],
 'value': 'xxxxxxxxxx'}
```



### Use moto

```
>>> import moto
>>> import boto3
>>> from pprint import pprint
>>> client = boto3.client('apigateway')
>>> moto.mock_apigateway().start()
>>> res = client.create_api_key(name='test')
>>> pprint(res)
{'ResponseMetadata': {'HTTPHeaders': {},
                      'HTTPStatusCode': 200,
                      'RetryAttempts': 0},
 'createdDate': datetime.datetime(2020, 7, 15, 11, 9, 43, tzinfo=tzlocal()),
 'enabled': True,
 'id': 'xxxxxxxxxx',
 'lastUpdatedDate': datetime.datetime(2020, 7, 15, 11, 9, 43, tzinfo=tzlocal()),
 'name': 'test',
 'value': 'xxxxxxxxxx'}
```




Discussion:

Resolving patch:
diff --git a/moto/apigateway/models.py b/moto/apigateway/models.py
--- a/moto/apigateway/models.py
+++ b/moto/apigateway/models.py
@@ -400,10 +400,10 @@ def __init__(
         self,
         name=None,
         description=None,
-        enabled=True,
+        enabled=False,
         generateDistinctId=False,
         value=None,
-        stageKeys=None,
+        stageKeys=[],
         tags=None,
         customerId=None,
     ):


Test patch:
diff --git a/tests/test_apigateway/test_apigateway.py b/tests/test_apigateway/test_apigateway.py
--- a/tests/test_apigateway/test_apigateway.py
+++ b/tests/test_apigateway/test_apigateway.py
@@ -1845,7 +1845,11 @@ def test_create_api_key():
     apikey_name = "TESTKEY1"
     payload = {"value": apikey_value, "name": apikey_name}
 
-    client.create_api_key(**payload)
+    response = client.create_api_key(**payload)
+    response["name"].should.equal(apikey_name)
+    response["value"].should.equal(apikey_value)
+    response["enabled"].should.equal(False)
+    response["stageKeys"].should.equal([])
 
     response = client.get_api_keys()
     len(response["items"]).should.equal(1)
Repository: getmoto/moto

Issue:
API Gateway:delete_api_key return wrong status code
API Gateway delete_api_key should return 202 for http status code.
But moto will return 200 ok.

### Use boto3

```
>>> import moto
>>> import boto3
>>> from pprint import pprint
>>> client = boto3.client('apigateway')
>>> res = client.delete_api_key(name='xxx')
>>> pprint(res)
{'ResponseMetadata': {'HTTPHeaders': {'connection': 'keep-alive',
                                      'content-length': '0',
                                      'content-type': 'application/json',
                                      'date': 'Wed, 15 Jul 2020 06:26:19 GMT',
                                      'x-amz-apigw-id': 'Ps4tyJ5ANjMEbow=',
                                      'x-amzn-requestid': '07ec4590-54b4-4dad-8ec5-b986a991446d'},
                      'HTTPStatusCode': 202,
                      'RequestId': '07ec4590-54b4-4dad-8ec5-b986a991446d',
                      'RetryAttempts': 0}}
```



### Use moto

```
>>> import moto
>>> import boto3
>>> from pprint import pprint
>>> client = boto3.client('apigateway')
>>> moto.mock_apigateway().start()
>>> res = client.create_api_key(apiKey='xxx')
>>> pprint(res)
{'ResponseMetadata': {'HTTPHeaders': {},
                      'HTTPStatusCode': 200,
                      'RetryAttempts': 0}}
```




Discussion:

Resolving patch:
diff --git a/moto/apigateway/responses.py b/moto/apigateway/responses.py
--- a/moto/apigateway/responses.py
+++ b/moto/apigateway/responses.py
@@ -466,6 +466,7 @@ def apikey_individual(self, request, full_url, headers):
         url_path_parts = self.path.split("/")
         apikey = url_path_parts[2]
 
+        status_code = 200
         if self.method == "GET":
             apikey_response = self.backend.get_apikey(apikey)
         elif self.method == "PATCH":
@@ -473,7 +474,9 @@ def apikey_individual(self, request, full_url, headers):
             apikey_response = self.backend.update_apikey(apikey, patch_operations)
         elif self.method == "DELETE":
             apikey_response = self.backend.delete_apikey(apikey)
-        return 200, {}, json.dumps(apikey_response)
+            status_code = 202
+
+        return status_code, {}, json.dumps(apikey_response)
 
     def usage_plans(self, request, full_url, headers):
         self.setup_class(request, full_url, headers)


Test patch:
diff --git a/tests/test_apigateway/test_apigateway.py b/tests/test_apigateway/test_apigateway.py
--- a/tests/test_apigateway/test_apigateway.py
+++ b/tests/test_apigateway/test_apigateway.py
@@ -1906,7 +1906,8 @@ def test_api_keys():
     response = client.get_api_keys()
     len(response["items"]).should.equal(2)
 
-    client.delete_api_key(apiKey=apikey_id)
+    response = client.delete_api_key(apiKey=apikey_id)
+    response["ResponseMetadata"]["HTTPStatusCode"].should.equal(202)
 
     response = client.get_api_keys()
     len(response["items"]).should.equal(1)
Repository: getmoto/moto

Issue:
ecs.update_service does not handle service_arns, just services names.
## Actual:
When running:
```
ecs_client.update_service(
            cluster=cluster_arn,
            service=service_arn,
            desiredCount=0
)
```
I'm getting `ServiceNotFoundException` raised, even though I'm using service and cluster ARNs returned by a call to `describe_services`, after creating the services with moto.

## Expected:
Service/Cluster names and ARNs should both be supported.

## Walkaround:
I changed my application logic to make it testable with moto, and it worked, but I shouldn't have to do that, especially that both `boto3` and AWS API allow using Names/ARNs interchangeably.  


Discussion:

Resolving patch:
diff --git a/moto/ecs/models.py b/moto/ecs/models.py
--- a/moto/ecs/models.py
+++ b/moto/ecs/models.py
@@ -931,9 +931,10 @@ def describe_services(self, cluster_str, service_names_or_arns):
         return result
 
     def update_service(
-        self, cluster_str, service_name, task_definition_str, desired_count
+        self, cluster_str, service_str, task_definition_str, desired_count
     ):
         cluster_name = cluster_str.split("/")[-1]
+        service_name = service_str.split("/")[-1]
         cluster_service_pair = "{0}:{1}".format(cluster_name, service_name)
         if cluster_service_pair in self.services:
             if task_definition_str is not None:


Test patch:
diff --git a/tests/test_ecs/test_ecs_boto3.py b/tests/test_ecs/test_ecs_boto3.py
--- a/tests/test_ecs/test_ecs_boto3.py
+++ b/tests/test_ecs/test_ecs_boto3.py
@@ -660,6 +660,15 @@ def test_update_service():
     response["service"]["desiredCount"].should.equal(0)
     response["service"]["schedulingStrategy"].should.equal("REPLICA")
 
+    # Verify we can pass the ARNs of the cluster and service
+    response = client.update_service(
+        cluster=response["service"]["clusterArn"],
+        service=response["service"]["serviceArn"],
+        taskDefinition="test_ecs_task",
+        desiredCount=1,
+    )
+    response["service"]["desiredCount"].should.equal(1)
+
 
 @mock_ecs
 def test_update_missing_service():
Repository: getmoto/moto

Issue:
Meta: Build on master failing
`test_invoke_function_get_ec2_volume` is failing with the following error:

```
error running lambda: lambda invoke failed output: START RequestId: c8528c6e-1b8f-1ac6-d527-46cbabb1f09e Version: 1
[ERROR] NoCredentialsError: Unable to locate credentials
```

## Background
This test executes a Lambda, and tries to retrieve some EC2 Volume-details from within the Docker-container.  
This now fails, since a few days, because of the above error.

Haven't had time to do proper research yet into the why or how, unfortunately.

## Cause
**TBD**

## Debug Logs
https://travis-ci.org/github/spulec/moto/jobs/715826076

## Potential solution
 - [ ] Add os.environ['AWS_SECRET_ACCESS_KEY'] to the test case
 - [ ] ...


FYI @spulec 


Discussion:

Resolving patch:
diff --git a/moto/awslambda/models.py b/moto/awslambda/models.py
--- a/moto/awslambda/models.py
+++ b/moto/awslambda/models.py
@@ -388,11 +388,16 @@ def _invoke_lambda(self, code, event=None, context=None):
             #       also need to hook it up to the other services so it can make kws/s3 etc calls
             #  Should get invoke_id /RequestId from invocation
             env_vars = {
+                "_HANDLER": self.handler,
+                "AWS_EXECUTION_ENV": "AWS_Lambda_{}".format(self.run_time),
                 "AWS_LAMBDA_FUNCTION_TIMEOUT": self.timeout,
                 "AWS_LAMBDA_FUNCTION_NAME": self.function_name,
                 "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": self.memory_size,
                 "AWS_LAMBDA_FUNCTION_VERSION": self.version,
                 "AWS_REGION": self.region,
+                "AWS_ACCESS_KEY_ID": "role-account-id",
+                "AWS_SECRET_ACCESS_KEY": "role-secret-key",
+                "AWS_SESSION_TOKEN": "session-token",
             }
 
             env_vars.update(self.environment_vars)


Test patch:
Repository: getmoto/moto

Issue:
IoT Core delete_thing_group does not behave like real boto3 for nonexistent group
### moto version: 
1.3.15

### module: 
`mock_iot`

### action: 
`delete_thing_group`

### expected behavior:

boto3's response is the same whether or not the thing group existed or not. It does not throw any exception if requested to delete a nonexistent thing group.

### actual behavior:

moto throws a `ResourceNotFoundException` if the thing group does not exist: 

    botocore.errorfactory.ResourceNotFoundException: An error occurred (ResourceNotFoundException) when calling the DeleteThingGroup operation: The specified resource does not exist


Discussion:

Resolving patch:
diff --git a/moto/iot/models.py b/moto/iot/models.py
--- a/moto/iot/models.py
+++ b/moto/iot/models.py
@@ -924,8 +924,12 @@ def delete_thing_group(self, thing_group_name, expected_version):
                 + thing_group_name
                 + " when there are still child groups attached to it"
             )
-        thing_group = self.describe_thing_group(thing_group_name)
-        del self.thing_groups[thing_group.arn]
+        try:
+            thing_group = self.describe_thing_group(thing_group_name)
+            del self.thing_groups[thing_group.arn]
+        except ResourceNotFoundException:
+            # AWS returns success even if the thing group does not exist.
+            pass
 
     def list_thing_groups(self, parent_group, name_prefix_filter, recursive):
         if recursive is None:


Test patch:
diff --git a/tests/test_iot/test_iot.py b/tests/test_iot/test_iot.py
--- a/tests/test_iot/test_iot.py
+++ b/tests/test_iot/test_iot.py
@@ -1038,11 +1038,15 @@ def test_delete_thing_group():
     res.should.have.key("thingGroups").which.should.have.length_of(1)
     res["thingGroups"].should_not.have.key(group_name_2a)
 
-    # now that there is no child group, we can delete the previus group safely
+    # now that there is no child group, we can delete the previous group safely
     client.delete_thing_group(thingGroupName=group_name_1a)
     res = client.list_thing_groups()
     res.should.have.key("thingGroups").which.should.have.length_of(0)
 
+    # Deleting an invalid thing group does not raise an error.
+    res = client.delete_thing_group(thingGroupName="non-existent-group-name")
+    res["ResponseMetadata"]["HTTPStatusCode"].should.equal(200)
+
 
 @mock_iot
 def test_describe_thing_group_metadata_hierarchy():
Repository: getmoto/moto

Issue:
[BUG] acm client: describe_certificate() does not work, unittest is broken as well.

While describing imported acm certificate,  if the certificate does not have any SANs, [get_extension_for_oid()](https://github.com/spulec/moto/blob/d00cefa25cfd338caaabcefc7a79e6e803f577cf/moto/acm/models.py#L296)  could throw a [cryptography.x509.ExtensionNotFound](https://cryptography.io/en/latest/x509/reference/#cryptography.x509.Extensions.get_extension_for_oid ).  

This is clearly not being handled.

The [unit test](https://github.com/spulec/moto/blob/d00cefa25cfd338caaabcefc7a79e6e803f577cf/tests/test_acm/test_acm.py#L129) should have failed here.  But unfortunately, it is overwritten by next function with same name. 

#3370 resolves this.



Discussion:

Resolving patch:
diff --git a/moto/acm/models.py b/moto/acm/models.py
--- a/moto/acm/models.py
+++ b/moto/acm/models.py
@@ -293,9 +293,12 @@ def describe(self):
             key_algo = "EC_prime256v1"
 
         # Look for SANs
-        san_obj = self._cert.extensions.get_extension_for_oid(
-            cryptography.x509.OID_SUBJECT_ALTERNATIVE_NAME
-        )
+        try:
+            san_obj = self._cert.extensions.get_extension_for_oid(
+                cryptography.x509.OID_SUBJECT_ALTERNATIVE_NAME
+            )
+        except cryptography.x509.ExtensionNotFound:
+            san_obj = None
         sans = []
         if san_obj is not None:
             sans = [item.value for item in san_obj.value]


Test patch:
diff --git a/tests/test_acm/test_acm.py b/tests/test_acm/test_acm.py
--- a/tests/test_acm/test_acm.py
+++ b/tests/test_acm/test_acm.py
@@ -140,7 +140,7 @@ def test_describe_certificate():
 
 
 @mock_acm
-def test_describe_certificate():
+def test_describe_certificate_with_bad_arn():
     client = boto3.client("acm", region_name="eu-central-1")
 
     try:
Repository: getmoto/moto

Issue:
EC2 VPNGatewayId Param Casing
Param casing of "VPNGatewayId" is not consistent with boto3 casing and user is unable to set this attribute while testing.

Update to be made in this file: moto/ec2/responses/vpn_connections.py
Line 10: "VPNGatewayId" -> "VpnGatewayId"

Boto3 docs of the same functionality to see the correct option is "VpnGatewayId":
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.create_vpn_gateway


Discussion:
Thanks for raising this @joshah-moors! Will mark it as a bug

Resolving patch:
diff --git a/moto/ec2/responses/vpn_connections.py b/moto/ec2/responses/vpn_connections.py
--- a/moto/ec2/responses/vpn_connections.py
+++ b/moto/ec2/responses/vpn_connections.py
@@ -7,7 +7,7 @@ class VPNConnections(BaseResponse):
     def create_vpn_connection(self):
         type = self._get_param("Type")
         cgw_id = self._get_param("CustomerGatewayId")
-        vgw_id = self._get_param("VPNGatewayId")
+        vgw_id = self._get_param("VpnGatewayId")
         static_routes = self._get_param("StaticRoutesOnly")
         vpn_connection = self.ec2_backend.create_vpn_connection(
             type, cgw_id, vgw_id, static_routes_only=static_routes


Test patch:
diff --git a/tests/test_ec2/test_vpn_connections.py b/tests/test_ec2/test_vpn_connections.py
--- a/tests/test_ec2/test_vpn_connections.py
+++ b/tests/test_ec2/test_vpn_connections.py
@@ -1,10 +1,11 @@
 from __future__ import unicode_literals
 import boto
+import boto3
 from nose.tools import assert_raises
 import sure  # noqa
 from boto.exception import EC2ResponseError
 
-from moto import mock_ec2_deprecated
+from moto import mock_ec2_deprecated, mock_ec2
 
 
 @mock_ec2_deprecated
@@ -51,3 +52,24 @@ def test_describe_vpn_connections():
     list_of_vpn_connections.should.have.length_of(2)
     list_of_vpn_connections = conn.get_all_vpn_connections(vpn.id)
     list_of_vpn_connections.should.have.length_of(1)
+
+
+@mock_ec2
+def test_create_vpn_connection_with_vpn_gateway():
+    client = boto3.client("ec2", region_name="us-east-1")
+
+    vpn_gateway = client.create_vpn_gateway(Type="ipsec.1").get("VpnGateway", {})
+    customer_gateway = client.create_customer_gateway(
+        Type="ipsec.1", PublicIp="205.251.242.54", BgpAsn=65534,
+    ).get("CustomerGateway", {})
+    vpn_connection = client.create_vpn_connection(
+        Type="ipsec.1",
+        VpnGatewayId=vpn_gateway["VpnGatewayId"],
+        CustomerGatewayId=customer_gateway["CustomerGatewayId"],
+    ).get("VpnConnection", {})
+
+    vpn_connection["Type"].should.equal("ipsec.1")
+    vpn_connection["VpnGatewayId"].should.equal(vpn_gateway["VpnGatewayId"])
+    vpn_connection["CustomerGatewayId"].should.equal(
+        customer_gateway["CustomerGatewayId"]
+    )
Repository: getmoto/moto

Issue:
CF error during template validation: TypeError: decode() takes 1 positional argument but 2 were given
Full error:
```
File "/home/travis/build/spulec/moto/moto/cloudformation/responses.py", line 399, in validate_template
    cfn_lint = self.cloudformation_backend.validate_template(template_body)
  File "/home/travis/build/spulec/moto/moto/cloudformation/models.py", line 748, in validate_template
    return validate_template_cfn_lint(template)
  File "/home/travis/build/spulec/moto/moto/cloudformation/utils.py", line 74, in validate_template_cfn_lint
    template, matches = decode.decode(abs_filename, False)
TypeError: decode() takes 1 positional argument but 2 were given
```

Error occurs after `cfn-lint` 0.39.0 was released. 

Travis build that highlights the errors: https://travis-ci.org/github/spulec/moto/jobs/738443110

Specific PR that changed the method-signature: https://github.com/aws-cloudformation/cfn-python-lint/pull/1580/files

PR incoming to fix this


Discussion:

Resolving patch:
diff --git a/moto/cloudformation/utils.py b/moto/cloudformation/utils.py
--- a/moto/cloudformation/utils.py
+++ b/moto/cloudformation/utils.py
@@ -71,7 +71,12 @@ def validate_template_cfn_lint(template):
     abs_filename = os.path.abspath(filename)
 
     # decode handles both yaml and json
-    template, matches = decode.decode(abs_filename, False)
+    try:
+        template, matches = decode.decode(abs_filename, False)
+    except TypeError:
+        # As of cfn-lint 0.39.0, the second argument (ignore_bad_template) was dropped
+        # https://github.com/aws-cloudformation/cfn-python-lint/pull/1580
+        template, matches = decode.decode(abs_filename)
 
     # Set cfn-lint to info
     core.configure_logging(None)


Test patch: