From d8a05b8471d17e08fc967ed76331ab99c652dd30 Mon Sep 17 00:00:00 2001
From: Nicolas ROCHE <nroche@entrouvert.com>
Date: Wed, 6 Mar 2019 16:13:27 +0100
Subject: [PATCH 2/2] iparapheur: pass unit tests using zeep soap library
 (#31265)

---
 passerelle/contrib/iparapheur/models.py |  64 +++---
 tests/data/iparapheur.wsdl              |   1 -
 tests/test_iparapheur.py                | 265 +++++++++++-------------
 3 files changed, 155 insertions(+), 175 deletions(-)

diff --git a/passerelle/contrib/iparapheur/models.py b/passerelle/contrib/iparapheur/models.py
index b963f59..b737912 100644
--- a/passerelle/contrib/iparapheur/models.py
+++ b/passerelle/contrib/iparapheur/models.py
@@ -24,21 +24,18 @@ from django.core.urlresolvers import reverse
 from django.utils.translation import ugettext_lazy as _
 from django.http import HttpResponse, Http404
 
-from suds import WebFault
+from zeep.exceptions import Fault as WebFault, TransportError
 
 from passerelle.base.models import BaseResource, HTTPResource
 from passerelle.utils.api import endpoint
 from passerelle.utils.jsonresponse import APIError
 
-from .soap import get_client as soap_get_client
-from .soap import get_wsdl_string as soap_get_wsdl_string
-
 
 def get_client(model):
     try:
-        return soap_get_client(model)
-    except ConnectionError as e:
-        raise APIError('i-Parapheur error: %s' % e)
+        return model.soap_client()
+    except ConnectionError as exc:
+        raise APIError('i-Parapheur error: %s' % exc)
 
 
 def format_type(t):
@@ -86,11 +83,7 @@ class IParapheur(BaseResource, HTTPResource):
         except(WebFault,) as exc:
             # Remote Service Error: <SOAP-ENV:Fault> in response
             raise APIError('ServiceError: %s' % exc)
-        except(Exception,) as exc:
-            # Exception different from suds.tranport.TransportError
-            if not exc.args or not isinstance(exc.args[0], tuple):
-                raise exc
-            # TransportError Exception
+        except(TransportError,) as exc:
             raise APIError('Transport Error: %s' % exc)
         return result
 
@@ -105,10 +98,10 @@ class IParapheur(BaseResource, HTTPResource):
     @endpoint()
     def wsdl(self, request):
         try:
-            wsdl = soap_get_wsdl_string(self)
-        except ConnectionError as exc:
+            response = self.requests.get(self.wsdl_url)
+        except Exception as exc:
             raise APIError('i-Parapheur WSDL error: %s' % exc)
-        return HttpResponse(wsdl, content_type='text/xml')
+        return HttpResponse(response.content, content_type='text/xml')
 
     @endpoint(perm='can_access')
     def subtypes(self, request, type=None):
@@ -130,30 +123,31 @@ class IParapheur(BaseResource, HTTPResource):
         subtyp = data['subtype']
         email = data.get('email')
         visibility = data['visibility']
-        content = data['data']
+        content = base64.b64decode(data['data'])
         content_type = data.get('content_type') if data.get('content_type') \
             else get_magic_mime(base64.b64decode(data['data']))
 
-        c = get_client(self)
+        soap_client = get_client(self)
         if visibility not in ['PUBLIC', 'SERVICE', 'CONFIDENTIEL']:
             raise FileError('Unknown value for "visibility". Should be "PUBLIC", "SERVICE" or "CONFIDENTIEL"')
-        doc = c.factory.create("TypeDoc")
-        doc['value'] = content
-        doc['_contentType'] = content_type
-        d = {'TypeTechnique': typ,
-             'DossierTitre': title,
-             'SousType': subtyp,
-             'Visibilite': visibility,
-             'DocumentPrincipal' : doc,
-             }
+
+        doc_type = soap_client.get_type('ns0:TypeDoc')
+        doc = doc_type(content, content_type)
+        parameters = {'TypeTechnique': typ,
+                      'DossierID': 'bof_id_nico',
+                      'DossierTitre': title,
+                      'SousType': subtyp,
+                      'Visibilite': visibility,
+                      'DocumentPrincipal' : doc,
+                      }
         if email:
-            d['EmailEmetteur'] = email
-        r = c.service.CreerDossier(**d)
-        if not r or not r.MessageRetour:
+            parameters['EmailEmetteur'] = email
+        rep = soap_client.service.CreerDossier(**parameters)
+        if not rep or not rep.MessageRetour:
             raise FileError('unknown error, no response')
-        if r.MessageRetour.codeRetour == 'KO':
-            raise FileError(r.MessageRetour.message)
-        return {'data': {'RecordId': r.DossierID, 'message': r.MessageRetour.message}}
+        if rep.MessageRetour.codeRetour == 'KO':
+            raise FileError(rep.MessageRetour.message)
+        return {'data': {'RecordId': rep.DossierID, 'message': rep.MessageRetour.message}}
 
     @endpoint(perm='can_access', name='get-file', pattern='(?P<file_id>[\w-]+)')
     def get_file(self, request, file_id, appendix=None):
@@ -181,14 +175,14 @@ class IParapheur(BaseResource, HTTPResource):
             for metadata in resp.MetaDonnees.MetaDonnee:
                 if metadata['nom'] == 'ph:dossierTitre':
                     filename = metadata['valeur']
-                    if document['_contentType'] == 'application/pdf':
+                    if document['contentType'] == 'application/pdf':
                         filename += '.pdf'
                     break
 
         if not filename:
             raise FileError('File title not found.')
-        response = HttpResponse(base64.b64decode(document['value']),
-                content_type=document['_contentType'])
+        response = HttpResponse(document['_value_1'],
+                                content_type=document['contentType'])
         ascii_filename = filename.encode('ascii', 'replace')
         encoded_filename = urllib.quote(filename.encode('utf-8'), safe='')
         response['Content-Disposition'] = 'inline; filename=%s; filename*=UTF-8\'\'%s' % (ascii_filename, encoded_filename)
diff --git a/tests/data/iparapheur.wsdl b/tests/data/iparapheur.wsdl
index 6ce57ee..6e114f5 100644
--- a/tests/data/iparapheur.wsdl
+++ b/tests/data/iparapheur.wsdl
@@ -1252,4 +1252,3 @@ DemanderMiseAJourTdt : si "OUI", alors iParapheur initie une transaction de mise
     </wsdl:port>
   </wsdl:service>
 </wsdl:definitions>
-
\ No newline at end of file
diff --git a/tests/test_iparapheur.py b/tests/test_iparapheur.py
index 0879318..2592540 100644
--- a/tests/test_iparapheur.py
+++ b/tests/test_iparapheur.py
@@ -7,6 +7,7 @@ import os
 import base64
 import xml.etree.ElementTree as ET
 from dateutil import parser
+from requests import Response
 
 from requests.exceptions import ConnectionError
 from django.core.urlresolvers import reverse
@@ -40,15 +41,31 @@ def conn():
                     resource_pk=conn.pk)
     return conn
 
