Permalink
Browse files

Add unit tests

This includes these changes to prepare the server module for testing:
* Guard app.run in __main__ test, so the module can be imported
* Access send_mqtt_message.publish via dot notation, so that test code can mock it
  • Loading branch information...
osteele committed Feb 3, 2018
1 parent 5a087cb commit d2057f51f88589e36136f4dfc689084bc2bf1253
Showing with 44 additions and 6 deletions.
  1. +2 −0 README.md
  2. +4 −0 requirements-dev.txt
  3. +9 −6 twilio_gateway.py
  4. +29 −0 twilio_gateway_test.py
@@ -58,6 +58,8 @@ See the [wiki](https://github.com/olin-build/twilio-mqtt-gateway/wiki/Runbook) a
Either install a local RabbitMQ server, *or* set `MQTT_URL` to a remote
server.

Run `pip install -r dev-requirements.txt`

Run `python twilio_gateway.py`.

Install [ngrok](https://ngrok.com). In another terminal, run
@@ -0,0 +1,4 @@
-r requirements.txt

pytest~=3.2.2
pytest-watch
@@ -2,10 +2,11 @@
import os
import sys

from flask import Flask, render_template
from flask import Flask, render_template, request
from twilio.twiml.messaging_response import MessagingResponse

from send_mqtt_messages import publish
import send_mqtt_messages


logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger('messages')
@@ -29,13 +30,15 @@ def sms_webhook():
topic = request.form['To'].replace('+', 'incoming-sms-')
payload = request.form.to_dict(flat=True)
logger.info('publish {} to {}'.format(payload, topic))
publish(topic, **request.form)
send_mqtt_messages.publish(topic, **request.form)

resp = MessagingResponse()
if RESPONSE_TEXT:
resp.message(RESPONSE_TEXT)
return str(resp)

logger.setLevel(logging.INFO)
logger.info(f"Listening on http://{HOST}:{PORT} FLASK_DEBUG={FLASK_DEBUG}'")
app.run(host=HOST, port=PORT, debug=FLASK_DEBUG)

if __name__ == '__main__':
logger.setLevel(logging.INFO)
logger.info(f"Listening on http://{HOST}:{PORT} FLASK_DEBUG={FLASK_DEBUG}'")
app.run(host=HOST, port=PORT, debug=FLASK_DEBUG)
@@ -0,0 +1,29 @@
import flask
import os
import sys

from unittest.mock import MagicMock, patch
from twilio_gateway import app
from flask import url_for

app.testing = True
client = app.test_client()


def test_home_page():
assert client.get('/').status_code == 200


@patch('send_mqtt_messages.publish')
def test_webhook(publish):
data = dict(
To='+16175552323',
From='+16175553434',
Body='message body',
)
assert client.post('/sms_webhook', data=data).status_code == 200
# FIXME the app should flatten these
assert publish.called_once_with('incoming-sms-16175552323',
From=['+16175553434'],
To=['+16175553434'],
Body=['message body'])

0 comments on commit d2057f5

Please sign in to comment.