diff --git a/tuskarclient/common/utils.py b/tuskarclient/common/utils.py index 9e28145..b951a46 100644 --- a/tuskarclient/common/utils.py +++ b/tuskarclient/common/utils.py @@ -88,6 +88,26 @@ def find_resource(manager, name_or_id): raise exc.CommandError(msg) +def marshal_association(args, resource_dict, assoc_name): + """Marshal resource association into an API request dict. + + Distinguish between 3 cases: + + - when the value in args is present, set the value in dict too, + - when the value in args is an empty string, set the value in dict + to none, + - when the value in args is None, it means the user did not specify + it on the command line and it should not be present in the dict + (important for update). + """ + assoc_value = getattr(args, assoc_name, None) + if assoc_value == '': + resource_dict[assoc_name] = None + elif assoc_value: + # TODO(jistr): support for selecting resources by name + resource_dict[assoc_name] = {'id': assoc_value} + + def string_to_bool(arg): return arg.strip().lower() in ('t', 'true', 'yes', '1') diff --git a/tuskarclient/tests/common/test_utils.py b/tuskarclient/tests/common/test_utils.py index ed2c4c1..474eb4d 100644 --- a/tuskarclient/tests/common/test_utils.py +++ b/tuskarclient/tests/common/test_utils.py @@ -46,3 +46,26 @@ class DefineCommandsTest(test_utils.TestCase): dummy.do_dummy_list = do_dummy_list dummy.other_method = mock.Mock('other_method', return_value=43) return dummy + + +class MarshalAssociationTest(test_utils.TestCase): + + def setUp(self): + super(MarshalAssociationTest, self).setUp() + self.args = mock.Mock(spec=['rack']) + self.dict = {} + + def test_with_id(self): + self.args.rack = '10' + utils.marshal_association(self.args, self.dict, 'rack') + self.assertEqual(self.dict['rack']['id'], '10') + + def test_with_empty_association(self): + self.args.rack = '' + utils.marshal_association(self.args, self.dict, 'rack') + self.assertEqual(self.dict['rack'], None) + + def test_when_unset(self): + self.args.rack = None + utils.marshal_association(self.args, self.dict, 'rack') + self.assertFalse('rack' in self.dict)