From 2d5cbe94fc312a35b774f6d128c4192e2f273a57 Mon Sep 17 00:00:00 2001
From: Nicolas ROCHE <nroche@entrouvert.com>
Date: Wed, 2 Oct 2019 18:21:50 +0200
Subject: [PATCH] oxyd: use self.requests to increase logging (#21464)

---
 passerelle/apps/choosit/models.py |  2 +-
 passerelle/apps/mobyt/models.py   |  2 +-
 passerelle/apps/oxyd/models.py    |  2 +-
 tests/test_api_access.py          | 49 +++++++++++++++++++++++++------
 tests/utils.py                    |  4 +--
 5 files changed, 45 insertions(+), 14 deletions(-)

diff --git a/passerelle/apps/choosit/models.py b/passerelle/apps/choosit/models.py
index 1ced4dc0..110ddfe1 100644
--- a/passerelle/apps/choosit/models.py
+++ b/passerelle/apps/choosit/models.py
@@ -91,7 +91,7 @@ class ChoositSMSGateway(BaseResource, SMSGatewayMixin):
             }
             data = {'data': json.dumps(params)}
             try:
-                r = requests.post(self.URL, data=data)
+                r = self.requests.post(self.URL, data=data)
             except requests.RequestException as e:
                 results.append('Choosit error: %s' % e)
             else:
diff --git a/passerelle/apps/mobyt/models.py b/passerelle/apps/mobyt/models.py
index 0159fbdf..07aafe33 100644
--- a/passerelle/apps/mobyt/models.py
+++ b/passerelle/apps/mobyt/models.py
@@ -65,7 +65,7 @@ class MobytSMSGateway(BaseResource, SMSGatewayMixin):
             'qty': self.quality,
         }
         try:
-            r = requests.post(self.URL, data=params)
+            r = self.requests.post(self.URL, data=params)
         except requests.RequestException, e:
             raise APIError('MobyT error: POST failed, %s' % e)
         if r.content[:2] != "OK":
diff --git a/passerelle/apps/oxyd/models.py b/passerelle/apps/oxyd/models.py
index 07df7833..a0b5f950 100644
--- a/passerelle/apps/oxyd/models.py
+++ b/passerelle/apps/oxyd/models.py
@@ -67,7 +67,7 @@ class OxydSMSGateway(BaseResource, SMSGatewayMixin):
                 'flash': '0',
             }
             try:
-                r = requests.post(self.URL, params)
+                r = self.requests.post(self.URL, params)
             except requests.RequestException as e:
                 results.append('OXYD error: POST failed, %s' % e)
             else:
diff --git a/tests/test_api_access.py b/tests/test_api_access.py
index 7dd8bbbf..c95a3fd8 100644
--- a/tests/test_api_access.py
+++ b/tests/test_api_access.py
@@ -6,6 +6,7 @@ from django.contrib.contenttypes.models import ContentType
 from django.core.urlresolvers import reverse
 
 import pytest
+import utils
 
 from django.test import override_settings
 
@@ -184,7 +185,7 @@ def test_access_apiuser_with_ip_restriction(app, oxyd):
     assert resp.json['err'] == 1
     assert resp.json['err_desc'] == 'Payload error: missing "message" in JSON payload'
 
-def test_logged_request_max_size(app, oxyd, settings):
+def test_logged_requests_and_responses_max_size(app, oxyd, settings):
     endpoint_url = reverse('generic-endpoint',
             kwargs={'connector': 'oxyd', 'slug': oxyd.slug, 'endpoint': 'send'})
     api = ApiUser.objects.create(username='public',
@@ -197,13 +198,43 @@ def test_logged_request_max_size(app, oxyd, settings):
                     resource_type=obj_type,
                     resource_pk=oxyd.pk,
     )
-    resp = app.post_json(endpoint_url, params={'foo': 'bar'})
-    assert ResourceLog.objects.all()[0].message[-9:] == '"bar"}\') '
-
-    # for empty payload the connector returns an APIError with
-    assert 'Error occurred' in ResourceLog.objects.all()[1].message
+    payload = {
+        'message': 'hello',
+        'from': '+33699999999',
+        'to': ['+33688888888', '+33677777777'],
+    }
+    headers = {'Content-Type': 'foo/bar'}
+    response = oxyd.TEST_DEFAULTS['test_vectors'][0]
+    oxyd.set_log_level('DEBUG')  # log request payload and response headers/content
+    settings.LOGGED_CONTENT_TYPES_MESSAGES = 'foo/bar'  # response content to log
+
+    assert settings.LOGGED_REQUEST_MAX_SIZE == 5000
+    assert settings.LOGGED_RESPONSES_MAX_SIZE == 4096
+    with utils.mock_url(oxyd.URL, response, headers=headers):
+        result = app.post_json(endpoint_url, params=payload)
+    assert len(ResourceLog.objects.all()) == 4
+
+    # initial POST query
+    assert len(ResourceLog.objects.all()[0].extra['connector_payload']) == 84
+
+    # connector POST queries
+    assert len(ResourceLog.objects.all()[1].extra['request_payload']) == 57
+    assert len(ResourceLog.objects.all()[2].extra['request_payload']) == 57
+    assert len(ResourceLog.objects.all()[1].extra['response_content']) == 244
+    assert len(ResourceLog.objects.all()[2].extra['response_content']) == 244
+
+    # connector reply
+    assert len(ResourceLog.objects.all()[3].extra['body']) == 86
 
     # troncate logs
-    settings.LOGGED_REQUEST_MAX_SIZE = 6
-    resp = app.post_json(endpoint_url, params={'foo': 'bar'})
-    assert ResourceLog.objects.all()[2].message[-8:] == '"foo"\') '
+    settings.LOGGED_REQUEST_MAX_SIZE = 10
+    settings.LOGGED_RESPONSES_MAX_SIZE = 20
+    with utils.mock_url(oxyd.URL, response, headers=headers):
+        result = app.post_json(endpoint_url, params=payload)
+    assert len(ResourceLog.objects.all()) == 8
+    assert len(ResourceLog.objects.all()[4].extra['connector_payload']) == 10
+    assert len(ResourceLog.objects.all()[5].extra['request_payload']) == 12
+    assert len(ResourceLog.objects.all()[6].extra['request_payload']) == 12
+    assert len(ResourceLog.objects.all()[5].extra['response_content']) == 22
+    assert len(ResourceLog.objects.all()[6].extra['response_content']) == 22
+    assert len(ResourceLog.objects.all()[7].extra['body']) == 12
diff --git a/tests/utils.py b/tests/utils.py
index f9a419bc..ec02813e 100644
--- a/tests/utils.py
+++ b/tests/utils.py
@@ -30,7 +30,7 @@ class FakedResponse(mock.Mock):
         return json.loads(self.content)
 
 
-def mock_url(url=None, response='', status_code=200):
+def mock_url(url=None, response='', status_code=200, headers=None):
     urlmatch_kwargs = {}
     if url:
         parsed = urlparse.urlparse(url)
@@ -44,7 +44,7 @@ def mock_url(url=None, response='', status_code=200):
 
     @httmock.urlmatch(**urlmatch_kwargs)
     def mocked(url, request):
-        return httmock.response(status_code, response, request=request)
+        return httmock.response(status_code, response, headers, request=request)
     return httmock.HTTMock(mocked)
 
 
-- 
2.23.0

