From a2ae8ebdc30220212ba95680cfadeade848c1a7d Mon Sep 17 00:00:00 2001 From: Cedric Brandily Date: Sun, 31 May 2015 19:42:46 +0200 Subject: [PATCH] Raise user-friendly exceptions in str2dict Currently str2dict raises non user-friendly exceptions when input is not valid: neutron subnet-create mynetwork 10/23 --allocation-pools=10/24 # implies str2dict('10/24') # raises: dictionary update sequence element #0 has length 1; 2 is required This change updates str2dict implementation in order to raise user-friendly exceptions. Closes-Bug: #1460336 Change-Id: Id381865e6e5d9bebcb2c984c0338126566a97c2b --- neutronclient/common/utils.py | 12 +++++++++--- neutronclient/tests/unit/test_utils.py | 7 +++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/neutronclient/common/utils.py b/neutronclient/common/utils.py index e0d5f546a..788b024ae 100644 --- a/neutronclient/common/utils.py +++ b/neutronclient/common/utils.py @@ -105,9 +105,15 @@ def str2dict(strdict): :param strdict: key1=value1,key2=value2 """ - if not strdict: - return {} - return dict([kv.split('=', 1) for kv in strdict.split(',')]) + result = {} + if strdict: + for kv in strdict.split(','): + key, sep, value = kv.partition('=') + if not sep: + msg = _("invalid key-value '%s', expected format: key=value") + raise argparse.ArgumentTypeError(msg % kv) + result[key] = value + return result def http_log_req(_logger, args, kwargs): diff --git a/neutronclient/tests/unit/test_utils.py b/neutronclient/tests/unit/test_utils.py index a8d3a6ead..27ebc0f17 100644 --- a/neutronclient/tests/unit/test_utils.py +++ b/neutronclient/tests/unit/test_utils.py @@ -13,6 +13,8 @@ # License for the specific language governing permissions and limitations # under the License. +import argparse + import testtools from neutronclient.common import exceptions @@ -42,6 +44,11 @@ class TestUtils(testtools.TestCase): expected = {} self.assertEqual(expected, utils.str2dict(input_str)) + def test_invalid_string_to_dictionary(self): + input_str = 'invalid' + self.assertRaises(argparse.ArgumentTypeError, + utils.str2dict, input_str) + def test_get_dict_item_properties(self): item = {'name': 'test_name', 'id': 'test_id'} fields = ('name', 'id')