This commit is contained in:
Stephan 2018-12-21 12:28:56 +01:00
commit e51d1bfade
172 changed files with 49629 additions and 49629 deletions

View file

@ -1,308 +1,308 @@
from __future__ import unicode_literals
import boto
from boto.exception import BotoServerError
from moto import mock_sns_deprecated
import sure # noqa
@mock_sns_deprecated
def test_create_platform_application():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
attributes={
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
},
)
application_arn = platform_application['CreatePlatformApplicationResponse'][
'CreatePlatformApplicationResult']['PlatformApplicationArn']
application_arn.should.equal(
'arn:aws:sns:us-east-1:123456789012:app/APNS/my-application')
@mock_sns_deprecated
def test_get_platform_application_attributes():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
attributes={
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
},
)
arn = platform_application['CreatePlatformApplicationResponse'][
'CreatePlatformApplicationResult']['PlatformApplicationArn']
attributes = conn.get_platform_application_attributes(arn)['GetPlatformApplicationAttributesResponse'][
'GetPlatformApplicationAttributesResult']['Attributes']
attributes.should.equal({
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
})
@mock_sns_deprecated
def test_get_missing_platform_application_attributes():
conn = boto.connect_sns()
conn.get_platform_application_attributes.when.called_with(
"a-fake-arn").should.throw(BotoServerError)
@mock_sns_deprecated
def test_set_platform_application_attributes():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
attributes={
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
},
)
arn = platform_application['CreatePlatformApplicationResponse'][
'CreatePlatformApplicationResult']['PlatformApplicationArn']
conn.set_platform_application_attributes(arn,
{"PlatformPrincipal": "other"}
)
attributes = conn.get_platform_application_attributes(arn)['GetPlatformApplicationAttributesResponse'][
'GetPlatformApplicationAttributesResult']['Attributes']
attributes.should.equal({
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "other",
})
@mock_sns_deprecated
def test_list_platform_applications():
conn = boto.connect_sns()
conn.create_platform_application(
name="application1",
platform="APNS",
)
conn.create_platform_application(
name="application2",
platform="APNS",
)
applications_repsonse = conn.list_platform_applications()
applications = applications_repsonse['ListPlatformApplicationsResponse'][
'ListPlatformApplicationsResult']['PlatformApplications']
applications.should.have.length_of(2)
@mock_sns_deprecated
def test_delete_platform_application():
conn = boto.connect_sns()
conn.create_platform_application(
name="application1",
platform="APNS",
)
conn.create_platform_application(
name="application2",
platform="APNS",
)
applications_repsonse = conn.list_platform_applications()
applications = applications_repsonse['ListPlatformApplicationsResponse'][
'ListPlatformApplicationsResult']['PlatformApplications']
applications.should.have.length_of(2)
application_arn = applications[0]['PlatformApplicationArn']
conn.delete_platform_application(application_arn)
applications_repsonse = conn.list_platform_applications()
applications = applications_repsonse['ListPlatformApplicationsResponse'][
'ListPlatformApplicationsResult']['PlatformApplications']
applications.should.have.length_of(1)
@mock_sns_deprecated
def test_create_platform_endpoint():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse'][
'CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"Enabled": False,
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse'][
'CreatePlatformEndpointResult']['EndpointArn']
endpoint_arn.should.contain(
"arn:aws:sns:us-east-1:123456789012:endpoint/APNS/my-application/")
@mock_sns_deprecated
def test_get_list_endpoints_by_platform_application():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse'][
'CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse'][
'CreatePlatformEndpointResult']['EndpointArn']
endpoint_list = conn.list_endpoints_by_platform_application(
platform_application_arn=application_arn
)['ListEndpointsByPlatformApplicationResponse']['ListEndpointsByPlatformApplicationResult']['Endpoints']
endpoint_list.should.have.length_of(1)
endpoint_list[0]['Attributes']['CustomUserData'].should.equal('some data')
endpoint_list[0]['EndpointArn'].should.equal(endpoint_arn)
@mock_sns_deprecated
def test_get_endpoint_attributes():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse'][
'CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"Enabled": False,
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse'][
'CreatePlatformEndpointResult']['EndpointArn']
attributes = conn.get_endpoint_attributes(endpoint_arn)['GetEndpointAttributesResponse'][
'GetEndpointAttributesResult']['Attributes']
attributes.should.equal({
"Token": "some_unique_id",
"Enabled": 'False',
"CustomUserData": "some data",
})
@mock_sns_deprecated
def test_get_missing_endpoint_attributes():
conn = boto.connect_sns()
conn.get_endpoint_attributes.when.called_with(
"a-fake-arn").should.throw(BotoServerError)
@mock_sns_deprecated
def test_set_endpoint_attributes():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse'][
'CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"Enabled": False,
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse'][
'CreatePlatformEndpointResult']['EndpointArn']
conn.set_endpoint_attributes(endpoint_arn,
{"CustomUserData": "other data"}
)
attributes = conn.get_endpoint_attributes(endpoint_arn)['GetEndpointAttributesResponse'][
'GetEndpointAttributesResult']['Attributes']
attributes.should.equal({
"Token": "some_unique_id",
"Enabled": 'False',
"CustomUserData": "other data",
})
@mock_sns_deprecated
def test_delete_endpoint():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse'][
'CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"Enabled": False,
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse'][
'CreatePlatformEndpointResult']['EndpointArn']
endpoint_list = conn.list_endpoints_by_platform_application(
platform_application_arn=application_arn
)['ListEndpointsByPlatformApplicationResponse']['ListEndpointsByPlatformApplicationResult']['Endpoints']
endpoint_list.should.have.length_of(1)
conn.delete_endpoint(endpoint_arn)
endpoint_list = conn.list_endpoints_by_platform_application(
platform_application_arn=application_arn
)['ListEndpointsByPlatformApplicationResponse']['ListEndpointsByPlatformApplicationResult']['Endpoints']
endpoint_list.should.have.length_of(0)
@mock_sns_deprecated
def test_publish_to_platform_endpoint():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse'][
'CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"Enabled": True,
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse'][
'CreatePlatformEndpointResult']['EndpointArn']
conn.publish(message="some message", message_structure="json",
target_arn=endpoint_arn)
from __future__ import unicode_literals
import boto
from boto.exception import BotoServerError
from moto import mock_sns_deprecated
import sure # noqa
@mock_sns_deprecated
def test_create_platform_application():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
attributes={
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
},
)
application_arn = platform_application['CreatePlatformApplicationResponse'][
'CreatePlatformApplicationResult']['PlatformApplicationArn']
application_arn.should.equal(
'arn:aws:sns:us-east-1:123456789012:app/APNS/my-application')
@mock_sns_deprecated
def test_get_platform_application_attributes():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
attributes={
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
},
)
arn = platform_application['CreatePlatformApplicationResponse'][
'CreatePlatformApplicationResult']['PlatformApplicationArn']
attributes = conn.get_platform_application_attributes(arn)['GetPlatformApplicationAttributesResponse'][
'GetPlatformApplicationAttributesResult']['Attributes']
attributes.should.equal({
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
})
@mock_sns_deprecated
def test_get_missing_platform_application_attributes():
conn = boto.connect_sns()
conn.get_platform_application_attributes.when.called_with(
"a-fake-arn").should.throw(BotoServerError)
@mock_sns_deprecated
def test_set_platform_application_attributes():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
attributes={
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
},
)
arn = platform_application['CreatePlatformApplicationResponse'][
'CreatePlatformApplicationResult']['PlatformApplicationArn']
conn.set_platform_application_attributes(arn,
{"PlatformPrincipal": "other"}
)
attributes = conn.get_platform_application_attributes(arn)['GetPlatformApplicationAttributesResponse'][
'GetPlatformApplicationAttributesResult']['Attributes']
attributes.should.equal({
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "other",
})
@mock_sns_deprecated
def test_list_platform_applications():
conn = boto.connect_sns()
conn.create_platform_application(
name="application1",
platform="APNS",
)
conn.create_platform_application(
name="application2",
platform="APNS",
)
applications_repsonse = conn.list_platform_applications()
applications = applications_repsonse['ListPlatformApplicationsResponse'][
'ListPlatformApplicationsResult']['PlatformApplications']
applications.should.have.length_of(2)
@mock_sns_deprecated
def test_delete_platform_application():
conn = boto.connect_sns()
conn.create_platform_application(
name="application1",
platform="APNS",
)
conn.create_platform_application(
name="application2",
platform="APNS",
)
applications_repsonse = conn.list_platform_applications()
applications = applications_repsonse['ListPlatformApplicationsResponse'][
'ListPlatformApplicationsResult']['PlatformApplications']
applications.should.have.length_of(2)
application_arn = applications[0]['PlatformApplicationArn']
conn.delete_platform_application(application_arn)
applications_repsonse = conn.list_platform_applications()
applications = applications_repsonse['ListPlatformApplicationsResponse'][
'ListPlatformApplicationsResult']['PlatformApplications']
applications.should.have.length_of(1)
@mock_sns_deprecated
def test_create_platform_endpoint():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse'][
'CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"Enabled": False,
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse'][
'CreatePlatformEndpointResult']['EndpointArn']
endpoint_arn.should.contain(
"arn:aws:sns:us-east-1:123456789012:endpoint/APNS/my-application/")
@mock_sns_deprecated
def test_get_list_endpoints_by_platform_application():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse'][
'CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse'][
'CreatePlatformEndpointResult']['EndpointArn']
endpoint_list = conn.list_endpoints_by_platform_application(
platform_application_arn=application_arn
)['ListEndpointsByPlatformApplicationResponse']['ListEndpointsByPlatformApplicationResult']['Endpoints']
endpoint_list.should.have.length_of(1)
endpoint_list[0]['Attributes']['CustomUserData'].should.equal('some data')
endpoint_list[0]['EndpointArn'].should.equal(endpoint_arn)
@mock_sns_deprecated
def test_get_endpoint_attributes():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse'][
'CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"Enabled": False,
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse'][
'CreatePlatformEndpointResult']['EndpointArn']
attributes = conn.get_endpoint_attributes(endpoint_arn)['GetEndpointAttributesResponse'][
'GetEndpointAttributesResult']['Attributes']
attributes.should.equal({
"Token": "some_unique_id",
"Enabled": 'False',
"CustomUserData": "some data",
})
@mock_sns_deprecated
def test_get_missing_endpoint_attributes():
conn = boto.connect_sns()
conn.get_endpoint_attributes.when.called_with(
"a-fake-arn").should.throw(BotoServerError)
@mock_sns_deprecated
def test_set_endpoint_attributes():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse'][
'CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"Enabled": False,
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse'][
'CreatePlatformEndpointResult']['EndpointArn']
conn.set_endpoint_attributes(endpoint_arn,
{"CustomUserData": "other data"}
)
attributes = conn.get_endpoint_attributes(endpoint_arn)['GetEndpointAttributesResponse'][
'GetEndpointAttributesResult']['Attributes']
attributes.should.equal({
"Token": "some_unique_id",
"Enabled": 'False',
"CustomUserData": "other data",
})
@mock_sns_deprecated
def test_delete_endpoint():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse'][
'CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"Enabled": False,
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse'][
'CreatePlatformEndpointResult']['EndpointArn']
endpoint_list = conn.list_endpoints_by_platform_application(
platform_application_arn=application_arn
)['ListEndpointsByPlatformApplicationResponse']['ListEndpointsByPlatformApplicationResult']['Endpoints']
endpoint_list.should.have.length_of(1)
conn.delete_endpoint(endpoint_arn)
endpoint_list = conn.list_endpoints_by_platform_application(
platform_application_arn=application_arn
)['ListEndpointsByPlatformApplicationResponse']['ListEndpointsByPlatformApplicationResult']['Endpoints']
endpoint_list.should.have.length_of(0)
@mock_sns_deprecated
def test_publish_to_platform_endpoint():
conn = boto.connect_sns()
platform_application = conn.create_platform_application(
name="my-application",
platform="APNS",
)
application_arn = platform_application['CreatePlatformApplicationResponse'][
'CreatePlatformApplicationResult']['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
platform_application_arn=application_arn,
token="some_unique_id",
custom_user_data="some user data",
attributes={
"Enabled": True,
},
)
endpoint_arn = endpoint['CreatePlatformEndpointResponse'][
'CreatePlatformEndpointResult']['EndpointArn']
conn.publish(message="some message", message_structure="json",
target_arn=endpoint_arn)

View file

