def parse_stack(self, t): stack_name = 'test_stack' tmpl = template.Template(t) stack = parser.Stack(utils.dummy_context(), stack_name, tmpl) stack.store() return stack
def test_to_parameters(self): """Tests property conversion to parameter values.""" provider = { 'HeatTemplateFormatVersion': '2012-12-12', 'Parameters': { 'Foo': {'Type': 'String'}, 'AList': {'Type': 'CommaDelimitedList'}, 'MemList': {'Type': 'CommaDelimitedList'}, 'ListEmpty': {'Type': 'CommaDelimitedList'}, 'ANum': {'Type': 'Number'}, 'AMap': {'Type': 'Json'}, }, 'Outputs': { 'Foo': {'Value': 'bar'}, }, } files = {'test_resource.template': json.dumps(provider)} class DummyResource(object): support_status = support.SupportStatus() attributes_schema = {"Foo": attributes.Schema("A test attribute")} properties_schema = { "Foo": {"Type": "String"}, "AList": {"Type": "List"}, "MemList": {"Type": "List"}, "ListEmpty": {"Type": "List"}, "ANum": {"Type": "Number"}, "AMap": {"Type": "Map"} } env = environment.Environment() resource._register_class('DummyResource', DummyResource) env.load({'resource_registry': {'DummyResource': 'test_resource.template'}}) stack = parser.Stack(utils.dummy_context(), 'test_stack', template.Template(empty_template, files=files, env=env), stack_id=str(uuid.uuid4())) map_prop_val = { "key1": "val1", "key2": ["lval1", "lval2", "lval3"], "key3": { "key4": 4, "key5": False } } prop_vals = { "Foo": "Bar", "AList": ["one", "two", "three"], "MemList": [{"key": "name", "value": "three"}, {"key": "name", "value": "four"}], "ListEmpty": [], "ANum": 5, "AMap": map_prop_val, } definition = rsrc_defn.ResourceDefinition('test_t_res', 'DummyResource', prop_vals) temp_res = template_resource.TemplateResource('test_t_res', definition, stack) temp_res.validate() converted_params = temp_res.child_params() self.assertTrue(converted_params) for key in DummyResource.properties_schema: self.assertIn(key, converted_params) # verify String conversion self.assertEqual("Bar", converted_params.get("Foo")) # verify List conversion self.assertEqual("one,two,three", converted_params.get("AList")) # verify Member List conversion mem_exp = ('.member.0.key=name,' '.member.0.value=three,' '.member.1.key=name,' '.member.1.value=four') self.assertEqual(mem_exp, converted_params.get("MemList")) # verify Number conversion self.assertEqual(5, converted_params.get("ANum")) # verify Map conversion self.assertEqual(map_prop_val, converted_params.get("AMap")) with mock.patch.object(properties.Properties, '__getitem__') as m_get: m_get.side_effect = ValueError('boom') # If the property doesn't exist on INIT, return default value temp_res.action = temp_res.INIT converted_params = temp_res.child_params() for key in DummyResource.properties_schema: self.assertIn(key, converted_params) self.assertEqual({}, converted_params['AMap']) self.assertEqual(0, converted_params['ANum']) # If the property doesn't exist past INIT, then error out temp_res.action = temp_res.CREATE self.assertRaises(ValueError, temp_res.child_params)
def test_get_attribute_autoscaling(self): t = template_format.parse(heat_autoscaling_group_template) tmpl = templatem.Template(t) stack = parser.Stack(utils.dummy_context(), 'test_att', tmpl) rsrc = stack['my_autoscaling_group'] self.assertEqual(0, rsrc.FnGetAtt(rsrc.CURRENT_SIZE))
def _stack_with_template(self, template_def): self.ctx = utils.dummy_context() self.stack = parser.Stack(self.ctx, 'software_deploly_test_stack', template.Template(template_def)) self.deployment = self.stack['deploy_mysql']
def _create_test_instance_with_nic(self, return_server, name): stack_name = '%s_s' % name t = template_format.parse(wp_template_with_nic) kwargs = { 'KeyName': 'test', 'InstanceType': 'm1.large', 'SubnetId': '4156c7a5-e8c4-4aff-a6e1-8f3c7bc83861' } tmpl = template.Template(t, env=environment.Environment(kwargs)) self.stack = parser.Stack(utils.dummy_context(), stack_name, tmpl, stack_id=str(uuid.uuid4())) image_id = 'CentOS 5.2' t['Resources']['WebServer']['Properties']['ImageId'] = image_id resource_defns = self.stack.t.resource_definitions(self.stack) nic = net_interfaces.NetworkInterface('%s_nic' % name, resource_defns['nic1'], self.stack) instance = instances.Instance('%s_name' % name, resource_defns['WebServer'], self.stack) metadata = instance.metadata_get() self._mock_get_image_id_success(image_id, 1) self.stub_SubnetConstraint_validate() self.patchobject(nic, 'client', return_value=FakeNeutron()) self.patchobject(neutron.NeutronClientPlugin, '_create', return_value=FakeNeutron()) self.patchobject(nova.NovaClientPlugin, '_create', return_value=self.fc) # need to resolve the template functions server_userdata = instance.client_plugin().build_userdata( metadata, instance.properties['UserData'], 'ec2-user') self.patchobject(nova.NovaClientPlugin, 'build_userdata', return_value=server_userdata) self.patchobject(self.fc.servers, 'create', return_value=return_server) # create network interface scheduler.TaskRunner(nic.create)() self.stack.resources["nic1"] = nic scheduler.TaskRunner(instance.create)() self.fc.servers.create.assert_called_once_with( image=1, flavor=3, key_name='test', name=utils.PhysName(stack_name, instance.name), security_groups=None, userdata=server_userdata, scheduler_hints=None, meta=None, nics=[{ 'port-id': '64d913c1-bcb1-42d2-8f0a-9593dbcaf251' }], availability_zone=None, block_device_mapping=None) self.m_f_i.assert_called_with(image_id) nova.NovaClientPlugin.build_userdata.assert_called_once_with( metadata, instance.properties['UserData'], 'ec2-user') neutron.NeutronClientPlugin._create.assert_called_once_with() nova.NovaClientPlugin._create.assert_called_once_with() glance.GlanceClientPlugin.find_image_by_name_or_id.assert_called_with( image_id) return instance
def parse_stack(self, t): stack_name = 'test_stack' tmpl = template.Template(t) self.stack = stack.Stack(self.ctx, stack_name, tmpl) self.stack.validate() self.stack.store()
def test_param_refs(self): env = environment.Environment({'foo': 'bar', 'blarg': 'wibble'}) tmpl = template.Template(parameter_template, env=env) stk = stack.Stack(self.ctx, 'test', tmpl) p_snippet = {"Ref": "foo"} self.assertEqual("bar", self.resolve(p_snippet, tmpl, stk))
def test_find_in_map(self): tmpl = template.Template(mapping_template) stk = stack.Stack(self.ctx, 'test', tmpl) find = {'Fn::FindInMap': ["ValidMapping", "TestKey", "TestValue"]} self.assertEqual("wibble", self.resolve(find, tmpl, stk))
def test_stack_update_equals(self, ctr): stack_name = 'test_stack_update_equals_resource_limit' params = {} tpl = { 'HeatTemplateFormatVersion': '2012-12-12', 'Resources': { 'A': { 'Type': 'GenericResourceType' }, 'B': { 'Type': 'GenericResourceType' }, 'C': { 'Type': 'GenericResourceType' } } } template = templatem.Template(tpl) old_stack = stack.Stack(self.ctx, stack_name, template) sid = old_stack.store() old_stack.set_stack_user_project_id('1234') s = stack_object.Stack.get_by_id(self.ctx, sid) ctr.return_value = 3 stk = stack.Stack(self.ctx, stack_name, template) # prepare mocks mock_stack = self.patchobject(stack, 'Stack', return_value=stk) mock_load = self.patchobject(stack.Stack, 'load', return_value=old_stack) mock_tmpl = self.patchobject(templatem, 'Template', return_value=stk.t) mock_env = self.patchobject(environment, 'Environment', return_value=stk.env) mock_validate = self.patchobject(stk, 'validate', return_value=None) # do update cfg.CONF.set_override('max_resources_per_stack', 3) api_args = {'timeout_mins': 60} result = self.man.update_stack(self.ctx, old_stack.identifier(), template, params, None, api_args) # assertions self.assertEqual(old_stack.identifier(), result) self.assertIsInstance(result, dict) self.assertTrue(result['stack_id']) root_stack_id = old_stack.root_stack_id() self.assertEqual(3, old_stack.total_resources(root_stack_id)) mock_tmpl.assert_called_once_with(template, files=None, env=stk.env) mock_env.assert_called_once_with(params) mock_stack.assert_called_once_with( self.ctx, stk.name, stk.t, convergence=False, current_traversal=old_stack.current_traversal, prev_raw_template_id=None, current_deps=None, disable_rollback=True, nested_depth=0, owner_id=None, parent_resource=None, stack_user_project_id='1234', strict_validate=True, tenant_id='test_tenant_id', timeout_mins=60, user_creds_id=u'1', username='******') mock_load.assert_called_once_with(self.ctx, stack=s) mock_validate.assert_called_once_with()
def test_wait_metadata(self, mock_identifier, mock_sleep, mock_check, mock_handle, *args): """Tests a wait condition metadata update after a signal call.""" # Setup Stack temp = template_format.parse(TEST_TEMPLATE_WAIT_CONDITION) template = tmpl.Template(temp) ctx = utils.dummy_context() stack = stk.Stack(ctx, 'test-stack', template, disable_rollback=True) stack.store() self.stub_KeypairConstraint_validate() res_id = identifier.ResourceIdentifier('test_tenant_id', stack.name, stack.id, '', 'WH') mock_identifier.return_value = res_id watch = stack['WC'] inst = stack['S2'] # Setup Sleep Behavior self.run_empty = True def check_empty(sleep_time): self.assertEqual('{}', watch.FnGetAtt('Data')) self.assertIsNone(inst.metadata_get()['test']) def update_metadata(unique_id, data, reason): self.man.resource_signal(ctx, dict(stack.identifier()), 'WH', { 'Data': data, 'Reason': reason, 'Status': 'SUCCESS', 'UniqueId': unique_id }, sync_call=True) def post_success(sleep_time): update_metadata('123', 'foo', 'bar') def side_effect_popper(sleep_time): wh = stack['WH'] if wh.status == wh.IN_PROGRESS: return elif self.run_empty: self.run_empty = False check_empty(sleep_time) else: post_success(sleep_time) mock_sleep.side_effect = side_effect_popper # Test Initial Creation stack.create() self.assertEqual((stack.CREATE, stack.COMPLETE), stack.state) self.assertEqual('{"123": "foo"}', watch.FnGetAtt('Data')) self.assertEqual('{"123": "foo"}', inst.metadata_get()['test']) # Test Update update_metadata('456', 'blarg', 'wibble') self.assertEqual({ '123': 'foo', '456': 'blarg' }, jsonutils.loads(watch.FnGetAtt('Data'))) self.assertEqual('{"123": "foo"}', inst.metadata_get()['test']) self.assertEqual({ '123': 'foo', '456': 'blarg' }, jsonutils.loads(inst.metadata_get(refresh=True)['test'])) # Verify outgoing calls self.assertEqual(2, mock_handle.call_count) self.assertEqual(2, mock_check.call_count)