Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Stephan Huber 2019-12-23 08:38:53 +01:00
commit 0527e88d46
541 changed files with 75504 additions and 51429 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
from moto.core import ACCOUNT_ID
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:{}:app/APNS/my-application".format(ACCOUNT_ID)
)
@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:{}:endpoint/APNS/my-application/".format(ACCOUNT_ID)
)
@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

@ -4,11 +4,12 @@ import boto3
from botocore.exceptions import ClientError
from moto import mock_sns
import sure # noqa
from moto.core import ACCOUNT_ID
@mock_sns
def test_create_platform_application():
conn = boto3.client('sns', region_name='us-east-1')
conn = boto3.client("sns", region_name="us-east-1")
response = conn.create_platform_application(
Name="my-application",
Platform="APNS",
@ -17,14 +18,15 @@ def test_create_platform_application():
"PlatformPrincipal": "platform_principal",
},
)
application_arn = response['PlatformApplicationArn']
application_arn = response["PlatformApplicationArn"]
application_arn.should.equal(
'arn:aws:sns:us-east-1:123456789012:app/APNS/my-application')
"arn:aws:sns:us-east-1:{}:app/APNS/my-application".format(ACCOUNT_ID)
)
@mock_sns
def test_get_platform_application_attributes():
conn = boto3.client('sns', region_name='us-east-1')
conn = boto3.client("sns", region_name="us-east-1")
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
@ -33,25 +35,29 @@ def test_get_platform_application_attributes():
"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",
})
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 = boto3.client("sns", region_name="us-east-1")
conn.get_platform_application_attributes.when.called_with(
PlatformApplicationArn="a-fake-arn").should.throw(ClientError)
PlatformApplicationArn="a-fake-arn"
).should.throw(ClientError)
@mock_sns
def test_set_platform_application_attributes():
conn = boto3.client('sns', region_name='us-east-1')
conn = boto3.client("sns", region_name="us-east-1")
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
@ -60,291 +66,249 @@ def test_set_platform_application_attributes():
"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",
})
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 = boto3.client("sns", region_name="us-east-1")
conn.create_platform_application(
Name="application1",
Platform="APNS",
Attributes={},
Name="application1", Platform="APNS", Attributes={}
)
conn.create_platform_application(
Name="application2",
Platform="APNS",
Attributes={},
Name="application2", Platform="APNS", Attributes={}
)
applications_repsonse = conn.list_platform_applications()
applications = applications_repsonse['PlatformApplications']
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 = boto3.client("sns", region_name="us-east-1")
conn.create_platform_application(
Name="application1",
Platform="APNS",
Attributes={},
Name="application1", Platform="APNS", Attributes={}
)
conn.create_platform_application(
Name="application2",
Platform="APNS",
Attributes={},
Name="application2", Platform="APNS", Attributes={}
)
applications_repsonse = conn.list_platform_applications()
applications = applications_repsonse['PlatformApplications']
applications = applications_repsonse["PlatformApplications"]
applications.should.have.length_of(2)
application_arn = applications[0]['PlatformApplicationArn']
application_arn = applications[0]["PlatformApplicationArn"]
conn.delete_platform_application(PlatformApplicationArn=application_arn)
applications_repsonse = conn.list_platform_applications()
applications = applications_repsonse['PlatformApplications']
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')
conn = boto3.client("sns", region_name="us-east-1")
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={},
Name="my-application", Platform="APNS", Attributes={}
)
application_arn = platform_application['PlatformApplicationArn']
application_arn = platform_application["PlatformApplicationArn"]
endpoint = conn.create_platform_endpoint(
PlatformApplicationArn=application_arn,
Token="some_unique_id",
CustomUserData="some user data",
Attributes={
"Enabled": 'false',
},
Attributes={"Enabled": "false"},
)
endpoint_arn = endpoint['EndpointArn']
endpoint_arn = endpoint["EndpointArn"]
endpoint_arn.should.contain(
"arn:aws:sns:us-east-1:123456789012:endpoint/APNS/my-application/")
"arn:aws:sns:us-east-1:{}:endpoint/APNS/my-application/".format(ACCOUNT_ID)
)
@mock_sns
def test_create_duplicate_platform_endpoint():
conn = boto3.client('sns', region_name='us-east-1')
conn = boto3.client("sns", region_name="us-east-1")
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={},
Name="my-application", Platform="APNS", Attributes={}
)
application_arn = platform_application['PlatformApplicationArn']
application_arn = platform_application["PlatformApplicationArn"]
endpoint = conn.create_platform_endpoint(
PlatformApplicationArn=application_arn,
Token="some_unique_id",
CustomUserData="some user data",
Attributes={
"Enabled": 'false',
},
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',
},
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')
conn = boto3.client("sns", region_name="us-east-1")
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={},
Name="my-application", Platform="APNS", Attributes={}
)
application_arn = platform_application['PlatformApplicationArn']
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",
},
Attributes={"CustomUserData": "some data"},
)
endpoint_arn = endpoint['EndpointArn']
endpoint_arn = endpoint["EndpointArn"]
endpoint_list = conn.list_endpoints_by_platform_application(
PlatformApplicationArn=application_arn
)['Endpoints']
)["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)
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')
conn = boto3.client("sns", region_name="us-east-1")
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={},
Name="my-application", Platform="APNS", Attributes={}
)
application_arn = platform_application['PlatformApplicationArn']
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",
},
Attributes={"Enabled": "false", "CustomUserData": "some data"},
)
endpoint_arn = endpoint['EndpointArn']
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",
})
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 = boto3.client("sns", region_name="us-east-1")
conn.get_endpoint_attributes.when.called_with(
EndpointArn="a-fake-arn").should.throw(ClientError)
EndpointArn="a-fake-arn"
).should.throw(ClientError)
@mock_sns
def test_set_endpoint_attributes():
conn = boto3.client('sns', region_name='us-east-1')
conn = boto3.client("sns", region_name="us-east-1")
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={},
Name="my-application", Platform="APNS", Attributes={}
)
application_arn = platform_application['PlatformApplicationArn']
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",
},
Attributes={"Enabled": "false", "CustomUserData": "some data"},
)
endpoint_arn = endpoint['EndpointArn']
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",
})
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')
conn = boto3.client("sns", region_name="us-east-1")
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={},
Name="my-application", Platform="APNS", Attributes={}
)
application_arn = platform_application['PlatformApplicationArn']
application_arn = platform_application["PlatformApplicationArn"]
endpoint = conn.create_platform_endpoint(
PlatformApplicationArn=application_arn,
Token="some_unique_id",
CustomUserData="some user data",
Attributes={
"Enabled": 'true',
},
Attributes={"Enabled": "true"},
)
endpoint_arn = endpoint['EndpointArn']
endpoint_arn = endpoint["EndpointArn"]
conn.publish(Message="some message",
MessageStructure="json", TargetArn=endpoint_arn)
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')
conn = boto3.client("sns", region_name="us-east-1")
platform_application = conn.create_platform_application(
Name="my-application",
Platform="APNS",
Attributes={},
Name="my-application", Platform="APNS", Attributes={}
)
application_arn = platform_application['PlatformApplicationArn']
application_arn = platform_application["PlatformApplicationArn"]
endpoint = conn.create_platform_endpoint(
PlatformApplicationArn=application_arn,
Token="some_unique_id",
CustomUserData="some user data",
Attributes={
"Enabled": 'false',
},
Attributes={"Enabled": "false"},
)
endpoint_arn = endpoint['EndpointArn']
endpoint_arn = endpoint["EndpointArn"]
conn.publish.when.called_with(
Message="some message",
MessageStructure="json",
TargetArn=endpoint_arn,
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 = boto3.client("sns", region_name="us-east-1")
conn.set_sms_attributes(attributes={'DefaultSMSType': 'Transactional', 'test': 'test'})
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')
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 = boto3.client("sns", region_name="us-east-1")
conn.set_sms_attributes(attributes={'DefaultSMSType': 'Transactional', 'test': 'test'})
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')
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,105 @@
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
from moto.core import ACCOUNT_ID
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:'
+ ACCOUNT_ID
+ ':some-topic",\n "Type": "Notification",\n "UnsubscribeURL": "https://sns.us-east-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-1:'
+ ACCOUNT_ID
+ ':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:{}:test-queue".format(ACCOUNT_ID)
)
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:{}:test-queue".format(ACCOUNT_ID)
)
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)

