From e2f3d71a453386953b8978040ecb82aa40c27bda Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Laur=C3=A9line=20Gu=C3=A9rin?= <zebuline@entrouvert.com>
Date: Tue, 3 Dec 2019 15:40:34 +0100
Subject: [PATCH 2/2] toulouse_axel: child_info endpoint (#38155)

---
 functests/toulouse_axel/conftest.py           |  2 +
 functests/toulouse_axel/test_toulouse_axel.py | 20 ++++++--
 passerelle/contrib/toulouse_axel/models.py    | 38 +++++++++++----
 tests/data/toulouse_axel/family_info.xml      |  2 +-
 tests/test_toulouse_axel.py                   | 46 +++++++++++++++++++
 5 files changed, 95 insertions(+), 13 deletions(-)

diff --git a/functests/toulouse_axel/conftest.py b/functests/toulouse_axel/conftest.py
index 73b7dbd8..f3a3e5f8 100644
--- a/functests/toulouse_axel/conftest.py
+++ b/functests/toulouse_axel/conftest.py
@@ -4,6 +4,7 @@ import pytest
 def pytest_addoption(parser):
     parser.addoption(
         "--url", help="Url of a passerelle Toulouse Axel connector instance")
+    parser.addoption("--nameid", help="Publik Name ID")
     parser.addoption("--firstname", help="first name of a user")
     parser.addoption("--lastname", help="Last name of a user")
     parser.addoption("--dob", help="Date of birth of a user")
@@ -18,6 +19,7 @@ def conn(request):
 @pytest.fixture(scope='session')
 def user(request):
     return {
+        'name_id': request.config.getoption("--nameid"),
         'first_name': request.config.getoption("--firstname"),
         'last_name': request.config.getoption("--lastname"),
         'dob': request.config.getoption("--dob"),
diff --git a/functests/toulouse_axel/test_toulouse_axel.py b/functests/toulouse_axel/test_toulouse_axel.py
index dec3ffb0..6c4dcb14 100644
--- a/functests/toulouse_axel/test_toulouse_axel.py
+++ b/functests/toulouse_axel/test_toulouse_axel.py
@@ -3,14 +3,16 @@ import requests
 
 
 def test_link(conn, user):
-    url = conn + '/link?NameID=123'
+    name_id = user['name_id']
+    url = conn + '/link?NameID=%s' % name_id
     payload = {
         'IDDUI': user['dui'],
         'NOM': user['last_name'],
         'PRENOM': user['first_name'],
         'NAISSANCE': user['dob'],
     }
-    print("Creating link with the following payload:\n%s" % payload)
+    print("Creating link with the following payload:")
+    pprint.pprint(payload)
     resp = requests.post(url, json=payload)
     resp.raise_for_status()
     res = resp.json()
@@ -18,10 +20,22 @@ def test_link(conn, user):
     pprint.pprint(res)
     print('\n')
 
-    url = conn + '/family_info?NameID=123'
+    print("GET family info")
+    url = conn + '/family_info?NameID=%s' % name_id
     resp = requests.get(url)
     resp.raise_for_status()
     res = resp.json()
     assert res['err'] == 0
     pprint.pprint(res)
     print('\n')
+
+    data = res
+    for child in data['data']['ENFANT']:
+        print("GET child info")
+        url = conn + '/child_info?NameID=%s&idpersonne=%s' % (name_id, child['IDPERSONNE'])
+        resp = requests.get(url)
+        resp.raise_for_status()
+        res = resp.json()
+        assert res['err'] == 0
+        pprint.pprint(res)
+        print('\n')
diff --git a/passerelle/contrib/toulouse_axel/models.py b/passerelle/contrib/toulouse_axel/models.py
index 002cae87..20fd7103 100644
--- a/passerelle/contrib/toulouse_axel/models.py
+++ b/passerelle/contrib/toulouse_axel/models.py
@@ -169,15 +169,9 @@ class ToulouseAxel(BaseResource):
             raise APIError('Data conflict', err='conflict')
         return {'link': link.pk, 'created': created, 'dui': link.dui}
 
-    @endpoint(
-        description=_("Get information about user's family"),
-        perm='can_access',
-        parameters={
-            'NameID': {'description': _('Publik ID')},
-        })
-    def family_info(self, request, NameID):
+    def get_family_data(self, name_id):
         try:
-            link = self.link_set.get(name_id=NameID)
+            link = self.link_set.get(name_id=name_id)
         except Link.DoesNotExist:
             raise APIError('Person not found', err='not-found')
 
@@ -185,7 +179,33 @@ class ToulouseAxel(BaseResource):
             result = ref_famille_dui(self, {'PORTAIL': {'DUI': {'IDDUI': link.dui}}})
         except AxelError as e:
             raise APIError('Axel error: %s' % e, err='error')
-        return {'data': result['DATA']['PORTAIL']['DUI']}
+        return result['DATA']['PORTAIL']['DUI']
+
+    @endpoint(
+        description=_("Get information about user's family"),
+        perm='can_access',
+        parameters={
+            'NameID': {'description': _('Publik ID')},
+        })
+    def family_info(self, request, NameID):
+        family_data = self.get_family_data(NameID)
+        return {'data': family_data}
+
+    @endpoint(
+        description=_("Get information about a child"),
+        perm='can_access',
+        parameters={
+            'NameID': {'description': _('Publik ID')},
+            'idpersonne': {'description': _('Child ID')},
+        })
+    def child_info(self, request, idpersonne, NameID):
+        family_data = self.get_family_data(NameID)
+
+        for child in family_data['ENFANT']:
+            if child['IDPERSONNE'] == idpersonne:
+                return {'data': child}
+
+        raise APIError('Child not found', err='not-found')
 
 
 class Link(models.Model):
diff --git a/tests/data/toulouse_axel/family_info.xml b/tests/data/toulouse_axel/family_info.xml
index 2632f990..2e42f007 100644
--- a/tests/data/toulouse_axel/family_info.xml
+++ b/tests/data/toulouse_axel/family_info.xml
@@ -157,7 +157,7 @@
       </CONTACT>
     </ENFANT>
     <ENFANT>
-      <IDPERSONNE>4242</IDPERSONNE>
+      <IDPERSONNE>3535</IDPERSONNE>
       <RATTACHEAUTREDUI>NON</RATTACHEAUTREDUI>
       <NOM>foo</NOM>
       <PRENOM>foo</PRENOM>
diff --git a/tests/test_toulouse_axel.py b/tests/test_toulouse_axel.py
index 146b208f..0806e376 100644
--- a/tests/test_toulouse_axel.py
+++ b/tests/test_toulouse_axel.py
@@ -245,3 +245,49 @@ def test_family_info_endpoint(app, resource):
         'SITUATIONFAMILIALE',
         'TELFIXE',
     ])
