Run black on moto & test directories.

This commit is contained in:
Asher Foa 2019-10-31 08:44:26 -07:00
commit 96e5b1993d
507 changed files with 52541 additions and 47814 deletions

File diff suppressed because it is too large Load diff

View file

@ -5,8 +5,8 @@ from moto import mock_sqs, settings
def test_context_manager_returns_mock():
with mock_sqs() as sqs_mock:
conn = boto3.client("sqs", region_name='us-west-1')
conn = boto3.client("sqs", region_name="us-west-1")
conn.create_queue(QueueName="queue1")
if not settings.TEST_SERVER_MODE:
list(sqs_mock.backends['us-west-1'].queues.keys()).should.equal(['queue1'])
list(sqs_mock.backends["us-west-1"].queues.keys()).should.equal(["queue1"])

View file

@ -9,9 +9,9 @@ from nose.tools import assert_raises
from moto import mock_ec2_deprecated, mock_s3_deprecated
'''
"""
Test the different ways that the decorator can be used
'''
"""
@mock_ec2_deprecated
@ -21,32 +21,32 @@ def test_basic_connect():
@mock_ec2_deprecated
def test_basic_decorator():
conn = boto.connect_ec2('the_key', 'the_secret')
conn = boto.connect_ec2("the_key", "the_secret")
list(conn.get_all_instances()).should.equal([])
def test_context_manager():
conn = boto.connect_ec2('the_key', 'the_secret')
conn = boto.connect_ec2("the_key", "the_secret")
with assert_raises(EC2ResponseError):
conn.get_all_instances()
with mock_ec2_deprecated():
conn = boto.connect_ec2('the_key', 'the_secret')
conn = boto.connect_ec2("the_key", "the_secret")
list(conn.get_all_instances()).should.equal([])
with assert_raises(EC2ResponseError):
conn = boto.connect_ec2('the_key', 'the_secret')
conn = boto.connect_ec2("the_key", "the_secret")
conn.get_all_instances()
def test_decorator_start_and_stop():
conn = boto.connect_ec2('the_key', 'the_secret')
conn = boto.connect_ec2("the_key", "the_secret")
with assert_raises(EC2ResponseError):
conn.get_all_instances()
mock = mock_ec2_deprecated()
mock.start()
conn = boto.connect_ec2('the_key', 'the_secret')
conn = boto.connect_ec2("the_key", "the_secret")
list(conn.get_all_instances()).should.equal([])
mock.stop()
@ -60,12 +60,12 @@ def test_decorater_wrapped_gets_set():
Moto decorator's __wrapped__ should get set to the tests function
"""
test_decorater_wrapped_gets_set.__wrapped__.__name__.should.equal(
'test_decorater_wrapped_gets_set')
"test_decorater_wrapped_gets_set"
)
@mock_ec2_deprecated
class Tester(object):
def test_the_class(self):
conn = boto.connect_ec2()
list(conn.get_all_instances()).should.have.length_of(0)
@ -77,19 +77,17 @@ class Tester(object):
@mock_s3_deprecated
class TesterWithSetup(unittest.TestCase):
def setUp(self):
self.conn = boto.connect_s3()
self.conn.create_bucket('mybucket')
self.conn.create_bucket("mybucket")
def test_still_the_same(self):
bucket = self.conn.get_bucket('mybucket')
bucket = self.conn.get_bucket("mybucket")
bucket.name.should.equal("mybucket")
@mock_s3_deprecated
class TesterWithStaticmethod(object):
@staticmethod
def static(*args):
assert not args or not isinstance(args[0], TesterWithStaticmethod)

View file

@ -6,9 +6,9 @@ import requests
from moto import mock_ec2, settings
if settings.TEST_SERVER_MODE:
BASE_URL = 'http://localhost:5000'
BASE_URL = "http://localhost:5000"
else:
BASE_URL = 'http://169.254.169.254'
BASE_URL = "http://169.254.169.254"
@mock_ec2
@ -21,26 +21,28 @@ def test_latest_meta_data():
def test_meta_data_iam():
res = requests.get("{0}/latest/meta-data/iam".format(BASE_URL))
json_response = res.json()
default_role = json_response['security-credentials']['default-role']
default_role.should.contain('AccessKeyId')
default_role.should.contain('SecretAccessKey')
default_role.should.contain('Token')
default_role.should.contain('Expiration')
default_role = json_response["security-credentials"]["default-role"]
default_role.should.contain("AccessKeyId")
default_role.should.contain("SecretAccessKey")
default_role.should.contain("Token")
default_role.should.contain("Expiration")
@mock_ec2
def test_meta_data_security_credentials():
res = requests.get(
"{0}/latest/meta-data/iam/security-credentials/".format(BASE_URL))
"{0}/latest/meta-data/iam/security-credentials/".format(BASE_URL)
)
res.content.should.equal(b"default-role")
@mock_ec2
def test_meta_data_default_role():
res = requests.get(
"{0}/latest/meta-data/iam/security-credentials/default-role".format(BASE_URL))
"{0}/latest/meta-data/iam/security-credentials/default-role".format(BASE_URL)
)
json_response = res.json()
json_response.should.contain('AccessKeyId')
json_response.should.contain('SecretAccessKey')
json_response.should.contain('Token')
json_response.should.contain('Expiration')
json_response.should.contain("AccessKeyId")
json_response.should.contain("SecretAccessKey")
json_response.should.contain("Token")
json_response.should.contain("Expiration")

