Verified Commit 2ef36928 authored by Eliot Berriot's avatar Eliot Berriot
Browse files

See #236: added a basic string list preference

parent c6cd3abf
from django.conf import settings
from django import forms
from dynamic_preferences import serializers
from dynamic_preferences import types
from dynamic_preferences.registries import global_preferences_registry
......@@ -10,3 +14,38 @@ class DefaultFromSettingMixin(object):
def get(pref):
manager = global_preferences_registry.manager()
return manager[pref]
class StringListSerializer(serializers.BaseSerializer):
separator = ','
sort = True
def to_db(cls, value, **kwargs):
if not value:
if type(value) not in [list, tuple]:
raise cls.exception(
"Cannot serialize, value {} is not a list or a tuple".format(
if cls.sort:
value = sorted(value)
return cls.separator.join(value)
def to_python(cls, value, **kwargs):
if not value:
return []
return value.split(',')
class StringListPreference(types.BasePreferenceType):
serializer = StringListSerializer
field_class = forms.MultipleChoiceField
def get_api_additional_data(self):
d = super(StringListPreference, self).get_api_additional_data()
d['choices'] = self.get('choices')
return d
import pytest
from dynamic_preferences.registries import global_preferences_registry
from funkwhale_api.common import preferences as common_preferences
def string_list_pref(preferences):
class P(common_preferences.StringListPreference):
default = ['hello']
section = 'test'
name = 'string_list'
del global_preferences_registry['test']['string_list']
@pytest.mark.parametrize('input,output', [
(['a', 'b', 'c'], 'a,b,c'),
(['a', 'c', 'b'], 'a,b,c'),
(('a', 'c', 'b'), 'a,b,c'),
([], None),
def test_string_list_serializer_to_db(input, output):
s = common_preferences.StringListSerializer.to_db(input) == output
@pytest.mark.parametrize('input,output', [
('a,b,c', ['a', 'b', 'c'], ),
(None, []),
('', []),
def test_string_list_serializer_to_python(input, output):
s = common_preferences.StringListSerializer.to_python(input) == output
def test_string_list_pref_default(string_list_pref, preferences):
assert preferences['test__string_list'] == ['hello']
def test_string_list_pref_set(string_list_pref, preferences):
preferences['test__string_list'] = ['world', 'hello']
assert preferences['test__string_list'] == ['hello', 'world']
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment