From 7edc24f37c78ea0a50bd564d7edc3cc9341a8497 Mon Sep 17 00:00:00 2001
From: Nicolas ROCHE <nroche@entrouvert.com>
Date: Sun, 26 Apr 2020 15:54:47 +0200
Subject: [PATCH] sms: send SMS asynchronously (#21465)

---
 passerelle/base/models.py |  9 +++++++--
 tests/test_orange.py      | 22 ++++++++++++++-------
 tests/test_sms.py         | 40 ++++++++++++++++++++++++++++++---------
 tests/utils.py            |  4 +++-
 4 files changed, 56 insertions(+), 19 deletions(-)

diff --git a/passerelle/base/models.py b/passerelle/base/models.py
index 0c39ae87..a7123ce1 100644
--- a/passerelle/base/models.py
+++ b/passerelle/base/models.py
@@ -957,19 +957,24 @@ class SMSResource(BaseResource):
             assert isinstance(data['from'], six.text_type), 'from is not a string'
             assert all(map(lambda x: isinstance(x, six.text_type), data['to'])), \
                 'to is not a list of strings'
         except (ValueError, AssertionError) as e:
             raise APIError('Payload error: %s' % e)
         data['message'] = data['message'][:self.max_message_length]
         logging.info('sending SMS to %r from %r', data['to'], data['from'])
         stop = not bool('nostop' in request.GET)
-        result = {'data': self.send_msg(data['message'], data['from'], data['to'], stop=stop)}
+        self.add_job('send_job',
+                     text=data['message'], sender=data['from'], destinations=data['to'],
+                     stop=stop)
+        return {'err': 0}
+
+    def send_job(self, *args, **kwargs):
+        self.send_msg(**kwargs)
         SMSLog.objects.create(appname=self.get_connector_slug(), slug=self.slug)
-        return result
 
     class Meta:
         abstract = True
 
 
 @six.python_2_unicode_compatible
 class SMSLog(models.Model):
     timestamp = models.DateTimeField(auto_now_add=True)
diff --git a/tests/test_orange.py b/tests/test_orange.py
index 80ea6b13..9078bd5c 100644
--- a/tests/test_orange.py
+++ b/tests/test_orange.py
@@ -19,17 +19,18 @@ import json
 
 import httmock
 import pytest
 
 from django.contrib.contenttypes.models import ContentType
 from django.utils.encoding import force_text
 
 from passerelle.apps.orange.models import OrangeSMSGateway, OrangeError
-from passerelle.base.models import ApiUser, AccessRight
+
+from passerelle.base.models import ApiUser, AccessRight, Job
 from passerelle.utils.jsonresponse import APIError
 
 
 NETLOC = 'contact-everyone.orange-business.com'
 JSON_HEADERS = {'content-type': 'application/json'}
 PAYLOAD = {
     'message': 'hello',
     'from': '+33699999999',
@@ -158,18 +159,25 @@ def test_diffusion(app, connector):
 
     with pytest.raises(OrangeError, match='Orange returned Invalid JSON content'):
         with httmock.HTTMock(mocked_response):
             orange.diffusion('my_token', 'gid2', PAYLOAD['to'], PAYLOAD['message'])
 
 
 def test_send_msg(app, connector):
     url = '/%s/%s/send/' % (connector.get_connector_slug(), connector.slug)
-    with httmock.HTTMock(response_token_ok, response_group_ok, response_diffusion_ok):
-        resp = app.post_json(url, params=PAYLOAD, status=200)
+    assert Job.objects.count() == 0
+    resp = app.post_json(url, params=PAYLOAD, status=200)
     assert not resp.json['err']
-    assert resp.json['data']['status'] == "I'm ok"
+    assert Job.objects.count() == 1
+    with httmock.HTTMock(response_token_ok, response_group_ok, response_diffusion_ok):
+        connector.jobs()
+    assert Job.objects.all()[0].status == 'completed'
 
     # not 201
+    resp = app.post_json(url, params=PAYLOAD, status=200)
+    assert not resp.json['err']
+    assert Job.objects.count() == 2
     with httmock.HTTMock(response_token_ok, response_group_ok, response_500):
-        resp = app.post_json(url, params=PAYLOAD, status=200)
-    assert resp.json['err']
-    assert resp.json['err_desc'] == 'Orange fails to send SMS: 500, my_error'
+        connector.jobs()
+    job = Job.objects.all()[1]
+    assert job.status == 'failed'
+    assert 'Orange fails to send SMS: 500, my_error' in job.status_details['error_summary']
diff --git a/tests/test_sms.py b/tests/test_sms.py
index 53d6f2ca..09291f39 100644
--- a/tests/test_sms.py
+++ b/tests/test_sms.py
@@ -1,15 +1,17 @@
+import isodate
 import mock
 import pytest
+from requests import RequestException
 
 from django.contrib.contenttypes.models import ContentType
 
 from passerelle.apps.ovh.models import OVHSMSGateway
-from passerelle.base.models import ApiUser, AccessRight, SMSResource, SMSLog
+from passerelle.base.models import ApiUser, AccessRight, Job, SMSResource, SMSLog
 
 from test_manager import login, admin_user
 
 import utils
 
 pytestmark = pytest.mark.django_db
 
 klasses = SMSResource.__subclasses__()
@@ -39,37 +41,55 @@ def connector(request, db):
     # no access check
     AccessRight.objects.create(codename='can_send_messages',
                                apiuser=api,
                                resource_type=obj_type,
                                resource_pk=c.pk)
     return c
 
 
-def test_connectors(app, connector):
+def test_connectors(app, connector, freezer):
     path = '/%s/%s/send/' % (connector.get_connector_slug(), connector.slug)
     result = app.post_json(path, params={})
     assert result.json['err'] == 1
     assert result.json['err_desc'].startswith('Payload error: ')
 
     payload = {
         'message': 'hello',
         'from': '+33699999999',
         'to': ['+33688888888', '+33677777777'],
     }
-    for test_vector in getattr(connector, 'TEST_DEFAULTS', {}).get('test_vectors', []):
+    test_vectors = getattr(connector, 'TEST_DEFAULTS', {}).get('test_vectors', [])
+    total = len(test_vectors)
+    nb_failed = 0
+    assert Job.objects.count() == 0
+    for test_vector in test_vectors:
+
+        # register job
+        freezer.move_to('2019-01-01 00:00:00')
+        result = app.post_json(path, params=payload)
+        assert result.json['err'] == 0
+        job_id = Job.objects.get(status='registered').id
+
+        # perform job
+        freezer.move_to('2019-01-01 01:00:03')
         with utils.mock_url(
                 connector.URL,
                 test_vector.get('response', ''),
                 test_vector.get('status_code', 200)):
-
-            result = app.post_json(path, params=payload)
-            for key, value in test_vector['result'].items():
-                assert key in result.json
-                assert result.json[key] == value
+            connector.jobs()
+        job = Job.objects.get(id=job_id)
+        if job.status == 'failed':
+            assert len(job.status_details['error_summary']) > 0
+            assert test_vector['result']['err_desc'] in job.status_details['error_summary']
+            nb_failed += 1
+        else:
+            assert job.status == 'completed'
+    assert Job.objects.count() == total
+    assert SMSLog.objects.count() == total - nb_failed
 
 
 def test_manage_views(admin_user, app, connector):
     url = '/%s/%s/' % (connector.get_connector_slug(), connector.slug)
     resp = app.get(url)
     assert 'Endpoints' in resp.text
     assert not 'accessright/add' in resp.text
     app = login(app)
@@ -86,25 +106,27 @@ def test_sms_max_message_length(app, connector):
     payload = {
         'message': message_above_limit,
         'from': '+33699999999',
         'to': ['+33688888888'],
     }
     with mock.patch.object(OVHSMSGateway, 'send_msg') as send_function:
         send_function.return_value = {}
         result = app.post_json(path, params=payload)
-        assert send_function.call_args[0][0] == 'a' * connector.max_message_length
+        connector.jobs()
+        assert send_function.call_args[1]['text'] == 'a' * connector.max_message_length
 
 
 @pytest.mark.parametrize('connector', [OVHSMSGateway], indirect=True)
 def test_sms_log(app, connector):
     path = '/%s/%s/send/' % (connector.get_connector_slug(), connector.slug)
     assert not SMSLog.objects.filter(appname=connector.get_connector_slug(), slug=connector.slug).exists()
 
     payload = {
         'message': 'plop',
         'from': '+33699999999',
         'to': ['+33688888888'],
     }
     with mock.patch.object(OVHSMSGateway, 'send_msg') as send_function:
         send_function.return_value = {}
         result = app.post_json(path, params=payload)
+        connector.jobs()
         assert SMSLog.objects.filter(appname=connector.get_connector_slug(), slug=connector.slug).exists()
diff --git a/tests/utils.py b/tests/utils.py
index 62fc82bc..6af91756 100644
--- a/tests/utils.py
+++ b/tests/utils.py
@@ -27,30 +27,32 @@ def setup_access_rights(obj):
 
 class FakedResponse(mock.Mock):
     headers = {}
 
     def json(self):
         return json_loads(self.content)
 
 
-def mock_url(url=None, response='', status_code=200, headers=None):
+def mock_url(url=None, response='', status_code=200, headers=None, exception=None):
     urlmatch_kwargs = {}
     if url:
         parsed = urlparse.urlparse(url)
         if parsed.netloc:
             urlmatch_kwargs['netloc'] = parsed.netloc
         if parsed.path:
             urlmatch_kwargs['path'] = parsed.path
 
     if not isinstance(response, str):
         response = json.dumps(response)
 
     @httmock.urlmatch(**urlmatch_kwargs)
     def mocked(url, request):
+        if exception:
+            raise exception
         return httmock.response(status_code, response, headers, request=request)
     return httmock.HTTMock(mocked)
 
 
 def make_resource(model_class, **kwargs):
     resource = model_class.objects.create(**kwargs)
     setup_access_rights(resource)
     return resource
-- 
2.26.2

