From 0da5ad4ab96d85d0c861fa86dc2d9600a6edf79f Mon Sep 17 00:00:00 2001 From: Jiri Stransky Date: Tue, 8 Oct 2013 17:04:31 +0200 Subject: [PATCH] Add function to marshal resource associations It will be useful e.g. for setting/updating links from Racks to Resource Classes, from Nodes to Racks or other similar associations. Change-Id: I7a525cc525940ee2ae72269004b5d8d1b27f123b --- tuskarclient/common/utils.py | 20 ++++++++++++++++++++ tuskarclient/tests/common/test_utils.py | 23 +++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/tuskarclient/common/utils.py b/tuskarclient/common/utils.py index 2298bfa..17f8872 100644 --- a/tuskarclient/common/utils.py +++ b/tuskarclient/common/utils.py @@ -84,6 +84,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)