Projet

Général

Profil

0001-solis-add-links-parameter-to-retreive-rsa-_links-inf.patch

Thomas Noël, 24 mai 2019 17:30

Télécharger (9,97 ko)

Voir les différences:

Subject: [PATCH] solis: add links parameter to retreive rsa _links information
 (#33377)

 passerelle/apps/solis/models.py | 48 +++++++++++++++++++++--
 tests/test_solis.py             | 67 +++++++++++++++++++++++++++++++--
 2 files changed, 108 insertions(+), 7 deletions(-)
passerelle/apps/solis/models.py
15 15
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 16

  
17 17
import base64
18
import copy
18 19
import json
19 20
import re
20 21
import unicodedata
21 22

  
22 23
from django.db import models
23 24
from django.template.loader import get_template
25
from django.utils.encoding import force_text
24 26
from django.utils.translation import ugettext_lazy as _
25 27
from django.utils.http import urlencode
26 28

  
......
454 456
        })
455 457
        return response.get('token')
456 458

  
459
    def rsa_get_link_content(self, link):
460
        '''returns content of a '_links' entry in a grsa referential'''
461
        if (not isinstance(link, dict) or not link.get('href')
462
                or not link['href'].startswith(self.service_url)):
463
            return None
464
        endpoint = link['href'][len(self.service_url):]
465
        try:
466
            return self.request(endpoint)
467
        except APIError as e:  # do not raise on linked informations
468
            return {
469
                'err': 1,
470
                'err_class': e.__class__.__name__,
471
                'err_desc': force_text(e)
472
            }
473

  
457 474
    def rsa_get_information(self, information, user_id=None, code=None, token=None,
458
                            index='search'):
475
                            index='search', links=None):
459 476
        # simulate "individu" referential: get user details from civi/individu/user_id
460 477
        if information == 'individu':
461 478
            if not user_id:
......
473 490
        if index.startswith('search'):  # it can be "search/next" in rdvs referential
474 491
            args = [('indexIndividu', user_id)] + args
475 492
        endpoint += '?' + urlencode(args)
476
        return self.request(endpoint)
493

  
494
        information = self.request(endpoint)
495

  
496
        if isinstance(information, dict) and '_links' in information:
497
            # return links in non-underscored key, usable in Django template
498
            information['rsa_links'] = copy.deepcopy(information['_links'])
499

  
500
            if links is not None:
501
                if not links.strip():  # get all links
502
                    links = information['rsa_links'].keys()
503
                else:
504
                    links = [link.strip() for link in links.split(',') if link.strip()]
505
                    links = [link for link in links if link in information['rsa_links']
506
                             and information['rsa_links'][link].get('href')]
507
                for link in links:
508
                    content = self.rsa_get_link_content(information['rsa_links'][link])
509
                    if content is not None:
510
                        information['rsa_links'][link]['content'] = content
511

  
512
        return information
477 513

  
478 514
    @endpoint(name='rsa-link', methods=['post'], perm='can_access',
479 515
              description=_('Create link between name_id and '
......
549 585
                  },
550 586
                  'index': {
551 587
                      'description': _('get a specific item, if applicable'),
588
                  },
589
                  'links': {
590
                      'description': _('get linked informations (comma separated list, empty for all)'),
591
                      'example_value': 'etatCivil,conjoint',
552 592
                  }
553 593
              })
554 594
    def rsa_user_info(self, request, name_id, user_id, information='individu',
555
                      index='search'):
595
                      index='search', links=None):
556 596
        try:
557 597
            link = SolisRSALink.objects.get(resource=self, name_id=name_id, user_id=user_id)
558 598
        except SolisRSALink.DoesNotExist:
559 599
            raise APIError('unknown link')
560 600
        response = self.rsa_get_information(information=information,
561 601
                                            user_id=user_id, code=link.code,
562
                                            index=index)
602
                                            index=index, links=links)
563 603
        if information == 'individu':
564 604
            text = get_template(self.text_template_name_rsa).render(response).strip()
565 605
            if text != link.text:
tests/test_solis.py
47 47
  "oriente": true,
48 48
  "_links": {
49 49
    "etatCivil": {
50
      "href": "http://solis.infodb.fr/solisapi-rsa/referentiels/civi/individu/4242/"
50
      "href": "https://solis.example.net/solisapi/referentiels/civi/individu/4242/"
51 51
    },
52 52
    "conjoint": {
53
      "href": "http://solis.infodb.fr/solisapi-rsa/referentiels/civi/individu/4273/"
53
      "href": "https://solis.example.net/solisapi/referentiels/civi/individu/4273/"
54 54
    }
55 55
  }