View file

@ -6,28 +6,32 @@ import requests
import boto3
from moto import mock_sqs, settings
base_url = "http://localhost:5000" if settings.TEST_SERVER_MODE else "http://motoapi.amazonaws.com"
base_url = (
"http://localhost:5000"
if settings.TEST_SERVER_MODE
else "http://motoapi.amazonaws.com"
)
@mock_sqs
def test_reset_api():
conn = boto3.client("sqs", region_name='us-west-1')
conn = boto3.client("sqs", region_name="us-west-1")
conn.create_queue(QueueName="queue1")
conn.list_queues()['QueueUrls'].should.have.length_of(1)
conn.list_queues()["QueueUrls"].should.have.length_of(1)
res = requests.post("{base_url}/moto-api/reset".format(base_url=base_url))
res.content.should.equal(b'{"status": "ok"}')
conn.list_queues().shouldnt.contain('QueueUrls') # No more queues
conn.list_queues().shouldnt.contain("QueueUrls") # No more queues
@mock_sqs
def test_data_api():
conn = boto3.client("sqs", region_name='us-west-1')
conn = boto3.client("sqs", region_name="us-west-1")
conn.create_queue(QueueName="queue1")
res = requests.post("{base_url}/moto-api/data.json".format(base_url=base_url))
queues = res.json()['sqs']['Queue']
queues = res.json()["sqs"]["Queue"]
len(queues).should.equal(1)
queue = queues[0]
queue['name'].should.equal("queue1")
queue["name"].should.equal("queue1")

View file

@ -9,14 +9,13 @@ from moto import mock_sqs_deprecated, mock_ec2_deprecated
class TestNestedDecorators(unittest.TestCase):
@mock_sqs_deprecated
def setup_sqs_queue(self):
conn = SQSConnection()
q = conn.create_queue('some-queue')
q = conn.create_queue("some-queue")
m = Message()
m.set_body('This is my first message.')
m.set_body("This is my first message.")
q.write(m)
self.assertEqual(q.count(), 1)
@ -26,4 +25,4 @@ class TestNestedDecorators(unittest.TestCase):
self.setup_sqs_queue()
conn = EC2Connection()
conn.run_instances('ami-123456')
conn.run_instances("ami-123456")

View file

@ -7,7 +7,7 @@ from moto import mock_sqs, settings
@mock_sqs
def test_passthrough_requests():
conn = boto3.client("sqs", region_name='us-west-1')
conn = boto3.client("sqs", region_name="us-west-1")
conn.create_queue(QueueName="queue1")
res = requests.get("https://httpbin.org/ip")
@ -15,6 +15,7 @@ def test_passthrough_requests():
if not settings.TEST_SERVER_MODE:
@mock_sqs
def test_requests_to_amazon_subdomains_dont_work():
res = requests.get("https://fakeservice.amazonaws.com/foo/bar")

View file