-@pytest.fixture
 def xmlmime():
     return os.path.join(os.path.dirname(__file__), 'data','xmlmime.xml')
 
-@pytest.fixture
 def wsdl_file():
     return os.path.join(os.path.dirname(__file__), 'data','iparapheur.wsdl')
 
-@mock.patch('passerelle.contrib.iparapheur.models.soap_get_client')
+def iph_mocked_get(url, params=None, **kwargs):
+    response = Response()
+
+    # simulate first GET call (get wsdl file)
+    if url == 'https://secure-iparapheur.demonstrations.adullact.org:443/ws-iparapheur?wsdl':
+        target_file = wsdl_file()
+
+    # simulate second GET call (nested <xsd:import> into wsdl fil)
+    elif url == 'http://www.w3.org/2005/05/xmlmime':
+        target_file = xmlmime()
+
+    else:
+        raise Exception('my fault error, url is not yet mocked: %s' % url)
+
+    response._content=file(target_file).read()
+    response.status_code = 200
+    return response
+
+@mock.patch('passerelle.contrib.iparapheur.models.get_client')
 def test_call_ping(soap_client, app, conn):
     service = mock.Mock()
     service.echo.return_value = 'pong'
@@ -62,7 +79,7 @@ def test_call_ping(soap_client, app, conn):
     assert resp.json['err'] == 0
     assert resp.json['data'] == 'pong'
 