@ -1,350 +1,350 @@
from __future__ import unicode_literals
import boto3
from botocore.exceptions import ClientError
from moto import mock_sns
import sure # noqa
@mock_sns
def test_create_platform_application():
conn = boto3.client('sns', region_name='us-east-1')
response = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
},
)
application_arn = response['PlatformApplicationArn']
application_arn.should.equal(
'arn:aws:sns:us-east-1:123456789012:app/APNS/my-application')
@mock_sns
def test_get_platform_application_attributes():
conn = boto3.client('sns', region_name='us-east-1')
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
},
)
arn = platform_application['PlatformApplicationArn']
attributes = conn.get_platform_application_attributes(
PlatformApplicationArn=arn)['Attributes']
attributes.should.equal({
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
})
@mock_sns
def test_get_missing_platform_application_attributes():
conn = boto3.client('sns', region_name='us-east-1')
conn.get_platform_application_attributes.when.called_with(
PlatformApplicationArn="a-fake-arn").should.throw(ClientError)
@mock_sns
def test_set_platform_application_attributes():
conn = boto3.client('sns', region_name='us-east-1')
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
},
)
arn = platform_application['PlatformApplicationArn']
conn.set_platform_application_attributes(PlatformApplicationArn=arn,
Attributes={
"PlatformPrincipal": "other"}
)
attributes = conn.get_platform_application_attributes(
PlatformApplicationArn=arn)['Attributes']
attributes.should.equal({
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "other",
})
@mock_sns
def test_list_platform_applications():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_platform_application(
Name="application1",
Platform="APNS",
Attributes={},
)
conn.create_platform_application(
Name="application2",
Platform="APNS",
Attributes={},
)
applications_repsonse = conn.list_platform_applications()
applications = applications_repsonse['PlatformApplications']
applications.should.have.length_of(2)
@mock_sns
def test_delete_platform_application():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_platform_application(
Name="application1",
Platform="APNS",
Attributes={},
)
conn.create_platform_application(
Name="application2",
Platform="APNS",
Attributes={},
)
applications_repsonse = conn.list_platform_applications()
applications = applications_repsonse['PlatformApplications']
applications.should.have.length_of(2)
application_arn = applications[0]['PlatformApplicationArn']
conn.delete_platform_application(PlatformApplicationArn=application_arn)
applications_repsonse = conn.list_platform_applications()
applications = applications_repsonse['PlatformApplications']
applications.should.have.length_of(1)
@mock_sns
def test_create_platform_endpoint():
conn = boto3.client('sns', region_name='us-east-1')
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={},
)
application_arn = platform_application['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
PlatformApplicationArn=application_arn,
Token="some_unique_id",
CustomUserData="some user data",
Attributes={
"Enabled": 'false',
},
)
endpoint_arn = endpoint['EndpointArn']
endpoint_arn.should.contain(
"arn:aws:sns:us-east-1:123456789012:endpoint/APNS/my-application/")
@mock_sns
def test_create_duplicate_platform_endpoint():
conn = boto3.client('sns', region_name='us-east-1')
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={},
)
application_arn = platform_application['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
PlatformApplicationArn=application_arn,
Token="some_unique_id",
CustomUserData="some user data",
Attributes={
"Enabled": 'false',
},
)
endpoint = conn.create_platform_endpoint.when.called_with(
PlatformApplicationArn=application_arn,
Token="some_unique_id",
CustomUserData="some user data",
Attributes={
"Enabled": 'false',
},
).should.throw(ClientError)
@mock_sns
def test_get_list_endpoints_by_platform_application():
conn = boto3.client('sns', region_name='us-east-1')
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={},
)
application_arn = platform_application['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
PlatformApplicationArn=application_arn,
Token="some_unique_id",
CustomUserData="some user data",
Attributes={
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['EndpointArn']
endpoint_list = conn.list_endpoints_by_platform_application(
PlatformApplicationArn=application_arn
)['Endpoints']
endpoint_list.should.have.length_of(1)
endpoint_list[0]['Attributes']['CustomUserData'].should.equal('some data')
endpoint_list[0]['EndpointArn'].should.equal(endpoint_arn)
@mock_sns
def test_get_endpoint_attributes():
conn = boto3.client('sns', region_name='us-east-1')
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={},
)
application_arn = platform_application['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
PlatformApplicationArn=application_arn,
Token="some_unique_id",
CustomUserData="some user data",
Attributes={
"Enabled": 'false',
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['EndpointArn']
attributes = conn.get_endpoint_attributes(
EndpointArn=endpoint_arn)['Attributes']
attributes.should.equal({
"Token": "some_unique_id",
"Enabled": 'false',
"CustomUserData": "some data",
})
@mock_sns
def test_get_missing_endpoint_attributes():
conn = boto3.client('sns', region_name='us-east-1')
conn.get_endpoint_attributes.when.called_with(
EndpointArn="a-fake-arn").should.throw(ClientError)
@mock_sns
def test_set_endpoint_attributes():
conn = boto3.client('sns', region_name='us-east-1')
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={},
)
application_arn = platform_application['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
PlatformApplicationArn=application_arn,
Token="some_unique_id",
CustomUserData="some user data",
Attributes={
"Enabled": 'false',
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['EndpointArn']
conn.set_endpoint_attributes(EndpointArn=endpoint_arn,
Attributes={"CustomUserData": "other data"}
)
attributes = conn.get_endpoint_attributes(
EndpointArn=endpoint_arn)['Attributes']
attributes.should.equal({
"Token": "some_unique_id",
"Enabled": 'false',
"CustomUserData": "other data",
})
@mock_sns
def test_publish_to_platform_endpoint():
conn = boto3.client('sns', region_name='us-east-1')
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={},
)
application_arn = platform_application['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
PlatformApplicationArn=application_arn,
Token="some_unique_id",
CustomUserData="some user data",
Attributes={
"Enabled": 'true',
},
)
endpoint_arn = endpoint['EndpointArn']
conn.publish(Message="some message",
MessageStructure="json", TargetArn=endpoint_arn)
@mock_sns
def test_publish_to_disabled_platform_endpoint():
conn = boto3.client('sns', region_name='us-east-1')
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={},
)
application_arn = platform_application['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
PlatformApplicationArn=application_arn,
Token="some_unique_id",
CustomUserData="some user data",
Attributes={
"Enabled": 'false',
},
)
endpoint_arn = endpoint['EndpointArn']
conn.publish.when.called_with(
Message="some message",
MessageStructure="json",
TargetArn=endpoint_arn,
).should.throw(ClientError)
@mock_sns
def test_set_sms_attributes():
conn = boto3.client('sns', region_name='us-east-1')
conn.set_sms_attributes(attributes={'DefaultSMSType': 'Transactional', 'test': 'test'})
response = conn.get_sms_attributes()
response.should.contain('attributes')
response['attributes'].should.contain('DefaultSMSType')
response['attributes'].should.contain('test')
response['attributes']['DefaultSMSType'].should.equal('Transactional')
response['attributes']['test'].should.equal('test')
@mock_sns
def test_get_sms_attributes_filtered():
conn = boto3.client('sns', region_name='us-east-1')
conn.set_sms_attributes(attributes={'DefaultSMSType': 'Transactional', 'test': 'test'})
response = conn.get_sms_attributes(attributes=['DefaultSMSType'])
response.should.contain('attributes')
response['attributes'].should.contain('DefaultSMSType')
response['attributes'].should_not.contain('test')
response['attributes']['DefaultSMSType'].should.equal('Transactional')
from __future__ import unicode_literals
import boto3
from botocore.exceptions import ClientError
from moto import mock_sns
import sure # noqa
@mock_sns
def test_create_platform_application():
conn = boto3.client('sns', region_name='us-east-1')
response = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
},
)
application_arn = response['PlatformApplicationArn']
application_arn.should.equal(
'arn:aws:sns:us-east-1:123456789012:app/APNS/my-application')
@mock_sns
def test_get_platform_application_attributes():
conn = boto3.client('sns', region_name='us-east-1')
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
},
)
arn = platform_application['PlatformApplicationArn']
attributes = conn.get_platform_application_attributes(
PlatformApplicationArn=arn)['Attributes']
attributes.should.equal({
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
})
@mock_sns
def test_get_missing_platform_application_attributes():
conn = boto3.client('sns', region_name='us-east-1')
conn.get_platform_application_attributes.when.called_with(
PlatformApplicationArn="a-fake-arn").should.throw(ClientError)
@mock_sns
def test_set_platform_application_attributes():
conn = boto3.client('sns', region_name='us-east-1')
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "platform_principal",
},
)
arn = platform_application['PlatformApplicationArn']
conn.set_platform_application_attributes(PlatformApplicationArn=arn,
Attributes={
"PlatformPrincipal": "other"}
)
attributes = conn.get_platform_application_attributes(
PlatformApplicationArn=arn)['Attributes']
attributes.should.equal({
"PlatformCredential": "platform_credential",
"PlatformPrincipal": "other",
})
@mock_sns
def test_list_platform_applications():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_platform_application(
Name="application1",
Platform="APNS",
Attributes={},
)
conn.create_platform_application(
Name="application2",
Platform="APNS",
Attributes={},
)
applications_repsonse = conn.list_platform_applications()
applications = applications_repsonse['PlatformApplications']
applications.should.have.length_of(2)
@mock_sns
def test_delete_platform_application():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_platform_application(
Name="application1",
Platform="APNS",
Attributes={},
)
conn.create_platform_application(
Name="application2",
Platform="APNS",
Attributes={},
)
applications_repsonse = conn.list_platform_applications()
applications = applications_repsonse['PlatformApplications']
applications.should.have.length_of(2)
application_arn = applications[0]['PlatformApplicationArn']
conn.delete_platform_application(PlatformApplicationArn=application_arn)
applications_repsonse = conn.list_platform_applications()
applications = applications_repsonse['PlatformApplications']
applications.should.have.length_of(1)
@mock_sns
def test_create_platform_endpoint():
conn = boto3.client('sns', region_name='us-east-1')
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={},
)
application_arn = platform_application['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
PlatformApplicationArn=application_arn,
Token="some_unique_id",
CustomUserData="some user data",
Attributes={
"Enabled": 'false',
},
)
endpoint_arn = endpoint['EndpointArn']
endpoint_arn.should.contain(
"arn:aws:sns:us-east-1:123456789012:endpoint/APNS/my-application/")
@mock_sns
def test_create_duplicate_platform_endpoint():
conn = boto3.client('sns', region_name='us-east-1')
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={},
)
application_arn = platform_application['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
PlatformApplicationArn=application_arn,
Token="some_unique_id",
CustomUserData="some user data",
Attributes={
"Enabled": 'false',
},
)
endpoint = conn.create_platform_endpoint.when.called_with(
PlatformApplicationArn=application_arn,
Token="some_unique_id",
CustomUserData="some user data",
Attributes={
"Enabled": 'false',
},
).should.throw(ClientError)
@mock_sns
def test_get_list_endpoints_by_platform_application():
conn = boto3.client('sns', region_name='us-east-1')
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={},
)
application_arn = platform_application['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
PlatformApplicationArn=application_arn,
Token="some_unique_id",
CustomUserData="some user data",
Attributes={
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['EndpointArn']
endpoint_list = conn.list_endpoints_by_platform_application(
PlatformApplicationArn=application_arn
)['Endpoints']
endpoint_list.should.have.length_of(1)
endpoint_list[0]['Attributes']['CustomUserData'].should.equal('some data')
endpoint_list[0]['EndpointArn'].should.equal(endpoint_arn)
@mock_sns
def test_get_endpoint_attributes():
conn = boto3.client('sns', region_name='us-east-1')
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={},
)
application_arn = platform_application['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
PlatformApplicationArn=application_arn,
Token="some_unique_id",
CustomUserData="some user data",
Attributes={
"Enabled": 'false',
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['EndpointArn']
attributes = conn.get_endpoint_attributes(
EndpointArn=endpoint_arn)['Attributes']
attributes.should.equal({
"Token": "some_unique_id",
"Enabled": 'false',
"CustomUserData": "some data",
})
@mock_sns
def test_get_missing_endpoint_attributes():
conn = boto3.client('sns', region_name='us-east-1')
conn.get_endpoint_attributes.when.called_with(
EndpointArn="a-fake-arn").should.throw(ClientError)
@mock_sns
def test_set_endpoint_attributes():
conn = boto3.client('sns', region_name='us-east-1')
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={},
)
application_arn = platform_application['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
PlatformApplicationArn=application_arn,
Token="some_unique_id",
CustomUserData="some user data",
Attributes={
"Enabled": 'false',
"CustomUserData": "some data",
},
)
endpoint_arn = endpoint['EndpointArn']
conn.set_endpoint_attributes(EndpointArn=endpoint_arn,
Attributes={"CustomUserData": "other data"}
)
attributes = conn.get_endpoint_attributes(
EndpointArn=endpoint_arn)['Attributes']
attributes.should.equal({
"Token": "some_unique_id",
"Enabled": 'false',
"CustomUserData": "other data",
})
@mock_sns
def test_publish_to_platform_endpoint():
conn = boto3.client('sns', region_name='us-east-1')
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={},
)
application_arn = platform_application['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
PlatformApplicationArn=application_arn,
Token="some_unique_id",
CustomUserData="some user data",
Attributes={
"Enabled": 'true',
},
)
endpoint_arn = endpoint['EndpointArn']
conn.publish(Message="some message",
MessageStructure="json", TargetArn=endpoint_arn)
@mock_sns
def test_publish_to_disabled_platform_endpoint():
conn = boto3.client('sns', region_name='us-east-1')
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={},
)
application_arn = platform_application['PlatformApplicationArn']
endpoint = conn.create_platform_endpoint(
PlatformApplicationArn=application_arn,
Token="some_unique_id",
CustomUserData="some user data",
Attributes={
"Enabled": 'false',
},
)
endpoint_arn = endpoint['EndpointArn']
conn.publish.when.called_with(
Message="some message",
MessageStructure="json",
TargetArn=endpoint_arn,
).should.throw(ClientError)
@mock_sns
def test_set_sms_attributes():
conn = boto3.client('sns', region_name='us-east-1')
conn.set_sms_attributes(attributes={'DefaultSMSType': 'Transactional', 'test': 'test'})
response = conn.get_sms_attributes()
response.should.contain('attributes')
response['attributes'].should.contain('DefaultSMSType')
response['attributes'].should.contain('test')
response['attributes']['DefaultSMSType'].should.equal('Transactional')
response['attributes']['test'].should.equal('test')
@mock_sns
def test_get_sms_attributes_filtered():
conn = boto3.client('sns', region_name='us-east-1')
conn.set_sms_attributes(attributes={'DefaultSMSType': 'Transactional', 'test': 'test'})
response = conn.get_sms_attributes(attributes=['DefaultSMSType'])
response.should.contain('attributes')
response['attributes'].should.contain('DefaultSMSType')
response['attributes'].should_not.contain('test')
response['attributes']['DefaultSMSType'].should.equal('Transactional')

View file

@ -1,69 +1,69 @@
from __future__ import unicode_literals
import boto
import json
import re
from freezegun import freeze_time
import sure # noqa
from moto import mock_sns_deprecated, mock_sqs_deprecated
MESSAGE_FROM_SQS_TEMPLATE = '{\n "Message": "%s",\n "MessageId": "%s",\n "Signature": "EXAMPLElDMXvB8r9R83tGoNn0ecwd5UjllzsvSvbItzfaMpN2nk5HVSw7XnOn/49IkxDKz8YrlH2qJXj2iZB0Zo2O71c4qQk1fMUDi3LGpij7RCW7AW9vYYsSqIKRnFS94ilu7NFhUzLiieYr4BKHpdTmdD6c0esKEYBpabxDSc=",\n "SignatureVersion": "1",\n "SigningCertURL": "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem",\n "Subject": "%s",\n "Timestamp": "2015-01-01T12:00:00.000Z",\n "TopicArn": "arn:aws:sns:%s:123456789012:some-topic",\n "Type": "Notification",\n "UnsubscribeURL": "https://sns.us-east-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-1:123456789012:some-topic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55"\n}'
@mock_sqs_deprecated
@mock_sns_deprecated
def test_publish_to_sqs():
conn = boto.connect_sns()
conn.create_topic("some-topic")
topics_json = conn.get_all_topics()
topic_arn = topics_json["ListTopicsResponse"][
"ListTopicsResult"]["Topics"][0]['TopicArn']
sqs_conn = boto.connect_sqs()
sqs_conn.create_queue("test-queue")
conn.subscribe(topic_arn, "sqs",
"arn:aws:sqs:us-east-1:123456789012:test-queue")
message_to_publish = 'my message'
subject_to_publish = "test subject"
with freeze_time("2015-01-01 12:00:00"):
published_message = conn.publish(topic=topic_arn, message=message_to_publish, subject=subject_to_publish)
published_message_id = published_message['PublishResponse']['PublishResult']['MessageId']
queue = sqs_conn.get_queue("test-queue")
message = queue.read(1)
expected = MESSAGE_FROM_SQS_TEMPLATE % (message_to_publish, published_message_id, subject_to_publish, 'us-east-1')
acquired_message = re.sub("\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z", '2015-01-01T12:00:00.000Z', message.get_body())
acquired_message.should.equal(expected)
@mock_sqs_deprecated
@mock_sns_deprecated
def test_publish_to_sqs_in_different_region():
conn = boto.sns.connect_to_region("us-west-1")
conn.create_topic("some-topic")
topics_json = conn.get_all_topics()
topic_arn = topics_json["ListTopicsResponse"][
"ListTopicsResult"]["Topics"][0]['TopicArn']
sqs_conn = boto.sqs.connect_to_region("us-west-2")
sqs_conn.create_queue("test-queue")
conn.subscribe(topic_arn, "sqs",
"arn:aws:sqs:us-west-2:123456789012:test-queue")
message_to_publish = 'my message'
subject_to_publish = "test subject"
with freeze_time("2015-01-01 12:00:00"):
published_message = conn.publish(topic=topic_arn, message=message_to_publish, subject=subject_to_publish)
published_message_id = published_message['PublishResponse']['PublishResult']['MessageId']
queue = sqs_conn.get_queue("test-queue")
message = queue.read(1)
expected = MESSAGE_FROM_SQS_TEMPLATE % (message_to_publish, published_message_id, subject_to_publish, 'us-west-1')
acquired_message = re.sub("\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z", '2015-01-01T12:00:00.000Z', message.get_body())
acquired_message.should.equal(expected)
from __future__ import unicode_literals
import boto
import json
import re
from freezegun import freeze_time
import sure # noqa
from moto import mock_sns_deprecated, mock_sqs_deprecated
MESSAGE_FROM_SQS_TEMPLATE = '{\n "Message": "%s",\n "MessageId": "%s",\n "Signature": "EXAMPLElDMXvB8r9R83tGoNn0ecwd5UjllzsvSvbItzfaMpN2nk5HVSw7XnOn/49IkxDKz8YrlH2qJXj2iZB0Zo2O71c4qQk1fMUDi3LGpij7RCW7AW9vYYsSqIKRnFS94ilu7NFhUzLiieYr4BKHpdTmdD6c0esKEYBpabxDSc=",\n "SignatureVersion": "1",\n "SigningCertURL": "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem",\n "Subject": "%s",\n "Timestamp": "2015-01-01T12:00:00.000Z",\n "TopicArn": "arn:aws:sns:%s:123456789012:some-topic",\n "Type": "Notification",\n "UnsubscribeURL": "https://sns.us-east-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-1:123456789012:some-topic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55"\n}'
@mock_sqs_deprecated
@mock_sns_deprecated
def test_publish_to_sqs():
conn = boto.connect_sns()
conn.create_topic("some-topic")
topics_json = conn.get_all_topics()
topic_arn = topics_json["ListTopicsResponse"][
"ListTopicsResult"]["Topics"][0]['TopicArn']
sqs_conn = boto.connect_sqs()
sqs_conn.create_queue("test-queue")
conn.subscribe(topic_arn, "sqs",
"arn:aws:sqs:us-east-1:123456789012:test-queue")
message_to_publish = 'my message'
subject_to_publish = "test subject"
with freeze_time("2015-01-01 12:00:00"):
published_message = conn.publish(topic=topic_arn, message=message_to_publish, subject=subject_to_publish)
published_message_id = published_message['PublishResponse']['PublishResult']['MessageId']
queue = sqs_conn.get_queue("test-queue")
message = queue.read(1)
expected = MESSAGE_FROM_SQS_TEMPLATE % (message_to_publish, published_message_id, subject_to_publish, 'us-east-1')
acquired_message = re.sub("\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z", '2015-01-01T12:00:00.000Z', message.get_body())
acquired_message.should.equal(expected)
@mock_sqs_deprecated
@mock_sns_deprecated
def test_publish_to_sqs_in_different_region():
conn = boto.sns.connect_to_region("us-west-1")
conn.create_topic("some-topic")
topics_json = conn.get_all_topics()
topic_arn = topics_json["ListTopicsResponse"][
"ListTopicsResult"]["Topics"][0]['TopicArn']
sqs_conn = boto.sqs.connect_to_region("us-west-2")
sqs_conn.create_queue("test-queue")
conn.subscribe(topic_arn, "sqs",
"arn:aws:sqs:us-west-2:123456789012:test-queue")
message_to_publish = 'my message'
subject_to_publish = "test subject"
with freeze_time("2015-01-01 12:00:00"):
published_message = conn.publish(topic=topic_arn, message=message_to_publish, subject=subject_to_publish)
published_message_id = published_message['PublishResponse']['PublishResult']['MessageId']
queue = sqs_conn.get_queue("test-queue")
message = queue.read(1)
expected = MESSAGE_FROM_SQS_TEMPLATE % (message_to_publish, published_message_id, subject_to_publish, 'us-west-1')
acquired_message = re.sub("\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z", '2015-01-01T12:00:00.000Z', message.get_body())
acquired_message.should.equal(expected)

