Merge "Fix json syntax in inline template"
diff --git a/functional/test_instance_group.py b/functional/test_instance_group.py
index 5de7ae1..9a79801 100644
--- a/functional/test_instance_group.py
+++ b/functional/test_instance_group.py
@@ -81,6 +81,33 @@
     value: {get_attr: [random1, value]}
 '''
 
+    # This is designed to fail.
+    bad_instance_template = '''
+heat_template_version: 2013-05-23
+parameters:
+  ImageId: {type: string}
+  InstanceType: {type: string}
+  KeyName: {type: string}
+  SecurityGroups: {type: comma_delimited_list}
+  UserData: {type: string}
+  Tags: {type: comma_delimited_list}
+
+resources:
+  random1:
+    type: OS::Heat::RandomString
+    depends_on: waiter
+  ready_poster:
+    type: AWS::CloudFormation::WaitConditionHandle
+  waiter:
+    type: AWS::CloudFormation::WaitCondition
+    properties:
+      Handle: {Ref: ready_poster}
+      Timeout: 1
+outputs:
+  PublicIp:
+    value: {get_attr: [random1, value]}
+'''
+
     def setUp(self):
         super(InstanceGroupTest, self).setUp()
         self.client = self.orchestration_client
@@ -95,6 +122,27 @@
         inst_list = self._stack_output(stack, 'InstanceList')
         self.assertEqual(expected_count, len(inst_list.split(',')))
 
+    def _get_nested_identifier(self, stack_identifier):
+        rsrc = self.client.resources.get(stack_identifier, 'JobServerGroup')
+        nested_link = [l for l in rsrc.links if l['rel'] == 'nested']
+        self.assertEqual(1, len(nested_link))
+        nested_href = nested_link[0]['href']
+        nested_id = nested_href.split('/')[-1]
+        nested_identifier = '/'.join(nested_href.split('/')[-2:])
+        physical_resource_id = rsrc.physical_resource_id
+        self.assertEqual(physical_resource_id, nested_id)
+        return nested_identifier
+
+    def _assert_instance_state(self, nested_identifier,
+                               num_complete, num_failed):
+        for res in self.client.resources.list(nested_identifier):
+            if 'COMPLETE' in res.resource_status:
+                num_complete = num_complete - 1
+            elif 'FAILED' in res.resource_status:
+                num_failed = num_failed - 1
+        self.assertEqual(0, num_failed)
+        self.assertEqual(0, num_complete)
+
     def test_basic_create_works(self):
         """Make sure the working case is good.
         Note this combines test_override_aws_ec2_instance into this test as
@@ -202,3 +250,78 @@
         # replacement will cause the resource physical_resource_id to change.
         rsrc = self.client.resources.get(stack_identifier, 'JobServerGroup')
         self.assertNotEqual(orig_asg_id, rsrc.physical_resource_id)
+
+    def test_create_instance_error_causes_group_error(self):
+        """If a resource in an instance group fails to be created, the instance
+        group itself will fail and the broken inner resource will remain.
+        """
+        stack_name = self._stack_rand_name()
+        files = {'provider.yaml': self.bad_instance_template}
+        env = {'resource_registry': {'AWS::EC2::Instance': 'provider.yaml'},
+               'parameters': {'size': 2,
+                              'image': self.conf.image_ref,
+                              'keyname': self.conf.keypair_name,
+                              'flavor': self.conf.instance_type}}
+
+        self.client.stacks.create(
+            stack_name=stack_name,
+            template=self.template,
+            files=files,
+            disable_rollback=True,
+            parameters={},
+            environment=env
+        )
+        self.addCleanup(self.client.stacks.delete, stack_name)
+        stack = self.client.stacks.get(stack_name)
+        stack_identifier = '%s/%s' % (stack_name, stack.id)
+        self._wait_for_stack_status(stack_identifier, 'CREATE_FAILED')
+        initial_resources = {
+            'JobServerConfig': 'AWS::AutoScaling::LaunchConfiguration',
+            'JobServerGroup': 'OS::Heat::InstanceGroup'}
+        self.assertEqual(initial_resources,
+                         self.list_resources(stack_identifier))
+
+        nested_ident = self._get_nested_identifier(stack_identifier)
+        self._assert_instance_state(nested_ident, 0, 2)
+
+    def test_update_instance_error_causes_group_error(self):
+        """If a resource in an instance group fails to be created during an
+        update, the instance group itself will fail and the broken inner
+        resource will remain.
+        """
+        files = {'provider.yaml': self.instance_template}
+        env = {'resource_registry': {'AWS::EC2::Instance': 'provider.yaml'},
+               'parameters': {'size': 2,
+                              'image': self.conf.image_ref,
+                              'keyname': self.conf.keypair_name,
+                              'flavor': self.conf.instance_type}}
+
+        stack_identifier = self.stack_create(template=self.template,
+                                             files=files,
+                                             environment=env)
+        initial_resources = {
+            'JobServerConfig': 'AWS::AutoScaling::LaunchConfiguration',
+            'JobServerGroup': 'OS::Heat::InstanceGroup'}
+        self.assertEqual(initial_resources,
+                         self.list_resources(stack_identifier))
+
+        stack = self.client.stacks.get(stack_identifier)
+        self.assert_instance_count(stack, 2)
+        nested_ident = self._get_nested_identifier(stack_identifier)
+        self._assert_instance_state(nested_ident, 2, 0)
+
+        env['parameters']['size'] = 3
+        files2 = {'provider.yaml': self.bad_instance_template}
+        self.client.stacks.update(
+            stack_id=stack_identifier,
+            template=self.template,
+            files=files2,
+            disable_rollback=True,
+            parameters={},
+            environment=env
+        )
+        self._wait_for_stack_status(stack_identifier, 'UPDATE_FAILED')
+
+        # assert that there are 3 bad instances
+        nested_ident = self._get_nested_identifier(stack_identifier)
+        self._assert_instance_state(nested_ident, 0, 3)
diff --git a/functional/test_resource_group.py b/functional/test_resource_group.py
new file mode 100644
index 0000000..afd9f55
--- /dev/null
+++ b/functional/test_resource_group.py
@@ -0,0 +1,92 @@
+#    Licensed under the Apache License, Version 2.0 (the "License"); you may
+#    not use this file except in compliance with the License. You may obtain
+#    a copy of the License at
+#
+#         http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+#    License for the specific language governing permissions and limitations
+#    under the License.
+
+import six
+
+from heatclient import exc
+
+from heat_integrationtests.common import test
+
+
+class ResourceGroupTest(test.HeatIntegrationTest):
+
+    def setUp(self):
+        super(ResourceGroupTest, self).setUp()
+        self.client = self.orchestration_client
+
+    def _group_nested_identifier(self, stack_identifier,
+                                 group_name='random_group'):
+        # Get the nested stack identifier from the group
+        rsrc = self.client.resources.get(stack_identifier, group_name)
+        physical_resource_id = rsrc.physical_resource_id
+
+        nested_stack = self.client.stacks.get(physical_resource_id)
+        nested_identifier = '%s/%s' % (nested_stack.stack_name,
+                                       nested_stack.id)
+        parent_id = stack_identifier.split("/")[-1]
+        self.assertEqual(parent_id, nested_stack.parent)
+        return nested_identifier
+
+    def test_resource_group_zero_novalidate(self):
+        # Nested resources should be validated only when size > 0
+        # This allows features to be disabled via size=0 without
+        # triggering validation of nested resource custom contraints
+        # e.g images etc in the nested schema.
+        nested_template_fail = '''
+heat_template_version: 2013-05-23
+resources:
+  random:
+    type: OS::Heat::RandomString
+    properties:
+        length: BAD
+'''
+
+        template_zero_nested = '''
+heat_template_version: 2013-05-23
+resources:
+  random_group:
+    type: OS::Heat::ResourceGroup
+    properties:
+      count: 0
+      resource_def:
+        type: My::RandomString
+'''
+
+        files = {'provider.yaml': nested_template_fail}
+        env = {'resource_registry':
+               {'My::RandomString': 'provider.yaml'}}
+        stack_identifier = self.stack_create(
+            template=template_zero_nested,
+            files=files,
+            environment=env
+        )
+
+        self.assertEqual({u'random_group': u'OS::Heat::ResourceGroup'},
+                         self.list_resources(stack_identifier))
+
+        # Check we created an empty nested stack
+        nested_identifier = self._group_nested_identifier(stack_identifier)
+        self.assertEqual({}, self.list_resources(nested_identifier))
+
+        # Prove validation works for non-zero create/update
+        template_two_nested = template_zero_nested.replace("count: 0",
+                                                           "count: 2")
+        expected_err = "length Value 'BAD' is not an integer"
+        ex = self.assertRaises(exc.HTTPBadRequest, self.update_stack,
+                               stack_identifier, template_two_nested,
+                               environment=env, files=files)
+        self.assertIn(expected_err, six.text_type(ex))
+
+        ex = self.assertRaises(exc.HTTPBadRequest, self.stack_create,
+                               template=template_two_nested,
+                               environment=env, files=files)
+        self.assertIn(expected_err, six.text_type(ex))