jeudi 3 septembre 2015

Use Moto to mock boto SNS calls in post_save signal

There is a post_save signal in a model called App that creates or updates an AWS SNS PlatformApplication:

@receiver(post_save, sender=App)
def post_save_app_handler(sender, **kwargs):
    app = kwargs.get('instance')
    c = sns.connect_to_region(
        region_name='eu-west-1',
        aws_access_key_id = settings.AWS_ACCESS_KEY_ID,
        aws_secret_access_key = settings.AWS_SECRET_ACCESS_KEY
    )

    if kwargs.get('created'):
        create_amazon_sns_apps(c, app)
    else:
        update_amazon_sns_apps(app)

def create_amazon_sns_apps(c, app):
    # Android - Google Cloud Messaging
    app.aws_sns_platform_app_arn_gcm = create_amazon_sns_apps_gcm(c, app)
    # same for iOS
    app.save()

def create_amazon_sns_apps_gcm(connection, app):
    pa_gcm_attrs = {
        'PlatformCredential': 'an-API-Key',
    }
    platform_application_name = "{0}-{1}-gcm".format(settings.AWS_SNS_PLATFORM_APPLICATION_PREFIX ,app.id)
    r = connection.create_platform_application(name=platform_application_name, platform="GCM", attributes=pa_gcm_attrs)
    return r['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']

I'm trying to write a test that checks if the App can be created correctly with my API.

I found the Moto libray but I can't find a way to test things that are in post_save signals. It looks like I can create elements in the setUp method and then use them in a test:

from moto import mock_s3, mock_sns

import boto


class APIZoneTestCase(APITestCase):
    @mock_sns
    @mock_s3
    def setUp(self):
       # ...
       self.app = App.objects.create(name='a1')
       # now runs post_signal, goes to amazon, creates the PlatformApplication, and sets the field aws_sns_gcm_arn using the response

    def test_one(self):
       # how do I check that app has the field app.aws_sns_platform_app_arn_gcm set correctly?

Aucun commentaire:

Enregistrer un commentaire