+
+
+def test_child_info_endpoint_axel_error(app, resource):
+    Link.objects.create(resource=resource, name_id='yyy', dui='XXX', person_id='42')
+    with mock.patch('passerelle.contrib.toulouse_axel.models.ref_famille_dui') as operation:
+        operation.side_effect = AxelError('FooBar')
+        resp = app.get('/toulouse-axel/test/child_info?NameID=yyy&idpersonne=zzz')
+        assert resp.json['err_desc'] == "Axel error: FooBar"
+
+
+def test_child_info_endpoint_no_result(app, resource):
+    resp = app.get('/toulouse-axel/test/child_info?NameID=yyy&idpersonne=zzz')
+    assert resp.json['err_desc'] == "Person not found"
+
+    Link.objects.create(resource=resource, name_id='yyy', dui='XXX', person_id='42')
+    filepath = os.path.join(os.path.dirname(__file__), 'data/toulouse_axel/family_info.xml')
+    with open(filepath) as xml:
+        content = xml.read()
+    with mock_getdata(content, 'RefFamilleDui'):
+        resp = app.get('/toulouse-axel/test/child_info?NameID=yyy&idpersonne=zzz')
+    assert resp.json['err_desc'] == "Child not found"
+
+
+def test_child_info_endpoint(app, resource):
+    Link.objects.create(resource=resource, name_id='yyy', dui='XXX', person_id='42')
+    filepath = os.path.join(os.path.dirname(__file__), 'data/toulouse_axel/family_info.xml')
+    with open(filepath) as xml:
+        content = xml.read()
+    with mock_getdata(content, 'RefFamilleDui'):
+        resp = app.get('/toulouse-axel/test/child_info?NameID=yyy&idpersonne=4242')
+    assert resp.json['err'] == 0
+    assert set(resp.json['data'].keys()) == set([
+        'ASSURANCE',
+        'CONTACT',
+        'DATENAISSANCE',
+        'IDPERSONNE',
+        'PRENOM',
+        'PRENOMMERE',
+        'PRENOMPERE',
+        'NOM',
+        'NOMMERE',
+        'NOMPERE',
+        'RATTACHEAUTREDUI',
+        'SANITAIRE',
+        'SEXE',
+    ])
-- 
2.20.1

