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
This commit is contained in:
Cedric Brandily
2015-05-31 19:42:46 +02:00
committed by Kahou Lei
parent 7eb3241650
commit a2ae8ebdc3
2 changed files with 16 additions and 3 deletions

View File

@@ -105,9 +105,15 @@ def str2dict(strdict):
:param strdict: key1=value1,key2=value2 :param strdict: key1=value1,key2=value2
""" """
if not strdict: result = {}
return {} if strdict:
return dict([kv.split('=', 1) for kv in strdict.split(',')]) 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): def http_log_req(_logger, args, kwargs):

View File

@@ -13,6 +13,8 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import argparse
import testtools import testtools
from neutronclient.common import exceptions from neutronclient.common import exceptions
@@ -42,6 +44,11 @@ class TestUtils(testtools.TestCase):
expected = {} expected = {}
self.assertEqual(expected, utils.str2dict(input_str)) 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): def test_get_dict_item_properties(self):
item = {'name': 'test_name', 'id': 'test_id'} item = {'name': 'test_name', 'id': 'test_id'}
fields = ('name', 'id') fields = ('name', 'id')