56 56
}'''
......
203 203
                                                            status_code=200)
204 204
            resp = app.post_json(endpoint,
205 205
                                 params={'name_id': NAMEID, 'user_id': '42', 'code': 'foo'},
206
                                 status=200)
206
                                 httptatus=200)
207 207
            assert requests_post.call_count == 2
208 208
            assert requests_get.call_count == 1
209 209
            assert resp.json['err'] == 0
......
830 830
                assert resp.json['err_desc'] == 'unknown link'
831 831
                assert resp.json['data'] is None
832 832

  
833
    # get referential for a linked user with links
834
    with mock.patch('passerelle.utils.Request.get') as requests_get:
835
        with mock.patch('passerelle.utils.Request.post') as requests_post:
836
            requests_post.return_value = utils.FakedResponse(content=RSATOKEN, status_code=200)
837
            endpoint_base = utils.generic_endpoint_url('solis', 'rsa-user-info', slug=solis.slug)
838

  
839
            requests_get.side_effect = [
840
                utils.FakedResponse(status_code=200, content=RSAALLOCATAIRES),  # base info
841
                utils.FakedResponse(status_code=200, content=CIVI_INDIVIDU),    # link 1
842
                utils.FakedResponse(status_code=200, content=CIVI_INDIVIDU)]    # link 2
843
            endpoint = endpoint_base + '?name_id=%s&user_id=4242&information=allocataires&links' % NAMEID
844
            resp = app.get(endpoint, status=200)
845
            assert requests_post.call_count == 1  # get a token
846
            assert requests_get.call_count == 3   # get informations + two links
847
            assert resp.json['err'] == 0
848
            assert resp.json['data']['rsa_links']['etatCivil']['content']['index'] == 4273
849
            assert resp.json['data']['rsa_links']['conjoint']['content']['index'] == 4273
850

  
851
            # get only conjoint
852
            requests_post.reset_mock()
853
            requests_get.reset_mock()
854
            requests_get.side_effect = [
855
                utils.FakedResponse(status_code=200, content=RSAALLOCATAIRES),  # base info
856
                utils.FakedResponse(status_code=200, content=CIVI_INDIVIDU)]    # link 1
857
            endpoint = endpoint_base + '?name_id=%s&user_id=4242&information=allocataires&links=conjoint, ,xx,' % NAMEID
858
            resp = app.get(endpoint, status=200)
859
            assert requests_post.call_count == 1  # get a token
860
            assert requests_get.call_count == 2   # get informations + conjoint
861
            assert resp.json['err'] == 0
862
            assert resp.json['data']['rsa_links']['conjoint']['content']['index'] == 4273
863
            assert 'content' not in resp.json['data']['rsa_links']['etatCivil']
864

  
865
            # error on link retreival
866
            requests_post.reset_mock()
867
            requests_get.reset_mock()
868
            requests_get.side_effect = [
869
                utils.FakedResponse(status_code=200, content=RSAALLOCATAIRES),   # base info
870
                utils.FakedResponse(status_code=404, content='{"foo": "bar"}'),  # link 1
871
                utils.FakedResponse(status_code=500, content='boom')]            # link 2
872
            endpoint = endpoint_base + '?name_id=%s&user_id=4242&information=allocataires&links' % NAMEID
873
            resp = app.get(endpoint, status=200)
874
            assert requests_post.call_count == 1  # get a token
875
            assert requests_get.call_count == 3   # get informations + two links
876
            assert resp.json['err'] == 0
877
            assert resp.json['data']['rsa_links']['etatCivil']['content']['err'] == 1
878
            assert resp.json['data']['rsa_links']['conjoint']['content']['err'] == 1
879

  
880
            # bad links, do nothing
881
            for content in (RSAALLOCATAIRES.replace('https:', 'http:'),
882
                            RSAALLOCATAIRES.replace('href', 'xxxx')):
883
                requests_post.reset_mock()
884
                requests_get.reset_mock()
885
                requests_get.side_effect = [utils.FakedResponse(status_code=200, content=content)]
886
                endpoint = endpoint_base + '?name_id=%s&user_id=4242&information=allocataires&links' % NAMEID
887
                resp = app.get(endpoint, status=200)
888
                assert requests_post.call_count == 1  # get a token
889
                assert requests_get.call_count == 1   # get informations only, not links
890
                assert resp.json['err'] == 0
891
                assert 'content' not in resp.json['data']['rsa_links']['conjoint']
892
                assert 'content' not in resp.json['data']['rsa_links']['etatCivil']
893

  
833 894
    # unlink
834 895
    endpoint = utils.generic_endpoint_url('solis', 'rsa-unlink', slug=solis.slug)
835 896
    for bad_params in ({}, {'user_id': '4273'}, {'name_id': NAMEID}):
836
-