View file

@ -1,489 +1,489 @@
from __future__ import unicode_literals
import base64
import json
import boto3
import re
from freezegun import freeze_time
import sure # noqa
import responses
from botocore.exceptions import ClientError
from nose.tools import assert_raises
from moto import mock_sns, mock_sqs
MESSAGE_FROM_SQS_TEMPLATE = '{\n "Message": "%s",\n "MessageId": "%s",\n "Signature": "EXAMPLElDMXvB8r9R83tGoNn0ecwd5UjllzsvSvbItzfaMpN2nk5HVSw7XnOn/49IkxDKz8YrlH2qJXj2iZB0Zo2O71c4qQk1fMUDi3LGpij7RCW7AW9vYYsSqIKRnFS94ilu7NFhUzLiieYr4BKHpdTmdD6c0esKEYBpabxDSc=",\n "SignatureVersion": "1",\n "SigningCertURL": "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem",\n "Subject": "my subject",\n "Timestamp": "2015-01-01T12:00:00.000Z",\n "TopicArn": "arn:aws:sns:%s:123456789012:some-topic",\n "Type": "Notification",\n "UnsubscribeURL": "https://sns.us-east-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-1:123456789012:some-topic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55"\n}'
@mock_sqs
@mock_sns
def test_publish_to_sqs():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
sqs_conn = boto3.resource('sqs', region_name='us-east-1')
sqs_conn.create_queue(QueueName="test-queue")
conn.subscribe(TopicArn=topic_arn,
Protocol="sqs",
Endpoint="arn:aws:sqs:us-east-1:123456789012:test-queue")
message = 'my message'
with freeze_time("2015-01-01 12:00:00"):
published_message = conn.publish(TopicArn=topic_arn, Message=message)
published_message_id = published_message['MessageId']
queue = sqs_conn.get_queue_by_name(QueueName="test-queue")
messages = queue.receive_messages(MaxNumberOfMessages=1)
expected = MESSAGE_FROM_SQS_TEMPLATE % (message, published_message_id, 'us-east-1')
acquired_message = re.sub("\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z", u'2015-01-01T12:00:00.000Z', messages[0].body)
acquired_message.should.equal(expected)
@mock_sqs
@mock_sns
def test_publish_to_sqs_raw():
sns = boto3.resource('sns', region_name='us-east-1')
topic = sns.create_topic(Name='some-topic')
sqs = boto3.resource('sqs', region_name='us-east-1')
queue = sqs.create_queue(QueueName='test-queue')
subscription = topic.subscribe(
Protocol='sqs', Endpoint=queue.attributes['QueueArn'])
subscription.set_attributes(
AttributeName='RawMessageDelivery', AttributeValue='true')
message = 'my message'
with freeze_time("2015-01-01 12:00:00"):
topic.publish(Message=message)
messages = queue.receive_messages(MaxNumberOfMessages=1)
messages[0].body.should.equal(message)
@mock_sqs
@mock_sns
def test_publish_to_sqs_bad():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
sqs_conn = boto3.resource('sqs', region_name='us-east-1')
sqs_conn.create_queue(QueueName="test-queue")
conn.subscribe(TopicArn=topic_arn,
Protocol="sqs",
Endpoint="arn:aws:sqs:us-east-1:123456789012:test-queue")
message = 'my message'
try:
# Test missing Value
conn.publish(
TopicArn=topic_arn, Message=message,
MessageAttributes={'store': {'DataType': 'String'}})
except ClientError as err:
err.response['Error']['Code'].should.equal('InvalidParameterValue')
try:
# Test empty DataType (if the DataType field is missing entirely
# botocore throws an exception during validation)
conn.publish(
TopicArn=topic_arn, Message=message,
MessageAttributes={'store': {
'DataType': '',
'StringValue': 'example_corp'
}})
except ClientError as err:
err.response['Error']['Code'].should.equal('InvalidParameterValue')
try:
# Test empty Value
conn.publish(
TopicArn=topic_arn, Message=message,
MessageAttributes={'store': {
'DataType': 'String',
'StringValue': ''
}})
except ClientError as err:
err.response['Error']['Code'].should.equal('InvalidParameterValue')
@mock_sqs
@mock_sns
def test_publish_to_sqs_msg_attr_byte_value():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
sqs_conn = boto3.resource('sqs', region_name='us-east-1')
queue = sqs_conn.create_queue(QueueName="test-queue")
conn.subscribe(TopicArn=topic_arn,
Protocol="sqs",
Endpoint="arn:aws:sqs:us-east-1:123456789012:test-queue")
message = 'my message'
conn.publish(
TopicArn=topic_arn, Message=message,
MessageAttributes={'store': {
'DataType': 'Binary',
'BinaryValue': b'\x02\x03\x04'
}})
messages = queue.receive_messages(MaxNumberOfMessages=5)
message_attributes = [
json.loads(m.body)['MessageAttributes'] for m in messages]
message_attributes.should.equal([{
'store': {
'Type': 'Binary',
'Value': base64.b64encode(b'\x02\x03\x04').decode()
}
}])
@mock_sns
def test_publish_sms():
client = boto3.client('sns', region_name='us-east-1')
client.create_topic(Name="some-topic")
resp = client.create_topic(Name="some-topic")
arn = resp['TopicArn']
client.subscribe(
TopicArn=arn,
Protocol='sms',
Endpoint='+15551234567'
)
result = client.publish(PhoneNumber="+15551234567", Message="my message")
result.should.contain('MessageId')
@mock_sns
def test_publish_bad_sms():
client = boto3.client('sns', region_name='us-east-1')
client.create_topic(Name="some-topic")
resp = client.create_topic(Name="some-topic")
arn = resp['TopicArn']
client.subscribe(
TopicArn=arn,
Protocol='sms',
Endpoint='+15551234567'
)
try:
# Test invalid number
client.publish(PhoneNumber="NAA+15551234567", Message="my message")
except ClientError as err:
err.response['Error']['Code'].should.equal('InvalidParameter')
try:
# Test not found number
client.publish(PhoneNumber="+44001234567", Message="my message")
except ClientError as err:
err.response['Error']['Code'].should.equal('ParameterValueInvalid')
@mock_sqs
@mock_sns
def test_publish_to_sqs_dump_json():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
sqs_conn = boto3.resource('sqs', region_name='us-east-1')
sqs_conn.create_queue(QueueName="test-queue")
conn.subscribe(TopicArn=topic_arn,
Protocol="sqs",
Endpoint="arn:aws:sqs:us-east-1:123456789012:test-queue")
message = json.dumps({
"Records": [{
"eventVersion": "2.0",
"eventSource": "aws:s3",
"s3": {
"s3SchemaVersion": "1.0"
}
}]
}, sort_keys=True)
with freeze_time("2015-01-01 12:00:00"):
published_message = conn.publish(TopicArn=topic_arn, Message=message)
published_message_id = published_message['MessageId']
queue = sqs_conn.get_queue_by_name(QueueName="test-queue")
messages = queue.receive_messages(MaxNumberOfMessages=1)
escaped = message.replace('"', '\\"')
expected = MESSAGE_FROM_SQS_TEMPLATE % (escaped, published_message_id, 'us-east-1')
acquired_message = re.sub("\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z", u'2015-01-01T12:00:00.000Z', messages[0].body)
acquired_message.should.equal(expected)
@mock_sqs
@mock_sns
def test_publish_to_sqs_in_different_region():
conn = boto3.client('sns', region_name='us-west-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
sqs_conn = boto3.resource('sqs', region_name='us-west-2')
sqs_conn.create_queue(QueueName="test-queue")
conn.subscribe(TopicArn=topic_arn,
Protocol="sqs",
Endpoint="arn:aws:sqs:us-west-2:123456789012:test-queue")
message = 'my message'
with freeze_time("2015-01-01 12:00:00"):
published_message = conn.publish(TopicArn=topic_arn, Message=message)
published_message_id = published_message['MessageId']
queue = sqs_conn.get_queue_by_name(QueueName="test-queue")
messages = queue.receive_messages(MaxNumberOfMessages=1)
expected = MESSAGE_FROM_SQS_TEMPLATE % (message, published_message_id, 'us-west-1')
acquired_message = re.sub("\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z", u'2015-01-01T12:00:00.000Z', messages[0].body)
acquired_message.should.equal(expected)
@freeze_time("2013-01-01")
@mock_sns
def test_publish_to_http():
def callback(request):
request.headers["Content-Type"].should.equal("text/plain; charset=UTF-8")
json.loads.when.called_with(
request.body.decode()
).should_not.throw(Exception)
return 200, {}, ""
responses.add_callback(
method="POST",
url="http://example.com/foobar",
callback=callback,
)
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
conn.subscribe(TopicArn=topic_arn,
Protocol="http",
Endpoint="http://example.com/foobar")
response = conn.publish(
TopicArn=topic_arn, Message="my message", Subject="my subject")
@mock_sqs
@mock_sns
def test_publish_subject():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
sqs_conn = boto3.resource('sqs', region_name='us-east-1')
sqs_conn.create_queue(QueueName="test-queue")
conn.subscribe(TopicArn=topic_arn,
Protocol="sqs",
Endpoint="arn:aws:sqs:us-east-1:123456789012:test-queue")
message = 'my message'
subject1 = 'test subject'
subject2 = 'test subject' * 20
with freeze_time("2015-01-01 12:00:00"):
conn.publish(TopicArn=topic_arn, Message=message, Subject=subject1)
# Just that it doesnt error is a pass
try:
with freeze_time("2015-01-01 12:00:00"):
conn.publish(TopicArn=topic_arn, Message=message, Subject=subject2)
except ClientError as err:
err.response['Error']['Code'].should.equal('InvalidParameter')
else:
raise RuntimeError('Should have raised an InvalidParameter exception')
@mock_sns
def test_publish_message_too_long():
sns = boto3.resource('sns', region_name='us-east-1')
topic = sns.create_topic(Name='some-topic')
with assert_raises(ClientError):
topic.publish(
Message="".join(["." for i in range(0, 262145)]))
# message short enough - does not raise an error
topic.publish(
Message="".join(["." for i in range(0, 262144)]))
def _setup_filter_policy_test(filter_policy):
sns = boto3.resource('sns', region_name='us-east-1')
topic = sns.create_topic(Name='some-topic')
sqs = boto3.resource('sqs', region_name='us-east-1')
queue = sqs.create_queue(QueueName='test-queue')
subscription = topic.subscribe(
Protocol='sqs', Endpoint=queue.attributes['QueueArn'])
subscription.set_attributes(
AttributeName='FilterPolicy', AttributeValue=json.dumps(filter_policy))
return topic, subscription, queue
@mock_sqs
@mock_sns
def test_filtering_exact_string():
topic, subscription, queue = _setup_filter_policy_test(
{'store': ['example_corp']})
topic.publish(
Message='match',
MessageAttributes={'store': {'DataType': 'String',
'StringValue': 'example_corp'}})
messages = queue.receive_messages(MaxNumberOfMessages=5)
message_bodies = [json.loads(m.body)['Message'] for m in messages]
message_bodies.should.equal(['match'])
message_attributes = [
json.loads(m.body)['MessageAttributes'] for m in messages]
message_attributes.should.equal(
[{'store': {'Type': 'String', 'Value': 'example_corp'}}])
@mock_sqs
@mock_sns
def test_filtering_exact_string_multiple_message_attributes():
topic, subscription, queue = _setup_filter_policy_test(
{'store': ['example_corp']})
topic.publish(
Message='match',
MessageAttributes={'store': {'DataType': 'String',
'StringValue': 'example_corp'},
'event': {'DataType': 'String',
'StringValue': 'order_cancelled'}})
messages = queue.receive_messages(MaxNumberOfMessages=5)
message_bodies = [json.loads(m.body)['Message'] for m in messages]
message_bodies.should.equal(['match'])
message_attributes = [
json.loads(m.body)['MessageAttributes'] for m in messages]
message_attributes.should.equal([{
'store': {'Type': 'String', 'Value': 'example_corp'},
'event': {'Type': 'String', 'Value': 'order_cancelled'}}])
@mock_sqs
@mock_sns
def test_filtering_exact_string_OR_matching():
topic, subscription, queue = _setup_filter_policy_test(
{'store': ['example_corp', 'different_corp']})
topic.publish(
Message='match example_corp',
MessageAttributes={'store': {'DataType': 'String',
'StringValue': 'example_corp'}})
topic.publish(
Message='match different_corp',
MessageAttributes={'store': {'DataType': 'String',
'StringValue': 'different_corp'}})
messages = queue.receive_messages(MaxNumberOfMessages=5)
message_bodies = [json.loads(m.body)['Message'] for m in messages]
message_bodies.should.equal(
['match example_corp', 'match different_corp'])
message_attributes = [
json.loads(m.body)['MessageAttributes'] for m in messages]
message_attributes.should.equal([
{'store': {'Type': 'String', 'Value': 'example_corp'}},
{'store': {'Type': 'String', 'Value': 'different_corp'}}])
@mock_sqs
@mock_sns
def test_filtering_exact_string_AND_matching_positive():
topic, subscription, queue = _setup_filter_policy_test(
{'store': ['example_corp'],
'event': ['order_cancelled']})
topic.publish(
Message='match example_corp order_cancelled',
MessageAttributes={'store': {'DataType': 'String',
'StringValue': 'example_corp'},
'event': {'DataType': 'String',
'StringValue': 'order_cancelled'}})
messages = queue.receive_messages(MaxNumberOfMessages=5)
message_bodies = [json.loads(m.body)['Message'] for m in messages]
message_bodies.should.equal(
['match example_corp order_cancelled'])
message_attributes = [
json.loads(m.body)['MessageAttributes'] for m in messages]
message_attributes.should.equal([{
'store': {'Type': 'String', 'Value': 'example_corp'},
'event': {'Type': 'String', 'Value': 'order_cancelled'}}])
@mock_sqs
@mock_sns
def test_filtering_exact_string_AND_matching_no_match():
topic, subscription, queue = _setup_filter_policy_test(
{'store': ['example_corp'],
'event': ['order_cancelled']})
topic.publish(
Message='match example_corp order_accepted',
MessageAttributes={'store': {'DataType': 'String',
'StringValue': 'example_corp'},
'event': {'DataType': 'String',
'StringValue': 'order_accepted'}})
messages = queue.receive_messages(MaxNumberOfMessages=5)
message_bodies = [json.loads(m.body)['Message'] for m in messages]
message_bodies.should.equal([])
message_attributes = [
json.loads(m.body)['MessageAttributes'] for m in messages]
message_attributes.should.equal([])
@mock_sqs
@mock_sns
def test_filtering_exact_string_no_match():
topic, subscription, queue = _setup_filter_policy_test(
{'store': ['example_corp']})
topic.publish(
Message='no match',
MessageAttributes={'store': {'DataType': 'String',
'StringValue': 'different_corp'}})
messages = queue.receive_messages(MaxNumberOfMessages=5)
message_bodies = [json.loads(m.body)['Message'] for m in messages]
message_bodies.should.equal([])
message_attributes = [
json.loads(m.body)['MessageAttributes'] for m in messages]
message_attributes.should.equal([])
@mock_sqs
@mock_sns
def test_filtering_exact_string_no_attributes_no_match():
topic, subscription, queue = _setup_filter_policy_test(
{'store': ['example_corp']})
topic.publish(Message='no match')
messages = queue.receive_messages(MaxNumberOfMessages=5)
message_bodies = [json.loads(m.body)['Message'] for m in messages]
message_bodies.should.equal([])
message_attributes = [
json.loads(m.body)['MessageAttributes'] for m in messages]
message_attributes.should.equal([])
from __future__ import unicode_literals
import base64
import json
import boto3
import re
from freezegun import freeze_time
import sure # noqa
import responses
from botocore.exceptions import ClientError
from nose.tools import assert_raises
from moto import mock_sns, mock_sqs
MESSAGE_FROM_SQS_TEMPLATE = '{\n "Message": "%s",\n "MessageId": "%s",\n "Signature": "EXAMPLElDMXvB8r9R83tGoNn0ecwd5UjllzsvSvbItzfaMpN2nk5HVSw7XnOn/49IkxDKz8YrlH2qJXj2iZB0Zo2O71c4qQk1fMUDi3LGpij7RCW7AW9vYYsSqIKRnFS94ilu7NFhUzLiieYr4BKHpdTmdD6c0esKEYBpabxDSc=",\n "SignatureVersion": "1",\n "SigningCertURL": "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem",\n "Subject": "my subject",\n "Timestamp": "2015-01-01T12:00:00.000Z",\n "TopicArn": "arn:aws:sns:%s:123456789012:some-topic",\n "Type": "Notification",\n "UnsubscribeURL": "https://sns.us-east-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-1:123456789012:some-topic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55"\n}'
@mock_sqs
@mock_sns
def test_publish_to_sqs():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
sqs_conn = boto3.resource('sqs', region_name='us-east-1')
sqs_conn.create_queue(QueueName="test-queue")
conn.subscribe(TopicArn=topic_arn,
Protocol="sqs",
Endpoint="arn:aws:sqs:us-east-1:123456789012:test-queue")
message = 'my message'
with freeze_time("2015-01-01 12:00:00"):
published_message = conn.publish(TopicArn=topic_arn, Message=message)
published_message_id = published_message['MessageId']
queue = sqs_conn.get_queue_by_name(QueueName="test-queue")
messages = queue.receive_messages(MaxNumberOfMessages=1)
expected = MESSAGE_FROM_SQS_TEMPLATE % (message, published_message_id, 'us-east-1')
acquired_message = re.sub("\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z", u'2015-01-01T12:00:00.000Z', messages[0].body)
acquired_message.should.equal(expected)
@mock_sqs
@mock_sns
def test_publish_to_sqs_raw():
sns = boto3.resource('sns', region_name='us-east-1')
topic = sns.create_topic(Name='some-topic')
sqs = boto3.resource('sqs', region_name='us-east-1')
queue = sqs.create_queue(QueueName='test-queue')
subscription = topic.subscribe(
Protocol='sqs', Endpoint=queue.attributes['QueueArn'])
subscription.set_attributes(
AttributeName='RawMessageDelivery', AttributeValue='true')
message = 'my message'
with freeze_time("2015-01-01 12:00:00"):
topic.publish(Message=message)
messages = queue.receive_messages(MaxNumberOfMessages=1)
messages[0].body.should.equal(message)
@mock_sqs
@mock_sns
def test_publish_to_sqs_bad():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
sqs_conn = boto3.resource('sqs', region_name='us-east-1')
sqs_conn.create_queue(QueueName="test-queue")
conn.subscribe(TopicArn=topic_arn,
Protocol="sqs",
Endpoint="arn:aws:sqs:us-east-1:123456789012:test-queue")
message = 'my message'
try:
# Test missing Value
conn.publish(
TopicArn=topic_arn, Message=message,
MessageAttributes={'store': {'DataType': 'String'}})
except ClientError as err:
err.response['Error']['Code'].should.equal('InvalidParameterValue')
try:
# Test empty DataType (if the DataType field is missing entirely
# botocore throws an exception during validation)
conn.publish(
TopicArn=topic_arn, Message=message,
MessageAttributes={'store': {
'DataType': '',
'StringValue': 'example_corp'
}})
except ClientError as err:
err.response['Error']['Code'].should.equal('InvalidParameterValue')
try:
# Test empty Value
conn.publish(
TopicArn=topic_arn, Message=message,
MessageAttributes={'store': {
'DataType': 'String',
'StringValue': ''
}})
except ClientError as err:
err.response['Error']['Code'].should.equal('InvalidParameterValue')
@mock_sqs
@mock_sns
def test_publish_to_sqs_msg_attr_byte_value():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
sqs_conn = boto3.resource('sqs', region_name='us-east-1')
queue = sqs_conn.create_queue(QueueName="test-queue")
conn.subscribe(TopicArn=topic_arn,
Protocol="sqs",
Endpoint="arn:aws:sqs:us-east-1:123456789012:test-queue")
message = 'my message'
conn.publish(
TopicArn=topic_arn, Message=message,
MessageAttributes={'store': {
'DataType': 'Binary',
'BinaryValue': b'\x02\x03\x04'
}})
messages = queue.receive_messages(MaxNumberOfMessages=5)
message_attributes = [
json.loads(m.body)['MessageAttributes'] for m in messages]
message_attributes.should.equal([{
'store': {
'Type': 'Binary',
'Value': base64.b64encode(b'\x02\x03\x04').decode()
}
}])
@mock_sns
def test_publish_sms():
client = boto3.client('sns', region_name='us-east-1')
client.create_topic(Name="some-topic")
resp = client.create_topic(Name="some-topic")
arn = resp['TopicArn']
client.subscribe(
TopicArn=arn,
Protocol='sms',
Endpoint='+15551234567'
)
result = client.publish(PhoneNumber="+15551234567", Message="my message")
result.should.contain('MessageId')
@mock_sns
def test_publish_bad_sms():
client = boto3.client('sns', region_name='us-east-1')
client.create_topic(Name="some-topic")
resp = client.create_topic(Name="some-topic")
arn = resp['TopicArn']
client.subscribe(
TopicArn=arn,
Protocol='sms',
Endpoint='+15551234567'
)
try:
# Test invalid number
client.publish(PhoneNumber="NAA+15551234567", Message="my message")
except ClientError as err:
err.response['Error']['Code'].should.equal('InvalidParameter')
try:
# Test not found number
client.publish(PhoneNumber="+44001234567", Message="my message")
except ClientError as err:
err.response['Error']['Code'].should.equal('ParameterValueInvalid')
@mock_sqs
@mock_sns
def test_publish_to_sqs_dump_json():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
sqs_conn = boto3.resource('sqs', region_name='us-east-1')
sqs_conn.create_queue(QueueName="test-queue")
conn.subscribe(TopicArn=topic_arn,
Protocol="sqs",
Endpoint="arn:aws:sqs:us-east-1:123456789012:test-queue")
message = json.dumps({
"Records": [{
"eventVersion": "2.0",
"eventSource": "aws:s3",
"s3": {
"s3SchemaVersion": "1.0"
}
}]
}, sort_keys=True)
with freeze_time("2015-01-01 12:00:00"):
published_message = conn.publish(TopicArn=topic_arn, Message=message)
published_message_id = published_message['MessageId']
queue = sqs_conn.get_queue_by_name(QueueName="test-queue")
messages = queue.receive_messages(MaxNumberOfMessages=1)
escaped = message.replace('"', '\\"')
expected = MESSAGE_FROM_SQS_TEMPLATE % (escaped, published_message_id, 'us-east-1')
acquired_message = re.sub("\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z", u'2015-01-01T12:00:00.000Z', messages[0].body)
acquired_message.should.equal(expected)
@mock_sqs
@mock_sns
def test_publish_to_sqs_in_different_region():
conn = boto3.client('sns', region_name='us-west-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
sqs_conn = boto3.resource('sqs', region_name='us-west-2')
sqs_conn.create_queue(QueueName="test-queue")
conn.subscribe(TopicArn=topic_arn,
Protocol="sqs",
Endpoint="arn:aws:sqs:us-west-2:123456789012:test-queue")
message = 'my message'
with freeze_time("2015-01-01 12:00:00"):
published_message = conn.publish(TopicArn=topic_arn, Message=message)
published_message_id = published_message['MessageId']
queue = sqs_conn.get_queue_by_name(QueueName="test-queue")
messages = queue.receive_messages(MaxNumberOfMessages=1)
expected = MESSAGE_FROM_SQS_TEMPLATE % (message, published_message_id, 'us-west-1')
acquired_message = re.sub("\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z", u'2015-01-01T12:00:00.000Z', messages[0].body)
acquired_message.should.equal(expected)
@freeze_time("2013-01-01")
@mock_sns
def test_publish_to_http():
def callback(request):
request.headers["Content-Type"].should.equal("text/plain; charset=UTF-8")
json.loads.when.called_with(
request.body.decode()
).should_not.throw(Exception)
return 200, {}, ""
responses.add_callback(
method="POST",
url="http://example.com/foobar",
callback=callback,
)
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
conn.subscribe(TopicArn=topic_arn,
Protocol="http",
Endpoint="http://example.com/foobar")
response = conn.publish(
TopicArn=topic_arn, Message="my message", Subject="my subject")
@mock_sqs
@mock_sns
def test_publish_subject():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
sqs_conn = boto3.resource('sqs', region_name='us-east-1')
sqs_conn.create_queue(QueueName="test-queue")
conn.subscribe(TopicArn=topic_arn,
Protocol="sqs",
Endpoint="arn:aws:sqs:us-east-1:123456789012:test-queue")
message = 'my message'
subject1 = 'test subject'
subject2 = 'test subject' * 20
with freeze_time("2015-01-01 12:00:00"):
conn.publish(TopicArn=topic_arn, Message=message, Subject=subject1)
# Just that it doesnt error is a pass
try:
with freeze_time("2015-01-01 12:00:00"):
conn.publish(TopicArn=topic_arn, Message=message, Subject=subject2)
except ClientError as err:
err.response['Error']['Code'].should.equal('InvalidParameter')
else:
raise RuntimeError('Should have raised an InvalidParameter exception')
@mock_sns
def test_publish_message_too_long():
sns = boto3.resource('sns', region_name='us-east-1')
topic = sns.create_topic(Name='some-topic')
with assert_raises(ClientError):
topic.publish(
Message="".join(["." for i in range(0, 262145)]))
# message short enough - does not raise an error
topic.publish(
Message="".join(["." for i in range(0, 262144)]))
def _setup_filter_policy_test(filter_policy):
sns = boto3.resource('sns', region_name='us-east-1')
topic = sns.create_topic(Name='some-topic')
sqs = boto3.resource('sqs', region_name='us-east-1')
queue = sqs.create_queue(QueueName='test-queue')
subscription = topic.subscribe(
Protocol='sqs', Endpoint=queue.attributes['QueueArn'])
subscription.set_attributes(
AttributeName='FilterPolicy', AttributeValue=json.dumps(filter_policy))
return topic, subscription, queue
@mock_sqs
@mock_sns
def test_filtering_exact_string():
topic, subscription, queue = _setup_filter_policy_test(
{'store': ['example_corp']})
topic.publish(
Message='match',
MessageAttributes={'store': {'DataType': 'String',
'StringValue': 'example_corp'}})
messages = queue.receive_messages(MaxNumberOfMessages=5)
message_bodies = [json.loads(m.body)['Message'] for m in messages]
message_bodies.should.equal(['match'])
message_attributes = [
json.loads(m.body)['MessageAttributes'] for m in messages]
message_attributes.should.equal(
[{'store': {'Type': 'String', 'Value': 'example_corp'}}])
@mock_sqs
@mock_sns
def test_filtering_exact_string_multiple_message_attributes():
topic, subscription, queue = _setup_filter_policy_test(
{'store': ['example_corp']})
topic.publish(
Message='match',
MessageAttributes={'store': {'DataType': 'String',
'StringValue': 'example_corp'},
'event': {'DataType': 'String',
'StringValue': 'order_cancelled'}})
messages = queue.receive_messages(MaxNumberOfMessages=5)
message_bodies = [json.loads(m.body)['Message'] for m in messages]
message_bodies.should.equal(['match'])
message_attributes = [
json.loads(m.body)['MessageAttributes'] for m in messages]
message_attributes.should.equal([{
'store': {'Type': 'String', 'Value': 'example_corp'},
'event': {'Type': 'String', 'Value': 'order_cancelled'}}])
@mock_sqs
@mock_sns
def test_filtering_exact_string_OR_matching():
topic, subscription, queue = _setup_filter_policy_test(
{'store': ['example_corp', 'different_corp']})
topic.publish(
Message='match example_corp',
MessageAttributes={'store': {'DataType': 'String',
'StringValue': 'example_corp'}})
topic.publish(
Message='match different_corp',
MessageAttributes={'store': {'DataType': 'String',
'StringValue': 'different_corp'}})
messages = queue.receive_messages(MaxNumberOfMessages=5)
message_bodies = [json.loads(m.body)['Message'] for m in messages]
message_bodies.should.equal(
['match example_corp', 'match different_corp'])
message_attributes = [
json.loads(m.body)['MessageAttributes'] for m in messages]
message_attributes.should.equal([
{'store': {'Type': 'String', 'Value': 'example_corp'}},
{'store': {'Type': 'String', 'Value': 'different_corp'}}])
@mock_sqs
@mock_sns
def test_filtering_exact_string_AND_matching_positive():
topic, subscription, queue = _setup_filter_policy_test(
{'store': ['example_corp'],
'event': ['order_cancelled']})
topic.publish(
Message='match example_corp order_cancelled',
MessageAttributes={'store': {'DataType': 'String',
'StringValue': 'example_corp'},
'event': {'DataType': 'String',
'StringValue': 'order_cancelled'}})
messages = queue.receive_messages(MaxNumberOfMessages=5)
message_bodies = [json.loads(m.body)['Message'] for m in messages]
message_bodies.should.equal(
['match example_corp order_cancelled'])
message_attributes = [
json.loads(m.body)['MessageAttributes'] for m in messages]
message_attributes.should.equal([{
'store': {'Type': 'String', 'Value': 'example_corp'},
'event': {'Type': 'String', 'Value': 'order_cancelled'}}])
@mock_sqs
@mock_sns
def test_filtering_exact_string_AND_matching_no_match():
topic, subscription, queue = _setup_filter_policy_test(
{'store': ['example_corp'],
'event': ['order_cancelled']})
topic.publish(
Message='match example_corp order_accepted',
MessageAttributes={'store': {'DataType': 'String',
'StringValue': 'example_corp'},
'event': {'DataType': 'String',
'StringValue': 'order_accepted'}})
messages = queue.receive_messages(MaxNumberOfMessages=5)
message_bodies = [json.loads(m.body)['Message'] for m in messages]
message_bodies.should.equal([])
message_attributes = [
json.loads(m.body)['MessageAttributes'] for m in messages]
message_attributes.should.equal([])
@mock_sqs
@mock_sns
def test_filtering_exact_string_no_match():
topic, subscription, queue = _setup_filter_policy_test(
{'store': ['example_corp']})
topic.publish(
Message='no match',
MessageAttributes={'store': {'DataType': 'String',
'StringValue': 'different_corp'}})
messages = queue.receive_messages(MaxNumberOfMessages=5)
message_bodies = [json.loads(m.body)['Message'] for m in messages]
message_bodies.should.equal([])
message_attributes = [
json.loads(m.body)['MessageAttributes'] for m in messages]
message_attributes.should.equal([])
@mock_sqs
@mock_sns
def test_filtering_exact_string_no_attributes_no_match():
topic, subscription, queue = _setup_filter_policy_test(
{'store': ['example_corp']})
topic.publish(Message='no match')
messages = queue.receive_messages(MaxNumberOfMessages=5)
message_bodies = [json.loads(m.body)['Message'] for m in messages]
message_bodies.should.equal([])
message_attributes = [
json.loads(m.body)['MessageAttributes'] for m in messages]
message_attributes.should.equal([])

View file

@ -1,24 +1,24 @@
from __future__ import unicode_literals
import sure # noqa
import moto.server as server
'''
Test the different server responses
'''
def test_sns_server_get():
backend = server.create_backend_app("sns")
test_client = backend.test_client()
topic_data = test_client.action_data("CreateTopic", Name="testtopic")
topic_data.should.contain("CreateTopicResult")
topic_data.should.contain(
"<TopicArn>arn:aws:sns:us-east-1:123456789012:testtopic</TopicArn>")
topics_data = test_client.action_data("ListTopics")
topics_data.should.contain("ListTopicsResult")
topic_data.should.contain(
"<TopicArn>arn:aws:sns:us-east-1:123456789012:testtopic</TopicArn>")
from __future__ import unicode_literals
import sure # noqa
import moto.server as server
'''
Test the different server responses
'''
def test_sns_server_get():
backend = server.create_backend_app("sns")
test_client = backend.test_client()
topic_data = test_client.action_data("CreateTopic", Name="testtopic")
topic_data.should.contain("CreateTopicResult")
topic_data.should.contain(
"<TopicArn>arn:aws:sns:us-east-1:123456789012:testtopic</TopicArn>")
topics_data = test_client.action_data("ListTopics")
topics_data.should.contain("ListTopicsResult")
topic_data.should.contain(
"<TopicArn>arn:aws:sns:us-east-1:123456789012:testtopic</TopicArn>")

View file

@ -1,135 +1,135 @@
from __future__ import unicode_literals
import boto
import sure # noqa
from moto import mock_sns_deprecated
from moto.sns.models import DEFAULT_PAGE_SIZE
@mock_sns_deprecated
def test_creating_subscription():
conn = boto.connect_sns()
conn.create_topic("some-topic")
topics_json = conn.get_all_topics()
topic_arn = topics_json["ListTopicsResponse"][
"ListTopicsResult"]["Topics"][0]['TopicArn']
conn.subscribe(topic_arn, "http", "http://example.com/")
subscriptions = conn.get_all_subscriptions()["ListSubscriptionsResponse"][
"ListSubscriptionsResult"]["Subscriptions"]
subscriptions.should.have.length_of(1)
subscription = subscriptions[0]
subscription["TopicArn"].should.equal(topic_arn)
subscription["Protocol"].should.equal("http")
subscription["SubscriptionArn"].should.contain(topic_arn)
subscription["Endpoint"].should.equal("http://example.com/")
# Now unsubscribe the subscription
conn.unsubscribe(subscription["SubscriptionArn"])
# And there should be zero subscriptions left
subscriptions = conn.get_all_subscriptions()["ListSubscriptionsResponse"][
"ListSubscriptionsResult"]["Subscriptions"]
subscriptions.should.have.length_of(0)
@mock_sns_deprecated
def test_deleting_subscriptions_by_deleting_topic():
conn = boto.connect_sns()
conn.create_topic("some-topic")
topics_json = conn.get_all_topics()
topic_arn = topics_json["ListTopicsResponse"][
"ListTopicsResult"]["Topics"][0]['TopicArn']
conn.subscribe(topic_arn, "http", "http://example.com/")
subscriptions = conn.get_all_subscriptions()["ListSubscriptionsResponse"][
"ListSubscriptionsResult"]["Subscriptions"]
subscriptions.should.have.length_of(1)
subscription = subscriptions[0]
subscription["TopicArn"].should.equal(topic_arn)
subscription["Protocol"].should.equal("http")
subscription["SubscriptionArn"].should.contain(topic_arn)
subscription["Endpoint"].should.equal("http://example.com/")
# Now delete the topic
conn.delete_topic(topic_arn)
# And there should now be 0 topics
topics_json = conn.get_all_topics()
topics = topics_json["ListTopicsResponse"]["ListTopicsResult"]["Topics"]
topics.should.have.length_of(0)
# And there should be zero subscriptions left
subscriptions = conn.get_all_subscriptions()["ListSubscriptionsResponse"][
"ListSubscriptionsResult"]["Subscriptions"]
subscriptions.should.have.length_of(0)
@mock_sns_deprecated
def test_getting_subscriptions_by_topic():
conn = boto.connect_sns()
conn.create_topic("topic1")
conn.create_topic("topic2")
topics_json = conn.get_all_topics()
topics = topics_json["ListTopicsResponse"]["ListTopicsResult"]["Topics"]
topic1_arn = topics[0]['TopicArn']
topic2_arn = topics[1]['TopicArn']
conn.subscribe(topic1_arn, "http", "http://example1.com/")
conn.subscribe(topic2_arn, "http", "http://example2.com/")
topic1_subscriptions = conn.get_all_subscriptions_by_topic(topic1_arn)[
"ListSubscriptionsByTopicResponse"]["ListSubscriptionsByTopicResult"]["Subscriptions"]
topic1_subscriptions.should.have.length_of(1)
topic1_subscriptions[0]['Endpoint'].should.equal("http://example1.com/")
@mock_sns_deprecated
def test_subscription_paging():
conn = boto.connect_sns()
conn.create_topic("topic1")
conn.create_topic("topic2")
topics_json = conn.get_all_topics()
topics = topics_json["ListTopicsResponse"]["ListTopicsResult"]["Topics"]
topic1_arn = topics[0]['TopicArn']
topic2_arn = topics[1]['TopicArn']
for index in range(DEFAULT_PAGE_SIZE + int(DEFAULT_PAGE_SIZE / 3)):
conn.subscribe(topic1_arn, 'email', 'email_' +
str(index) + '@test.com')
conn.subscribe(topic2_arn, 'email', 'email_' +
str(index) + '@test.com')
all_subscriptions = conn.get_all_subscriptions()
all_subscriptions["ListSubscriptionsResponse"]["ListSubscriptionsResult"][
"Subscriptions"].should.have.length_of(DEFAULT_PAGE_SIZE)
next_token = all_subscriptions["ListSubscriptionsResponse"][
"ListSubscriptionsResult"]["NextToken"]
next_token.should.equal(DEFAULT_PAGE_SIZE)
all_subscriptions = conn.get_all_subscriptions(next_token=next_token * 2)
all_subscriptions["ListSubscriptionsResponse"]["ListSubscriptionsResult"][
"Subscriptions"].should.have.length_of(int(DEFAULT_PAGE_SIZE * 2 / 3))
next_token = all_subscriptions["ListSubscriptionsResponse"][
"ListSubscriptionsResult"]["NextToken"]
next_token.should.equal(None)
topic1_subscriptions = conn.get_all_subscriptions_by_topic(topic1_arn)
topic1_subscriptions["ListSubscriptionsByTopicResponse"]["ListSubscriptionsByTopicResult"][
"Subscriptions"].should.have.length_of(DEFAULT_PAGE_SIZE)
next_token = topic1_subscriptions["ListSubscriptionsByTopicResponse"][
"ListSubscriptionsByTopicResult"]["NextToken"]
next_token.should.equal(DEFAULT_PAGE_SIZE)
topic1_subscriptions = conn.get_all_subscriptions_by_topic(
topic1_arn, next_token=next_token)
topic1_subscriptions["ListSubscriptionsByTopicResponse"]["ListSubscriptionsByTopicResult"][
"Subscriptions"].should.have.length_of(int(DEFAULT_PAGE_SIZE / 3))
next_token = topic1_subscriptions["ListSubscriptionsByTopicResponse"][
"ListSubscriptionsByTopicResult"]["NextToken"]
next_token.should.equal(None)
from __future__ import unicode_literals
import boto
import sure # noqa
from moto import mock_sns_deprecated
from moto.sns.models import DEFAULT_PAGE_SIZE
@mock_sns_deprecated
def test_creating_subscription():
conn = boto.connect_sns()
conn.create_topic("some-topic")
topics_json = conn.get_all_topics()
topic_arn = topics_json["ListTopicsResponse"][
"ListTopicsResult"]["Topics"][0]['TopicArn']
conn.subscribe(topic_arn, "http", "http://example.com/")
subscriptions = conn.get_all_subscriptions()["ListSubscriptionsResponse"][
"ListSubscriptionsResult"]["Subscriptions"]
subscriptions.should.have.length_of(1)
subscription = subscriptions[0]
subscription["TopicArn"].should.equal(topic_arn)
subscription["Protocol"].should.equal("http")
subscription["SubscriptionArn"].should.contain(topic_arn)
subscription["Endpoint"].should.equal("http://example.com/")
# Now unsubscribe the subscription
conn.unsubscribe(subscription["SubscriptionArn"])
# And there should be zero subscriptions left
subscriptions = conn.get_all_subscriptions()["ListSubscriptionsResponse"][
"ListSubscriptionsResult"]["Subscriptions"]
subscriptions.should.have.length_of(0)
@mock_sns_deprecated
def test_deleting_subscriptions_by_deleting_topic():
conn = boto.connect_sns()
conn.create_topic("some-topic")
topics_json = conn.get_all_topics()
topic_arn = topics_json["ListTopicsResponse"][
"ListTopicsResult"]["Topics"][0]['TopicArn']
conn.subscribe(topic_arn, "http", "http://example.com/")
subscriptions = conn.get_all_subscriptions()["ListSubscriptionsResponse"][
"ListSubscriptionsResult"]["Subscriptions"]
subscriptions.should.have.length_of(1)
subscription = subscriptions[0]
subscription["TopicArn"].should.equal(topic_arn)
subscription["Protocol"].should.equal("http")
subscription["SubscriptionArn"].should.contain(topic_arn)
subscription["Endpoint"].should.equal("http://example.com/")
# Now delete the topic
conn.delete_topic(topic_arn)
# And there should now be 0 topics
topics_json = conn.get_all_topics()
topics = topics_json["ListTopicsResponse"]["ListTopicsResult"]["Topics"]
topics.should.have.length_of(0)
# And there should be zero subscriptions left
subscriptions = conn.get_all_subscriptions()["ListSubscriptionsResponse"][
"ListSubscriptionsResult"]["Subscriptions"]
subscriptions.should.have.length_of(0)
@mock_sns_deprecated
def test_getting_subscriptions_by_topic():
conn = boto.connect_sns()
conn.create_topic("topic1")
conn.create_topic("topic2")
topics_json = conn.get_all_topics()
topics = topics_json["ListTopicsResponse"]["ListTopicsResult"]["Topics"]
topic1_arn = topics[0]['TopicArn']
topic2_arn = topics[1]['TopicArn']
conn.subscribe(topic1_arn, "http", "http://example1.com/")
conn.subscribe(topic2_arn, "http", "http://example2.com/")
topic1_subscriptions = conn.get_all_subscriptions_by_topic(topic1_arn)[
"ListSubscriptionsByTopicResponse"]["ListSubscriptionsByTopicResult"]["Subscriptions"]
topic1_subscriptions.should.have.length_of(1)
topic1_subscriptions[0]['Endpoint'].should.equal("http://example1.com/")
@mock_sns_deprecated
def test_subscription_paging():
conn = boto.connect_sns()
conn.create_topic("topic1")
conn.create_topic("topic2")
topics_json = conn.get_all_topics()
topics = topics_json["ListTopicsResponse"]["ListTopicsResult"]["Topics"]
topic1_arn = topics[0]['TopicArn']
topic2_arn = topics[1]['TopicArn']
for index in range(DEFAULT_PAGE_SIZE + int(DEFAULT_PAGE_SIZE / 3)):
conn.subscribe(topic1_arn, 'email', 'email_' +
str(index) + '@test.com')
conn.subscribe(topic2_arn, 'email', 'email_' +
str(index) + '@test.com')
all_subscriptions = conn.get_all_subscriptions()
all_subscriptions["ListSubscriptionsResponse"]["ListSubscriptionsResult"][
"Subscriptions"].should.have.length_of(DEFAULT_PAGE_SIZE)
next_token = all_subscriptions["ListSubscriptionsResponse"][
"ListSubscriptionsResult"]["NextToken"]
next_token.should.equal(DEFAULT_PAGE_SIZE)
all_subscriptions = conn.get_all_subscriptions(next_token=next_token * 2)
all_subscriptions["ListSubscriptionsResponse"]["ListSubscriptionsResult"][
"Subscriptions"].should.have.length_of(int(DEFAULT_PAGE_SIZE * 2 / 3))
next_token = all_subscriptions["ListSubscriptionsResponse"][
"ListSubscriptionsResult"]["NextToken"]
next_token.should.equal(None)
topic1_subscriptions = conn.get_all_subscriptions_by_topic(topic1_arn)
topic1_subscriptions["ListSubscriptionsByTopicResponse"]["ListSubscriptionsByTopicResult"][
"Subscriptions"].should.have.length_of(DEFAULT_PAGE_SIZE)
next_token = topic1_subscriptions["ListSubscriptionsByTopicResponse"][
"ListSubscriptionsByTopicResult"]["NextToken"]
next_token.should.equal(DEFAULT_PAGE_SIZE)
topic1_subscriptions = conn.get_all_subscriptions_by_topic(
topic1_arn, next_token=next_token)
topic1_subscriptions["ListSubscriptionsByTopicResponse"]["ListSubscriptionsByTopicResult"][
"Subscriptions"].should.have.length_of(int(DEFAULT_PAGE_SIZE / 3))
next_token = topic1_subscriptions["ListSubscriptionsByTopicResponse"][
"ListSubscriptionsByTopicResult"]["NextToken"]
next_token.should.equal(None)

View file

@ -1,396 +1,396 @@
from __future__ import unicode_literals
import boto3
import json
import sure # noqa
from botocore.exceptions import ClientError
from nose.tools import assert_raises
from moto import mock_sns
from moto.sns.models import DEFAULT_PAGE_SIZE
@mock_sns
def test_subscribe_sms():
client = boto3.client('sns', region_name='us-east-1')
client.create_topic(Name="some-topic")
resp = client.create_topic(Name="some-topic")
arn = resp['TopicArn']
resp = client.subscribe(
TopicArn=arn,
Protocol='sms',
Endpoint='+15551234567'
)
resp.should.contain('SubscriptionArn')
@mock_sns
def test_double_subscription():
client = boto3.client('sns', region_name='us-east-1')
client.create_topic(Name="some-topic")
resp = client.create_topic(Name="some-topic")
arn = resp['TopicArn']
do_subscribe_sqs = lambda sqs_arn: client.subscribe(
TopicArn=arn,
Protocol='sqs',
Endpoint=sqs_arn
)
resp1 = do_subscribe_sqs('arn:aws:sqs:elasticmq:000000000000:foo')
resp2 = do_subscribe_sqs('arn:aws:sqs:elasticmq:000000000000:foo')
resp1['SubscriptionArn'].should.equal(resp2['SubscriptionArn'])
@mock_sns
def test_subscribe_bad_sms():
client = boto3.client('sns', region_name='us-east-1')
client.create_topic(Name="some-topic")
resp = client.create_topic(Name="some-topic")
arn = resp['TopicArn']
try:
# Test invalid number
client.subscribe(
TopicArn=arn,
Protocol='sms',
Endpoint='NAA+15551234567'
)
except ClientError as err:
err.response['Error']['Code'].should.equal('InvalidParameter')
@mock_sns
def test_creating_subscription():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
conn.subscribe(TopicArn=topic_arn,
Protocol="http",
Endpoint="http://example.com/")
subscriptions = conn.list_subscriptions()["Subscriptions"]
subscriptions.should.have.length_of(1)
subscription = subscriptions[0]
subscription["TopicArn"].should.equal(topic_arn)
subscription["Protocol"].should.equal("http")
subscription["SubscriptionArn"].should.contain(topic_arn)
subscription["Endpoint"].should.equal("http://example.com/")
# Now unsubscribe the subscription
conn.unsubscribe(SubscriptionArn=subscription["SubscriptionArn"])
# And there should be zero subscriptions left
subscriptions = conn.list_subscriptions()["Subscriptions"]
subscriptions.should.have.length_of(0)
@mock_sns
def test_deleting_subscriptions_by_deleting_topic():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
conn.subscribe(TopicArn=topic_arn,
Protocol="http",
Endpoint="http://example.com/")
subscriptions = conn.list_subscriptions()["Subscriptions"]
subscriptions.should.have.length_of(1)
subscription = subscriptions[0]
subscription["TopicArn"].should.equal(topic_arn)
subscription["Protocol"].should.equal("http")
subscription["SubscriptionArn"].should.contain(topic_arn)
subscription["Endpoint"].should.equal("http://example.com/")
# Now delete the topic
conn.delete_topic(TopicArn=topic_arn)
# And there should now be 0 topics
topics_json = conn.list_topics()
topics = topics_json["Topics"]
topics.should.have.length_of(0)
# And there should be zero subscriptions left
subscriptions = conn.list_subscriptions()["Subscriptions"]
subscriptions.should.have.length_of(0)
@mock_sns
def test_getting_subscriptions_by_topic():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="topic1")
conn.create_topic(Name="topic2")
response = conn.list_topics()
topics = response["Topics"]
topic1_arn = topics[0]['TopicArn']
topic2_arn = topics[1]['TopicArn']
conn.subscribe(TopicArn=topic1_arn,
Protocol="http",
Endpoint="http://example1.com/")
conn.subscribe(TopicArn=topic2_arn,
Protocol="http",
Endpoint="http://example2.com/")
topic1_subscriptions = conn.list_subscriptions_by_topic(TopicArn=topic1_arn)[
"Subscriptions"]
topic1_subscriptions.should.have.length_of(1)
topic1_subscriptions[0]['Endpoint'].should.equal("http://example1.com/")
@mock_sns
def test_subscription_paging():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="topic1")
response = conn.list_topics()
topics = response["Topics"]
topic1_arn = topics[0]['TopicArn']
for index in range(DEFAULT_PAGE_SIZE + int(DEFAULT_PAGE_SIZE / 3)):
conn.subscribe(TopicArn=topic1_arn,
Protocol='email',
Endpoint='email_' + str(index) + '@test.com')
all_subscriptions = conn.list_subscriptions()
all_subscriptions["Subscriptions"].should.have.length_of(DEFAULT_PAGE_SIZE)
next_token = all_subscriptions["NextToken"]
next_token.should.equal(str(DEFAULT_PAGE_SIZE))
all_subscriptions = conn.list_subscriptions(NextToken=next_token)
all_subscriptions["Subscriptions"].should.have.length_of(
int(DEFAULT_PAGE_SIZE / 3))
all_subscriptions.shouldnt.have("NextToken")
topic1_subscriptions = conn.list_subscriptions_by_topic(
TopicArn=topic1_arn)
topic1_subscriptions["Subscriptions"].should.have.length_of(
DEFAULT_PAGE_SIZE)
next_token = topic1_subscriptions["NextToken"]
next_token.should.equal(str(DEFAULT_PAGE_SIZE))
topic1_subscriptions = conn.list_subscriptions_by_topic(
TopicArn=topic1_arn, NextToken=next_token)
topic1_subscriptions["Subscriptions"].should.have.length_of(
int(DEFAULT_PAGE_SIZE / 3))
topic1_subscriptions.shouldnt.have("NextToken")
@mock_sns
def test_creating_subscription_with_attributes():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
delivery_policy = json.dumps({
'healthyRetryPolicy': {
"numRetries": 10,
"minDelayTarget": 1,
"maxDelayTarget":2
}
})
filter_policy = json.dumps({
"store": ["example_corp"],
"event": ["order_cancelled"],
"encrypted": [False],
"customer_interests": ["basketball", "baseball"]
})
conn.subscribe(TopicArn=topic_arn,
Protocol="http",
Endpoint="http://example.com/",
Attributes={
'RawMessageDelivery': 'true',
'DeliveryPolicy': delivery_policy,
'FilterPolicy': filter_policy
})
subscriptions = conn.list_subscriptions()["Subscriptions"]
subscriptions.should.have.length_of(1)
subscription = subscriptions[0]
subscription["TopicArn"].should.equal(topic_arn)
subscription["Protocol"].should.equal("http")
subscription["SubscriptionArn"].should.contain(topic_arn)
subscription["Endpoint"].should.equal("http://example.com/")
# Test the subscription attributes have been set
subscription_arn = subscription["SubscriptionArn"]
attrs = conn.get_subscription_attributes(
SubscriptionArn=subscription_arn
)
attrs['Attributes']['RawMessageDelivery'].should.equal('true')
attrs['Attributes']['DeliveryPolicy'].should.equal(delivery_policy)
attrs['Attributes']['FilterPolicy'].should.equal(filter_policy)
# Now unsubscribe the subscription
conn.unsubscribe(SubscriptionArn=subscription["SubscriptionArn"])
# And there should be zero subscriptions left
subscriptions = conn.list_subscriptions()["Subscriptions"]
subscriptions.should.have.length_of(0)
# invalid attr name
with assert_raises(ClientError):
conn.subscribe(TopicArn=topic_arn,
Protocol="http",
Endpoint="http://example.com/",
Attributes={
'InvalidName': 'true'
})
@mock_sns
def test_set_subscription_attributes():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
conn.subscribe(TopicArn=topic_arn,
Protocol="http",
Endpoint="http://example.com/")
subscriptions = conn.list_subscriptions()["Subscriptions"]
subscriptions.should.have.length_of(1)
subscription = subscriptions[0]
subscription["TopicArn"].should.equal(topic_arn)
subscription["Protocol"].should.equal("http")
subscription["SubscriptionArn"].should.contain(topic_arn)
subscription["Endpoint"].should.equal("http://example.com/")
subscription_arn = subscription["SubscriptionArn"]
attrs = conn.get_subscription_attributes(
SubscriptionArn=subscription_arn
)
attrs.should.have.key('Attributes')
conn.set_subscription_attributes(
SubscriptionArn=subscription_arn,
AttributeName='RawMessageDelivery',
AttributeValue='true'
)
delivery_policy = json.dumps({
'healthyRetryPolicy': {
"numRetries": 10,
"minDelayTarget": 1,
"maxDelayTarget":2
}
})
conn.set_subscription_attributes(
SubscriptionArn=subscription_arn,
AttributeName='DeliveryPolicy',
AttributeValue=delivery_policy
)
filter_policy = json.dumps({
"store": ["example_corp"],
"event": ["order_cancelled"],
"encrypted": [False],
"customer_interests": ["basketball", "baseball"]
})
conn.set_subscription_attributes(
SubscriptionArn=subscription_arn,
AttributeName='FilterPolicy',
AttributeValue=filter_policy
)
attrs = conn.get_subscription_attributes(
SubscriptionArn=subscription_arn
)
attrs['Attributes']['RawMessageDelivery'].should.equal('true')
attrs['Attributes']['DeliveryPolicy'].should.equal(delivery_policy)
attrs['Attributes']['FilterPolicy'].should.equal(filter_policy)
# not existing subscription
with assert_raises(ClientError):
conn.set_subscription_attributes(
SubscriptionArn='invalid',
AttributeName='RawMessageDelivery',
AttributeValue='true'
)
with assert_raises(ClientError):
attrs = conn.get_subscription_attributes(
SubscriptionArn='invalid'
)
# invalid attr name
with assert_raises(ClientError):
conn.set_subscription_attributes(
SubscriptionArn=subscription_arn,
AttributeName='InvalidName',
AttributeValue='true'
)
@mock_sns
def test_check_not_opted_out():
conn = boto3.client('sns', region_name='us-east-1')
response = conn.check_if_phone_number_is_opted_out(phoneNumber='+447428545375')
response.should.contain('isOptedOut')
response['isOptedOut'].should.be(False)
@mock_sns
def test_check_opted_out():
# Phone number ends in 99 so is hardcoded in the endpoint to return opted
# out status
conn = boto3.client('sns', region_name='us-east-1')
response = conn.check_if_phone_number_is_opted_out(phoneNumber='+447428545399')
response.should.contain('isOptedOut')
response['isOptedOut'].should.be(True)
@mock_sns
def test_check_opted_out_invalid():
conn = boto3.client('sns', region_name='us-east-1')
# Invalid phone number
with assert_raises(ClientError):
conn.check_if_phone_number_is_opted_out(phoneNumber='+44742LALALA')
@mock_sns
def test_list_opted_out():
conn = boto3.client('sns', region_name='us-east-1')
response = conn.list_phone_numbers_opted_out()
response.should.contain('phoneNumbers')
len(response['phoneNumbers']).should.be.greater_than(0)
@mock_sns
def test_opt_in():
conn = boto3.client('sns', region_name='us-east-1')
response = conn.list_phone_numbers_opted_out()
current_len = len(response['phoneNumbers'])
assert current_len > 0
conn.opt_in_phone_number(phoneNumber=response['phoneNumbers'][0])
response = conn.list_phone_numbers_opted_out()
len(response['phoneNumbers']).should.be.greater_than(0)
len(response['phoneNumbers']).should.be.lower_than(current_len)
@mock_sns
def test_confirm_subscription():
conn = boto3.client('sns', region_name='us-east-1')
response = conn.create_topic(Name='testconfirm')
conn.confirm_subscription(
TopicArn=response['TopicArn'],
Token='2336412f37fb687f5d51e6e241d59b68c4e583a5cee0be6f95bbf97ab8d2441cf47b99e848408adaadf4c197e65f03473d53c4ba398f6abbf38ce2e8ebf7b4ceceb2cd817959bcde1357e58a2861b05288c535822eb88cac3db04f592285249971efc6484194fc4a4586147f16916692',
AuthenticateOnUnsubscribe='true'
)
from __future__ import unicode_literals
import boto3
import json
import sure # noqa
from botocore.exceptions import ClientError
from nose.tools import assert_raises
from moto import mock_sns
from moto.sns.models import DEFAULT_PAGE_SIZE
@mock_sns
def test_subscribe_sms():
client = boto3.client('sns', region_name='us-east-1')
client.create_topic(Name="some-topic")
resp = client.create_topic(Name="some-topic")
arn = resp['TopicArn']
resp = client.subscribe(
TopicArn=arn,
Protocol='sms',
Endpoint='+15551234567'
)
resp.should.contain('SubscriptionArn')
@mock_sns
def test_double_subscription():
client = boto3.client('sns', region_name='us-east-1')
client.create_topic(Name="some-topic")
resp = client.create_topic(Name="some-topic")
arn = resp['TopicArn']
do_subscribe_sqs = lambda sqs_arn: client.subscribe(
TopicArn=arn,
Protocol='sqs',
Endpoint=sqs_arn
)
resp1 = do_subscribe_sqs('arn:aws:sqs:elasticmq:000000000000:foo')
resp2 = do_subscribe_sqs('arn:aws:sqs:elasticmq:000000000000:foo')
resp1['SubscriptionArn'].should.equal(resp2['SubscriptionArn'])
@mock_sns
def test_subscribe_bad_sms():
client = boto3.client('sns', region_name='us-east-1')
client.create_topic(Name="some-topic")
resp = client.create_topic(Name="some-topic")
arn = resp['TopicArn']
try:
# Test invalid number
client.subscribe(
TopicArn=arn,
Protocol='sms',
Endpoint='NAA+15551234567'
)
except ClientError as err:
err.response['Error']['Code'].should.equal('InvalidParameter')
@mock_sns
def test_creating_subscription():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
conn.subscribe(TopicArn=topic_arn,
Protocol="http",
Endpoint="http://example.com/")
subscriptions = conn.list_subscriptions()["Subscriptions"]
subscriptions.should.have.length_of(1)
subscription = subscriptions[0]
subscription["TopicArn"].should.equal(topic_arn)
subscription["Protocol"].should.equal("http")
subscription["SubscriptionArn"].should.contain(topic_arn)
subscription["Endpoint"].should.equal("http://example.com/")
# Now unsubscribe the subscription
conn.unsubscribe(SubscriptionArn=subscription["SubscriptionArn"])
# And there should be zero subscriptions left
subscriptions = conn.list_subscriptions()["Subscriptions"]
subscriptions.should.have.length_of(0)
@mock_sns
def test_deleting_subscriptions_by_deleting_topic():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
conn.subscribe(TopicArn=topic_arn,
Protocol="http",
Endpoint="http://example.com/")
subscriptions = conn.list_subscriptions()["Subscriptions"]
subscriptions.should.have.length_of(1)
subscription = subscriptions[0]
subscription["TopicArn"].should.equal(topic_arn)
subscription["Protocol"].should.equal("http")
subscription["SubscriptionArn"].should.contain(topic_arn)
subscription["Endpoint"].should.equal("http://example.com/")
# Now delete the topic
conn.delete_topic(TopicArn=topic_arn)
# And there should now be 0 topics
topics_json = conn.list_topics()
topics = topics_json["Topics"]
topics.should.have.length_of(0)
# And there should be zero subscriptions left
subscriptions = conn.list_subscriptions()["Subscriptions"]
subscriptions.should.have.length_of(0)
@mock_sns
def test_getting_subscriptions_by_topic():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="topic1")
conn.create_topic(Name="topic2")
response = conn.list_topics()
topics = response["Topics"]
topic1_arn = topics[0]['TopicArn']
topic2_arn = topics[1]['TopicArn']
conn.subscribe(TopicArn=topic1_arn,
Protocol="http",
Endpoint="http://example1.com/")
conn.subscribe(TopicArn=topic2_arn,
Protocol="http",
Endpoint="http://example2.com/")
topic1_subscriptions = conn.list_subscriptions_by_topic(TopicArn=topic1_arn)[
"Subscriptions"]
topic1_subscriptions.should.have.length_of(1)
topic1_subscriptions[0]['Endpoint'].should.equal("http://example1.com/")
@mock_sns
def test_subscription_paging():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="topic1")
response = conn.list_topics()
topics = response["Topics"]
topic1_arn = topics[0]['TopicArn']
for index in range(DEFAULT_PAGE_SIZE + int(DEFAULT_PAGE_SIZE / 3)):
conn.subscribe(TopicArn=topic1_arn,
Protocol='email',
Endpoint='email_' + str(index) + '@test.com')
all_subscriptions = conn.list_subscriptions()
all_subscriptions["Subscriptions"].should.have.length_of(DEFAULT_PAGE_SIZE)
next_token = all_subscriptions["NextToken"]
next_token.should.equal(str(DEFAULT_PAGE_SIZE))
all_subscriptions = conn.list_subscriptions(NextToken=next_token)
all_subscriptions["Subscriptions"].should.have.length_of(
int(DEFAULT_PAGE_SIZE / 3))
all_subscriptions.shouldnt.have("NextToken")
topic1_subscriptions = conn.list_subscriptions_by_topic(
TopicArn=topic1_arn)
topic1_subscriptions["Subscriptions"].should.have.length_of(
DEFAULT_PAGE_SIZE)
next_token = topic1_subscriptions["NextToken"]
next_token.should.equal(str(DEFAULT_PAGE_SIZE))
topic1_subscriptions = conn.list_subscriptions_by_topic(
TopicArn=topic1_arn, NextToken=next_token)
topic1_subscriptions["Subscriptions"].should.have.length_of(
int(DEFAULT_PAGE_SIZE / 3))
topic1_subscriptions.shouldnt.have("NextToken")
@mock_sns
def test_creating_subscription_with_attributes():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
delivery_policy = json.dumps({
'healthyRetryPolicy': {
"numRetries": 10,
"minDelayTarget": 1,
"maxDelayTarget":2
}
})
filter_policy = json.dumps({
"store": ["example_corp"],
"event": ["order_cancelled"],
"encrypted": [False],
"customer_interests": ["basketball", "baseball"]
})
conn.subscribe(TopicArn=topic_arn,
Protocol="http",
Endpoint="http://example.com/",
Attributes={
'RawMessageDelivery': 'true',
'DeliveryPolicy': delivery_policy,
'FilterPolicy': filter_policy
})
subscriptions = conn.list_subscriptions()["Subscriptions"]
subscriptions.should.have.length_of(1)
subscription = subscriptions[0]
subscription["TopicArn"].should.equal(topic_arn)
subscription["Protocol"].should.equal("http")
subscription["SubscriptionArn"].should.contain(topic_arn)
subscription["Endpoint"].should.equal("http://example.com/")
# Test the subscription attributes have been set
subscription_arn = subscription["SubscriptionArn"]
attrs = conn.get_subscription_attributes(
SubscriptionArn=subscription_arn
)
attrs['Attributes']['RawMessageDelivery'].should.equal('true')
attrs['Attributes']['DeliveryPolicy'].should.equal(delivery_policy)
attrs['Attributes']['FilterPolicy'].should.equal(filter_policy)
# Now unsubscribe the subscription
conn.unsubscribe(SubscriptionArn=subscription["SubscriptionArn"])
# And there should be zero subscriptions left
subscriptions = conn.list_subscriptions()["Subscriptions"]
subscriptions.should.have.length_of(0)
# invalid attr name
with assert_raises(ClientError):
conn.subscribe(TopicArn=topic_arn,
Protocol="http",
Endpoint="http://example.com/",
Attributes={
'InvalidName': 'true'
})
@mock_sns
def test_set_subscription_attributes():
conn = boto3.client('sns', region_name='us-east-1')
conn.create_topic(Name="some-topic")
response = conn.list_topics()
topic_arn = response["Topics"][0]['TopicArn']
conn.subscribe(TopicArn=topic_arn,
Protocol="http",
Endpoint="http://example.com/")
subscriptions = conn.list_subscriptions()["Subscriptions"]
subscriptions.should.have.length_of(1)
subscription = subscriptions[0]
subscription["TopicArn"].should.equal(topic_arn)
subscription["Protocol"].should.equal("http")
subscription["SubscriptionArn"].should.contain(topic_arn)
subscription["Endpoint"].should.equal("http://example.com/")
subscription_arn = subscription["SubscriptionArn"]
attrs = conn.get_subscription_attributes(
SubscriptionArn=subscription_arn
)
attrs.should.have.key('Attributes')
conn.set_subscription_attributes(
SubscriptionArn=subscription_arn,
AttributeName='RawMessageDelivery',
AttributeValue='true'
)
delivery_policy = json.dumps({
'healthyRetryPolicy': {
"numRetries": 10,
"minDelayTarget": 1,
"maxDelayTarget":2
}
})
conn.set_subscription_attributes(
SubscriptionArn=subscription_arn,
AttributeName='DeliveryPolicy',
AttributeValue=delivery_policy
)
filter_policy = json.dumps({
"store": ["example_corp"],
"event": ["order_cancelled"],
"encrypted": [False],
"customer_interests": ["basketball", "baseball"]
})
conn.set_subscription_attributes(
SubscriptionArn=subscription_arn,
AttributeName='FilterPolicy',
AttributeValue=filter_policy
)
attrs = conn.get_subscription_attributes(
SubscriptionArn=subscription_arn
)
attrs['Attributes']['RawMessageDelivery'].should.equal('true')
attrs['Attributes']['DeliveryPolicy'].should.equal(delivery_policy)
attrs['Attributes']['FilterPolicy'].should.equal(filter_policy)
# not existing subscription
with assert_raises(ClientError):
conn.set_subscription_attributes(
SubscriptionArn='invalid',
AttributeName='RawMessageDelivery',
AttributeValue='true'
)
with assert_raises(ClientError):
attrs = conn.get_subscription_attributes(
SubscriptionArn='invalid'
)
# invalid attr name
with assert_raises(ClientError):
conn.set_subscription_attributes(
SubscriptionArn=subscription_arn,
AttributeName='InvalidName',
AttributeValue='true'
)
@mock_sns
def test_check_not_opted_out():
conn = boto3.client('sns', region_name='us-east-1')
response = conn.check_if_phone_number_is_opted_out(phoneNumber='+447428545375')
response.should.contain('isOptedOut')
response['isOptedOut'].should.be(False)
@mock_sns
def test_check_opted_out():
# Phone number ends in 99 so is hardcoded in the endpoint to return opted
# out status
conn = boto3.client('sns', region_name='us-east-1')
response = conn.check_if_phone_number_is_opted_out(phoneNumber='+447428545399')
response.should.contain('isOptedOut')
response['isOptedOut'].should.be(True)
@mock_sns
def test_check_opted_out_invalid():
conn = boto3.client('sns', region_name='us-east-1')
# Invalid phone number
with assert_raises(ClientError):
conn.check_if_phone_number_is_opted_out(phoneNumber='+44742LALALA')
@mock_sns
def test_list_opted_out():
conn = boto3.client('sns', region_name='us-east-1')
response = conn.list_phone_numbers_opted_out()
response.should.contain('phoneNumbers')
len(response['phoneNumbers']).should.be.greater_than(0)
@mock_sns
def test_opt_in():
conn = boto3.client('sns', region_name='us-east-1')
response = conn.list_phone_numbers_opted_out()
current_len = len(response['phoneNumbers'])
assert current_len > 0
conn.opt_in_phone_number(phoneNumber=response['phoneNumbers'][0])
response = conn.list_phone_numbers_opted_out()
len(response['phoneNumbers']).should.be.greater_than(0)
len(response['phoneNumbers']).should.be.lower_than(current_len)
@mock_sns
def test_confirm_subscription():
conn = boto3.client('sns', region_name='us-east-1')
response = conn.create_topic(Name='testconfirm')
conn.confirm_subscription(
TopicArn=response['TopicArn'],
Token='2336412f37fb687f5d51e6e241d59b68c4e583a5cee0be6f95bbf97ab8d2441cf47b99e848408adaadf4c197e65f03473d53c4ba398f6abbf38ce2e8ebf7b4ceceb2cd817959bcde1357e58a2861b05288c535822eb88cac3db04f592285249971efc6484194fc4a4586147f16916692',
AuthenticateOnUnsubscribe='true'
)