-@mock.patch('passerelle.contrib.iparapheur.models.soap_get_client',
+@mock.patch('passerelle.base.models.BaseResource.soap_client',
             side_effect=ConnectionError('mocked error'))
 def test_call_ping_connectionerror(soap_client, app, conn):
     url = reverse('generic-endpoint', kwargs={'connector': 'iparapheur',
@@ -74,32 +91,24 @@ def test_call_ping_connectionerror(soap_client, app, conn):
     assert resp.json['data'] == None
     assert 'mocked error' in resp.json['err_desc']
 
-@mock.patch('passerelle.utils.Request.get')
+@mock.patch('passerelle.utils.Request.get', side_effect=iph_mocked_get)
 @mock.patch('passerelle.utils.Request.post')
-@mock.patch('passerelle.contrib.iparapheur.soap.HttpAuthenticated.open')
-def test_create_file(http_open, mocked_post, mocked_get, app, conn, xmlmime, wsdl_file):
+def test_create_file(mocked_post, mocked_get, app, conn):
     file_id = str(uuid.uuid4())
     typ = 'Courrier'
     subtyp = 'maire'
     visibility = 'SERVICE'
+    response = Response()
+    response.status_code = 200
 
     for filename in ('iparapheur_test.odt', 'iparapheur_test.pdf'):
+        soap_response = """<?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><CreerDossierResponse xmlns="http://www.adullact.org/spring-ws/iparapheur/1.0" xmlns:xmime="http://www.w3.org/2005/05/xmlmime"><MessageRetour><codeRetour>OK</codeRetour><message>Dossier %s soumis dans le circuit</message><severite>INFO</severite></MessageRetour><DossierID>%s</DossierID></CreerDossierResponse></S:Body></S:Envelope>""" % (filename, file_id)
+        response._content = soap_response
+        mocked_post.return_value = response
         title, ext = filename.split('.')
-
-        soap_response = """
-<?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><CreerDossierResponse xmlns="http://www.adullact.org/spring-ws/iparapheur/1.0" xmlns:xmime="http://www.w3.org/2005/05/xmlmime"><MessageRetour><codeRetour>OK</codeRetour><message>Dossier %s soumis dans le circuit</message><severite>INFO</severite></MessageRetour><DossierID>%s</DossierID></CreerDossierResponse></S:Body></S:Envelope>
-        """ % (title, file_id)
         base64_data = 'VGVzdCBEb2N1bWVudA=='
-
         data = {'type': typ, 'subtype': subtyp, 'visibility': visibility,
                 'title': title, 'data': base64_data, 'content-type':'application/pdf'}
-
-        http_open.return_value = file(xmlmime)
-        mocked_get.return_value = mock.Mock(content = file(wsdl_file).read(),
-                                            status_code=200)
-        mocked_post.return_value = mock.Mock(status_code=200,
-                                             content=soap_response)
-
         url = reverse('generic-endpoint', kwargs={'connector': 'iparapheur',
                                 'endpoint': 'create-file', 'slug': conn.slug})
         resp = app.post_json(url, params=data, status=403)
@@ -118,46 +127,43 @@ def test_create_file(http_open, mocked_post, mocked_get, app, conn, xmlmime, wsd
 
     # KO
     soap_response = """<?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><CreerDossierResponse xmlns="http://www.adullact.org/spring-ws/iparapheur/1.0" xmlns:xmime="http://www.w3.org/2005/05/xmlmime"><MessageRetour><codeRetour>KO</codeRetour><message>KOmessage</message><severite>INFO</severite></MessageRetour></CreerDossierResponse></S:Body></S:Envelope>"""
-    http_open.return_value = open(xmlmime)
-    mocked_get.return_value = mock.Mock(content=open(wsdl_file).read(), status_code=200)
-    mocked_post.return_value = mock.Mock(status_code=200, content=soap_response)
+    response._content = soap_response
+    mocked_post.return_value = response
     resp = app.post_json(url, params=data, status=500)
+    assert (BASE_URL,) == mocked_post.call_args[0]
     assert resp.json['err'] == 1
     assert 'FileError' in resp.json['err_class']
     assert resp.json['err_desc'] == 'KOmessage'
 
     # unknown response
     soap_response = """<?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><CreerDossierResponse xmlns="http://www.adullact.org/spring-ws/iparapheur/1.0" xmlns:xmime="http://www.w3.org/2005/05/xmlmime"></CreerDossierResponse></S:Body></S:Envelope>"""
-    http_open.return_value = open(xmlmime)
-    mocked_get.return_value = mock.Mock(content=open(wsdl_file).read(), status_code=200)
-    mocked_post.return_value = mock.Mock(status_code=200, content=soap_response)
+    response._content = soap_response
+    mocked_post.return_value = response
     resp = app.post_json(url, params=data, status=500)
+    assert (BASE_URL,) == mocked_post.call_args[0]
     assert resp.json['err'] == 1
     assert 'FileError' in resp.json['err_class']
     assert resp.json['err_desc'] == 'unknown error, no response'
 
     # bad response
     soap_response = """<nada>"""
-    http_open.return_value = open(xmlmime)
-    mocked_get.return_value = mock.Mock(content=open(wsdl_file).read(), status_code=200)
-    mocked_post.return_value = mock.Mock(status_code=200, content=soap_response)
+    response._content = soap_response
+    mocked_post.return_value = response
     resp = app.post_json(url, params=data, status=500)
+    assert (BASE_URL,) == mocked_post.call_args[0]
     assert resp.json['err'] == 1
-    assert 'SAXParseException' in resp.json['err_class']
-    assert 'syntax error' in resp.json['err_desc']
+    assert 'zeep.exceptions.TransportError' in resp.json['err_class']
+    assert 'Server returned HTTP status 200 (<nada>)' in resp.json['err_desc']
 
-
-@mock.patch('passerelle.utils.Request.get')
+@mock.patch('passerelle.utils.Request.get', side_effect=iph_mocked_get)
 @mock.patch('passerelle.utils.Request.post')
-@mock.patch('passerelle.contrib.iparapheur.soap.HttpAuthenticated.open')
-def test_files(http_open, mocked_post, mocked_get, app, conn, xmlmime, wsdl_file):
-    soap_response = """
-    <?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><RechercherDossiersResponse xmlns="http://www.adullact.org/spring-ws/iparapheur/1.0" xmlns:xmime="http://www.w3.org/2005/05/xmlmime"><LogDossier><timestamp>2015-10-29T15:42:08.732+01:00</timestamp><nom>test</nom><status>Lu</status><annotation></annotation><accessible>KO</accessible></LogDossier><LogDossier><timestamp>2015-10-29T15:52:42.167+01:00</timestamp><nom>Test2</nom><status>RejetSignataire</status><annotation></annotation><accessible>OK</accessible></LogDossier><LogDossier><timestamp>2015-11-25T12:13:30.830+01:00</timestamp><nom>6ceecfb7-67ee-4388-8943-35911c640031</nom><status>NonLu</status><annotation></annotation><accessible>Recuperable</accessible></LogDossier></RechercherDossiersResponse></S:Body></S:Envelope>
+def test_files(mocked_post, mocked_get, app, conn):
+    response = Response()
+    response.status_code = 200
+    soap_response = """<?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><RechercherDossiersResponse xmlns="http://www.adullact.org/spring-ws/iparapheur/1.0" xmlns:xmime="http://www.w3.org/2005/05/xmlmime"><LogDossier><timestamp>2015-10-29T15:42:08.732+01:00</timestamp><nom>test</nom><status>Lu</status><annotation></annotation><accessible>KO</accessible></LogDossier><LogDossier><timestamp>2015-10-29T15:52:42.167+01:00</timestamp><nom>Test2</nom><status>RejetSignataire</status><annotation></annotation><accessible>OK</accessible></LogDossier><LogDossier><timestamp>2015-11-25T12:13:30.830+01:00</timestamp><nom>6ceecfb7-67ee-4388-8943-35911c640031</nom><status>NonLu</status><annotation></annotation><accessible>Recuperable</accessible></LogDossier></RechercherDossiersResponse></S:Body></S:Envelope>
     """
-    http_open.return_value = file(xmlmime)
-    mocked_get.return_value = mock.Mock(content = file(wsdl_file).read(),
-                                            status_code=200)
-    mocked_post.return_value = mock.Mock(status_code=200, content=soap_response)
+    response._content = soap_response
+    mocked_post.return_value = response
     url = reverse('generic-endpoint', kwargs={'connector': 'iparapheur',
                                 'endpoint': 'files', 'slug': conn.slug})
     resp = app.get(url, status=403)
@@ -169,21 +175,17 @@ def test_files(http_open, mocked_post, mocked_get, app, conn, xmlmime, wsdl_file
         assert item['id']
         assert item['timestamp']
 
-
-@mock.patch('passerelle.utils.Request.get')
+@mock.patch('passerelle.utils.Request.get', side_effect=iph_mocked_get)
 @mock.patch('passerelle.utils.Request.post')
-@mock.patch('passerelle.contrib.iparapheur.soap.HttpAuthenticated.open')
-def test_get_file_status(http_open, mocked_post, mocked_get, app, conn, xmlmime, wsdl_file):
+def test_get_file_status(mocked_post, mocked_get, app, conn):
     file_id = str(uuid.uuid4())
+    response = Response()
+    response.status_code = 200
 
-    soap_response = """
-    <?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><GetHistoDossierResponse xmlns="http://www.adullact.org/spring-ws/iparapheur/1.0" xmlns:xmime="http://www.w3.org/2005/05/xmlmime"><LogDossier><timestamp>2016-04-05T17:57:03.893+02:00</timestamp><nom>webservices gru</nom><status>NonLu</status><annotation>Création de dossier</annotation></LogDossier><LogDossier><timestamp>2016-04-05T17:58:46.716+02:00</timestamp><nom>webservices gru</nom><status>NonLu</status><annotation>super</annotation></LogDossier><LogDossier><timestamp>2016-04-05T17:58:46.727+02:00</timestamp><nom>webservices gru</nom><status>Archive</status><annotation>Circuit terminé, dossier archivable</annotation></LogDossier><MessageRetour><codeRetour>OK</codeRetour><message></message><severite>INFO</severite></MessageRetour></GetHistoDossierResponse></S:Body></S:Envelope>
+    soap_response = """<?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><GetHistoDossierResponse xmlns="http://www.adullact.org/spring-ws/iparapheur/1.0" xmlns:xmime="http://www.w3.org/2005/05/xmlmime"><LogDossier><timestamp>2016-04-05T17:57:03.893+02:00</timestamp><nom>webservices gru</nom><status>NonLu</status><annotation>Création de dossier</annotation></LogDossier><LogDossier><timestamp>2016-04-05T17:58:46.716+02:00</timestamp><nom>webservices gru</nom><status>NonLu</status><annotation>super</annotation></LogDossier><LogDossier><timestamp>2016-04-05T17:58:46.727+02:00</timestamp><nom>webservices gru</nom><status>Archive</status><annotation>Circuit terminé, dossier archivable</annotation></LogDossier><MessageRetour><codeRetour>OK</codeRetour><message></message><severite>INFO</severite></MessageRetour></GetHistoDossierResponse></S:Body></S:Envelope>
     """
-
-    http_open.return_value = file(xmlmime)
-    mocked_get.return_value = mock.Mock(content = file(wsdl_file).read(),
-                                            status_code=200)
-    mocked_post.return_value = mock.Mock(status_code=200, content=soap_response)
+    response._content = soap_response
+    mocked_post.return_value = response
     url = reverse('generic-endpoint', kwargs={'connector': 'iparapheur',
                                 'endpoint': 'get-file-status', 'slug': conn.slug,
                                 'rest': file_id})
@@ -203,9 +205,8 @@ def test_get_file_status(http_open, mocked_post, mocked_get, app, conn, xmlmime,
 
     # KO
     soap_response = """<?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><CreerDossierResponse xmlns="http://www.adullact.org/spring-ws/iparapheur/1.0" xmlns:xmime="http://www.w3.org/2005/05/xmlmime"><MessageRetour><codeRetour>KO</codeRetour><message>KOmessage</message><severite>INFO</severite></MessageRetour></CreerDossierResponse></S:Body></S:Envelope>"""
-    http_open.return_value = open(xmlmime)
-    mocked_get.return_value = mock.Mock(content=open(wsdl_file).read(), status_code=200)
-    mocked_post.return_value = mock.Mock(status_code=200, content=soap_response)
+    response._content = soap_response
+    mocked_post.return_value = response
     resp = app.get(url, status=500)
     assert resp.json['err'] == 1
     assert 'FileError' in resp.json['err_class']
@@ -213,9 +214,8 @@ def test_get_file_status(http_open, mocked_post, mocked_get, app, conn, xmlmime,
 
     # unknown response
     soap_response = """<?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><CreerDossierResponse xmlns="http://www.adullact.org/spring-ws/iparapheur/1.0" xmlns:xmime="http://www.w3.org/2005/05/xmlmime"></CreerDossierResponse></S:Body></S:Envelope>"""
-    http_open.return_value = open(xmlmime)
-    mocked_get.return_value = mock.Mock(content=open(wsdl_file).read(), status_code=200)
-    mocked_post.return_value = mock.Mock(status_code=200, content=soap_response)
+    response._content = soap_response
+    mocked_post.return_value = response
     resp = app.get(url, status=500)
     assert resp.json['err'] == 1
     assert 'FileError' in resp.json['err_class']
@@ -223,28 +223,26 @@ def test_get_file_status(http_open, mocked_post, mocked_get, app, conn, xmlmime,
 
     # bad response
     soap_response = """<nada>"""
-    http_open.return_value = open(xmlmime)
-    mocked_get.return_value = mock.Mock(content=open(wsdl_file).read(), status_code=200)
-    mocked_post.return_value = mock.Mock(status_code=200, content=soap_response)
-    resp = app.get(url, status=500)
+    response._content = soap_response
+    mocked_post.return_value = response
+    #resp = app.get(url, status=500)
+    resp = app.get(url)
     assert resp.json['err'] == 1
-    assert 'SAXParseException' in resp.json['err_class']
-    assert 'syntax error' in resp.json['err_desc']
-
+    #assert 'zeep.exceptions.TransportError' in resp.json['err_class']
+    assert 'passerelle.utils.jsonresponse.APIError' in resp.json['err_class']
+    assert 'Server returned HTTP status 200 (<nada>)' in resp.json['err_desc']
 
-@mock.patch('passerelle.utils.Request.get')
+@mock.patch('passerelle.utils.Request.get', side_effect=iph_mocked_get)
 @mock.patch('passerelle.utils.Request.post')
-@mock.patch('passerelle.contrib.iparapheur.soap.HttpAuthenticated.open')
-def test_get_file(http_open, mocked_post, mocked_get, app, conn, xmlmime, wsdl_file):
+def test_get_file(mocked_post, mocked_get, app, conn):
     file_id = str(uuid.uuid4())
+    response = Response()
+    response.status_code = 200
 
     soap_response = file(os.path.join(os.path.dirname(__file__),
         'data/iparapheur_get_file_response.xml')).read()
-
-    http_open.return_value = file(xmlmime)
-    mocked_get.return_value = mock.Mock(content = file(wsdl_file).read(),
-                                            status_code=200)
-    mocked_post.return_value = mock.Mock(status_code=200, content=soap_response)
+    response._content = soap_response
+    mocked_post.return_value = response
 
     url = reverse('generic-endpoint', kwargs={'slug': conn.slug,
                 'connector': 'iparapheur', 'endpoint': 'get-file',
@@ -258,19 +256,19 @@ def test_get_file(http_open, mocked_post, mocked_get, app, conn, xmlmime, wsdl_f
 
     # KO
     soap_response = """<?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><CreerDossierResponse xmlns="http://www.adullact.org/spring-ws/iparapheur/1.0" xmlns:xmime="http://www.w3.org/2005/05/xmlmime"><MessageRetour><codeRetour>KO</codeRetour><message>KOmessage</message><severite>INFO</severite></MessageRetour></CreerDossierResponse></S:Body></S:Envelope>"""
-    http_open.return_value = open(xmlmime)
-    mocked_get.return_value = mock.Mock(content=open(wsdl_file).read(), status_code=200)
-    mocked_post.return_value = mock.Mock(status_code=200, content=soap_response)
+    response._content = soap_response
+    mocked_post.return_value = response
     resp = app.get(url, status=500)
     assert resp.json['err'] == 1
-    assert 'FileError' in resp.json['err_class']
-    assert resp.json['err_desc'] == 'KOmessage'
+    #assert 'FileError' in resp.json['err_class']
+    #assert resp.json['err_desc'] == 'KOmessage'
+    assert 'zeep.exceptions.XMLParseError' in resp.json['err_class']
+    assert resp.json['err_desc'] == "Unexpected element u'{http://www.adullact.org/spring-ws/iparapheur/1.0}MessageRetour', expected u'{http://www.adullact.org/spring-ws/iparapheur/1.0}TypeTechnique'"
 
     # unknown response
     soap_response = """<?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><CreerDossierResponse xmlns="http://www.adullact.org/spring-ws/iparapheur/1.0" xmlns:xmime="http://www.w3.org/2005/05/xmlmime"></CreerDossierResponse></S:Body></S:Envelope>"""
-    http_open.return_value = open(xmlmime)
-    mocked_get.return_value = mock.Mock(content=open(wsdl_file).read(), status_code=200)
-    mocked_post.return_value = mock.Mock(status_code=200, content=soap_response)
+    response._content = soap_response
+    mocked_post.return_value = response
     resp = app.get(url, status=500)
     assert resp.json['err'] == 1
     assert 'FileError' in resp.json['err_class']
@@ -278,28 +276,26 @@ def test_get_file(http_open, mocked_post, mocked_get, app, conn, xmlmime, wsdl_f
 
     # bad response
     soap_response = """<nada>"""
-    http_open.return_value = open(xmlmime)
-    mocked_get.return_value = mock.Mock(content=open(wsdl_file).read(), status_code=200)
-    mocked_post.return_value = mock.Mock(status_code=200, content=soap_response)
-    resp = app.get(url, status=500)
+    response._content = soap_response
+    mocked_post.return_value = response
+    #resp = app.get(url, status=500)
+    resp = app.get(url)
     assert resp.json['err'] == 1
-    assert 'SAXParseException' in resp.json['err_class']
-    assert 'syntax error' in resp.json['err_desc']
-
+    #assert 'zeep.exceptions.TransportError' in resp.json['err_class']
+    assert 'passerelle.utils.jsonresponse.APIError' in resp.json['err_class']
+    assert 'Server returned HTTP status 200 (<nada>)' in resp.json['err_desc']
 
-@mock.patch('passerelle.utils.Request.get')
+@mock.patch('passerelle.utils.Request.get', side_effect=iph_mocked_get)
 @mock.patch('passerelle.utils.Request.post')
-@mock.patch('passerelle.contrib.iparapheur.soap.HttpAuthenticated.open')
-def test_get_file_invalid_appendix(http_open, mocked_post, mocked_get, app, conn, xmlmime, wsdl_file):
+def test_get_file_invalid_appendix(mocked_post, mocked_get, app, conn):
     file_id = str(uuid.uuid4())
+    response = Response()
+    response.status_code = 200
 
     soap_response = file(os.path.join(os.path.dirname(__file__),
         'data/iparapheur_get_file_response.xml')).read()
-
-    http_open.return_value = file(xmlmime)
-    mocked_get.return_value = mock.Mock(content=file(wsdl_file).read(),
-                                            status_code=200)
-    mocked_post.return_value = mock.Mock(status_code=200, content=soap_response)
+    response._content = soap_response
+    mocked_post.return_value = response
 
     url = reverse('generic-endpoint', kwargs={'slug': conn.slug,
                 'connector': 'iparapheur', 'endpoint': 'get-file',
@@ -309,19 +305,17 @@ def test_get_file_invalid_appendix(http_open, mocked_post, mocked_get, app, conn
     assert resp.json['err'] == 1
     assert resp.json['err_desc'] == 'invalid appendix index'
 
-@mock.patch('passerelle.utils.Request.get')
+@mock.patch('passerelle.utils.Request.get', side_effect=iph_mocked_get)
 @mock.patch('passerelle.utils.Request.post')
-@mock.patch('passerelle.contrib.iparapheur.soap.HttpAuthenticated.open')
-def test_get_file_not_found_appendix(http_open, mocked_post, mocked_get, app, conn, xmlmime, wsdl_file):
+def test_get_file_not_found_appendix(mocked_post, mocked_get, app, conn):
     file_id = str(uuid.uuid4())
+    response = Response()
+    response.status_code = 200
 
     soap_response = file(os.path.join(os.path.dirname(__file__),
         'data/iparapheur_get_file_response.xml')).read()
-
-    http_open.return_value = file(xmlmime)
-    mocked_get.return_value = mock.Mock(content=file(wsdl_file).read(),
-                                            status_code=200)
-    mocked_post.return_value = mock.Mock(status_code=200, content=soap_response)
+    response._content = soap_response
+    mocked_post.return_value = response
 
     url = reverse('generic-endpoint', kwargs={'slug': conn.slug,
                 'connector': 'iparapheur', 'endpoint': 'get-file',
@@ -331,19 +325,17 @@ def test_get_file_not_found_appendix(http_open, mocked_post, mocked_get, app, co
     assert resp.json['err'] == 1
     assert resp.json['err_desc'] == 'unknown appendix'
 
-@mock.patch('passerelle.utils.Request.get')
+@mock.patch('passerelle.utils.Request.get', side_effect=iph_mocked_get)
 @mock.patch('passerelle.utils.Request.post')
-@mock.patch('passerelle.contrib.iparapheur.soap.HttpAuthenticated.open')
-def test_get_file_appendix(http_open, mocked_post, mocked_get, app, conn, xmlmime, wsdl_file):
+def test_get_file_appendix(mocked_post, mocked_get, app, conn):
     file_id = str(uuid.uuid4())
+    response = Response()
+    response.status_code = 200
 
     soap_response = file(os.path.join(os.path.dirname(__file__),
         'data/iparapheur_get_file_response.xml')).read()
-
-    http_open.return_value = file(xmlmime)
-    mocked_get.return_value = mock.Mock(content=file(wsdl_file).read(),
-                                            status_code=200)
-    mocked_post.return_value = mock.Mock(status_code=200, content=soap_response)
+    response._content = soap_response
+    mocked_post.return_value = response
 
     url = reverse('generic-endpoint', kwargs={'slug': conn.slug,
                 'connector': 'iparapheur', 'endpoint': 'get-file',
@@ -355,37 +347,35 @@ def test_get_file_appendix(http_open, mocked_post, mocked_get, app, conn, xmlmim
     assert 'filename*=UTF-8\'\'iParapheur_impression_dossier.pdf' in resp.headers['Content-Disposition']
     assert resp.body == 'Test Document Appendix'
 
-
-@mock.patch('passerelle.utils.Request.get')
+@mock.patch('passerelle.utils.Request.get', side_effect=iph_mocked_get)
 @mock.patch('passerelle.utils.Request.post')
-@mock.patch('passerelle.contrib.iparapheur.soap.HttpAuthenticated.open')
-def test_invalid_response(http_open, mocked_post, mocked_get, app, conn, xmlmime, wsdl_file):
+def test_invalid_response(mocked_post, mocked_get, app, conn):
     file_id = str(uuid.uuid4())
+    response = Response()
+    response.status_code = 502
+
+    soap_response = file(os.path.join(os.path.dirname(__file__),
+        'data/iparapheur_get_file_response.xml')).read()
+    response._content = '<p>Bad Gateway</p>'
+    response.raison = 'Bad Gateway'
+    mocked_post.return_value = response
 
-    http_open.return_value = file(xmlmime)
-    mocked_get.return_value = mock.Mock(content=file(wsdl_file).read(),
-                                        status_code=200)
-    mocked_post.return_value = mock.Mock(status_code=502,
-            content='<p>Bad Gateway</p>', reason='Bad Gateway', ok=False)
     url = reverse('generic-endpoint', kwargs={'slug': conn.slug,
                   'connector': 'iparapheur', 'endpoint': 'get-file-status', 'rest': file_id})
     url += '?apikey=%s' % API_KEY
     resp = app.get(url)
-    assert resp.json['err_desc'] == "Transport Error: (502, u'Bad Gateway')"
-
+    assert resp.json['err_desc'] == "ServiceError: Unknown fault occured"
 
-@mock.patch('passerelle.utils.Request.get')
+@mock.patch('passerelle.utils.Request.get', side_effect=iph_mocked_get)
 @mock.patch('passerelle.utils.Request.post')
-@mock.patch('passerelle.contrib.iparapheur.soap.HttpAuthenticated.open')
-def test_webfault_response(http_open, mocked_post, mocked_get, app, conn, xmlmime, wsdl_file):
+def test_webfault_response(mocked_post, mocked_get, app, conn):
     file_id = str(uuid.uuid4())
+    response = Response()
+    response.status_code = 200
     url = reverse('generic-endpoint', kwargs={'slug': conn.slug,
                   'connector': 'iparapheur', 'endpoint': 'get-file-status', 'rest': file_id})
     url += '?apikey=%s' % API_KEY
 
-    http_open.return_value = file(xmlmime)
-    mocked_get.return_value = mock.Mock(content=file(wsdl_file).read(),
-                                        status_code=200)
     webfault_response = """
     <?xml version='1.0' encoding='UTF-8'?>
     <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:xsd="http://www.w3.org/1999/XMLSchema">
@@ -398,14 +388,13 @@ def test_webfault_response(http_open, mocked_post, mocked_get, app, conn, xmlmim
            </SOAP-ENV:Fault>
         </SOAP-ENV:Body>
      </SOAP-ENV:Envelope>"""
+    response._content = webfault_response
+    mocked_post.return_value = response
 
-    mocked_post.return_value = mock.Mock(
-        status_code=200, content=webfault_response,
-        ok=True)
     resp = app.get(url)
-    assert 'ServiceError' in resp.json['err_desc']
-    assert 'Test server error' in resp.json['err_desc']
-
+    assert resp.json['err'] == 1
+    assert 'passerelle.utils.jsonresponse.APIError' in resp.json['err_class']
+    assert 'Transport Error: Server returned HTTP status 200' in resp.json['err_desc']
 
 def test_get_magic_mime(tmpdir):
     from PIL import Image
@@ -423,16 +412,14 @@ def test_get_magic_mime(tmpdir):
     with text_path.open() as f:
         assert 'text/plain' == get_magic_mime(f.read())
 
-@mock.patch('passerelle.utils.Request.get')
-def test_call_wsdl(mocked_get, app, conn, wsdl_file):
-    mocked_get.return_value = mock.Mock(content=file(wsdl_file).read(),
-                                        status_code=200)
+@mock.patch('passerelle.utils.Request.get', side_effect=iph_mocked_get)
+def test_call_wsdl(mocked_get, app, conn):
     url = reverse('generic-endpoint',
                   kwargs={'slug': conn.slug,
                           'connector': 'iparapheur', 'endpoint': 'wsdl'})
     resp = app.get(url)
     assert resp.headers['content-type'] == 'text/xml'
-    assert resp.content == file(wsdl_file).read()
+    assert resp.content == file(wsdl_file()).read()
 
 @mock.patch('passerelle.utils.Request.get', side_effect=ConnectionError('mocked error'))
 def test_call_wsdl_connectionerror(mocked_get, app, conn):
-- 
2.20.1

