pythonflasktwiliotwilio-programmable-chat

How can I write assertions for testing a twilio app within the reply sms function


I'm trying to write functional tests for a twilio application using flask and python. For the very first step, I will send a text that will trigger the twilip app to reply. I want to test this and make sure the app is replying with the right text.

I'm new to python and I'm not sure how to add assertions or integrate pytest within this. I'm expecting my messages in a certain order as well. What else can I use besides the else if statements. At the end of the last reply, I want to print something to the console that will tell me my test passed. Can I integrate a testing with this? Thanks in advance

app = Flask(__name__)

def send_sms():
    account_sid = os.environ['TWILIO_ACCOUNT_SID']
    auth_token = os.environ['TWILIO_AUTH_TOKEN']
    client = Client(account_sid, auth_token)

    message = client.messages \
        .create(
            body='I am interested in joining',
            from_='+15017122661',
            to='+15558675310'
        )
    
@app.route("/sms", methods=['GET', 'POST'])
def incoming_sms():
    body = request.values.get('Body', None)

    resp = MessagingResponse()

    if 'Please enter your name' in body:
        # I want to write assertions for the messages in the body
        resp.message("John Doe")
    elif 'Please enter your age' in body:
        resp.message("20")
    elif 'Please enter your city' in body: 
        resp.message("Los Angeles")
    elif 'Please enter your state' in body: 
        resp.message("California")

    return str(resp)

if __name__ == "__main__":
    send_sms()
    app.run()

Solution

  • I would not recommend actually sending SMS messages, or even making API requests, as part of your tests. You should not need to test external dependencies, just test your own responses.

    In this case, you seem to be testing your responses to incoming Twilio messages. You can use pytest and Flask to achieve this. You can use Flask's built in test_client for this, by making POST requests to your endpoints with the data you want to test with and then make assertions against the response.

    The Flask documentation on testing is fairly comprehensive on how to go about this. I'd read through there and see how far you get. If you get particularly stuck, then I'd recommend asking a new question here and sharing the code and tests you've tried to write.