View file

@ -1,133 +1,133 @@
from __future__ import unicode_literals
import boto
import json
import six
import sure # noqa
from boto.exception import BotoServerError
from moto import mock_sns_deprecated
from moto.sns.models import DEFAULT_TOPIC_POLICY, DEFAULT_EFFECTIVE_DELIVERY_POLICY, DEFAULT_PAGE_SIZE
@mock_sns_deprecated
def test_create_and_delete_topic():
conn = boto.connect_sns()
conn.create_topic("some-topic")
topics_json = conn.get_all_topics()
topics = topics_json["ListTopicsResponse"]["ListTopicsResult"]["Topics"]
topics.should.have.length_of(1)
topics[0]['TopicArn'].should.equal(
"arn:aws:sns:{0}:123456789012:some-topic"
.format(conn.region.name)
)
# Delete the topic
conn.delete_topic(topics[0]['TopicArn'])
# And there should now be 0 topics
topics_json = conn.get_all_topics()
topics = topics_json["ListTopicsResponse"]["ListTopicsResult"]["Topics"]
topics.should.have.length_of(0)
@mock_sns_deprecated
def test_get_missing_topic():
conn = boto.connect_sns()
conn.get_topic_attributes.when.called_with(
"a-fake-arn").should.throw(BotoServerError)
@mock_sns_deprecated
def test_create_topic_in_multiple_regions():
for region in ['us-west-1', 'us-west-2']:
conn = boto.sns.connect_to_region(region)
conn.create_topic("some-topic")
list(conn.get_all_topics()["ListTopicsResponse"][
"ListTopicsResult"]["Topics"]).should.have.length_of(1)
@mock_sns_deprecated
def test_topic_corresponds_to_region():
for region in ['us-east-1', 'us-west-2']:
conn = boto.sns.connect_to_region(region)
conn.create_topic("some-topic")
topics_json = conn.get_all_topics()
topic_arn = topics_json["ListTopicsResponse"][
"ListTopicsResult"]["Topics"][0]['TopicArn']
topic_arn.should.equal(
"arn:aws:sns:{0}:123456789012:some-topic".format(region))
@mock_sns_deprecated
def test_topic_attributes():
conn = boto.connect_sns()
conn.create_topic("some-topic")
topics_json = conn.get_all_topics()
topic_arn = topics_json["ListTopicsResponse"][
"ListTopicsResult"]["Topics"][0]['TopicArn']
attributes = conn.get_topic_attributes(topic_arn)['GetTopicAttributesResponse'][
'GetTopicAttributesResult']['Attributes']
attributes["TopicArn"].should.equal(
"arn:aws:sns:{0}:123456789012:some-topic"
.format(conn.region.name)
)
attributes["Owner"].should.equal(123456789012)
json.loads(attributes["Policy"]).should.equal(DEFAULT_TOPIC_POLICY)
attributes["DisplayName"].should.equal("")
attributes["SubscriptionsPending"].should.equal(0)
attributes["SubscriptionsConfirmed"].should.equal(0)
attributes["SubscriptionsDeleted"].should.equal(0)
attributes["DeliveryPolicy"].should.equal("")
json.loads(attributes["EffectiveDeliveryPolicy"]).should.equal(
DEFAULT_EFFECTIVE_DELIVERY_POLICY)
# boto can't handle prefix-mandatory strings:
# i.e. unicode on Python 2 -- u"foobar"
# and bytes on Python 3 -- b"foobar"
if six.PY2:
policy = {b"foo": b"bar"}
displayname = b"My display name"
delivery = {b"http": {b"defaultHealthyRetryPolicy": {b"numRetries": 5}}}
else:
policy = {u"foo": u"bar"}
displayname = u"My display name"
delivery = {u"http": {u"defaultHealthyRetryPolicy": {u"numRetries": 5}}}
conn.set_topic_attributes(topic_arn, "Policy", policy)
conn.set_topic_attributes(topic_arn, "DisplayName", displayname)
conn.set_topic_attributes(topic_arn, "DeliveryPolicy", delivery)
attributes = conn.get_topic_attributes(topic_arn)['GetTopicAttributesResponse'][
'GetTopicAttributesResult']['Attributes']
attributes["Policy"].should.equal("{'foo': 'bar'}")
attributes["DisplayName"].should.equal("My display name")
attributes["DeliveryPolicy"].should.equal(
"{'http': {'defaultHealthyRetryPolicy': {'numRetries': 5}}}")
@mock_sns_deprecated
def test_topic_paging():
conn = boto.connect_sns()
for index in range(DEFAULT_PAGE_SIZE + int(DEFAULT_PAGE_SIZE / 2)):
conn.create_topic("some-topic_" + str(index))
topics_json = conn.get_all_topics()
topics_list = topics_json["ListTopicsResponse"][
"ListTopicsResult"]["Topics"]
next_token = topics_json["ListTopicsResponse"][
"ListTopicsResult"]["NextToken"]
len(topics_list).should.equal(DEFAULT_PAGE_SIZE)
next_token.should.equal(DEFAULT_PAGE_SIZE)
topics_json = conn.get_all_topics(next_token=next_token)
topics_list = topics_json["ListTopicsResponse"][
"ListTopicsResult"]["Topics"]
next_token = topics_json["ListTopicsResponse"][
"ListTopicsResult"]["NextToken"]
topics_list.should.have.length_of(int(DEFAULT_PAGE_SIZE / 2))
next_token.should.equal(None)
from __future__ import unicode_literals
import boto
import json
import six
import sure # noqa
from boto.exception import BotoServerError
from moto import mock_sns_deprecated
from moto.sns.models import DEFAULT_TOPIC_POLICY, DEFAULT_EFFECTIVE_DELIVERY_POLICY, DEFAULT_PAGE_SIZE
@mock_sns_deprecated
def test_create_and_delete_topic():
conn = boto.connect_sns()
conn.create_topic("some-topic")
topics_json = conn.get_all_topics()
topics = topics_json["ListTopicsResponse"]["ListTopicsResult"]["Topics"]
topics.should.have.length_of(1)
topics[0]['TopicArn'].should.equal(
"arn:aws:sns:{0}:123456789012:some-topic"
.format(conn.region.name)
)
# Delete the topic
conn.delete_topic(topics[0]['TopicArn'])
# And there should now be 0 topics
topics_json = conn.get_all_topics()
topics = topics_json["ListTopicsResponse"]["ListTopicsResult"]["Topics"]
topics.should.have.length_of(0)
@mock_sns_deprecated
def test_get_missing_topic():
conn = boto.connect_sns()
conn.get_topic_attributes.when.called_with(
"a-fake-arn").should.throw(BotoServerError)
@mock_sns_deprecated
def test_create_topic_in_multiple_regions():
for region in ['us-west-1', 'us-west-2']:
conn = boto.sns.connect_to_region(region)
conn.create_topic("some-topic")
list(conn.get_all_topics()["ListTopicsResponse"][
"ListTopicsResult"]["Topics"]).should.have.length_of(1)
@mock_sns_deprecated
def test_topic_corresponds_to_region():
for region in ['us-east-1', 'us-west-2']:
conn = boto.sns.connect_to_region(region)
conn.create_topic("some-topic")
topics_json = conn.get_all_topics()
topic_arn = topics_json["ListTopicsResponse"][
"ListTopicsResult"]["Topics"][0]['TopicArn']
topic_arn.should.equal(
"arn:aws:sns:{0}:123456789012:some-topic".format(region))
@mock_sns_deprecated
def test_topic_attributes():
conn = boto.connect_sns()
conn.create_topic("some-topic")
topics_json = conn.get_all_topics()
topic_arn = topics_json["ListTopicsResponse"][
"ListTopicsResult"]["Topics"][0]['TopicArn']
attributes = conn.get_topic_attributes(topic_arn)['GetTopicAttributesResponse'][
'GetTopicAttributesResult']['Attributes']
attributes["TopicArn"].should.equal(
"arn:aws:sns:{0}:123456789012:some-topic"
.format(conn.region.name)
)
attributes["Owner"].should.equal(123456789012)
json.loads(attributes["Policy"]).should.equal(DEFAULT_TOPIC_POLICY)
attributes["DisplayName"].should.equal("")
attributes["SubscriptionsPending"].should.equal(0)
attributes["SubscriptionsConfirmed"].should.equal(0)
attributes["SubscriptionsDeleted"].should.equal(0)
attributes["DeliveryPolicy"].should.equal("")
json.loads(attributes["EffectiveDeliveryPolicy"]).should.equal(
DEFAULT_EFFECTIVE_DELIVERY_POLICY)
# boto can't handle prefix-mandatory strings:
# i.e. unicode on Python 2 -- u"foobar"
# and bytes on Python 3 -- b"foobar"
if six.PY2:
policy = {b"foo": b"bar"}
displayname = b"My display name"
delivery = {b"http": {b"defaultHealthyRetryPolicy": {b"numRetries": 5}}}
else:
policy = {u"foo": u"bar"}
displayname = u"My display name"
delivery = {u"http": {u"defaultHealthyRetryPolicy": {u"numRetries": 5}}}
conn.set_topic_attributes(topic_arn, "Policy", policy)
conn.set_topic_attributes(topic_arn, "DisplayName", displayname)
conn.set_topic_attributes(topic_arn, "DeliveryPolicy", delivery)
attributes = conn.get_topic_attributes(topic_arn)['GetTopicAttributesResponse'][
'GetTopicAttributesResult']['Attributes']
attributes["Policy"].should.equal("{'foo': 'bar'}")
attributes["DisplayName"].should.equal("My display name")
attributes["DeliveryPolicy"].should.equal(
"{'http': {'defaultHealthyRetryPolicy': {'numRetries': 5}}}")
@mock_sns_deprecated
def test_topic_paging():
conn = boto.connect_sns()
for index in range(DEFAULT_PAGE_SIZE + int(DEFAULT_PAGE_SIZE / 2)):
conn.create_topic("some-topic_" + str(index))
topics_json = conn.get_all_topics()
topics_list = topics_json["ListTopicsResponse"][
"ListTopicsResult"]["Topics"]
next_token = topics_json["ListTopicsResponse"][
"ListTopicsResult"]["NextToken"]
len(topics_list).should.equal(DEFAULT_PAGE_SIZE)
next_token.should.equal(DEFAULT_PAGE_SIZE)
topics_json = conn.get_all_topics(next_token=next_token)
topics_list = topics_json["ListTopicsResponse"][
"ListTopicsResult"]["Topics"]
next_token = topics_json["ListTopicsResponse"][
"ListTopicsResult"]["NextToken"]
topics_list.should.have.length_of(int(DEFAULT_PAGE_SIZE / 2))
next_token.should.equal(None)

