1

I want to create a backend for sending SMS/Text like the EmailBackEnd I can accomplish the task of sending SMS just fine but the trouble is testing.

I can test how many email's are sent during the tests using django.core.mail.outbox I want to do something similar for SMS say sms.smsoutbox so how would I go about writing something like this for Django.

I understand that email outbox resides in the localmemory for the duration of a single test so what I may be asking is that how do you put something in localmemory for the duration of a test.

Thanks already.

naveen.panwar
  • 393
  • 11
  • 21

1 Answers1

1

I think good 'ol mock would be your best bet here, assuming you're using some known-good SMS API such as AWS SNS. Borrowing from this SO post, let's assume your email function looks like this

import boto3

def send_sms(number, message):
    sns = boto3.client('sns')
    sns.publish(PhoneNumber=number, Message=message)

Your testcase might look like this

from django.test import TestCase, mock
from src import send_sms

class SendSMSTestCase(TestCase)

    @mock.patch('boto3.client')
    def test_send_sms(self, mock_client):
        mock_publish = self.mock_client.return_value.publish

        send_sms('+18005551212', 'Hello there!')

        mock_publish.assert_called_once_with(
            PhoneNumber='+18005551212',
            Message='Hello there!'
        )

You're trusting that the SMS API call (in this case, SNS via Boto) is tested and will work, and you're just testing that your code calls it correctly.

You could build more machinery to reimplement the django.core.mail.outbox for SMS, but it's probably not necessary.

kevinharvey
  • 858
  • 6
  • 16