From 063b0c47994bb962eaf7d5ad57beedefc8c5e916 Mon Sep 17 00:00:00 2001 From: rr- Date: Fri, 15 Apr 2016 22:49:34 +0200 Subject: [PATCH] server/context: add get_param_as_list --- server/szurubooru/api/context.py | 10 ++++++++++ server/szurubooru/tests/api/test_context.py | 10 ++++++++++ 2 files changed, 20 insertions(+) diff --git a/server/szurubooru/api/context.py b/server/szurubooru/api/context.py index 72dea32..4238efc 100644 --- a/server/szurubooru/api/context.py +++ b/server/szurubooru/api/context.py @@ -15,6 +15,16 @@ class Context(object): def get_file(self, name): return self.files.get(name, None) + def get_param_as_list(self, name, required=False, default=None): + if name in self.input: + param = self.input[name] + if not isinstance(param, list): + return [param] + return param + if not required: + return default + raise errors.ValidationError('Required paramter %r is missing.' % name) + def get_param_as_string(self, name, required=False, default=None): if name in self.input: param = self.input[name] diff --git a/server/szurubooru/tests/api/test_context.py b/server/szurubooru/tests/api/test_context.py index 2fce5be..3b56e9b 100644 --- a/server/szurubooru/tests/api/test_context.py +++ b/server/szurubooru/tests/api/test_context.py @@ -13,6 +13,16 @@ def test_get_file(): assert ctx.get_file('key') == b'content' assert ctx.get_file('key2') is None +def test_getting_list_parameter(): + ctx = api.Context() + ctx.input = {'key': 'value', 'list': ['1', '2', '3']} + assert ctx.get_param_as_list('key') == ['value'] + assert ctx.get_param_as_list('key2') is None + assert ctx.get_param_as_list('key2', default=['def']) == ['def'] + assert ctx.get_param_as_list('list') == ['1', '2', '3'] + with pytest.raises(errors.ValidationError): + ctx.get_param_as_list('key2', required=True) + def test_getting_string_parameter(): ctx = api.Context() ctx.input = {'key': 'value', 'list': ['1', '2', '3']}