File diff suppressed because it is too large Load diff

View file

@ -1,24 +1,27 @@
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
from moto.core import ACCOUNT_ID
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:{}:testtopic</TopicArn>".format(ACCOUNT_ID)
)
topics_data = test_client.action_data("ListTopics")
topics_data.should.contain("ListTopicsResult")
topic_data.should.contain(
"<TopicArn>arn:aws:sns:us-east-1:{}:testtopic</TopicArn>".format(ACCOUNT_ID)
)

View file

@ -1,135 +1,149 @@
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,507 @@
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,
DEFAULT_EFFECTIVE_DELIVERY_POLICY,
DEFAULT_ACCOUNT_ID,
)
@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.have.key("SubscriptionArn")
resp = client.subscribe(TopicArn=arn, Protocol="sms", Endpoint="+15/55-123.4567")
resp.should.have.key("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")
client.subscribe.when.called_with(
TopicArn=arn, Protocol="sms", Endpoint="+15--551234567"
).should.throw(ClientError, "Invalid SMS endpoint: +15--551234567")
client.subscribe.when.called_with(
TopicArn=arn, Protocol="sms", Endpoint="+15551234567."
).should.throw(ClientError, "Invalid SMS endpoint: +15551234567.")
client.subscribe.when.called_with(
TopicArn=arn, Protocol="sms", Endpoint="/+15551234567"
).should.throw(ClientError, "Invalid SMS endpoint: /+15551234567")
@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_subscribe_attributes():
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="http", Endpoint="http://test.com")
response = client.get_subscription_attributes(
SubscriptionArn=resp["SubscriptionArn"]
)
response.should.contain("Attributes")
attributes = response["Attributes"]
attributes["PendingConfirmation"].should.equal("false")
attributes["ConfirmationWasAuthenticated"].should.equal("true")
attributes["Endpoint"].should.equal("http://test.com")
attributes["TopicArn"].should.equal(arn)
attributes["Protocol"].should.equal("http")
attributes["SubscriptionArn"].should.equal(resp["SubscriptionArn"])
attributes["Owner"].should.equal(str(DEFAULT_ACCOUNT_ID))
attributes["RawMessageDelivery"].should.equal("false")
json.loads(attributes["EffectiveDeliveryPolicy"]).should.equal(
DEFAULT_EFFECTIVE_DELIVERY_POLICY
)
@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"],
"price": [100, 100.12],
"error": [None],
}
)
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"],
"price": [100, 100.12],
"error": [None],
}
)
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_subscribe_invalid_filter_policy():
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"]
try:
conn.subscribe(
TopicArn=topic_arn,
Protocol="http",
Endpoint="http://example.com/",
Attributes={
"FilterPolicy": json.dumps({"store": [str(i) for i in range(151)]})
},
)
except ClientError as err:
err.response["Error"]["Code"].should.equal("InvalidParameter")
err.response["Error"]["Message"].should.equal(
"Invalid parameter: FilterPolicy: Filter policy is too complex"
)
try:
conn.subscribe(
TopicArn=topic_arn,
Protocol="http",
Endpoint="http://example.com/",
Attributes={"FilterPolicy": json.dumps({"store": [["example_corp"]]})},
)
except ClientError as err:
err.response["Error"]["Code"].should.equal("InvalidParameter")
err.response["Error"]["Message"].should.equal(
"Invalid parameter: FilterPolicy: Match value must be String, number, true, false, or null"
)
try:
conn.subscribe(
TopicArn=topic_arn,
Protocol="http",
Endpoint="http://example.com/",
Attributes={"FilterPolicy": json.dumps({"store": [{"exists": None}]})},
)
except ClientError as err:
err.response["Error"]["Code"].should.equal("InvalidParameter")
err.response["Error"]["Message"].should.equal(
"Invalid parameter: FilterPolicy: exists match pattern must be either true or false."
)
try:
conn.subscribe(
TopicArn=topic_arn,
Protocol="http",
Endpoint="http://example.com/",
Attributes={"FilterPolicy": json.dumps({"store": [{"error": True}]})},
)
except ClientError as err:
err.response["Error"]["Code"].should.equal("InvalidParameter")
err.response["Error"]["Message"].should.equal(
"Invalid parameter: FilterPolicy: Unrecognized match type error"
)
try:
conn.subscribe(
TopicArn=topic_arn,
Protocol="http",
Endpoint="http://example.com/",
Attributes={"FilterPolicy": json.dumps({"store": [1000000001]})},
)
except ClientError as err:
err.response["Error"]["Code"].should.equal("InternalFailure")
@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,164 @@
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_EFFECTIVE_DELIVERY_POLICY, DEFAULT_PAGE_SIZE
from moto.core import ACCOUNT_ID
@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}:{1}:some-topic".format(conn.region.name, ACCOUNT_ID)
)
# 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}:{1}:some-topic".format(region, ACCOUNT_ID)
)
@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}:{1}:some-topic".format(conn.region.name, ACCOUNT_ID)
)
attributes["Owner"].should.equal(ACCOUNT_ID)
json.loads(attributes["Policy"]).should.equal(
{
"Version": "2008-10-17",
"Id": "__default_policy_ID",
"Statement": [
{
"Effect": "Allow",
"Sid": "__default_statement_ID",
"Principal": {"AWS": "*"},
"Action": [
"SNS:GetTopicAttributes",
"SNS:SetTopicAttributes",
"SNS:AddPermission",
"SNS:RemovePermission",
"SNS:DeleteTopic",
"SNS:Subscribe",
"SNS:ListSubscriptionsByTopic",
"SNS:Publish",
"SNS:Receive",
],
"Resource": "arn:aws:sns:us-east-1:{}:some-topic".format(
ACCOUNT_ID
),
"Condition": {"StringEquals": {"AWS:SourceOwner": ACCOUNT_ID}},
}
],
}
)
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 = {b"http": {b"defaultHealthyRetryPolicy": {b"numRetries": 5}}}
else:
policy = json.dumps({"foo": "bar"})
displayname = "My display name"
delivery = {"http": {"defaultHealthyRetryPolicy": {"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

@ -7,25 +7,27 @@ 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
from moto.sns.models import DEFAULT_EFFECTIVE_DELIVERY_POLICY, DEFAULT_PAGE_SIZE
from moto.core import ACCOUNT_ID
@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):
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)
topics[0]["TopicArn"].should.equal(
"arn:aws:sns:{0}:{1}:{2}".format(
conn._client_config.region_name, ACCOUNT_ID, topic_name
)
)
# Delete the topic
conn.delete_topic(TopicArn=topics[0]['TopicArn'])
conn.delete_topic(TopicArn=topics[0]["TopicArn"])
# And there should now be 0 topics
topics_json = conn.list_topics()
@ -36,66 +38,89 @@ def test_create_and_delete_topic():
@mock_sns
def test_create_topic_with_attributes():
conn = boto3.client("sns", region_name="us-east-1")
conn.create_topic(Name='some-topic-with-attribute', Attributes={'DisplayName': 'test-topic'})
conn.create_topic(
Name="some-topic-with-attribute", Attributes={"DisplayName": "test-topic"}
)
topics_json = conn.list_topics()
topic_arn = topics_json["Topics"][0]['TopicArn']
topic_arn = topics_json["Topics"][0]["TopicArn"]
attributes = conn.get_topic_attributes(TopicArn=topic_arn)['Attributes']
attributes['DisplayName'].should.equal('test-topic')
attributes = conn.get_topic_attributes(TopicArn=topic_arn)["Attributes"]
attributes["DisplayName"].should.equal("test-topic")
@mock_sns
def test_create_topic_with_tags():
conn = boto3.client("sns", region_name="us-east-1")
response = conn.create_topic(
Name="some-topic-with-tags",
Tags=[
{"Key": "tag_key_1", "Value": "tag_value_1"},
{"Key": "tag_key_2", "Value": "tag_value_2"},
],
)
topic_arn = response["TopicArn"]
conn.list_tags_for_resource(ResourceArn=topic_arn)["Tags"].should.equal(
[
{"Key": "tag_key_1", "Value": "tag_value_1"},
{"Key": "tag_key_2", "Value": "tag_value_2"},
]
)
@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']
topic_arn = conn.create_topic(Name="some-topic")["TopicArn"]
conn.set_topic_attributes(
TopicArn=topic_arn,
AttributeName="DisplayName",
AttributeValue="should_be_set"
TopicArn=topic_arn, AttributeName="DisplayName", AttributeValue="should_be_set"
)
topic_display_name = conn.get_topic_attributes(
TopicArn=topic_arn
)['Attributes']['DisplayName']
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']
# 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)
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 = [':', ";", "!", "@", "|", "^", "%"]
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)
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)
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)
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']:
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)
@ -103,13 +128,14 @@ def test_create_topic_in_multiple_regions():
@mock_sns
def test_topic_corresponds_to_region():
for region in ['us-east-1', 'us-west-2']:
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 = topics_json["Topics"][0]["TopicArn"]
topic_arn.should.equal(
"arn:aws:sns:{0}:123456789012:some-topic".format(region))
"arn:aws:sns:{0}:{1}:some-topic".format(region, ACCOUNT_ID)
)
@mock_sns
@ -118,22 +144,51 @@ def test_topic_attributes():
conn.create_topic(Name="some-topic")
topics_json = conn.list_topics()
topic_arn = topics_json["Topics"][0]['TopicArn']
topic_arn = topics_json["Topics"][0]["TopicArn"]
attributes = conn.get_topic_attributes(TopicArn=topic_arn)['Attributes']
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)
"arn:aws:sns:{0}:{1}:some-topic".format(
conn._client_config.region_name, ACCOUNT_ID
)
)
attributes["Owner"].should.equal(ACCOUNT_ID)
json.loads(attributes["Policy"]).should.equal(
{
"Version": "2008-10-17",
"Id": "__default_policy_ID",
"Statement": [
{
"Effect": "Allow",
"Sid": "__default_statement_ID",
"Principal": {"AWS": "*"},
"Action": [
"SNS:GetTopicAttributes",
"SNS:SetTopicAttributes",
"SNS:AddPermission",
"SNS:RemovePermission",
"SNS:DeleteTopic",
"SNS:Subscribe",
"SNS:ListSubscriptionsByTopic",
"SNS:Publish",
"SNS:Receive",
],
"Resource": "arn:aws:sns:us-east-1:{}:some-topic".format(
ACCOUNT_ID
),
"Condition": {"StringEquals": {"AWS:SourceOwner": ACCOUNT_ID}},
}
],
}
)
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["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)
DEFAULT_EFFECTIVE_DELIVERY_POLICY
)
# boto can't handle prefix-mandatory strings:
# i.e. unicode on Python 2 -- u"foobar"
@ -142,27 +197,30 @@ def test_topic_attributes():
policy = json.dumps({b"foo": b"bar"})
displayname = b"My display name"
delivery = json.dumps(
{b"http": {b"defaultHealthyRetryPolicy": {b"numRetries": 5}}})
{b"http": {b"defaultHealthyRetryPolicy": {b"numRetries": 5}}}
)
else:
policy = json.dumps({u"foo": u"bar"})
displayname = u"My display name"
policy = json.dumps({"foo": "bar"})
displayname = "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)
{"http": {"defaultHealthyRetryPolicy": {"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 = 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}}}')
'{"http": {"defaultHealthyRetryPolicy": {"numRetries": 5}}}'
)
@mock_sns
@ -187,16 +245,269 @@ def test_topic_paging():
@mock_sns
def test_add_remove_permissions():
conn = boto3.client('sns', region_name='us-east-1')
response = conn.create_topic(Name='testpermissions')
client = boto3.client("sns", region_name="us-east-1")
topic_arn = client.create_topic(Name="test-permissions")["TopicArn"]
conn.add_permission(
TopicArn=response['TopicArn'],
Label='Test1234',
AWSAccountId=['999999999999'],
ActionName=['AddPermission']
client.add_permission(
TopicArn=topic_arn,
Label="test",
AWSAccountId=["999999999999"],
ActionName=["Publish"],
)
conn.remove_permission(
TopicArn=response['TopicArn'],
Label='Test1234'
response = client.get_topic_attributes(TopicArn=topic_arn)
json.loads(response["Attributes"]["Policy"]).should.equal(
{
"Version": "2008-10-17",
"Id": "__default_policy_ID",
"Statement": [
{
"Effect": "Allow",
"Sid": "__default_statement_ID",
"Principal": {"AWS": "*"},
"Action": [
"SNS:GetTopicAttributes",
"SNS:SetTopicAttributes",
"SNS:AddPermission",
"SNS:RemovePermission",
"SNS:DeleteTopic",
"SNS:Subscribe",
"SNS:ListSubscriptionsByTopic",
"SNS:Publish",
"SNS:Receive",
],
"Resource": "arn:aws:sns:us-east-1:{}:test-permissions".format(
ACCOUNT_ID
),
"Condition": {"StringEquals": {"AWS:SourceOwner": ACCOUNT_ID}},
},
{
"Sid": "test",
"Effect": "Allow",
"Principal": {"AWS": "arn:aws:iam::999999999999:root"},
"Action": "SNS:Publish",
"Resource": "arn:aws:sns:us-east-1:{}:test-permissions".format(
ACCOUNT_ID
),
},
],
}
)
client.remove_permission(TopicArn=topic_arn, Label="test")
response = client.get_topic_attributes(TopicArn=topic_arn)
json.loads(response["Attributes"]["Policy"]).should.equal(
{
"Version": "2008-10-17",
"Id": "__default_policy_ID",
"Statement": [
{
"Effect": "Allow",
"Sid": "__default_statement_ID",
"Principal": {"AWS": "*"},
"Action": [
"SNS:GetTopicAttributes",
"SNS:SetTopicAttributes",
"SNS:AddPermission",
"SNS:RemovePermission",
"SNS:DeleteTopic",
"SNS:Subscribe",
"SNS:ListSubscriptionsByTopic",
"SNS:Publish",
"SNS:Receive",
],
"Resource": "arn:aws:sns:us-east-1:{}:test-permissions".format(
ACCOUNT_ID
),
"Condition": {"StringEquals": {"AWS:SourceOwner": ACCOUNT_ID}},
}
],
}
)
client.add_permission(
TopicArn=topic_arn,
Label="test",
AWSAccountId=["888888888888", "999999999999"],
ActionName=["Publish", "Subscribe"],
)
response = client.get_topic_attributes(TopicArn=topic_arn)
json.loads(response["Attributes"]["Policy"])["Statement"][1].should.equal(
{
"Sid": "test",
"Effect": "Allow",
"Principal": {
"AWS": [
"arn:aws:iam::888888888888:root",
"arn:aws:iam::999999999999:root",
]
},
"Action": ["SNS:Publish", "SNS:Subscribe"],
"Resource": "arn:aws:sns:us-east-1:{}:test-permissions".format(ACCOUNT_ID),
}
)
# deleting non existing permission should be successful
client.remove_permission(TopicArn=topic_arn, Label="non-existing")
@mock_sns
def test_add_permission_errors():
client = boto3.client("sns", region_name="us-east-1")
topic_arn = client.create_topic(Name="test-permissions")["TopicArn"]
client.add_permission(
TopicArn=topic_arn,
Label="test",
AWSAccountId=["999999999999"],
ActionName=["Publish"],
)
client.add_permission.when.called_with(
TopicArn=topic_arn,
Label="test",
AWSAccountId=["999999999999"],
ActionName=["AddPermission"],
).should.throw(ClientError, "Statement already exists")
client.add_permission.when.called_with(
TopicArn=topic_arn + "-not-existing",
Label="test-2",
AWSAccountId=["999999999999"],
ActionName=["AddPermission"],
).should.throw(ClientError, "Topic does not exist")
client.add_permission.when.called_with(
TopicArn=topic_arn,
Label="test-2",
AWSAccountId=["999999999999"],
ActionName=["NotExistingAction"],
).should.throw(ClientError, "Policy statement action out of service scope!")
@mock_sns
def test_remove_permission_errors():
client = boto3.client("sns", region_name="us-east-1")
topic_arn = client.create_topic(Name="test-permissions")["TopicArn"]
client.add_permission(
TopicArn=topic_arn,
Label="test",
AWSAccountId=["999999999999"],
ActionName=["Publish"],
)
client.remove_permission.when.called_with(
TopicArn=topic_arn + "-not-existing", Label="test"
).should.throw(ClientError, "Topic does not exist")
@mock_sns
def test_tag_topic():
conn = boto3.client("sns", region_name="us-east-1")
response = conn.create_topic(Name="some-topic-with-tags")
topic_arn = response["TopicArn"]
conn.tag_resource(
ResourceArn=topic_arn, Tags=[{"Key": "tag_key_1", "Value": "tag_value_1"}]
)
conn.list_tags_for_resource(ResourceArn=topic_arn)["Tags"].should.equal(
[{"Key": "tag_key_1", "Value": "tag_value_1"}]
)
conn.tag_resource(
ResourceArn=topic_arn, Tags=[{"Key": "tag_key_2", "Value": "tag_value_2"}]
)
conn.list_tags_for_resource(ResourceArn=topic_arn)["Tags"].should.equal(
[
{"Key": "tag_key_1", "Value": "tag_value_1"},
{"Key": "tag_key_2", "Value": "tag_value_2"},
]
)
conn.tag_resource(
ResourceArn=topic_arn, Tags=[{"Key": "tag_key_1", "Value": "tag_value_X"}]
)
conn.list_tags_for_resource(ResourceArn=topic_arn)["Tags"].should.equal(
[
{"Key": "tag_key_1", "Value": "tag_value_X"},
{"Key": "tag_key_2", "Value": "tag_value_2"},
]
)
@mock_sns
def test_untag_topic():
conn = boto3.client("sns", region_name="us-east-1")
response = conn.create_topic(
Name="some-topic-with-tags",
Tags=[
{"Key": "tag_key_1", "Value": "tag_value_1"},
{"Key": "tag_key_2", "Value": "tag_value_2"},
],
)
topic_arn = response["TopicArn"]
conn.untag_resource(ResourceArn=topic_arn, TagKeys=["tag_key_1"])
conn.list_tags_for_resource(ResourceArn=topic_arn)["Tags"].should.equal(
[{"Key": "tag_key_2", "Value": "tag_value_2"}]
)
# removing a non existing tag should not raise any error
conn.untag_resource(ResourceArn=topic_arn, TagKeys=["not-existing-tag"])
conn.list_tags_for_resource(ResourceArn=topic_arn)["Tags"].should.equal(
[{"Key": "tag_key_2", "Value": "tag_value_2"}]
)
@mock_sns
def test_list_tags_for_resource_error():
conn = boto3.client("sns", region_name="us-east-1")
conn.create_topic(
Name="some-topic-with-tags", Tags=[{"Key": "tag_key_1", "Value": "tag_value_X"}]
)
conn.list_tags_for_resource.when.called_with(
ResourceArn="not-existing-topic"
).should.throw(ClientError, "Resource does not exist")
@mock_sns
def test_tag_resource_errors():
conn = boto3.client("sns", region_name="us-east-1")
response = conn.create_topic(
Name="some-topic-with-tags", Tags=[{"Key": "tag_key_1", "Value": "tag_value_X"}]
)
topic_arn = response["TopicArn"]
conn.tag_resource.when.called_with(
ResourceArn="not-existing-topic",
Tags=[{"Key": "tag_key_1", "Value": "tag_value_1"}],
).should.throw(ClientError, "Resource does not exist")
too_many_tags = [
{"Key": "tag_key_{}".format(i), "Value": "tag_value_{}".format(i)}
for i in range(51)
]
conn.tag_resource.when.called_with(
ResourceArn=topic_arn, Tags=too_many_tags
).should.throw(
ClientError, "Could not complete request: tag quota of per resource exceeded"
)
# when the request fails, the tags should not be updated
conn.list_tags_for_resource(ResourceArn=topic_arn)["Tags"].should.equal(
[{"Key": "tag_key_1", "Value": "tag_value_X"}]
)
@mock_sns
def test_untag_resource_error():
conn = boto3.client("sns", region_name="us-east-1")
conn.create_topic(
Name="some-topic-with-tags", Tags=[{"Key": "tag_key_1", "Value": "tag_value_X"}]
)
conn.untag_resource.when.called_with(
ResourceArn="not-existing-topic", TagKeys=["tag_key_1"]
).should.throw(ClientError, "Resource does not exist")