@ -9,81 +9,86 @@ from moto.core.responses import flatten_json_request_body
def test_flatten_json_request_body():
spec = AWSServiceSpec(
'data/emr/2009-03-31/service-2.json').input_spec('RunJobFlow')
spec = AWSServiceSpec("data/emr/2009-03-31/service-2.json").input_spec("RunJobFlow")
body = {
'Name': 'cluster',
'Instances': {
'Ec2KeyName': 'ec2key',
'InstanceGroups': [
{'InstanceRole': 'MASTER',
'InstanceType': 'm1.small'},
{'InstanceRole': 'CORE',
'InstanceType': 'm1.medium'},
"Name": "cluster",
"Instances": {
"Ec2KeyName": "ec2key",
"InstanceGroups": [
{"InstanceRole": "MASTER", "InstanceType": "m1.small"},
{"InstanceRole": "CORE", "InstanceType": "m1.medium"},
],
'Placement': {'AvailabilityZone': 'us-east-1'},
"Placement": {"AvailabilityZone": "us-east-1"},
},
'Steps': [
{'HadoopJarStep': {
'Properties': [
{'Key': 'k1', 'Value': 'v1'},
{'Key': 'k2', 'Value': 'v2'}
],
'Args': ['arg1', 'arg2']}},
"Steps": [
{
"HadoopJarStep": {
"Properties": [
{"Key": "k1", "Value": "v1"},
{"Key": "k2", "Value": "v2"},
],
"Args": ["arg1", "arg2"],
}
}
],
"Configurations": [
{
"Classification": "class",
"Properties": {"propkey1": "propkey1", "propkey2": "propkey2"},
},
{"Classification": "anotherclass", "Properties": {"propkey3": "propkey3"}},
],
'Configurations': [
{'Classification': 'class',
'Properties': {'propkey1': 'propkey1',
'propkey2': 'propkey2'}},
{'Classification': 'anotherclass',
'Properties': {'propkey3': 'propkey3'}},
]
}
flat = flatten_json_request_body('', body, spec)
flat['Name'].should.equal(body['Name'])
flat['Instances.Ec2KeyName'].should.equal(body['Instances']['Ec2KeyName'])
flat = flatten_json_request_body("", body, spec)
flat["Name"].should.equal(body["Name"])
flat["Instances.Ec2KeyName"].should.equal(body["Instances"]["Ec2KeyName"])
for idx in range(2):
flat['Instances.InstanceGroups.member.' + str(idx + 1) + '.InstanceRole'].should.equal(
body['Instances']['InstanceGroups'][idx]['InstanceRole'])
flat['Instances.InstanceGroups.member.' + str(idx + 1) + '.InstanceType'].should.equal(
body['Instances']['InstanceGroups'][idx]['InstanceType'])
flat['Instances.Placement.AvailabilityZone'].should.equal(
body['Instances']['Placement']['AvailabilityZone'])
flat[
"Instances.InstanceGroups.member." + str(idx + 1) + ".InstanceRole"
].should.equal(body["Instances"]["InstanceGroups"][idx]["InstanceRole"])
flat[
"Instances.InstanceGroups.member." + str(idx + 1) + ".InstanceType"
].should.equal(body["Instances"]["InstanceGroups"][idx]["InstanceType"])
flat["Instances.Placement.AvailabilityZone"].should.equal(
body["Instances"]["Placement"]["AvailabilityZone"]
)
for idx in range(1):
prefix = 'Steps.member.' + str(idx + 1) + '.HadoopJarStep'
step = body['Steps'][idx]['HadoopJarStep']
prefix = "Steps.member." + str(idx + 1) + ".HadoopJarStep"
step = body["Steps"][idx]["HadoopJarStep"]
i = 0
while prefix + '.Properties.member.' + str(i + 1) + '.Key' in flat:
flat[prefix + '.Properties.member.' +
str(i + 1) + '.Key'].should.equal(step['Properties'][i]['Key'])
flat[prefix + '.Properties.member.' +
str(i + 1) + '.Value'].should.equal(step['Properties'][i]['Value'])
while prefix + ".Properties.member." + str(i + 1) + ".Key" in flat:
flat[prefix + ".Properties.member." + str(i + 1) + ".Key"].should.equal(
step["Properties"][i]["Key"]
)
flat[prefix + ".Properties.member." + str(i + 1) + ".Value"].should.equal(
step["Properties"][i]["Value"]
)
i += 1
i = 0
while prefix + '.Args.member.' + str(i + 1) in flat:
flat[prefix + '.Args.member.' +
str(i + 1)].should.equal(step['Args'][i])
while prefix + ".Args.member." + str(i + 1) in flat:
flat[prefix + ".Args.member." + str(i + 1)].should.equal(step["Args"][i])
i += 1
for idx in range(2):
flat['Configurations.member.' + str(idx + 1) + '.Classification'].should.equal(
body['Configurations'][idx]['Classification'])
flat["Configurations.member." + str(idx + 1) + ".Classification"].should.equal(
body["Configurations"][idx]["Classification"]
)
props = {}
i = 1
keyfmt = 'Configurations.member.{0}.Properties.entry.{1}'
keyfmt = "Configurations.member.{0}.Properties.entry.{1}"
key = keyfmt.format(idx + 1, i)
while key + '.key' in flat:
props[flat[key + '.key']] = flat[key + '.value']
while key + ".key" in flat:
props[flat[key + ".key"]] = flat[key + ".value"]
i += 1
key = keyfmt.format(idx + 1, i)
props.should.equal(body['Configurations'][idx]['Properties'])
props.should.equal(body["Configurations"][idx]["Properties"])
def test_parse_qs_unicode_decode_error():
body = b'{"key": "%D0"}, "C": "#0 = :0"}'
request = AWSPreparedRequest('GET', 'http://request', {'foo': 'bar'}, body, False)
request = AWSPreparedRequest("GET", "http://request", {"foo": "bar"}, body, False)
BaseResponse().setup_class(request, request.url, request.headers)

View file

@ -8,13 +8,15 @@ from moto.server import main, create_backend_app, DomainDispatcherApplication
def test_wrong_arguments():
try:
main(["name", "test1", "test2", "test3"])
assert False, ("main() when called with the incorrect number of args"
" should raise a system exit")
assert False, (
"main() when called with the incorrect number of args"
" should raise a system exit"
)
except SystemExit:
pass
@patch('moto.server.run_simple')
@patch("moto.server.run_simple")
def test_right_arguments(run_simple):
main(["s3"])
func_call = run_simple.call_args[0]
@ -22,7 +24,7 @@ def test_right_arguments(run_simple):
func_call[1].should.equal(5000)
@patch('moto.server.run_simple')
@patch("moto.server.run_simple")
def test_port_argument(run_simple):
main(["s3", "--port", "8080"])
func_call = run_simple.call_args[0]
@ -33,15 +35,15 @@ def test_port_argument(run_simple):
def test_domain_dispatched():
dispatcher = DomainDispatcherApplication(create_backend_app)
backend_app = dispatcher.get_application(
{"HTTP_HOST": "email.us-east1.amazonaws.com"})
{"HTTP_HOST": "email.us-east1.amazonaws.com"}
)
keys = list(backend_app.view_functions.keys())
keys[0].should.equal('EmailResponse.dispatch')
keys[0].should.equal("EmailResponse.dispatch")
def test_domain_dispatched_with_service():
# If we pass a particular service, always return that.
dispatcher = DomainDispatcherApplication(create_backend_app, service="s3")
backend_app = dispatcher.get_application(
{"HTTP_HOST": "s3.us-east1.amazonaws.com"})
backend_app = dispatcher.get_application({"HTTP_HOST": "s3.us-east1.amazonaws.com"})
keys = set(backend_app.view_functions.keys())
keys.should.contain('ResponseObject.key_response')
keys.should.contain("ResponseObject.key_response")

View file

@ -6,16 +6,16 @@ from six import PY3
class TestSocketPair(unittest.TestCase):
@mock_dynamodb2_deprecated
def test_asyncio_deprecated(self):
if PY3:
self.assertIn(
'moto.packages.httpretty.core.fakesock.socket',
"moto.packages.httpretty.core.fakesock.socket",
str(socket.socket),
'Our mock should be present'
"Our mock should be present",
)
import asyncio
self.assertIsNotNone(asyncio.get_event_loop())
@mock_dynamodb2_deprecated
@ -24,9 +24,9 @@ class TestSocketPair(unittest.TestCase):
# In Python2, the fakesocket is not set, for some reason.
if PY3:
self.assertIn(
'moto.packages.httpretty.core.fakesock.socket',
"moto.packages.httpretty.core.fakesock.socket",
str(socket.socket),
'Our mock should be present'
"Our mock should be present",
)
a, b = socket.socketpair()
self.assertIsNotNone(a)
@ -36,7 +36,6 @@ class TestSocketPair(unittest.TestCase):
if b:
b.close()
@mock_dynamodb2
def test_socket_pair(self):
a, b = socket.socketpair()

View file

@ -14,8 +14,9 @@ def test_flask_path_converting_simple():
def test_flask_path_converting_regex():
convert_regex_to_flask_path(
"/(?P<key_name>[a-zA-Z0-9\-_]+)").should.equal('/<regex("[a-zA-Z0-9\-_]+"):key_name>')
convert_regex_to_flask_path("/(?P<key_name>[a-zA-Z0-9\-_]+)").should.equal(
'/<regex("[a-zA-Z0-9\-_]+"):key_name>'
)
convert_regex_to_flask_path("(?P<account_id>\d+)/(?P<queue_name>.*)$").should.equal(
'<regex("\d+"):account_id>/<regex(".*"):queue_name>'

View file

@ -3,7 +3,11 @@ from __future__ import unicode_literals
import sure # noqa
from freezegun import freeze_time
from moto.core.utils import camelcase_to_underscores, underscores_to_camelcase, unix_time
from moto.core.utils import (
camelcase_to_underscores,
underscores_to_camelcase,
unix_time,
)
def test_camelcase_to_underscores():
@ -18,9 +22,7 @@ def test_camelcase_to_underscores():
def test_underscores_to_camelcase():
cases = {
"the_new_attribute": "theNewAttribute",
}
cases = {"the_new_attribute": "theNewAttribute"}
for arg, expected in cases.items():
underscores_to_camelcase(arg).should.equal(expected)