Projet

Général

Profil

0002-api-accept-int-on-StringOrListField-serialiser-60351.patch

Nicolas Roche, 03 février 2022 08:48

Télécharger (2,58 ko)

Voir les différences:

Subject: [PATCH 2/2] api: accept int on StringOrListField serialiser (#60351)

 chrono/api/serializers.py | 3 +++
 tests/api/test_event.py   | 7 +++++++
 2 files changed, 10 insertions(+)
chrono/api/serializers.py
18 18
    return objects
19 19

  
20 20

  
21 21
class StringOrListField(serializers.ListField):
22 22
    def to_internal_value(self, data):
23 23
        if isinstance(data, list) and len(data) == 1 and isinstance(data[0], str):
24 24
            # accept comma separated string passed as a list of only one string item
25 25
            data = data[0]
26
        elif isinstance(data, int):
27
            # accept int as the first element of a list
28
            data = [data]
26 29
        if isinstance(data, str):
27 30
            data = [s.strip() for s in data.split(',') if s.strip()]
28 31
        return super().to_internal_value(data)
29 32

  
30 33

  
31 34
class CommaSeparatedStringField(serializers.ListField):
32 35
    def get_value(self, dictionary):
33 36
        return super(serializers.ListField, self).get_value(dictionary)
tests/api/test_event.py
1 1
import datetime
2
import json
2 3

  
3 4
import pytest
4 5
from django.utils.timezone import localtime, now
5 6

  
6 7
from chrono.agendas.models import Agenda, Booking, Event
7 8

  
8 9
pytestmark = pytest.mark.django_db
9 10

  
......
185 186
        'start_datetime': '2022-02-03 16:00',
186 187
        'places': '1',
187 188
        'recurrence_days': days_in,
188 189
    }
189 190
    resp = app.post(api_url, params=params)
190 191
    assert not resp.json['err']
191 192
    assert Event.objects.get().recurrence_days == days_out
192 193

  
194
    headers = {'Content-type': 'application/json'}
195
    data = '{"start_datetime": "2022-02-03 17:00", "places": 2, "recurrence_days": %s}' % json.dumps(days_in)
196
    resp = app.post(api_url, headers=headers, params=data)
197
    assert not resp.json['err']
198
    assert Event.objects.get(places=2).recurrence_days == days_out
199

  
193 200

  
194 201
@pytest.mark.freeze_time('2021-11-01')
195 202
def test_add_event(app, user):
196 203
    api_url = '/api/agenda/%s/event/' % ('999')
197 204

  
198 205
    # no authentication
199 206
    resp = app.post(api_url, status=401)
200 207
    assert resp.json['detail'] == 'Authentication credentials were not provided.'
201
-