View file

@ -1,190 +1,190 @@
from __future__ import unicode_literals
import boto3
import six
import json
import sure # noqa
from botocore.exceptions import ClientError
from moto import mock_sns
from moto.sns.models import DEFAULT_TOPIC_POLICY, DEFAULT_EFFECTIVE_DELIVERY_POLICY, DEFAULT_PAGE_SIZE
@mock_sns
def test_create_and_delete_topic():
conn = boto3.client("sns", region_name="us-east-1")
for topic_name in ('some-topic', '-some-topic-', '_some-topic_', 'a' * 256):
conn.create_topic(Name=topic_name)
topics_json = conn.list_topics()
topics = topics_json["Topics"]
topics.should.have.length_of(1)
topics[0]['TopicArn'].should.equal(
"arn:aws:sns:{0}:123456789012:{1}"
.format(conn._client_config.region_name, topic_name)
)
# Delete the topic
conn.delete_topic(TopicArn=topics[0]['TopicArn'])
# And there should now be 0 topics
topics_json = conn.list_topics()
topics = topics_json["Topics"]
topics.should.have.length_of(0)
@mock_sns
def test_create_topic_should_be_indempodent():
conn = boto3.client("sns", region_name="us-east-1")
topic_arn = conn.create_topic(Name="some-topic")['TopicArn']
conn.set_topic_attributes(
TopicArn=topic_arn,
AttributeName="DisplayName",
AttributeValue="should_be_set"
)
topic_display_name = conn.get_topic_attributes(
TopicArn=topic_arn
)['Attributes']['DisplayName']
topic_display_name.should.be.equal("should_be_set")
#recreate topic to prove indempodentcy
topic_arn = conn.create_topic(Name="some-topic")['TopicArn']
topic_display_name = conn.get_topic_attributes(
TopicArn=topic_arn
)['Attributes']['DisplayName']
topic_display_name.should.be.equal("should_be_set")
@mock_sns
def test_get_missing_topic():
conn = boto3.client("sns", region_name="us-east-1")
conn.get_topic_attributes.when.called_with(
TopicArn="a-fake-arn").should.throw(ClientError)
@mock_sns
def test_create_topic_must_meet_constraints():
conn = boto3.client("sns", region_name="us-east-1")
common_random_chars = [':', ";", "!", "@", "|", "^", "%"]
for char in common_random_chars:
conn.create_topic.when.called_with(
Name="no%s_invalidchar" % char).should.throw(ClientError)
conn.create_topic.when.called_with(
Name="no spaces allowed").should.throw(ClientError)
@mock_sns
def test_create_topic_should_be_of_certain_length():
conn = boto3.client("sns", region_name="us-east-1")
too_short = ""
conn.create_topic.when.called_with(
Name=too_short).should.throw(ClientError)
too_long = "x" * 257
conn.create_topic.when.called_with(
Name=too_long).should.throw(ClientError)
@mock_sns
def test_create_topic_in_multiple_regions():
for region in ['us-west-1', 'us-west-2']:
conn = boto3.client("sns", region_name=region)
conn.create_topic(Name="some-topic")
list(conn.list_topics()["Topics"]).should.have.length_of(1)
@mock_sns
def test_topic_corresponds_to_region():
for region in ['us-east-1', 'us-west-2']:
conn = boto3.client("sns", region_name=region)
conn.create_topic(Name="some-topic")
topics_json = conn.list_topics()
topic_arn = topics_json["Topics"][0]['TopicArn']
topic_arn.should.equal(
"arn:aws:sns:{0}:123456789012:some-topic".format(region))
@mock_sns
def test_topic_attributes():
conn = boto3.client("sns", region_name="us-east-1")
conn.create_topic(Name="some-topic")
topics_json = conn.list_topics()
topic_arn = topics_json["Topics"][0]['TopicArn']
attributes = conn.get_topic_attributes(TopicArn=topic_arn)['Attributes']
attributes["TopicArn"].should.equal(
"arn:aws:sns:{0}:123456789012:some-topic"
.format(conn._client_config.region_name)
)
attributes["Owner"].should.equal('123456789012')
json.loads(attributes["Policy"]).should.equal(DEFAULT_TOPIC_POLICY)
attributes["DisplayName"].should.equal("")
attributes["SubscriptionsPending"].should.equal('0')
attributes["SubscriptionsConfirmed"].should.equal('0')
attributes["SubscriptionsDeleted"].should.equal('0')
attributes["DeliveryPolicy"].should.equal("")
json.loads(attributes["EffectiveDeliveryPolicy"]).should.equal(
DEFAULT_EFFECTIVE_DELIVERY_POLICY)
# boto can't handle prefix-mandatory strings:
# i.e. unicode on Python 2 -- u"foobar"
# and bytes on Python 3 -- b"foobar"
if six.PY2:
policy = json.dumps({b"foo": b"bar"})
displayname = b"My display name"
delivery = json.dumps(
{b"http": {b"defaultHealthyRetryPolicy": {b"numRetries": 5}}})
else:
policy = json.dumps({u"foo": u"bar"})
displayname = u"My display name"
delivery = json.dumps(
{u"http": {u"defaultHealthyRetryPolicy": {u"numRetries": 5}}})
conn.set_topic_attributes(TopicArn=topic_arn,
AttributeName="Policy",
AttributeValue=policy)
conn.set_topic_attributes(TopicArn=topic_arn,
AttributeName="DisplayName",
AttributeValue=displayname)
conn.set_topic_attributes(TopicArn=topic_arn,
AttributeName="DeliveryPolicy",
AttributeValue=delivery)
attributes = conn.get_topic_attributes(TopicArn=topic_arn)['Attributes']
attributes["Policy"].should.equal('{"foo": "bar"}')
attributes["DisplayName"].should.equal("My display name")
attributes["DeliveryPolicy"].should.equal(
'{"http": {"defaultHealthyRetryPolicy": {"numRetries": 5}}}')
@mock_sns
def test_topic_paging():
conn = boto3.client("sns", region_name="us-east-1")
for index in range(DEFAULT_PAGE_SIZE + int(DEFAULT_PAGE_SIZE / 2)):
conn.create_topic(Name="some-topic_" + str(index))
response = conn.list_topics()
topics_list = response["Topics"]
next_token = response["NextToken"]
len(topics_list).should.equal(DEFAULT_PAGE_SIZE)
int(next_token).should.equal(DEFAULT_PAGE_SIZE)
response = conn.list_topics(NextToken=next_token)
topics_list = response["Topics"]
response.shouldnt.have("NextToken")
topics_list.should.have.length_of(int(DEFAULT_PAGE_SIZE / 2))
@mock_sns
def test_add_remove_permissions():
conn = boto3.client('sns', region_name='us-east-1')
response = conn.create_topic(Name='testpermissions')
conn.add_permission(
TopicArn=response['TopicArn'],
Label='Test1234',
AWSAccountId=['999999999999'],
ActionName=['AddPermission']
)
conn.remove_permission(
TopicArn=response['TopicArn'],
Label='Test1234'
)
from __future__ import unicode_literals
import boto3
import six
import json
import sure # noqa
from botocore.exceptions import ClientError
from moto import mock_sns
from moto.sns.models import DEFAULT_TOPIC_POLICY, DEFAULT_EFFECTIVE_DELIVERY_POLICY, DEFAULT_PAGE_SIZE
@mock_sns
def test_create_and_delete_topic():
conn = boto3.client("sns", region_name="us-east-1")
for topic_name in ('some-topic', '-some-topic-', '_some-topic_', 'a' * 256):
conn.create_topic(Name=topic_name)
topics_json = conn.list_topics()
topics = topics_json["Topics"]
topics.should.have.length_of(1)
topics[0]['TopicArn'].should.equal(
"arn:aws:sns:{0}:123456789012:{1}"
.format(conn._client_config.region_name, topic_name)
)
# Delete the topic
conn.delete_topic(TopicArn=topics[0]['TopicArn'])
# And there should now be 0 topics
topics_json = conn.list_topics()
topics = topics_json["Topics"]
topics.should.have.length_of(0)
@mock_sns
def test_create_topic_should_be_indempodent():
conn = boto3.client("sns", region_name="us-east-1")
topic_arn = conn.create_topic(Name="some-topic")['TopicArn']
conn.set_topic_attributes(
TopicArn=topic_arn,
AttributeName="DisplayName",
AttributeValue="should_be_set"
)
topic_display_name = conn.get_topic_attributes(
TopicArn=topic_arn
)['Attributes']['DisplayName']
topic_display_name.should.be.equal("should_be_set")
#recreate topic to prove indempodentcy
topic_arn = conn.create_topic(Name="some-topic")['TopicArn']
topic_display_name = conn.get_topic_attributes(
TopicArn=topic_arn
)['Attributes']['DisplayName']
topic_display_name.should.be.equal("should_be_set")
@mock_sns
def test_get_missing_topic():
conn = boto3.client("sns", region_name="us-east-1")
conn.get_topic_attributes.when.called_with(
TopicArn="a-fake-arn").should.throw(ClientError)
@mock_sns
def test_create_topic_must_meet_constraints():
conn = boto3.client("sns", region_name="us-east-1")
common_random_chars = [':', ";", "!", "@", "|", "^", "%"]
for char in common_random_chars:
conn.create_topic.when.called_with(
Name="no%s_invalidchar" % char).should.throw(ClientError)
conn.create_topic.when.called_with(
Name="no spaces allowed").should.throw(ClientError)
@mock_sns
def test_create_topic_should_be_of_certain_length():
conn = boto3.client("sns", region_name="us-east-1")
too_short = ""
conn.create_topic.when.called_with(
Name=too_short).should.throw(ClientError)
too_long = "x" * 257
conn.create_topic.when.called_with(
Name=too_long).should.throw(ClientError)
@mock_sns
def test_create_topic_in_multiple_regions():
for region in ['us-west-1', 'us-west-2']:
conn = boto3.client("sns", region_name=region)
conn.create_topic(Name="some-topic")
list(conn.list_topics()["Topics"]).should.have.length_of(1)
@mock_sns
def test_topic_corresponds_to_region():
for region in ['us-east-1', 'us-west-2']:
conn = boto3.client("sns", region_name=region)
conn.create_topic(Name="some-topic")
topics_json = conn.list_topics()
topic_arn = topics_json["Topics"][0]['TopicArn']
topic_arn.should.equal(
"arn:aws:sns:{0}:123456789012:some-topic".format(region))
@mock_sns
def test_topic_attributes():
conn = boto3.client("sns", region_name="us-east-1")
conn.create_topic(Name="some-topic")
topics_json = conn.list_topics()
topic_arn = topics_json["Topics"][0]['TopicArn']
attributes = conn.get_topic_attributes(TopicArn=topic_arn)['Attributes']
attributes["TopicArn"].should.equal(
"arn:aws:sns:{0}:123456789012:some-topic"
.format(conn._client_config.region_name)
)
attributes["Owner"].should.equal('123456789012')
json.loads(attributes["Policy"]).should.equal(DEFAULT_TOPIC_POLICY)
attributes["DisplayName"].should.equal("")
attributes["SubscriptionsPending"].should.equal('0')
attributes["SubscriptionsConfirmed"].should.equal('0')
attributes["SubscriptionsDeleted"].should.equal('0')
attributes["DeliveryPolicy"].should.equal("")
json.loads(attributes["EffectiveDeliveryPolicy"]).should.equal(
DEFAULT_EFFECTIVE_DELIVERY_POLICY)
# boto can't handle prefix-mandatory strings:
# i.e. unicode on Python 2 -- u"foobar"
# and bytes on Python 3 -- b"foobar"
if six.PY2:
policy = json.dumps({b"foo": b"bar"})
displayname = b"My display name"
delivery = json.dumps(
{b"http": {b"defaultHealthyRetryPolicy": {b"numRetries": 5}}})
else:
policy = json.dumps({u"foo": u"bar"})
displayname = u"My display name"
delivery = json.dumps(
{u"http": {u"defaultHealthyRetryPolicy": {u"numRetries": 5}}})
conn.set_topic_attributes(TopicArn=topic_arn,
AttributeName="Policy",
AttributeValue=policy)
conn.set_topic_attributes(TopicArn=topic_arn,
AttributeName="DisplayName",
AttributeValue=displayname)
conn.set_topic_attributes(TopicArn=topic_arn,
AttributeName="DeliveryPolicy",
AttributeValue=delivery)
attributes = conn.get_topic_attributes(TopicArn=topic_arn)['Attributes']
attributes["Policy"].should.equal('{"foo": "bar"}')
attributes["DisplayName"].should.equal("My display name")
attributes["DeliveryPolicy"].should.equal(
'{"http": {"defaultHealthyRetryPolicy": {"numRetries": 5}}}')
@mock_sns
def test_topic_paging():
conn = boto3.client("sns", region_name="us-east-1")
for index in range(DEFAULT_PAGE_SIZE + int(DEFAULT_PAGE_SIZE / 2)):
conn.create_topic(Name="some-topic_" + str(index))
response = conn.list_topics()
topics_list = response["Topics"]
next_token = response["NextToken"]
len(topics_list).should.equal(DEFAULT_PAGE_SIZE)
int(next_token).should.equal(DEFAULT_PAGE_SIZE)
response = conn.list_topics(NextToken=next_token)
topics_list = response["Topics"]
response.shouldnt.have("NextToken")
topics_list.should.have.length_of(int(DEFAULT_PAGE_SIZE / 2))
@mock_sns
def test_add_remove_permissions():
conn = boto3.client('sns', region_name='us-east-1')
response = conn.create_topic(Name='testpermissions')
conn.add_permission(
TopicArn=response['TopicArn'],
Label='Test1234',
AWSAccountId=['999999999999'],
ActionName=['AddPermission']
)
conn.remove_permission(
TopicArn=response['TopicArn'],
Label='Test1234'
)