diff --git a/desktop/core/src/desktop/lib/conf.py b/desktop/core/src/desktop/lib/conf.py index 6779005dcd1..35bdf3933fc 100644 --- a/desktop/core/src/desktop/lib/conf.py +++ b/desktop/core/src/desktop/lib/conf.py @@ -63,6 +63,7 @@ import os import re +import ast import sys import json import logging @@ -230,6 +231,10 @@ def __init__(self, key=_ANONYMOUS, default=None, dynamic_default=None, required= LOG.warning("%s is of type bool. Resetting it as type 'coerce_bool'." " Please fix it permanently" % (key,)) type = coerce_bool + if type is list: + LOG.warning("%s is of type list. Resetting it as type 'coerce_list'." " Please fix it permanently" % (key,)) + type = coerce_list + self.key = key self.default_value = default self.dynamic_default = dynamic_default @@ -661,6 +666,19 @@ def coerce_csv(value): raise Exception("Could not coerce %r to csv array." % value) +def coerce_list(value) -> list: + if isinstance(value, str): + try: + result = ast.literal_eval(value) + if isinstance(result, list): + return result + except (SyntaxError, ValueError): + return [value] + elif isinstance(value, list): + return value + raise Exception("Could not coerce %r to list." % value) + + def coerce_json_dict(value): if isinstance(value, string_types): return json.loads(value) diff --git a/desktop/core/src/desktop/lib/conf_test.py b/desktop/core/src/desktop/lib/conf_test.py index 82ae76b025b..82db8c72352 100644 --- a/desktop/core/src/desktop/lib/conf_test.py +++ b/desktop/core/src/desktop/lib/conf_test.py @@ -24,6 +24,7 @@ import configobj from desktop.lib.conf import * +from desktop.lib.conf import coerce_bool, coerce_list def my_dynamic_default(): @@ -187,6 +188,22 @@ def test_coerce_bool(self): with pytest.raises(Exception): coerce_bool(tuple("foo")) + def test_coerce_list(self): + assert coerce_list("[]") == [] + assert coerce_list("Test val") == ["Test val"] + assert coerce_list("['Test val 1', 'Test val 2']") == ["Test val 1", "Test val 2"] + assert coerce_list("['Test val 1', 'Test val 2, 3']") == ["Test val 1", "Test val 2, 3"] + assert coerce_list("['Test val 1', 'Test val \\'2\\'']") == ["Test val 1", "Test val '2'"] + + assert coerce_list(['Test val 1', 'Test val 2']) == ["Test val 1", "Test val 2"] + + with pytest.raises(Exception): + coerce_list(tuple("foo")) + with pytest.raises(Exception): + coerce_list(1) + with pytest.raises(Exception): + coerce_list("{1:1, 2:2}") + def test_print_help(self): out = string_io() self.conf.print_help(out=out, skip_header=True)