heat cleanups to align unit tests with pep8 1.3.4

Lots of (mostly whitespace) cleanups to align all the unit test code
with pep8 v1.3.4

ref bug 1092057

Change-Id: I5c847f20b3516af3dd3d7211b0fc697c59bf914c
Signed-off-by: Steven Hardy <shardy@redhat.com>
This commit is contained in:
Steven Hardy 2012-12-19 17:23:05 +00:00
parent 1a4decc02f
commit 7ebef0b9dc
27 changed files with 1096 additions and 1152 deletions

View File

@ -30,7 +30,7 @@ def assert_has_keys(dict, required=[], optional=[]):
except AssertionError: except AssertionError:
extra_keys = set(keys).difference(set(required + optional)) extra_keys = set(keys).difference(set(required + optional))
raise AssertionError("found unexpected keys: %s" % raise AssertionError("found unexpected keys: %s" %
list(extra_keys)) list(extra_keys))
class FakeClient(object): class FakeClient(object):
@ -43,10 +43,10 @@ class FakeClient(object):
called = self.client.callstack[pos][0:2] called = self.client.callstack[pos][0:2]
assert self.client.callstack, \ assert self.client.callstack, \
"Expected %s %s but no calls were made." % expected "Expected %s %s but no calls were made." % expected
assert expected == called, 'Expected %s %s; got %s %s' % \ assert expected == called, 'Expected %s %s; got %s %s' % \
(expected + called) (expected + called)
if body is not None: if body is not None:
assert self.client.callstack[pos][2] == body assert self.client.callstack[pos][2] == body
@ -58,7 +58,7 @@ class FakeClient(object):
expected = (method, url) expected = (method, url)
assert self.client.callstack, \ assert self.client.callstack, \
"Expected %s %s but no calls were made." % expected "Expected %s %s but no calls were made." % expected
found = False found = False
for entry in self.client.callstack: for entry in self.client.callstack:
@ -67,7 +67,7 @@ class FakeClient(object):
break break
assert found, 'Expected %s %s; got %s' % \ assert found, 'Expected %s %s; got %s' % \
(expected, self.client.callstack) (expected, self.client.callstack)
if body is not None: if body is not None:
try: try:
assert entry[2] == body assert entry[2] == body

View File

@ -37,8 +37,8 @@ class AWSCommon(unittest.TestCase):
'Parameters.member.2.ParameterKey': 'blarg', 'Parameters.member.2.ParameterKey': 'blarg',
'Parameters.member.2.ParameterValue': 'wibble'} 'Parameters.member.2.ParameterValue': 'wibble'}
params = api_utils.extract_param_pairs(p, prefix='Parameters', params = api_utils.extract_param_pairs(p, prefix='Parameters',
keyname='ParameterKey', keyname='ParameterKey',
valuename='ParameterValue') valuename='ParameterValue')
self.assertEqual(len(params), 2) self.assertEqual(len(params), 2)
self.assertTrue('foo' in params) self.assertTrue('foo' in params)
self.assertEqual(params['foo'], 'bar') self.assertEqual(params['foo'], 'bar')
@ -51,8 +51,8 @@ class AWSCommon(unittest.TestCase):
'Parameters.member.2.1.ParameterKey': 'blarg', 'Parameters.member.2.1.ParameterKey': 'blarg',
'Parameters.member.2.1.ParameterValue': 'wibble'} 'Parameters.member.2.1.ParameterValue': 'wibble'}
params = api_utils.extract_param_pairs(p, prefix='Parameters', params = api_utils.extract_param_pairs(p, prefix='Parameters',
keyname='ParameterKey', keyname='ParameterKey',
valuename='ParameterValue') valuename='ParameterValue')
self.assertFalse(params) self.assertFalse(params)
def test_params_extract_garbage(self): def test_params_extract_garbage(self):
@ -61,8 +61,8 @@ class AWSCommon(unittest.TestCase):
'Foo.1.ParameterKey': 'blarg', 'Foo.1.ParameterKey': 'blarg',
'Foo.1.ParameterValue': 'wibble'} 'Foo.1.ParameterValue': 'wibble'}
params = api_utils.extract_param_pairs(p, prefix='Parameters', params = api_utils.extract_param_pairs(p, prefix='Parameters',
keyname='ParameterKey', keyname='ParameterKey',
valuename='ParameterValue') valuename='ParameterValue')
self.assertEqual(len(params), 1) self.assertEqual(len(params), 1)
self.assertTrue('foo' in params) self.assertTrue('foo' in params)
self.assertEqual(params['foo'], 'bar') self.assertEqual(params['foo'], 'bar')
@ -71,22 +71,22 @@ class AWSCommon(unittest.TestCase):
p = {'prefixParameters.member.Foo.Bar.ParameterKey': 'foo', p = {'prefixParameters.member.Foo.Bar.ParameterKey': 'foo',
'Parameters.member.Foo.Bar.ParameterValue': 'bar'} 'Parameters.member.Foo.Bar.ParameterValue': 'bar'}
params = api_utils.extract_param_pairs(p, prefix='Parameters', params = api_utils.extract_param_pairs(p, prefix='Parameters',
keyname='ParameterKey', keyname='ParameterKey',
valuename='ParameterValue') valuename='ParameterValue')
self.assertFalse(params) self.assertFalse(params)
def test_params_extract_garbage_suffix(self): def test_params_extract_garbage_suffix(self):
p = {'Parameters.member.1.ParameterKeysuffix': 'foo', p = {'Parameters.member.1.ParameterKeysuffix': 'foo',
'Parameters.member.1.ParameterValue': 'bar'} 'Parameters.member.1.ParameterValue': 'bar'}
params = api_utils.extract_param_pairs(p, prefix='Parameters', params = api_utils.extract_param_pairs(p, prefix='Parameters',
keyname='ParameterKey', keyname='ParameterKey',
valuename='ParameterValue') valuename='ParameterValue')
self.assertFalse(params) self.assertFalse(params)
def test_extract_param_list(self): def test_extract_param_list(self):
p = {'MetricData.member.1.MetricName': 'foo', p = {'MetricData.member.1.MetricName': 'foo',
'MetricData.member.1.Unit': 'Bytes', 'MetricData.member.1.Unit': 'Bytes',
'MetricData.member.1.Value': 234333} 'MetricData.member.1.Value': 234333}
params = api_utils.extract_param_list(p, prefix='MetricData') params = api_utils.extract_param_list(p, prefix='MetricData')
self.assertEqual(len(params), 1) self.assertEqual(len(params), 1)
self.assertTrue('MetricName' in params[0]) self.assertTrue('MetricName' in params[0])
@ -98,8 +98,8 @@ class AWSCommon(unittest.TestCase):
def test_extract_param_list_garbage_prefix(self): def test_extract_param_list_garbage_prefix(self):
p = {'AMetricData.member.1.MetricName': 'foo', p = {'AMetricData.member.1.MetricName': 'foo',
'MetricData.member.1.Unit': 'Bytes', 'MetricData.member.1.Unit': 'Bytes',
'MetricData.member.1.Value': 234333} 'MetricData.member.1.Value': 234333}
params = api_utils.extract_param_list(p, prefix='MetricData') params = api_utils.extract_param_list(p, prefix='MetricData')
self.assertEqual(len(params), 1) self.assertEqual(len(params), 1)
self.assertTrue('MetricName' not in params[0]) self.assertTrue('MetricName' not in params[0])
@ -110,15 +110,15 @@ class AWSCommon(unittest.TestCase):
def test_extract_param_list_garbage_prefix2(self): def test_extract_param_list_garbage_prefix2(self):
p = {'AMetricData.member.1.MetricName': 'foo', p = {'AMetricData.member.1.MetricName': 'foo',
'BMetricData.member.1.Unit': 'Bytes', 'BMetricData.member.1.Unit': 'Bytes',
'CMetricData.member.1.Value': 234333} 'CMetricData.member.1.Value': 234333}
params = api_utils.extract_param_list(p, prefix='MetricData') params = api_utils.extract_param_list(p, prefix='MetricData')
self.assertEqual(len(params), 0) self.assertEqual(len(params), 0)
def test_extract_param_list_garbage_suffix(self): def test_extract_param_list_garbage_suffix(self):
p = {'MetricData.member.1.AMetricName': 'foo', p = {'MetricData.member.1.AMetricName': 'foo',
'MetricData.member.1.Unit': 'Bytes', 'MetricData.member.1.Unit': 'Bytes',
'MetricData.member.1.Value': 234333} 'MetricData.member.1.Value': 234333}
params = api_utils.extract_param_list(p, prefix='MetricData') params = api_utils.extract_param_list(p, prefix='MetricData')
self.assertEqual(len(params), 1) self.assertEqual(len(params), 1)
self.assertTrue('MetricName' not in params[0]) self.assertTrue('MetricName' not in params[0])
@ -129,11 +129,11 @@ class AWSCommon(unittest.TestCase):
def test_extract_param_list_multiple(self): def test_extract_param_list_multiple(self):
p = {'MetricData.member.1.MetricName': 'foo', p = {'MetricData.member.1.MetricName': 'foo',
'MetricData.member.1.Unit': 'Bytes', 'MetricData.member.1.Unit': 'Bytes',
'MetricData.member.1.Value': 234333, 'MetricData.member.1.Value': 234333,
'MetricData.member.2.MetricName': 'foo2', 'MetricData.member.2.MetricName': 'foo2',
'MetricData.member.2.Unit': 'Bytes', 'MetricData.member.2.Unit': 'Bytes',
'MetricData.member.2.Value': 12345} 'MetricData.member.2.Value': 12345}
params = api_utils.extract_param_list(p, prefix='MetricData') params = api_utils.extract_param_list(p, prefix='MetricData')
self.assertEqual(len(params), 2) self.assertEqual(len(params), 2)
self.assertTrue('MetricName' in params[0]) self.assertTrue('MetricName' in params[0])
@ -148,11 +148,11 @@ class AWSCommon(unittest.TestCase):
def test_extract_param_list_multiple_missing(self): def test_extract_param_list_multiple_missing(self):
# Handle case where there is an empty list item # Handle case where there is an empty list item
p = {'MetricData.member.1.MetricName': 'foo', p = {'MetricData.member.1.MetricName': 'foo',
'MetricData.member.1.Unit': 'Bytes', 'MetricData.member.1.Unit': 'Bytes',
'MetricData.member.1.Value': 234333, 'MetricData.member.1.Value': 234333,
'MetricData.member.3.MetricName': 'foo2', 'MetricData.member.3.MetricName': 'foo2',
'MetricData.member.3.Unit': 'Bytes', 'MetricData.member.3.Unit': 'Bytes',
'MetricData.member.3.Value': 12345} 'MetricData.member.3.Value': 12345}
params = api_utils.extract_param_list(p, prefix='MetricData') params = api_utils.extract_param_list(p, prefix='MetricData')
self.assertEqual(len(params), 2) self.assertEqual(len(params), 2)
self.assertTrue('MetricName' in params[0]) self.assertTrue('MetricName' in params[0])
@ -166,11 +166,11 @@ class AWSCommon(unittest.TestCase):
def test_extract_param_list_badindex(self): def test_extract_param_list_badindex(self):
p = {'MetricData.member.xyz.MetricName': 'foo', p = {'MetricData.member.xyz.MetricName': 'foo',
'MetricData.member.$!&^.Unit': 'Bytes', 'MetricData.member.$!&^.Unit': 'Bytes',
'MetricData.member.+.Value': 234333, 'MetricData.member.+.Value': 234333,
'MetricData.member.--.MetricName': 'foo2', 'MetricData.member.--.MetricName': 'foo2',
'MetricData.member._3.Unit': 'Bytes', 'MetricData.member._3.Unit': 'Bytes',
'MetricData.member.-1000.Value': 12345} 'MetricData.member.-1000.Value': 12345}
params = api_utils.extract_param_list(p, prefix='MetricData') params = api_utils.extract_param_list(p, prefix='MetricData')
self.assertEqual(len(params), 0) self.assertEqual(len(params), 0)

View File

@ -78,10 +78,10 @@ class StackControllerTest(unittest.TestCase):
# Stub out the RPC call to the engine with a pre-canned response # Stub out the RPC call to the engine with a pre-canned response
engine_resp = {u'stacks': [ engine_resp = {u'stacks': [
{u'stack_identity': {u'tenant': u't', {u'stack_identity': {u'tenant': u't',
u'stack_name': u'wordpress', u'stack_name': u'wordpress',
u'stack_id': u'1', u'stack_id': u'1',
u'path': u''}, u'path': u''},
u'updated_time': u'2012-07-09T09:13:11Z', u'updated_time': u'2012-07-09T09:13:11Z',
u'template_description': u'blah', u'template_description': u'blah',
u'stack_status_reason': u'Stack successfully created', u'stack_status_reason': u'Stack successfully created',
@ -89,23 +89,25 @@ class StackControllerTest(unittest.TestCase):
u'stack_name': u'wordpress', u'stack_name': u'wordpress',
u'stack_status': u'CREATE_COMPLETE'}]} u'stack_status': u'CREATE_COMPLETE'}]}
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'list_stacks', rpc.call(dummy_req.context, self.topic,
'args': {}, {'method': 'list_stacks',
'version': self.api_version}, None 'args': {},
).AndReturn(engine_resp) 'version': self.api_version},
None).AndReturn(engine_resp)
self.m.ReplayAll() self.m.ReplayAll()
# Call the list controller function and compare the response # Call the list controller function and compare the response
result = self.controller.list(dummy_req) result = self.controller.list(dummy_req)
expected = {'ListStacksResponse': {'ListStacksResult': expected = {'ListStacksResponse': {'ListStacksResult':
{'StackSummaries': [ {'StackSummaries':
{u'StackId': u'arn:openstack:heat::t:stacks/wordpress/1', [{u'StackId': u'arn:openstack:heat::t:stacks/wordpress/1',
u'LastUpdatedTime': u'2012-07-09T09:13:11Z', u'LastUpdatedTime': u'2012-07-09T09:13:11Z',
u'TemplateDescription': u'blah', u'TemplateDescription': u'blah',
u'StackStatusReason': u'Stack successfully created', u'StackStatusReason': u'Stack successfully created',
u'CreationTime': u'2012-07-09T09:12:45Z', u'CreationTime': u'2012-07-09T09:12:45Z',
u'StackName': u'wordpress', u'StackStatus': u'CREATE_COMPLETE'}]}}} u'StackName': u'wordpress',
u'StackStatus': u'CREATE_COMPLETE'}]}}}
self.assertEqual(result, expected) self.assertEqual(result, expected)
def test_list_rmt_aterr(self): def test_list_rmt_aterr(self):
@ -115,10 +117,11 @@ class StackControllerTest(unittest.TestCase):
# Insert an engine RPC error and ensure we map correctly to the # Insert an engine RPC error and ensure we map correctly to the
# heat exception type # heat exception type
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'list_stacks', rpc.call(dummy_req.context, self.topic,
'args': {}, {'method': 'list_stacks',
'version': self.api_version}, None 'args': {},
).AndRaise(rpc_common.RemoteError("AttributeError")) 'version': self.api_version},
None).AndRaise(rpc_common.RemoteError("AttributeError"))
self.m.ReplayAll() self.m.ReplayAll()
@ -134,10 +137,11 @@ class StackControllerTest(unittest.TestCase):
# Insert an engine RPC error and ensure we map correctly to the # Insert an engine RPC error and ensure we map correctly to the
# heat exception type # heat exception type
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'list_stacks', rpc.call(dummy_req.context, self.topic,
'args': {}, {'method': 'list_stacks',
'version': self.api_version}, None 'args': {},
).AndRaise(rpc_common.RemoteError("Exception")) 'version': self.api_version},
None).AndRaise(rpc_common.RemoteError("Exception"))
self.m.ReplayAll() self.m.ReplayAll()
@ -155,76 +159,79 @@ class StackControllerTest(unittest.TestCase):
# Stub out the RPC call to the engine with a pre-canned response # Stub out the RPC call to the engine with a pre-canned response
# Note the engine returns a load of keys we don't actually use # Note the engine returns a load of keys we don't actually use
# so this is a subset of the real response format # so this is a subset of the real response format
engine_resp = {u'stacks': [ engine_resp = {u'stacks':
{u'stack_identity': {u'tenant': u't', [{u'stack_identity':
u'stack_name': u'wordpress', {u'tenant': u't',
u'stack_id': u'6', u'stack_name': u'wordpress',
u'path': u''}, u'stack_id': u'6',
u'updated_time': u'2012-07-09T09:13:11Z', u'path': u''},
u'parameters':{ u'updated_time': u'2012-07-09T09:13:11Z',
u'DBUsername': u'admin', u'parameters': {u'DBUsername': u'admin',
u'LinuxDistribution': u'F17', u'LinuxDistribution': u'F17',
u'InstanceType': u'm1.large', u'InstanceType': u'm1.large',
u'DBRootPassword': u'admin', u'DBRootPassword': u'admin',
u'DBPassword': u'admin', u'DBPassword': u'admin',
u'DBName': u'wordpress'}, u'DBName': u'wordpress'},
u'outputs': u'outputs':
[{u'output_key': u'WebsiteURL', [{u'output_key': u'WebsiteURL',
u'description': u'URL for Wordpress wiki', u'description': u'URL for Wordpress wiki',
u'output_value': u'http://10.0.0.8/wordpress'}], u'output_value': u'http://10.0.0.8/wordpress'}],
u'stack_status_reason': u'Stack successfully created', u'stack_status_reason': u'Stack successfully created',
u'creation_time': u'2012-07-09T09:12:45Z', u'creation_time': u'2012-07-09T09:12:45Z',
u'stack_name': u'wordpress', u'stack_name': u'wordpress',
u'notification_topics': [], u'notification_topics': [],
u'stack_status': u'CREATE_COMPLETE', u'stack_status': u'CREATE_COMPLETE',
u'description': u'blah', u'description': u'blah',
u'disable_rollback': True, u'disable_rollback': True,
u'timeout_mins':60, u'timeout_mins':60,
u'capabilities':[]}]} u'capabilities':[]}]}
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'identify_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_name': stack_name}, {'method': 'identify_stack',
'version': self.api_version}, None).AndReturn(identity) 'args': {'stack_name': stack_name},
rpc.call(dummy_req.context, self.topic, {'method': 'show_stack', 'version': self.api_version}, None).AndReturn(identity)
'args': {'stack_identity': identity}, rpc.call(dummy_req.context, self.topic,
'version': self.api_version}, None).AndReturn(engine_resp) {'method': 'show_stack',
'args': {'stack_identity': identity},
'version': self.api_version}, None).AndReturn(engine_resp)
self.m.ReplayAll() self.m.ReplayAll()
# Call the list controller function and compare the response # Call the list controller function and compare the response
response = self.controller.describe(dummy_req) response = self.controller.describe(dummy_req)
expected = {'DescribeStacksResponse': {'DescribeStacksResult': expected = {'DescribeStacksResponse':
{'Stacks': {'DescribeStacksResult':
[{'StackId': u'arn:openstack:heat::t:stacks/wordpress/6', {'Stacks':
'StackStatusReason': u'Stack successfully created', [{'StackId': u'arn:openstack:heat::t:stacks/wordpress/6',
'Description': u'blah', 'StackStatusReason': u'Stack successfully created',
'Parameters': 'Description': u'blah',
[{'ParameterValue': u'admin', 'Parameters':
'ParameterKey': u'DBUsername'}, [{'ParameterValue': u'admin',
{'ParameterValue': u'F17', 'ParameterKey': u'DBUsername'},
'ParameterKey': u'LinuxDistribution'}, {'ParameterValue': u'F17',
{'ParameterValue': u'm1.large', 'ParameterKey': u'LinuxDistribution'},
'ParameterKey': u'InstanceType'}, {'ParameterValue': u'm1.large',
{'ParameterValue': u'admin', 'ParameterKey': u'InstanceType'},
'ParameterKey': u'DBRootPassword'}, {'ParameterValue': u'admin',
{'ParameterValue': u'admin', 'ParameterKey': u'DBRootPassword'},
'ParameterKey': u'DBPassword'}, {'ParameterValue': u'admin',
{'ParameterValue': u'wordpress', 'ParameterKey': u'DBPassword'},
'ParameterKey': u'DBName'}], {'ParameterValue': u'wordpress',
'Outputs': 'ParameterKey': u'DBName'}],
[{'OutputKey': u'WebsiteURL', 'Outputs':
'OutputValue': u'http://10.0.0.8/wordpress', [{'OutputKey': u'WebsiteURL',
'Description': u'URL for Wordpress wiki'}], 'OutputValue': u'http://10.0.0.8/wordpress',
'TimeoutInMinutes': 60, 'Description': u'URL for Wordpress wiki'}],
'CreationTime': u'2012-07-09T09:12:45Z', 'TimeoutInMinutes': 60,
'Capabilities': [], 'CreationTime': u'2012-07-09T09:12:45Z',
'StackName': u'wordpress', 'Capabilities': [],
'NotificationARNs': [], 'StackName': u'wordpress',
'StackStatus': u'CREATE_COMPLETE', 'NotificationARNs': [],
'DisableRollback': True, 'StackStatus': u'CREATE_COMPLETE',
'LastUpdatedTime': u'2012-07-09T09:13:11Z'}]}}} 'DisableRollback': True,
'LastUpdatedTime': u'2012-07-09T09:13:11Z'}]}}}
self.assertEqual(response, expected) self.assertEqual(response, expected)
@ -240,73 +247,74 @@ class StackControllerTest(unittest.TestCase):
# Stub out the RPC call to the engine with a pre-canned response # Stub out the RPC call to the engine with a pre-canned response
# Note the engine returns a load of keys we don't actually use # Note the engine returns a load of keys we don't actually use
# so this is a subset of the real response format # so this is a subset of the real response format
engine_resp = {u'stacks': [ engine_resp = {u'stacks':
{u'stack_identity': {u'tenant': u't', [{u'stack_identity': {u'tenant': u't',
u'stack_name': u'wordpress', u'stack_name': u'wordpress',
u'stack_id': u'6', u'stack_id': u'6',
u'path': u''}, u'path': u''},
u'updated_time': u'2012-07-09T09:13:11Z', u'updated_time': u'2012-07-09T09:13:11Z',
u'parameters':{ u'parameters': {u'DBUsername': u'admin',
u'DBUsername': u'admin', u'LinuxDistribution': u'F17',
u'LinuxDistribution': u'F17', u'InstanceType': u'm1.large',
u'InstanceType': u'm1.large', u'DBRootPassword': u'admin',
u'DBRootPassword': u'admin', u'DBPassword': u'admin',
u'DBPassword': u'admin', u'DBName': u'wordpress'},
u'DBName': u'wordpress'}, u'outputs':
u'outputs': [{u'output_key': u'WebsiteURL',
[{u'output_key': u'WebsiteURL', u'description': u'URL for Wordpress wiki',
u'description': u'URL for Wordpress wiki', u'output_value': u'http://10.0.0.8/wordpress'}],
u'output_value': u'http://10.0.0.8/wordpress'}], u'stack_status_reason': u'Stack successfully created',
u'stack_status_reason': u'Stack successfully created', u'creation_time': u'2012-07-09T09:12:45Z',
u'creation_time': u'2012-07-09T09:12:45Z', u'stack_name': u'wordpress',
u'stack_name': u'wordpress', u'notification_topics': [],
u'notification_topics': [], u'stack_status': u'CREATE_COMPLETE',
u'stack_status': u'CREATE_COMPLETE', u'description': u'blah',
u'description': u'blah', u'disable_rollback': True,
u'disable_rollback': True, u'timeout_mins':60,
u'timeout_mins':60, u'capabilities':[]}]}
u'capabilities':[]}]}
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'show_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_identity': identity}, {'method': 'show_stack',
'version': self.api_version}, None).AndReturn(engine_resp) 'args': {'stack_identity': identity},
'version': self.api_version}, None).AndReturn(engine_resp)
self.m.ReplayAll() self.m.ReplayAll()
# Call the list controller function and compare the response # Call the list controller function and compare the response
response = self.controller.describe(dummy_req) response = self.controller.describe(dummy_req)
expected = {'DescribeStacksResponse': {'DescribeStacksResult': expected = {'DescribeStacksResponse':
{'Stacks': {'DescribeStacksResult':
[{'StackId': u'arn:openstack:heat::t:stacks/wordpress/6', {'Stacks':
'StackStatusReason': u'Stack successfully created', [{'StackId': u'arn:openstack:heat::t:stacks/wordpress/6',
'Description': u'blah', 'StackStatusReason': u'Stack successfully created',
'Parameters': 'Description': u'blah',
[{'ParameterValue': u'admin', 'Parameters':
'ParameterKey': u'DBUsername'}, [{'ParameterValue': u'admin',
{'ParameterValue': u'F17', 'ParameterKey': u'DBUsername'},
'ParameterKey': u'LinuxDistribution'}, {'ParameterValue': u'F17',
{'ParameterValue': u'm1.large', 'ParameterKey': u'LinuxDistribution'},
'ParameterKey': u'InstanceType'}, {'ParameterValue': u'm1.large',
{'ParameterValue': u'admin', 'ParameterKey': u'InstanceType'},
'ParameterKey': u'DBRootPassword'}, {'ParameterValue': u'admin',
{'ParameterValue': u'admin', 'ParameterKey': u'DBRootPassword'},
'ParameterKey': u'DBPassword'}, {'ParameterValue': u'admin',
{'ParameterValue': u'wordpress', 'ParameterKey': u'DBPassword'},
'ParameterKey': u'DBName'}], {'ParameterValue': u'wordpress',
'Outputs': 'ParameterKey': u'DBName'}],
[{'OutputKey': u'WebsiteURL', 'Outputs':
'OutputValue': u'http://10.0.0.8/wordpress', [{'OutputKey': u'WebsiteURL',
'Description': u'URL for Wordpress wiki'}], 'OutputValue': u'http://10.0.0.8/wordpress',
'TimeoutInMinutes': 60, 'Description': u'URL for Wordpress wiki'}],
'CreationTime': u'2012-07-09T09:12:45Z', 'TimeoutInMinutes': 60,
'Capabilities': [], 'CreationTime': u'2012-07-09T09:12:45Z',
'StackName': u'wordpress', 'Capabilities': [],
'NotificationARNs': [], 'StackName': u'wordpress',
'StackStatus': u'CREATE_COMPLETE', 'NotificationARNs': [],
'DisableRollback': True, 'StackStatus': u'CREATE_COMPLETE',
'LastUpdatedTime': u'2012-07-09T09:13:11Z'}]}}} 'DisableRollback': True,
'LastUpdatedTime': u'2012-07-09T09:13:11Z'}]}}}
self.assertEqual(response, expected) self.assertEqual(response, expected)
@ -319,13 +327,15 @@ class StackControllerTest(unittest.TestCase):
# Insert an engine RPC error and ensure we map correctly to the # Insert an engine RPC error and ensure we map correctly to the
# heat exception type # heat exception type
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'identify_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_name': stack_name}, {'method': 'identify_stack',
'version': self.api_version}, None).AndReturn(identity) 'args': {'stack_name': stack_name},
rpc.call(dummy_req.context, self.topic, {'method': 'show_stack', 'version': self.api_version}, None).AndReturn(identity)
'args': {'stack_identity': identity}, rpc.call(dummy_req.context, self.topic,
'version': self.api_version}, None {'method': 'show_stack',
).AndRaise(rpc_common.RemoteError("AttributeError")) 'args': {'stack_identity': identity},
'version': self.api_version}, None
).AndRaise(rpc_common.RemoteError("AttributeError"))
self.m.ReplayAll() self.m.ReplayAll()
@ -341,10 +351,11 @@ class StackControllerTest(unittest.TestCase):
# Insert an engine RPC error and ensure we map correctly to the # Insert an engine RPC error and ensure we map correctly to the
# heat exception type # heat exception type
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'identify_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_name': stack_name}, {'method': 'identify_stack',
'version': self.api_version}, None 'args': {'stack_name': stack_name},
).AndRaise(rpc_common.RemoteError("AttributeError")) 'version': self.api_version}, None
).AndRaise(rpc_common.RemoteError("AttributeError"))
self.m.ReplayAll() self.m.ReplayAll()
@ -383,13 +394,13 @@ class StackControllerTest(unittest.TestCase):
u'path': u''} u'path': u''}
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'create_stack', rpc.call(dummy_req.context, self.topic,
'args': {'method': 'create_stack',
{'stack_name': stack_name, 'args': {'stack_name': stack_name,
'template': template, 'template': template,
'params': engine_parms, 'params': engine_parms,
'args': engine_args}, 'args': engine_args},
'version': self.api_version}, None).AndReturn(engine_resp) 'version': self.api_version}, None).AndReturn(engine_resp)
self.m.ReplayAll() self.m.ReplayAll()
@ -444,14 +455,14 @@ class StackControllerTest(unittest.TestCase):
# heat exception type # heat exception type
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'create_stack', rpc.call(dummy_req.context, self.topic,
'args': {'method': 'create_stack',
{'stack_name': stack_name, 'args': {'stack_name': stack_name,
'template': template, 'template': template,
'params': engine_parms, 'params': engine_parms,
'args': engine_args}, 'args': engine_args},
'version': self.api_version}, None 'version': self.api_version}, None
).AndRaise(rpc_common.RemoteError("AttributeError")) ).AndRaise(rpc_common.RemoteError("AttributeError"))
self.m.ReplayAll() self.m.ReplayAll()
@ -478,14 +489,13 @@ class StackControllerTest(unittest.TestCase):
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
engine_err = {'Description': 'Something went wrong'} engine_err = {'Description': 'Something went wrong'}
rpc.call(dummy_req.context, self.topic, {'method': 'create_stack', rpc.call(dummy_req.context, self.topic,
'args': {'method': 'create_stack',
{'stack_name': stack_name, 'args': {'stack_name': stack_name,
'template': template, 'template': template,
'params': engine_parms, 'params': engine_parms,
'args': engine_args}, 'args': engine_args},
'version': self.api_version}, None 'version': self.api_version}, None).AndReturn(engine_err)
).AndReturn(engine_err)
self.m.ReplayAll() self.m.ReplayAll()
@ -512,17 +522,19 @@ class StackControllerTest(unittest.TestCase):
identity = dict(identifier.HeatIdentifier('t', stack_name, '1')) identity = dict(identifier.HeatIdentifier('t', stack_name, '1'))
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'identify_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_name': stack_name}, {'method': 'identify_stack',
'version': self.api_version}, None).AndReturn(identity) 'args': {'stack_name': stack_name},
'version': self.api_version}, None).AndReturn(identity)
rpc.call(dummy_req.context, self.topic, {'method': 'update_stack', rpc.call(dummy_req.context, self.topic,
'args': {'method': 'update_stack',
{'stack_identity': identity, 'args': {'stack_identity': identity,
'template': template, 'template': template,
'params': engine_parms, 'params': engine_parms,
'args': engine_args}, 'args': engine_args},
'version': self.api_version}, None).AndReturn(identity) 'version': self.api_version},
None).AndReturn(identity)
self.m.ReplayAll() self.m.ReplayAll()
@ -551,10 +563,11 @@ class StackControllerTest(unittest.TestCase):
# Insert an engine RPC error and ensure we map correctly to the # Insert an engine RPC error and ensure we map correctly to the
# heat exception type # heat exception type
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'identify_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_name': stack_name}, {'method': 'identify_stack',
'version': self.api_version}, None 'args': {'stack_name': stack_name},
).AndRaise(rpc_common.RemoteError("AttributeError")) 'version': self.api_version}, None
).AndRaise(rpc_common.RemoteError("AttributeError"))
self.m.ReplayAll() self.m.ReplayAll()
@ -578,20 +591,22 @@ class StackControllerTest(unittest.TestCase):
engine_resp = template engine_resp = template
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'identify_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_name': stack_name}, {'method': 'identify_stack',
'version': self.api_version}, None).AndReturn(identity) 'args': {'stack_name': stack_name},
rpc.call(dummy_req.context, self.topic, {'method': 'get_template', 'version': self.api_version}, None).AndReturn(identity)
'args': rpc.call(dummy_req.context, self.topic,
{'stack_identity': identity}, {'method': 'get_template',
'version': self.api_version}, None).AndReturn(engine_resp) 'args': {'stack_identity': identity},
'version': self.api_version}, None).AndReturn(engine_resp)
self.m.ReplayAll() self.m.ReplayAll()
response = self.controller.get_template(dummy_req) response = self.controller.get_template(dummy_req)
expected = {'GetTemplateResponse': {'GetTemplateResult': expected = {'GetTemplateResponse':
{'TemplateBody': template}}} {'GetTemplateResult':
{'TemplateBody': template}}}
self.assertEqual(response, expected) self.assertEqual(response, expected)
@ -605,14 +620,15 @@ class StackControllerTest(unittest.TestCase):
# Insert an engine RPC error and ensure we map correctly to the # Insert an engine RPC error and ensure we map correctly to the
# heat exception type # heat exception type
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'identify_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_name': stack_name}, {'method': 'identify_stack',
'version': self.api_version}, None).AndReturn(identity) 'args': {'stack_name': stack_name},
rpc.call(dummy_req.context, self.topic, {'method': 'get_template', 'version': self.api_version}, None).AndReturn(identity)
'args': rpc.call(dummy_req.context, self.topic,
{'stack_identity': identity}, {'method': 'get_template',
'version': self.api_version}, None 'args': {'stack_identity': identity},
).AndRaise(rpc_common.RemoteError("AttributeError")) 'version': self.api_version}, None
).AndRaise(rpc_common.RemoteError("AttributeError"))
self.m.ReplayAll() self.m.ReplayAll()
@ -629,10 +645,11 @@ class StackControllerTest(unittest.TestCase):
# Insert an engine RPC error and ensure we map correctly to the # Insert an engine RPC error and ensure we map correctly to the
# heat exception type # heat exception type
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'identify_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_name': stack_name}, {'method': 'identify_stack',
'version': self.api_version}, None 'args': {'stack_name': stack_name},
).AndRaise(rpc_common.RemoteError("AttributeError")) 'version': self.api_version}, None
).AndRaise(rpc_common.RemoteError("AttributeError"))
self.m.ReplayAll() self.m.ReplayAll()
@ -652,13 +669,14 @@ class StackControllerTest(unittest.TestCase):
engine_resp = None engine_resp = None
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'identify_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_name': stack_name}, {'method': 'identify_stack',
'version': self.api_version}, None).AndReturn(identity) 'args': {'stack_name': stack_name},
rpc.call(dummy_req.context, self.topic, {'method': 'get_template', 'version': self.api_version}, None).AndReturn(identity)
'args': rpc.call(dummy_req.context, self.topic,
{'stack_identity': identity}, {'method': 'get_template',
'version': self.api_version}, None).AndReturn(engine_resp) 'args': {'stack_identity': identity},
'version': self.api_version}, None).AndReturn(engine_resp)
self.m.ReplayAll() self.m.ReplayAll()
@ -696,13 +714,15 @@ class StackControllerTest(unittest.TestCase):
# Stub out the RPC call to the engine with a pre-canned response # Stub out the RPC call to the engine with a pre-canned response
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'identify_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_name': stack_name}, {'method': 'identify_stack',
'version': self.api_version}, None).AndReturn(identity) 'args': {'stack_name': stack_name},
'version': self.api_version}, None).AndReturn(identity)
# Engine returns None when delete successful # Engine returns None when delete successful
rpc.call(dummy_req.context, self.topic, {'method': 'delete_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_identity': identity}, {'method': 'delete_stack',
'version': self.api_version}, None).AndReturn(None) 'args': {'stack_identity': identity},
'version': self.api_version}, None).AndReturn(None)
self.m.ReplayAll() self.m.ReplayAll()
@ -720,16 +740,18 @@ class StackControllerTest(unittest.TestCase):
# Stub out the RPC call to the engine with a pre-canned response # Stub out the RPC call to the engine with a pre-canned response
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'identify_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_name': stack_name}, {'method': 'identify_stack',
'version': self.api_version}, None).AndReturn(identity) 'args': {'stack_name': stack_name},
'version': self.api_version}, None).AndReturn(identity)
# Insert an engine RPC error and ensure we map correctly to the # Insert an engine RPC error and ensure we map correctly to the
# heat exception type # heat exception type
rpc.call(dummy_req.context, self.topic, {'method': 'delete_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_identity': identity}, {'method': 'delete_stack',
'version': self.api_version}, None 'args': {'stack_identity': identity},
).AndRaise(rpc_common.RemoteError("AttributeError")) 'version': self.api_version}, None
).AndRaise(rpc_common.RemoteError("AttributeError"))
self.m.ReplayAll() self.m.ReplayAll()
@ -746,10 +768,11 @@ class StackControllerTest(unittest.TestCase):
# Insert an engine RPC error and ensure we map correctly to the # Insert an engine RPC error and ensure we map correctly to the
# heat exception type # heat exception type
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'identify_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_name': stack_name}, {'method': 'identify_stack',
'version': self.api_version}, None 'args': {'stack_name': stack_name},
).AndRaise(rpc_common.RemoteError("AttributeError")) 'version': self.api_version}, None
).AndRaise(rpc_common.RemoteError("AttributeError"))
self.m.ReplayAll() self.m.ReplayAll()
@ -765,52 +788,53 @@ class StackControllerTest(unittest.TestCase):
dummy_req = self._dummy_GET_request(params) dummy_req = self._dummy_GET_request(params)
# Stub out the RPC call to the engine with a pre-canned response # Stub out the RPC call to the engine with a pre-canned response
engine_resp = {u'events': [{u'stack_name': u'wordpress', engine_resp = {u'events':
u'event_time': u'2012-07-23T13:05:39Z', [{u'stack_name': u'wordpress',
u'stack_identity': {u'tenant': u't', u'event_time': u'2012-07-23T13:05:39Z',
u'stack_name': u'wordpress', u'stack_identity': {u'tenant': u't',
u'stack_id': u'6', u'stack_name': u'wordpress',
u'path': u''}, u'stack_id': u'6',
u'logical_resource_id': u'WikiDatabase', u'path': u''},
u'resource_status_reason': u'state changed', u'logical_resource_id': u'WikiDatabase',
u'event_identity': { u'resource_status_reason': u'state changed',
u'tenant': u't', u'event_identity':
u'stack_name': u'wordpress', {u'tenant': u't',
u'stack_id': u'6', u'stack_name': u'wordpress',
u'path': u'/resources/WikiDatabase/events/42' u'stack_id': u'6',
}, u'path': u'/resources/WikiDatabase/events/42'},
u'resource_status': u'IN_PROGRESS', u'resource_status': u'IN_PROGRESS',
u'physical_resource_id': None, u'physical_resource_id': None,
u'resource_properties': u'resource_properties': {u'UserData': u'blah'},
{u'UserData': u'blah'}, u'resource_type': u'AWS::EC2::Instance'}]}
u'resource_type': u'AWS::EC2::Instance'}]}
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'identify_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_name': stack_name}, {'method': 'identify_stack',
'version': self.api_version}, None).AndReturn(identity) 'args': {'stack_name': stack_name},
rpc.call(dummy_req.context, self.topic, {'method': 'list_events', 'version': self.api_version}, None).AndReturn(identity)
'args': rpc.call(dummy_req.context, self.topic,
{'stack_identity': identity}, {'method': 'list_events',
'version': self.api_version}, None).AndReturn(engine_resp) 'args': {'stack_identity': identity},
'version': self.api_version}, None).AndReturn(engine_resp)
self.m.ReplayAll() self.m.ReplayAll()
response = self.controller.events_list(dummy_req) response = self.controller.events_list(dummy_req)
expected = {'DescribeStackEventsResponse': expected = {'DescribeStackEventsResponse':
{'DescribeStackEventsResult': {'DescribeStackEventsResult':
{'StackEvents': {'StackEvents':
[{'EventId': u'42', [{'EventId': u'42',
'StackId': u'arn:openstack:heat::t:stacks/wordpress/6', 'StackId': u'arn:openstack:heat::t:stacks/wordpress/6',
'ResourceStatus': u'IN_PROGRESS', 'ResourceStatus': u'IN_PROGRESS',
'ResourceType': u'AWS::EC2::Instance', 'ResourceType': u'AWS::EC2::Instance',
'Timestamp': u'2012-07-23T13:05:39Z', 'Timestamp': u'2012-07-23T13:05:39Z',
'StackName': u'wordpress', 'StackName': u'wordpress',
'ResourceProperties': json.dumps({u'UserData': u'blah'}), 'ResourceProperties':
'PhysicalResourceId': None, json.dumps({u'UserData': u'blah'}),
'ResourceStatusReason': u'state changed', 'PhysicalResourceId': None,
'LogicalResourceId': u'WikiDatabase'}]}}} 'ResourceStatusReason': u'state changed',
'LogicalResourceId': u'WikiDatabase'}]}}}
self.assertEqual(response, expected) self.assertEqual(response, expected)
@ -823,14 +847,15 @@ class StackControllerTest(unittest.TestCase):
# Insert an engine RPC error and ensure we map correctly to the # Insert an engine RPC error and ensure we map correctly to the
# heat exception type # heat exception type
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'identify_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_name': stack_name}, {'method': 'identify_stack',
'version': self.api_version}, None).AndReturn(identity) 'args': {'stack_name': stack_name},
rpc.call(dummy_req.context, self.topic, {'method': 'list_events', 'version': self.api_version}, None).AndReturn(identity)
'args': rpc.call(dummy_req.context, self.topic,
{'stack_identity': identity}, {'method': 'list_events',
'version': self.api_version}, None 'args': {'stack_identity': identity},
).AndRaise(rpc_common.RemoteError("Exception")) 'version': self.api_version}, None
).AndRaise(rpc_common.RemoteError("Exception"))
self.m.ReplayAll() self.m.ReplayAll()
@ -846,10 +871,11 @@ class StackControllerTest(unittest.TestCase):
# Insert an engine RPC error and ensure we map correctly to the # Insert an engine RPC error and ensure we map correctly to the
# heat exception type # heat exception type
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'identify_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_name': stack_name}, {'method': 'identify_stack',
'version': self.api_version}, None 'args': {'stack_name': stack_name},
).AndRaise(rpc_common.RemoteError("AttributeError")) 'version': self.api_version}, None
).AndRaise(rpc_common.RemoteError("AttributeError"))
self.m.ReplayAll() self.m.ReplayAll()
@ -884,22 +910,23 @@ class StackControllerTest(unittest.TestCase):
u'path': u''}, u'path': u''},
u'resource_status': u'CREATE_COMPLETE', u'resource_status': u'CREATE_COMPLETE',
u'physical_resource_id': u'physical_resource_id':
u'a3455d8c-9f88-404d-a85b-5315293e67de', u'a3455d8c-9f88-404d-a85b-5315293e67de',
u'resource_type': u'AWS::EC2::Instance', u'resource_type': u'AWS::EC2::Instance',
u'metadata': {u'wordpress': []}} u'metadata': {u'wordpress': []}}
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'identify_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_name': stack_name}, {'method': 'identify_stack',
'version': self.api_version}, None).AndReturn(identity) 'args': {'stack_name': stack_name},
'version': self.api_version}, None).AndReturn(identity)
args = { args = {
'stack_identity': identity, 'stack_identity': identity,
'resource_name': dummy_req.params.get('LogicalResourceId'), 'resource_name': dummy_req.params.get('LogicalResourceId'),
} }
rpc.call(dummy_req.context, self.topic, rpc.call(dummy_req.context, self.topic,
{'method': 'describe_stack_resource', {'method': 'describe_stack_resource',
'args': args, 'args': args,
'version': self.api_version}, None).AndReturn(engine_resp) 'version': self.api_version}, None).AndReturn(engine_resp)
self.m.ReplayAll() self.m.ReplayAll()
@ -916,7 +943,7 @@ class StackControllerTest(unittest.TestCase):
'LastUpdatedTimestamp': u'2012-07-23T13:06:00Z', 'LastUpdatedTimestamp': u'2012-07-23T13:06:00Z',
'StackName': u'wordpress', 'StackName': u'wordpress',
'PhysicalResourceId': 'PhysicalResourceId':
u'a3455d8c-9f88-404d-a85b-5315293e67de', u'a3455d8c-9f88-404d-a85b-5315293e67de',
'Metadata': {u'wordpress': []}, 'Metadata': {u'wordpress': []},
'LogicalResourceId': u'WikiDatabase'}}}} 'LogicalResourceId': u'WikiDatabase'}}}}
@ -949,23 +976,24 @@ class StackControllerTest(unittest.TestCase):
u'path': u''}, u'path': u''},
u'resource_status': u'CREATE_COMPLETE', u'resource_status': u'CREATE_COMPLETE',
u'physical_resource_id': u'physical_resource_id':
u'a3455d8c-9f88-404d-a85b-5315293e67de', u'a3455d8c-9f88-404d-a85b-5315293e67de',
u'resource_type': u'AWS::EC2::Instance', u'resource_type': u'AWS::EC2::Instance',
u'metadata': {u'ensureRunning': u'true''true'}}] u'metadata': {u'ensureRunning': u'true''true'}}]
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'identify_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_name': stack_name}, {'method': 'identify_stack',
'version': self.api_version}, None).AndReturn(identity) 'args': {'stack_name': stack_name},
'version': self.api_version}, None).AndReturn(identity)
args = { args = {
'stack_identity': identity, 'stack_identity': identity,
'physical_resource_id': None, 'physical_resource_id': None,
'logical_resource_id': dummy_req.params.get('LogicalResourceId'), 'logical_resource_id': dummy_req.params.get('LogicalResourceId'),
} }
rpc.call(dummy_req.context, self.topic, rpc.call(dummy_req.context, self.topic,
{'method': 'describe_stack_resources', {'method': 'describe_stack_resources',
'args': args, 'args': args,
'version': self.api_version}, None).AndReturn(engine_resp) 'version': self.api_version}, None).AndReturn(engine_resp)
self.m.ReplayAll() self.m.ReplayAll()
@ -974,16 +1002,16 @@ class StackControllerTest(unittest.TestCase):
expected = {'DescribeStackResourcesResponse': expected = {'DescribeStackResourcesResponse':
{'DescribeStackResourcesResult': {'DescribeStackResourcesResult':
{'StackResources': {'StackResources':
[{'StackId': u'arn:openstack:heat::t:stacks/wordpress/6', [{'StackId': u'arn:openstack:heat::t:stacks/wordpress/6',
'ResourceStatus': u'CREATE_COMPLETE', 'ResourceStatus': u'CREATE_COMPLETE',
'Description': u'', 'Description': u'',
'ResourceType': u'AWS::EC2::Instance', 'ResourceType': u'AWS::EC2::Instance',
'Timestamp': u'2012-07-23T13:06:00Z', 'Timestamp': u'2012-07-23T13:06:00Z',
'ResourceStatusReason': None, 'ResourceStatusReason': None,
'StackName': u'wordpress', 'StackName': u'wordpress',
'PhysicalResourceId': 'PhysicalResourceId':
u'a3455d8c-9f88-404d-a85b-5315293e67de', u'a3455d8c-9f88-404d-a85b-5315293e67de',
'LogicalResourceId': u'WikiDatabase'}]}}} 'LogicalResourceId': u'WikiDatabase'}]}}}
self.assertEqual(response, expected) self.assertEqual(response, expected)
@ -997,10 +1025,11 @@ class StackControllerTest(unittest.TestCase):
# Insert an engine RPC error and ensure we map correctly to the # Insert an engine RPC error and ensure we map correctly to the
# heat exception type # heat exception type
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'identify_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_name': stack_name}, {'method': 'identify_stack',
'version': self.api_version}, None 'args': {'stack_name': stack_name},
).AndRaise(rpc_common.RemoteError("AttributeError")) 'version': self.api_version}, None
).AndRaise(rpc_common.RemoteError("AttributeError"))
self.m.ReplayAll() self.m.ReplayAll()
@ -1019,7 +1048,7 @@ class StackControllerTest(unittest.TestCase):
dummy_req = self._dummy_GET_request(params) dummy_req = self._dummy_GET_request(params)
ret = self.controller.describe_stack_resources(dummy_req) ret = self.controller.describe_stack_resources(dummy_req)
self.assertEqual(type(ret), self.assertEqual(type(ret),
exception.HeatInvalidParameterCombinationError) exception.HeatInvalidParameterCombinationError)
def test_list_stack_resources(self): def test_list_stack_resources(self):
# Format a dummy request # Format a dummy request
@ -1030,12 +1059,11 @@ class StackControllerTest(unittest.TestCase):
dummy_req = self._dummy_GET_request(params) dummy_req = self._dummy_GET_request(params)
# Stub out the RPC call to the engine with a pre-canned response # Stub out the RPC call to the engine with a pre-canned response
engine_resp = [{u'resource_identity': { engine_resp = [{u'resource_identity':
u'tenant': u't', {u'tenant': u't',
u'stack_name': u'wordpress', u'stack_name': u'wordpress',
u'stack_id': u'6', u'stack_id': u'6',
u'path': u'/resources/WikiDatabase' u'path': u'/resources/WikiDatabase'},
},
u'stack_name': u'wordpress', u'stack_name': u'wordpress',
u'logical_resource_id': u'WikiDatabase', u'logical_resource_id': u'WikiDatabase',
u'resource_status_reason': None, u'resource_status_reason': None,
@ -1046,17 +1074,18 @@ class StackControllerTest(unittest.TestCase):
u'path': u''}, u'path': u''},
u'resource_status': u'CREATE_COMPLETE', u'resource_status': u'CREATE_COMPLETE',
u'physical_resource_id': u'physical_resource_id':
u'a3455d8c-9f88-404d-a85b-5315293e67de', u'a3455d8c-9f88-404d-a85b-5315293e67de',
u'resource_type': u'AWS::EC2::Instance'}] u'resource_type': u'AWS::EC2::Instance'}]
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'identify_stack',
'args': {'stack_name': stack_name},
'version': self.api_version}, None).AndReturn(identity)
rpc.call(dummy_req.context, self.topic, rpc.call(dummy_req.context, self.topic,
{'method': 'list_stack_resources', {'method': 'identify_stack',
'args': {'stack_identity': identity}, 'args': {'stack_name': stack_name},
'version': self.api_version}, None).AndReturn(engine_resp) 'version': self.api_version}, None).AndReturn(identity)
rpc.call(dummy_req.context, self.topic,
{'method': 'list_stack_resources',
'args': {'stack_identity': identity},
'version': self.api_version}, None).AndReturn(engine_resp)
self.m.ReplayAll() self.m.ReplayAll()
@ -1064,13 +1093,13 @@ class StackControllerTest(unittest.TestCase):
expected = {'ListStackResourcesResponse': {'ListStackResourcesResult': expected = {'ListStackResourcesResponse': {'ListStackResourcesResult':
{'StackResourceSummaries': {'StackResourceSummaries':
[{'ResourceStatus': u'CREATE_COMPLETE', [{'ResourceStatus': u'CREATE_COMPLETE',
'ResourceType': u'AWS::EC2::Instance', 'ResourceType': u'AWS::EC2::Instance',
'ResourceStatusReason': None, 'ResourceStatusReason': None,
'LastUpdatedTimestamp': u'2012-07-23T13:06:00Z', 'LastUpdatedTimestamp': u'2012-07-23T13:06:00Z',
'PhysicalResourceId': 'PhysicalResourceId':
u'a3455d8c-9f88-404d-a85b-5315293e67de', u'a3455d8c-9f88-404d-a85b-5315293e67de',
'LogicalResourceId': u'WikiDatabase'}]}}} 'LogicalResourceId': u'WikiDatabase'}]}}}
self.assertEqual(response, expected) self.assertEqual(response, expected)
@ -1083,10 +1112,11 @@ class StackControllerTest(unittest.TestCase):
# Insert an engine RPC error and ensure we map correctly to the # Insert an engine RPC error and ensure we map correctly to the
# heat exception type # heat exception type
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'method': 'identify_stack', rpc.call(dummy_req.context, self.topic,
'args': {'stack_name': stack_name}, {'method': 'identify_stack',
'version': self.api_version}, None 'args': {'stack_name': stack_name},
).AndRaise(rpc_common.RemoteError("AttributeError")) 'version': self.api_version}, None
).AndRaise(rpc_common.RemoteError("AttributeError"))
self.m.ReplayAll() self.m.ReplayAll()

View File

@ -105,11 +105,11 @@ class WatchControllerTest(unittest.TestCase):
u'updated_time': u'2012-08-30T14:10:46Z'}] u'updated_time': u'2012-08-30T14:10:46Z'}]
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'args': rpc.call(dummy_req.context, self.topic,
{'watch_name': watch_name}, {'args': {'watch_name': watch_name},
'method': 'show_watch', 'method': 'show_watch',
'version': self.api_version}, 'version': self.api_version},
None).AndReturn(engine_resp) None).AndReturn(engine_resp)
self.m.ReplayAll() self.m.ReplayAll()
@ -117,32 +117,32 @@ class WatchControllerTest(unittest.TestCase):
response = self.controller.describe_alarms(dummy_req) response = self.controller.describe_alarms(dummy_req)
expected = {'DescribeAlarmsResponse': {'DescribeAlarmsResult': expected = {'DescribeAlarmsResponse': {'DescribeAlarmsResult':
{'MetricAlarms': [ {'MetricAlarms': [
{'EvaluationPeriods': u'1', {'EvaluationPeriods': u'1',
'StateReasonData': None, 'StateReasonData': None,
'AlarmArn': None, 'AlarmArn': None,
'StateUpdatedTimestamp': u'2012-08-30T14:13:21Z', 'StateUpdatedTimestamp': u'2012-08-30T14:13:21Z',
'AlarmConfigurationUpdatedTimestamp': 'AlarmConfigurationUpdatedTimestamp':
u'2012-08-30T14:10:46Z', u'2012-08-30T14:10:46Z',
'AlarmActions': [u'WebServerRestartPolicy'], 'AlarmActions': [u'WebServerRestartPolicy'],
'Threshold': u'2', 'Threshold': u'2',
'AlarmDescription': u'Restart the WikiDatabase', 'AlarmDescription': u'Restart the WikiDatabase',
'Namespace': u'system/linux', 'Namespace': u'system/linux',
'Period': u'300', 'Period': u'300',
'StateValue': u'NORMAL', 'StateValue': u'NORMAL',
'ComparisonOperator': u'GreaterThanThreshold', 'ComparisonOperator': u'GreaterThanThreshold',
'AlarmName': u'HttpFailureAlarm', 'AlarmName': u'HttpFailureAlarm',
'Unit': None, 'Unit': None,
'Statistic': u'SampleCount', 'Statistic': u'SampleCount',
'StateReason': None, 'StateReason': None,
'InsufficientDataActions': None, 'InsufficientDataActions': None,
'OKActions': None, 'OKActions': None,
'MetricName': u'ServiceFailure', 'MetricName': u'ServiceFailure',
'ActionsEnabled': None, 'ActionsEnabled': None,
'Dimensions': [ 'Dimensions':
{'Name': 'StackId', [{'Name': 'StackId',
'Value': u'21617058-781e-4262-97ab-5f9df371ee52'} 'Value': u'21617058-781e-4262-97ab-5f9df371ee52'}]
]}]}}} }]}}}
self.assert_(response == expected) self.assert_(response == expected)
@ -181,20 +181,19 @@ class WatchControllerTest(unittest.TestCase):
# Stub out the RPC call to the engine with a pre-canned response # Stub out the RPC call to the engine with a pre-canned response
# We dummy three different metrics and namespaces to test # We dummy three different metrics and namespaces to test
# filtering by parameter # filtering by parameter
engine_resp = [ engine_resp = [{u'timestamp': u'2012-08-30T15:09:02Z',
{u'timestamp': u'2012-08-30T15:09:02Z',
u'watch_name': u'HttpFailureAlarm', u'watch_name': u'HttpFailureAlarm',
u'namespace': u'system/linux', u'namespace': u'system/linux',
u'metric_name': u'ServiceFailure', u'metric_name': u'ServiceFailure',
u'data': {u'Units': u'Counter', u'Value': 1}}, u'data': {u'Units': u'Counter', u'Value': 1}},
{u'timestamp': u'2012-08-30T15:10:03Z', {u'timestamp': u'2012-08-30T15:10:03Z',
u'watch_name': u'HttpFailureAlarm2', u'watch_name': u'HttpFailureAlarm2',
u'namespace': u'system/linux2', u'namespace': u'system/linux2',
u'metric_name': u'ServiceFailure2', u'metric_name': u'ServiceFailure2',
u'data': {u'Units': u'Counter', u'Value': 1}}, u'data': {u'Units': u'Counter', u'Value': 1}},
{u'timestamp': u'2012-08-30T15:16:03Z', {u'timestamp': u'2012-08-30T15:16:03Z',
u'watch_name': u'HttpFailureAlar3m', u'watch_name': u'HttpFailureAlar3m',
u'namespace': u'system/linux3', u'namespace': u'system/linux3',
u'metric_name': u'ServiceFailure3', u'metric_name': u'ServiceFailure3',
@ -204,43 +203,51 @@ class WatchControllerTest(unittest.TestCase):
# Current engine implementation means we filter in the API # Current engine implementation means we filter in the API
# and pass None/None for namespace/watch_name which returns # and pass None/None for namespace/watch_name which returns
# all metric data which we post-process in the API # all metric data which we post-process in the API
rpc.call(dummy_req.context, self.topic, {'args': rpc.call(dummy_req.context, self.topic,
{'namespace': None, {'args': {'namespace': None, 'metric_name': None},
'metric_name': None}, 'method': 'show_watch_metric',
'method': 'show_watch_metric', 'version': self.api_version}, 'version': self.api_version},
None).AndReturn(engine_resp) None).AndReturn(engine_resp)
self.m.ReplayAll() self.m.ReplayAll()
# First pass no query paramters filtering, should get all three # First pass no query paramters filtering, should get all three
response = self.controller.list_metrics(dummy_req) response = self.controller.list_metrics(dummy_req)
expected = {'ListMetricsResponse': {'ListMetricsResult': {'Metrics': [ expected = {'ListMetricsResponse':
{'Namespace': u'system/linux', {'ListMetricsResult':
'Dimensions': [ {'Metrics': [{'Namespace': u'system/linux',
{'Name': 'AlarmName', 'Value': u'HttpFailureAlarm'}, 'Dimensions':
{'Name': 'Timestamp', [{'Name': 'AlarmName',
'Value': u'2012-08-30T15:09:02Z'}, 'Value': u'HttpFailureAlarm'},
{'Name': u'Units', 'Value': u'Counter'}, {'Name': 'Timestamp',
{'Name': u'Value', 'Value': 1}], 'Value': u'2012-08-30T15:09:02Z'},
'MetricName': u'ServiceFailure'}, {'Name': u'Units',
'Value': u'Counter'},
{'Namespace': u'system/linux2', {'Name': u'Value',
'Dimensions': [ 'Value': 1}],
{'Name': 'AlarmName', 'Value': u'HttpFailureAlarm2'}, 'MetricName': u'ServiceFailure'},
{'Name': 'Timestamp', {'Namespace': u'system/linux2',
'Value': u'2012-08-30T15:10:03Z'}, 'Dimensions':
{'Name': u'Units', 'Value': u'Counter'}, [{'Name': 'AlarmName',
{'Name': u'Value', 'Value': 1}], 'Value': u'HttpFailureAlarm2'},
'MetricName': u'ServiceFailure2'}, {'Name': 'Timestamp',
'Value': u'2012-08-30T15:10:03Z'},
{'Namespace': u'system/linux3', {'Name': u'Units',
'Dimensions': [ 'Value': u'Counter'},
{'Name': 'AlarmName', 'Value': u'HttpFailureAlar3m'}, {'Name': u'Value',
{'Name': 'Timestamp', 'Value': 1}],
'Value': u'2012-08-30T15:16:03Z'}, 'MetricName': u'ServiceFailure2'},
{'Name': u'Units', 'Value': u'Counter'}, {'Namespace': u'system/linux3',
{'Name': u'Value', 'Value': 1}], 'Dimensions':
'MetricName': u'ServiceFailure3'}]}}} [{'Name': 'AlarmName',
'Value': u'HttpFailureAlar3m'},
{'Name': 'Timestamp',
'Value': u'2012-08-30T15:16:03Z'},
{'Name': u'Units',
'Value': u'Counter'},
{'Name': u'Value',
'Value': 1}],
'MetricName': u'ServiceFailure3'}]}}}
self.assert_(response == expected) self.assert_(response == expected)
def test_list_metrics_filter_name(self): def test_list_metrics_filter_name(self):
@ -253,20 +260,19 @@ class WatchControllerTest(unittest.TestCase):
# Stub out the RPC call to the engine with a pre-canned response # Stub out the RPC call to the engine with a pre-canned response
# We dummy three different metrics and namespaces to test # We dummy three different metrics and namespaces to test
# filtering by parameter # filtering by parameter
engine_resp = [ engine_resp = [{u'timestamp': u'2012-08-30T15:09:02Z',
{u'timestamp': u'2012-08-30T15:09:02Z',
u'watch_name': u'HttpFailureAlarm', u'watch_name': u'HttpFailureAlarm',
u'namespace': u'system/linux', u'namespace': u'system/linux',
u'metric_name': u'ServiceFailure', u'metric_name': u'ServiceFailure',
u'data': {u'Units': u'Counter', u'Value': 1}}, u'data': {u'Units': u'Counter', u'Value': 1}},
{u'timestamp': u'2012-08-30T15:10:03Z', {u'timestamp': u'2012-08-30T15:10:03Z',
u'watch_name': u'HttpFailureAlarm2', u'watch_name': u'HttpFailureAlarm2',
u'namespace': u'system/linux2', u'namespace': u'system/linux2',
u'metric_name': u'ServiceFailure2', u'metric_name': u'ServiceFailure2',
u'data': {u'Units': u'Counter', u'Value': 1}}, u'data': {u'Units': u'Counter', u'Value': 1}},
{u'timestamp': u'2012-08-30T15:16:03Z', {u'timestamp': u'2012-08-30T15:16:03Z',
u'watch_name': u'HttpFailureAlar3m', u'watch_name': u'HttpFailureAlar3m',
u'namespace': u'system/linux3', u'namespace': u'system/linux3',
u'metric_name': u'ServiceFailure3', u'metric_name': u'ServiceFailure3',
@ -286,16 +292,20 @@ class WatchControllerTest(unittest.TestCase):
# First pass no query paramters filtering, should get all three # First pass no query paramters filtering, should get all three
response = self.controller.list_metrics(dummy_req) response = self.controller.list_metrics(dummy_req)
expected = {'ListMetricsResponse': {'ListMetricsResult': {'Metrics': [ expected = {'ListMetricsResponse':
{'Namespace': u'system/linux', {'ListMetricsResult':
'Dimensions': [ {'Metrics':
{'Name': 'AlarmName', 'Value': u'HttpFailureAlarm'}, [{'Namespace': u'system/linux',
{'Name': 'Timestamp', 'Dimensions':
'Value': u'2012-08-30T15:09:02Z'}, [{'Name': 'AlarmName',
{'Name': u'Units', 'Value': u'Counter'}, 'Value': u'HttpFailureAlarm'},
{'Name': u'Value', 'Value': 1}], {'Name': 'Timestamp',
'MetricName': u'ServiceFailure'}, 'Value': u'2012-08-30T15:09:02Z'},
]}}} {'Name': u'Units',
'Value': u'Counter'},
{'Name': u'Value',
'Value': 1}],
'MetricName': u'ServiceFailure'}]}}}
self.assert_(response == expected) self.assert_(response == expected)
def test_list_metrics_filter_namespace(self): def test_list_metrics_filter_namespace(self):
@ -309,20 +319,19 @@ class WatchControllerTest(unittest.TestCase):
# Stub out the RPC call to the engine with a pre-canned response # Stub out the RPC call to the engine with a pre-canned response
# We dummy three different metrics and namespaces to test # We dummy three different metrics and namespaces to test
# filtering by parameter # filtering by parameter
engine_resp = [ engine_resp = [{u'timestamp': u'2012-08-30T15:09:02Z',
{u'timestamp': u'2012-08-30T15:09:02Z',
u'watch_name': u'HttpFailureAlarm', u'watch_name': u'HttpFailureAlarm',
u'namespace': u'atestnamespace/foo', u'namespace': u'atestnamespace/foo',
u'metric_name': u'ServiceFailure', u'metric_name': u'ServiceFailure',
u'data': {u'Units': u'Counter', u'Value': 1}}, u'data': {u'Units': u'Counter', u'Value': 1}},
{u'timestamp': u'2012-08-30T15:10:03Z', {u'timestamp': u'2012-08-30T15:10:03Z',
u'watch_name': u'HttpFailureAlarm2', u'watch_name': u'HttpFailureAlarm2',
u'namespace': u'atestnamespace/foo', u'namespace': u'atestnamespace/foo',
u'metric_name': u'ServiceFailure2', u'metric_name': u'ServiceFailure2',
u'data': {u'Units': u'Counter', u'Value': 1}}, u'data': {u'Units': u'Counter', u'Value': 1}},
{u'timestamp': u'2012-08-30T15:16:03Z', {u'timestamp': u'2012-08-30T15:16:03Z',
u'watch_name': u'HttpFailureAlar3m', u'watch_name': u'HttpFailureAlar3m',
u'namespace': u'system/linux3', u'namespace': u'system/linux3',
u'metric_name': u'ServiceFailure3', u'metric_name': u'ServiceFailure3',
@ -341,22 +350,31 @@ class WatchControllerTest(unittest.TestCase):
self.m.ReplayAll() self.m.ReplayAll()
response = self.controller.list_metrics(dummy_req) response = self.controller.list_metrics(dummy_req)
expected = {'ListMetricsResponse': {'ListMetricsResult': {'Metrics': [ expected = {'ListMetricsResponse':
{'Namespace': u'atestnamespace/foo', {'ListMetricsResult':
'Dimensions': [ {'Metrics':
{'Name': 'AlarmName', 'Value': u'HttpFailureAlarm'}, [{'Namespace': u'atestnamespace/foo',
{'Name': 'Timestamp', 'Value': u'2012-08-30T15:09:02Z'}, 'Dimensions':
{'Name': u'Units', 'Value': u'Counter'}, [{'Name': 'AlarmName',
{'Name': u'Value', 'Value': 1}], 'Value': u'HttpFailureAlarm'},
'MetricName': u'ServiceFailure'}, {'Name': 'Timestamp',
'Value': u'2012-08-30T15:09:02Z'},
{'Namespace': u'atestnamespace/foo', {'Name': u'Units',
'Dimensions': [ 'Value': u'Counter'},
{'Name': 'AlarmName', 'Value': u'HttpFailureAlarm2'}, {'Name': u'Value',
{'Name': 'Timestamp', 'Value': u'2012-08-30T15:10:03Z'}, 'Value': 1}],
{'Name': u'Units', 'Value': u'Counter'}, 'MetricName': u'ServiceFailure'},
{'Name': u'Value', 'Value': 1}], {'Namespace': u'atestnamespace/foo',
'MetricName': u'ServiceFailure2'}]}}} 'Dimensions':
[{'Name': 'AlarmName',
'Value': u'HttpFailureAlarm2'},
{'Name': 'Timestamp',
'Value': u'2012-08-30T15:10:03Z'},
{'Name': u'Units',
'Value': u'Counter'},
{'Name': u'Value',
'Value': 1}],
'MetricName': u'ServiceFailure2'}]}}}
self.assert_(response == expected) self.assert_(response == expected)
def test_put_metric_alarm(self): def test_put_metric_alarm(self):
@ -373,9 +391,9 @@ class WatchControllerTest(unittest.TestCase):
u'MetricData.member.1.Value': u'1', u'MetricData.member.1.Value': u'1',
u'MetricData.member.1.MetricName': u'ServiceFailure', u'MetricData.member.1.MetricName': u'ServiceFailure',
u'MetricData.member.1.Dimensions.member.1.Name': u'MetricData.member.1.Dimensions.member.1.Name':
u'AlarmName', u'AlarmName',
u'MetricData.member.1.Dimensions.member.1.Value': u'MetricData.member.1.Dimensions.member.1.Value':
u'HttpFailureAlarm', u'HttpFailureAlarm',
u'Action': u'PutMetricData'} u'Action': u'PutMetricData'}
dummy_req = self._dummy_GET_request(params) dummy_req = self._dummy_GET_request(params)
@ -384,13 +402,15 @@ class WatchControllerTest(unittest.TestCase):
engine_resp = {} engine_resp = {}
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'args': {'stats_data': rpc.call(dummy_req.context, self.topic,
{'Namespace': u'system/linux', {'args':
u'ServiceFailure': {'stats_data':
{'Value': u'1', {'Namespace': u'system/linux',
'Unit': u'Count', u'ServiceFailure':
'Dimensions': []}}, {'Value': u'1',
'watch_name': u'HttpFailureAlarm'}, 'Unit': u'Count',
'Dimensions': []}},
'watch_name': u'HttpFailureAlarm'},
'method': 'create_watch_data', 'method': 'create_watch_data',
'version': self.api_version}, 'version': self.api_version},
None).AndReturn(engine_resp) None).AndReturn(engine_resp)
@ -404,8 +424,8 @@ class WatchControllerTest(unittest.TestCase):
def test_set_alarm_state(self): def test_set_alarm_state(self):
state_map = {'OK': engine_api.WATCH_STATE_OK, state_map = {'OK': engine_api.WATCH_STATE_OK,
'ALARM': engine_api.WATCH_STATE_ALARM, 'ALARM': engine_api.WATCH_STATE_ALARM,
'INSUFFICIENT_DATA': engine_api.WATCH_STATE_NODATA} 'INSUFFICIENT_DATA': engine_api.WATCH_STATE_NODATA}
for state in state_map.keys(): for state in state_map.keys():
params = {u'StateValue': state, params = {u'StateValue': state,
@ -422,12 +442,13 @@ class WatchControllerTest(unittest.TestCase):
engine_resp = {} engine_resp = {}
self.m.StubOutWithMock(rpc, 'call') self.m.StubOutWithMock(rpc, 'call')
rpc.call(dummy_req.context, self.topic, {'args': rpc.call(dummy_req.context, self.topic,
{'state': state_map[state], {'args':
'watch_name': u'HttpFailureAlarm'}, {'state': state_map[state],
'method': 'set_watch_state', 'watch_name': u'HttpFailureAlarm'},
'version': self.api_version}, 'method': 'set_watch_state',
None).AndReturn(engine_resp) 'version': self.api_version},
None).AndReturn(engine_resp)
self.m.ReplayAll() self.m.ReplayAll()

View File

@ -81,12 +81,12 @@ class InstantiationDataTest(unittest.TestCase):
blarg: wibble blarg: wibble
''' '''
parsed = {u'HeatTemplateFormatVersion': u'2012-12-12', parsed = {u'HeatTemplateFormatVersion': u'2012-12-12',
u'Mappings': {}, u'Mappings': {},
u'Outputs': {}, u'Outputs': {},
u'Parameters': {}, u'Parameters': {},
u'Resources': {}, u'Resources': {},
u'blarg': u'wibble', u'blarg': u'wibble',
u'foo': u'bar'} u'foo': u'bar'}
body = {'template': template} body = {'template': template}
data = stacks.InstantiationData(body) data = stacks.InstantiationData(body)
@ -469,8 +469,8 @@ class StackControllerTest(ControllerTest, unittest.TestCase):
stack_name=identity.stack_name, stack_name=identity.stack_name,
path='resources') path='resources')
except webob.exc.HTTPFound as found: except webob.exc.HTTPFound as found:
self.assertEqual(found.location, self._url(identity) + self.assertEqual(found.location,
'/resources') self._url(identity) + '/resources')
else: else:
self.fail('No redirect generated') self.fail('No redirect generated')
self.m.VerifyAll() self.m.VerifyAll()
@ -867,7 +867,7 @@ class ResourceControllerTest(ControllerTest, unittest.TestCase):
u'stack_identity': stack_identity, u'stack_identity': stack_identity,
u'resource_status': u'CREATE_COMPLETE', u'resource_status': u'CREATE_COMPLETE',
u'physical_resource_id': u'physical_resource_id':
u'a3455d8c-9f88-404d-a85b-5315293e67de', u'a3455d8c-9f88-404d-a85b-5315293e67de',
u'resource_type': u'AWS::EC2::Instance', u'resource_type': u'AWS::EC2::Instance',
} }
] ]
@ -884,22 +884,17 @@ class ResourceControllerTest(ControllerTest, unittest.TestCase):
stack_id=stack_identity.stack_id) stack_id=stack_identity.stack_id)
expected = { expected = {
'resources': [ 'resources': [{'links': [{'href': self._url(res_identity),
{ 'rel': 'self'},
'links': [ {'href': self._url(stack_identity),
{'href': self._url(res_identity), 'rel': 'self'}, 'rel': 'stack'}],
{'href': self._url(stack_identity), 'rel': 'stack'}, u'logical_resource_id': res_name,
], u'resource_status_reason': None,
u'logical_resource_id': res_name, u'updated_time': u'2012-07-23T13:06:00Z',
u'resource_status_reason': None, u'resource_status': u'CREATE_COMPLETE',
u'updated_time': u'2012-07-23T13:06:00Z', u'physical_resource_id':
u'resource_status': u'CREATE_COMPLETE', u'a3455d8c-9f88-404d-a85b-5315293e67de',
u'physical_resource_id': u'resource_type': u'AWS::EC2::Instance'}]}
u'a3455d8c-9f88-404d-a85b-5315293e67de',
u'resource_type': u'AWS::EC2::Instance',
}
]
}
self.assertEqual(result, expected) self.assertEqual(result, expected)
self.m.VerifyAll() self.m.VerifyAll()
@ -944,7 +939,7 @@ class ResourceControllerTest(ControllerTest, unittest.TestCase):
u'stack_identity': dict(stack_identity), u'stack_identity': dict(stack_identity),
u'resource_status': u'CREATE_COMPLETE', u'resource_status': u'CREATE_COMPLETE',
u'physical_resource_id': u'physical_resource_id':
u'a3455d8c-9f88-404d-a85b-5315293e67de', u'a3455d8c-9f88-404d-a85b-5315293e67de',
u'resource_type': u'AWS::EC2::Instance', u'resource_type': u'AWS::EC2::Instance',
u'metadata': {u'ensureRunning': u'true'} u'metadata': {u'ensureRunning': u'true'}
} }
@ -974,7 +969,7 @@ class ResourceControllerTest(ControllerTest, unittest.TestCase):
u'updated_time': u'2012-07-23T13:06:00Z', u'updated_time': u'2012-07-23T13:06:00Z',
u'resource_status': u'CREATE_COMPLETE', u'resource_status': u'CREATE_COMPLETE',
u'physical_resource_id': u'physical_resource_id':
u'a3455d8c-9f88-404d-a85b-5315293e67de', u'a3455d8c-9f88-404d-a85b-5315293e67de',
u'resource_type': u'AWS::EC2::Instance', u'resource_type': u'AWS::EC2::Instance',
} }
} }
@ -1027,7 +1022,7 @@ class ResourceControllerTest(ControllerTest, unittest.TestCase):
u'stack_identity': dict(stack_identity), u'stack_identity': dict(stack_identity),
u'resource_status': u'CREATE_COMPLETE', u'resource_status': u'CREATE_COMPLETE',
u'physical_resource_id': u'physical_resource_id':
u'a3455d8c-9f88-404d-a85b-5315293e67de', u'a3455d8c-9f88-404d-a85b-5315293e67de',
u'resource_type': u'AWS::EC2::Instance', u'resource_type': u'AWS::EC2::Instance',
u'metadata': {u'ensureRunning': u'true'} u'metadata': {u'ensureRunning': u'true'}
} }
@ -1325,7 +1320,7 @@ class EventControllerTest(ControllerTest, unittest.TestCase):
u'event_identity': dict(ev_identity), u'event_identity': dict(ev_identity),
u'resource_status': u'CREATE_COMPLETE', u'resource_status': u'CREATE_COMPLETE',
u'physical_resource_id': u'physical_resource_id':
u'a3455d8c-9f88-404d-a85b-5315293e67de', u'a3455d8c-9f88-404d-a85b-5315293e67de',
u'resource_properties': {u'UserData': u'blah'}, u'resource_properties': {u'UserData': u'blah'},
u'resource_type': u'AWS::EC2::Instance', u'resource_type': u'AWS::EC2::Instance',
} }
@ -1357,7 +1352,7 @@ class EventControllerTest(ControllerTest, unittest.TestCase):
u'event_time': u'2012-07-23T13:06:00Z', u'event_time': u'2012-07-23T13:06:00Z',
u'resource_status': u'CREATE_COMPLETE', u'resource_status': u'CREATE_COMPLETE',
u'physical_resource_id': u'physical_resource_id':
u'a3455d8c-9f88-404d-a85b-5315293e67de', u'a3455d8c-9f88-404d-a85b-5315293e67de',
u'resource_type': u'AWS::EC2::Instance', u'resource_type': u'AWS::EC2::Instance',
u'resource_properties': {u'UserData': u'blah'}, u'resource_properties': {u'UserData': u'blah'},
} }
@ -1374,7 +1369,7 @@ class EventControllerTest(ControllerTest, unittest.TestCase):
res_identity = identifier.ResourceIdentifier(resource_name=res_name, res_identity = identifier.ResourceIdentifier(resource_name=res_name,
**stack_identity) **stack_identity)
ev_identity = identifier.EventIdentifier(event_id='41', ev_identity = identifier.EventIdentifier(event_id='41',
**res_identity) **res_identity)
req = self._get(stack_identity._tenant_path() + req = self._get(stack_identity._tenant_path() +
'/resources/' + res_name + '/events/' + event_id) '/resources/' + res_name + '/events/' + event_id)
@ -1417,7 +1412,7 @@ class EventControllerTest(ControllerTest, unittest.TestCase):
res_identity = identifier.ResourceIdentifier(resource_name=res_name, res_identity = identifier.ResourceIdentifier(resource_name=res_name,
**stack_identity) **stack_identity)
ev_identity = identifier.EventIdentifier(event_id='41', ev_identity = identifier.EventIdentifier(event_id='41',
**res_identity) **res_identity)
req = self._get(stack_identity._tenant_path() + req = self._get(stack_identity._tenant_path() +
'/resources/' + res_name + '/events/' + event_id) '/resources/' + res_name + '/events/' + event_id)

View File

@ -60,8 +60,8 @@ class AutoScalingTest(unittest.TestCase):
def create_scaling_group(self, t, stack, resource_name): def create_scaling_group(self, t, stack, resource_name):
resource = asc.AutoScalingGroup(resource_name, resource = asc.AutoScalingGroup(resource_name,
t['Resources'][resource_name], t['Resources'][resource_name],
stack) stack)
self.assertEqual(None, resource.validate()) self.assertEqual(None, resource.validate())
self.assertEqual(None, resource.create()) self.assertEqual(None, resource.create())
self.assertEqual(asc.AutoScalingGroup.CREATE_COMPLETE, resource.state) self.assertEqual(asc.AutoScalingGroup.CREATE_COMPLETE, resource.state)
@ -69,8 +69,8 @@ class AutoScalingTest(unittest.TestCase):
def create_scaling_policy(self, t, stack, resource_name): def create_scaling_policy(self, t, stack, resource_name):
resource = asc.ScalingPolicy(resource_name, resource = asc.ScalingPolicy(resource_name,
t['Resources'][resource_name], t['Resources'][resource_name],
stack) stack)
self.assertEqual(None, resource.validate()) self.assertEqual(None, resource.validate())
self.assertEqual(None, resource.create()) self.assertEqual(None, resource.create())
self.assertEqual(asc.ScalingPolicy.CREATE_COMPLETE, self.assertEqual(asc.ScalingPolicy.CREATE_COMPLETE,
@ -88,7 +88,7 @@ class AutoScalingTest(unittest.TestCase):
self.assertEqual('WebServerGroup', resource.FnGetRefId()) self.assertEqual('WebServerGroup', resource.FnGetRefId())
self.assertEqual('WebServerGroup-0', resource.resource_id) self.assertEqual('WebServerGroup-0', resource.resource_id)
self.assertEqual(asc.AutoScalingGroup.UPDATE_REPLACE, self.assertEqual(asc.AutoScalingGroup.UPDATE_REPLACE,
resource.handle_update()) resource.handle_update())
resource.delete() resource.delete()
@ -131,12 +131,12 @@ class AutoScalingTest(unittest.TestCase):
# reduce by 50% # reduce by 50%
resource.adjust(-50, 'PercentChangeInCapacity') resource.adjust(-50, 'PercentChangeInCapacity')
self.assertEqual('WebServerGroup-0', self.assertEqual('WebServerGroup-0',
resource.resource_id) resource.resource_id)
# raise by 200% # raise by 200%
resource.adjust(200, 'PercentChangeInCapacity') resource.adjust(200, 'PercentChangeInCapacity')
self.assertEqual('WebServerGroup-0,WebServerGroup-1,WebServerGroup-2', self.assertEqual('WebServerGroup-0,WebServerGroup-1,WebServerGroup-2',
resource.resource_id) resource.resource_id)
resource.delete() resource.delete()
@ -154,12 +154,11 @@ class AutoScalingTest(unittest.TestCase):
'WebServerScaleUpPolicy') 'WebServerScaleUpPolicy')
up_policy.alarm() up_policy.alarm()
self.assertEqual('WebServerGroup-0,WebServerGroup-1', self.assertEqual('WebServerGroup-0,WebServerGroup-1',
resource.resource_id) resource.resource_id)
down_policy = self.create_scaling_policy(t, stack, down_policy = self.create_scaling_policy(t, stack,
'WebServerScaleDownPolicy') 'WebServerScaleDownPolicy')
down_policy.alarm() down_policy.alarm()
self.assertEqual('WebServerGroup-0', self.assertEqual('WebServerGroup-0', resource.resource_id)
resource.resource_id)
resource.delete() resource.delete()

View File

@ -33,7 +33,8 @@ class CliTest(unittest.TestCase):
fullpath = basepath + '/bin/' + bin fullpath = basepath + '/bin/' + bin
proc = subprocess.Popen(fullpath, proc = subprocess.Popen(fullpath,
stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = proc.communicate() stdout, stderr = proc.communicate()
if proc.returncode: if proc.returncode:

View File

@ -63,8 +63,8 @@ class DBInstanceTest(unittest.TestCase):
def create_dbinstance(self, t, stack, resource_name): def create_dbinstance(self, t, stack, resource_name):
resource = dbi.DBInstance(resource_name, resource = dbi.DBInstance(resource_name,
t['Resources'][resource_name], t['Resources'][resource_name],
stack) stack)
self.assertEqual(None, resource.validate()) self.assertEqual(None, resource.validate())
self.assertEqual(None, resource.create()) self.assertEqual(None, resource.create())
self.assertEqual(dbi.DBInstance.CREATE_COMPLETE, resource.state) self.assertEqual(dbi.DBInstance.CREATE_COMPLETE, resource.state)

View File

@ -63,8 +63,8 @@ class EIPTest(unittest.TestCase):
def create_eip(self, t, stack, resource_name): def create_eip(self, t, stack, resource_name):
resource = eip.ElasticIp(resource_name, resource = eip.ElasticIp(resource_name,
t['Resources'][resource_name], t['Resources'][resource_name],
stack) stack)
self.assertEqual(None, resource.validate()) self.assertEqual(None, resource.validate())
self.assertEqual(None, resource.create()) self.assertEqual(None, resource.create())
self.assertEqual(eip.ElasticIp.CREATE_COMPLETE, resource.state) self.assertEqual(eip.ElasticIp.CREATE_COMPLETE, resource.state)
@ -72,8 +72,8 @@ class EIPTest(unittest.TestCase):
def create_association(self, t, stack, resource_name): def create_association(self, t, stack, resource_name):
resource = eip.ElasticIpAssociation(resource_name, resource = eip.ElasticIpAssociation(resource_name,
t['Resources'][resource_name], t['Resources'][resource_name],
stack) stack)
self.assertEqual(None, resource.validate()) self.assertEqual(None, resource.validate())
self.assertEqual(None, resource.create()) self.assertEqual(None, resource.create())
self.assertEqual(eip.ElasticIpAssociation.CREATE_COMPLETE, self.assertEqual(eip.ElasticIpAssociation.CREATE_COMPLETE,
@ -98,7 +98,7 @@ class EIPTest(unittest.TestCase):
self.assertEqual('1', resource.FnGetAtt('AllocationId')) self.assertEqual('1', resource.FnGetAtt('AllocationId'))
self.assertEqual(eip.ElasticIp.UPDATE_REPLACE, self.assertEqual(eip.ElasticIp.UPDATE_REPLACE,
resource.handle_update()) resource.handle_update())
try: try:
resource.FnGetAtt('Foo') resource.FnGetAtt('Foo')

View File

@ -218,9 +218,9 @@ class stackServiceCreateUpdateDeleteTest(unittest.TestCase):
stack_name = 'service_create/test_stack' stack_name = 'service_create/test_stack'
stack = get_wordpress_stack('test_stack', self.ctx) stack = get_wordpress_stack('test_stack', self.ctx)
self.assertRaises(ValueError, self.man.create_stack, self.assertRaises(ValueError,
self.ctx, stack_name, self.man.create_stack,
stack.t, {}, {}) self.ctx, stack_name, stack.t, {}, {})
def test_stack_create_invalid_resource_name(self): def test_stack_create_invalid_resource_name(self):
stack_name = 'service_create_test_stack_invalid_res' stack_name = 'service_create_test_stack_invalid_res'
@ -229,9 +229,10 @@ class stackServiceCreateUpdateDeleteTest(unittest.TestCase):
tmpl['Resources']['Web/Server'] = tmpl['Resources']['WebServer'] tmpl['Resources']['Web/Server'] = tmpl['Resources']['WebServer']
del tmpl['Resources']['WebServer'] del tmpl['Resources']['WebServer']
self.assertRaises(ValueError, self.man.create_stack, self.assertRaises(ValueError,
self.ctx, stack_name, self.man.create_stack,
stack.t, {}, {}) self.ctx, stack_name,
stack.t, {}, {})
def test_stack_delete(self): def test_stack_delete(self):
stack_name = 'service_delete_test_stack' stack_name = 'service_delete_test_stack'
@ -414,9 +415,10 @@ class stackServiceTest(unittest.TestCase):
def test_stack_by_name_tenants(self): def test_stack_by_name_tenants(self):
self.assertEqual(self.stack.id, self.assertEqual(self.stack.id,
db_api.stack_get_by_name(self.ctx, self.stack_name).id) db_api.stack_get_by_name(self.ctx,
self.stack_name).id)
ctx2 = create_context(self.m, self.username, ctx2 = create_context(self.m, self.username,
'stack_service_test_tenant2') 'stack_service_test_tenant2')
self.assertEqual(None, db_api.stack_get_by_name(ctx2, self.stack_name)) self.assertEqual(None, db_api.stack_get_by_name(ctx2, self.stack_name))
def test_stack_event_list(self): def test_stack_event_list(self):
@ -448,7 +450,7 @@ class stackServiceTest(unittest.TestCase):
self.assertTrue('resource_status' in ev) self.assertTrue('resource_status' in ev)
self.assertTrue(ev['resource_status'] in ('IN_PROGRESS', self.assertTrue(ev['resource_status'] in ('IN_PROGRESS',
'CREATE_COMPLETE')) 'CREATE_COMPLETE'))
self.assertTrue('resource_status_reason' in ev) self.assertTrue('resource_status_reason' in ev)
self.assertEqual(ev['resource_status_reason'], 'state changed') self.assertEqual(ev['resource_status_reason'], 'state changed')
@ -599,8 +601,8 @@ class stackServiceTest(unittest.TestCase):
def test_stack_resources_describe_no_filter(self): def test_stack_resources_describe_no_filter(self):
resources = self.man.describe_stack_resources(self.ctx, resources = self.man.describe_stack_resources(self.ctx,
self.stack_identity, self.stack_identity,
None, None) None, None)
self.assertEqual(len(resources), 1) self.assertEqual(len(resources), 1)
r = resources[0] r = resources[0]
@ -674,16 +676,15 @@ class stackServiceTest(unittest.TestCase):
values = {'stack_id': self.stack.id, values = {'stack_id': self.stack.id,
'state': 'NORMAL', 'state': 'NORMAL',
'name': u'HttpFailureAlarm', 'name': u'HttpFailureAlarm',
'rule': { 'rule': {u'EvaluationPeriods': u'1',
u'EvaluationPeriods': u'1', u'AlarmActions': [u'WebServerRestartPolicy'],
u'AlarmActions': [u'WebServerRestartPolicy'], u'AlarmDescription': u'Restart the WikiDatabase',
u'AlarmDescription': u'Restart the WikiDatabase', u'Namespace': u'system/linux',
u'Namespace': u'system/linux', u'Period': u'300',
u'Period': u'300', u'ComparisonOperator': u'GreaterThanThreshold',
u'ComparisonOperator': u'GreaterThanThreshold', u'Statistic': u'SampleCount',
u'Statistic': u'SampleCount', u'Threshold': u'2',
u'Threshold': u'2', u'MetricName': u'ServiceFailure'}}
u'MetricName': u'ServiceFailure'}}
db_ret = db_api.watch_rule_create(self.ctx, values) db_ret = db_api.watch_rule_create(self.ctx, values)
self.assertNotEqual(db_ret, None) self.assertNotEqual(db_ret, None)
values['name'] = "AnotherWatch" values['name'] = "AnotherWatch"
@ -716,16 +717,15 @@ class stackServiceTest(unittest.TestCase):
values = {'stack_id': self.stack.id, values = {'stack_id': self.stack.id,
'state': 'NORMAL', 'state': 'NORMAL',
'name': u'HttpFailureAlarm', 'name': u'HttpFailureAlarm',
'rule': { 'rule': {u'EvaluationPeriods': u'1',
u'EvaluationPeriods': u'1', u'AlarmActions': [u'WebServerRestartPolicy'],
u'AlarmActions': [u'WebServerRestartPolicy'], u'AlarmDescription': u'Restart the WikiDatabase',
u'AlarmDescription': u'Restart the WikiDatabase', u'Namespace': u'system/linux',
u'Namespace': u'system/linux', u'Period': u'300',
u'Period': u'300', u'ComparisonOperator': u'GreaterThanThreshold',
u'ComparisonOperator': u'GreaterThanThreshold', u'Statistic': u'SampleCount',
u'Statistic': u'SampleCount', u'Threshold': u'2',
u'Threshold': u'2', u'MetricName': u'ServiceFailure'}}
u'MetricName': u'ServiceFailure'}}
db_ret = db_api.watch_rule_create(self.ctx, values) db_ret = db_api.watch_rule_create(self.ctx, values)
self.assertNotEqual(db_ret, None) self.assertNotEqual(db_ret, None)
@ -733,10 +733,9 @@ class stackServiceTest(unittest.TestCase):
watch = db_api.watch_rule_get_by_name(self.ctx, "HttpFailureAlarm") watch = db_api.watch_rule_get_by_name(self.ctx, "HttpFailureAlarm")
self.assertNotEqual(watch, None) self.assertNotEqual(watch, None)
values = {'watch_rule_id': watch.id, values = {'watch_rule_id': watch.id,
'data': { 'data': {u'Namespace': u'system/linux',
u'Namespace': u'system/linux', u'ServiceFailure': {
u'ServiceFailure': { u'Units': u'Counter', u'Value': 1}}}
u'Units': u'Counter', u'Value': 1}}}
watch = db_api.watch_data_create(self.ctx, values) watch = db_api.watch_data_create(self.ctx, values)
# Check there is one result returned # Check there is one result returned
@ -762,16 +761,15 @@ class stackServiceTest(unittest.TestCase):
values = {'stack_id': self.stack.id, values = {'stack_id': self.stack.id,
'state': 'NORMAL', 'state': 'NORMAL',
'name': u'OverrideAlarm', 'name': u'OverrideAlarm',
'rule': { 'rule': {u'EvaluationPeriods': u'1',
u'EvaluationPeriods': u'1', u'AlarmActions': [u'WebServerRestartPolicy'],
u'AlarmActions': [u'WebServerRestartPolicy'], u'AlarmDescription': u'Restart the WikiDatabase',
u'AlarmDescription': u'Restart the WikiDatabase', u'Namespace': u'system/linux',
u'Namespace': u'system/linux', u'Period': u'300',
u'Period': u'300', u'ComparisonOperator': u'GreaterThanThreshold',
u'ComparisonOperator': u'GreaterThanThreshold', u'Statistic': u'SampleCount',
u'Statistic': u'SampleCount', u'Threshold': u'2',
u'Threshold': u'2', u'MetricName': u'ServiceFailure'}}
u'MetricName': u'ServiceFailure'}}
db_ret = db_api.watch_rule_create(self.ctx, values) db_ret = db_api.watch_rule_create(self.ctx, values)
self.assertNotEqual(db_ret, None) self.assertNotEqual(db_ret, None)
@ -802,16 +800,15 @@ class stackServiceTest(unittest.TestCase):
values = {'stack_id': self.stack.id, values = {'stack_id': self.stack.id,
'state': 'NORMAL', 'state': 'NORMAL',
'name': u'OverrideAlarm2', 'name': u'OverrideAlarm2',
'rule': { 'rule': {u'EvaluationPeriods': u'1',
u'EvaluationPeriods': u'1', u'AlarmActions': [u'WebServerRestartPolicy'],
u'AlarmActions': [u'WebServerRestartPolicy'], u'AlarmDescription': u'Restart the WikiDatabase',
u'AlarmDescription': u'Restart the WikiDatabase', u'Namespace': u'system/linux',
u'Namespace': u'system/linux', u'Period': u'300',
u'Period': u'300', u'ComparisonOperator': u'GreaterThanThreshold',
u'ComparisonOperator': u'GreaterThanThreshold', u'Statistic': u'SampleCount',
u'Statistic': u'SampleCount', u'Threshold': u'2',
u'Threshold': u'2', u'MetricName': u'ServiceFailure'}}
u'MetricName': u'ServiceFailure'}}
db_ret = db_api.watch_rule_create(self.ctx, values) db_ret = db_api.watch_rule_create(self.ctx, values)
self.assertNotEqual(db_ret, None) self.assertNotEqual(db_ret, None)

View File

@ -114,7 +114,7 @@ class IdentifierTest(unittest.TestCase):
def test_arn_url_parse_qs(self): def test_arn_url_parse_qs(self):
url = self.url_prefix +\ url = self.url_prefix +\
'arn%3Aopenstack%3Aheat%3A%3At%3Astacks/s/i/p?foo=bar' 'arn%3Aopenstack%3Aheat%3A%3At%3Astacks/s/i/p?foo=bar'
hi = identifier.HeatIdentifier.from_arn_url(url) hi = identifier.HeatIdentifier.from_arn_url(url)
self.assertEqual(hi.tenant, 't') self.assertEqual(hi.tenant, 't')
self.assertEqual(hi.stack_name, 's') self.assertEqual(hi.stack_name, 's')

View File

@ -64,13 +64,14 @@ class instancesTest(unittest.TestCase):
# need to resolve the template functions # need to resolve the template functions
server_userdata = instance._build_userdata( server_userdata = instance._build_userdata(
instance.t['Properties']['UserData']) instance.t['Properties']['UserData'])
self.m.StubOutWithMock(self.fc.servers, 'create') self.m.StubOutWithMock(self.fc.servers, 'create')
self.fc.servers.create(image=1, flavor=1, key_name='test', self.fc.servers.create(
name='%s.%s' % (stack_name, instance.name), image=1, flavor=1, key_name='test',
security_groups=None, name='%s.%s' % (stack_name, instance.name),
userdata=server_userdata, scheduler_hints=None, security_groups=None,
meta=None).AndReturn(self.fc.servers.list()[1]) userdata=server_userdata, scheduler_hints=None,
meta=None).AndReturn(self.fc.servers.list()[1])
self.m.ReplayAll() self.m.ReplayAll()
self.assertEqual(instance.create(), None) self.assertEqual(instance.create(), None)
@ -103,13 +104,14 @@ class instancesTest(unittest.TestCase):
# need to resolve the template functions # need to resolve the template functions
server_userdata = instance._build_userdata( server_userdata = instance._build_userdata(
instance.t['Properties']['UserData']) instance.t['Properties']['UserData'])
self.m.StubOutWithMock(self.fc.servers, 'create') self.m.StubOutWithMock(self.fc.servers, 'create')
self.fc.servers.create(image=1, flavor=1, key_name='test', self.fc.servers.create(
name='%s.%s' % (stack_name, instance.name), image=1, flavor=1, key_name='test',
security_groups=None, name='%s.%s' % (stack_name, instance.name),
userdata=server_userdata, scheduler_hints=None, security_groups=None,
meta=None).AndReturn(self.fc.servers.list()[1]) userdata=server_userdata, scheduler_hints=None,
meta=None).AndReturn(self.fc.servers.list()[1])
self.m.ReplayAll() self.m.ReplayAll()
self.assertEqual(instance.create(), None) self.assertEqual(instance.create(), None)

View File

@ -76,8 +76,8 @@ class LoadBalancerTest(unittest.TestCase):
def create_loadbalancer(self, t, stack, resource_name): def create_loadbalancer(self, t, stack, resource_name):
resource = lb.LoadBalancer(resource_name, resource = lb.LoadBalancer(resource_name,
t['Resources'][resource_name], t['Resources'][resource_name],
stack) stack)
self.assertEqual(None, resource.validate()) self.assertEqual(None, resource.validate())
self.assertEqual(None, resource.create()) self.assertEqual(None, resource.create())
self.assertEqual(lb.LoadBalancer.CREATE_COMPLETE, resource.state) self.assertEqual(lb.LoadBalancer.CREATE_COMPLETE, resource.state)
@ -85,12 +85,12 @@ class LoadBalancerTest(unittest.TestCase):
def test_loadbalancer(self): def test_loadbalancer(self):
lb.LoadBalancer.nova().AndReturn(self.fc) lb.LoadBalancer.nova().AndReturn(self.fc)
# parser.Stack.store(mox.IgnoreArg()).AndReturn('5678')
instance.Instance.nova().MultipleTimes().AndReturn(self.fc) instance.Instance.nova().MultipleTimes().AndReturn(self.fc)
self.fc.servers.create(flavor=2, image=745, key_name='test', self.fc.servers.create(
meta=None, name=u'test_stack.LoadBalancer.LB_instance', flavor=2, image=745, key_name='test',
scheduler_hints=None, userdata=mox.IgnoreArg(), meta=None, name=u'test_stack.LoadBalancer.LB_instance',
security_groups=None).AndReturn(self.fc.servers.list()[1]) scheduler_hints=None, userdata=mox.IgnoreArg(),
security_groups=None).AndReturn(self.fc.servers.list()[1])
#stack.Stack.create_with_template(mox.IgnoreArg()).AndReturn(None) #stack.Stack.create_with_template(mox.IgnoreArg()).AndReturn(None)
Metadata.__set__(mox.IgnoreArg(), Metadata.__set__(mox.IgnoreArg(),
mox.IgnoreArg()).AndReturn(None) mox.IgnoreArg()).AndReturn(None)
@ -112,9 +112,9 @@ class LoadBalancerTest(unittest.TestCase):
self.assertEqual(None, resource.validate()) self.assertEqual(None, resource.validate())
hc['Timeout'] = 35 hc['Timeout'] = 35
self.assertEqual({'Error': self.assertEqual(
'Interval must be larger than Timeout'}, {'Error': 'Interval must be larger than Timeout'},
resource.validate()) resource.validate())
hc['Timeout'] = 5 hc['Timeout'] = 5
self.assertEqual('LoadBalancer', resource.FnGetRefId()) self.assertEqual('LoadBalancer', resource.FnGetRefId())

View File

@ -291,7 +291,7 @@ class ParametersTest(unittest.TestCase):
def test_schema_invariance(self): def test_schema_invariance(self):
params1 = parameters.Parameters('test', params_schema, params1 = parameters.Parameters('test', params_schema,
{'Defaulted': 'wibble'}) {'Defaulted': 'wibble'})
self.assertEqual(params1['Defaulted'], 'wibble') self.assertEqual(params1['Defaulted'], 'wibble')
params2 = parameters.Parameters('test', params_schema) params2 = parameters.Parameters('test', params_schema)

View File

@ -88,8 +88,8 @@ class ParserTest(unittest.TestCase):
self.assertTrue(parsed is not raw) self.assertTrue(parsed is not raw)
def test_join_recursive(self): def test_join_recursive(self):
raw = {'Fn::Join': ['\n', [{'Fn::Join': [' ', ['foo', 'bar']]}, raw = {'Fn::Join': ['\n', [{'Fn::Join':
'baz']]} [' ', ['foo', 'bar']]}, 'baz']]}
self.assertEqual(join(raw), 'foo bar\nbaz') self.assertEqual(join(raw), 'foo bar\nbaz')
@ -206,19 +206,20 @@ class TemplateTest(unittest.TestCase):
def test_join_reduce(self): def test_join_reduce(self):
join = {"Fn::Join": [" ", ["foo", "bar", "baz", {'Ref': 'baz'}, join = {"Fn::Join": [" ", ["foo", "bar", "baz", {'Ref': 'baz'},
"bink", "bonk"]]} "bink", "bonk"]]}
self.assertEqual(parser.Template.reduce_joins(join), self.assertEqual(
{"Fn::Join": [" ", ["foo bar baz", {'Ref': 'baz'}, parser.Template.reduce_joins(join),
"bink bonk"]]}) {"Fn::Join": [" ", ["foo bar baz", {'Ref': 'baz'}, "bink bonk"]]})
join = {"Fn::Join": [" ", ["foo", {'Ref': 'baz'}, join = {"Fn::Join": [" ", ["foo", {'Ref': 'baz'},
"bink"]]} "bink"]]}
self.assertEqual(parser.Template.reduce_joins(join), self.assertEqual(
{"Fn::Join": [" ", ["foo", {'Ref': 'baz'}, parser.Template.reduce_joins(join),
"bink"]]}) {"Fn::Join": [" ", ["foo", {'Ref': 'baz'}, "bink"]]})
join = {"Fn::Join": [" ", [{'Ref': 'baz'}]]} join = {"Fn::Join": [" ", [{'Ref': 'baz'}]]}
self.assertEqual(parser.Template.reduce_joins(join), self.assertEqual(
parser.Template.reduce_joins(join),
{"Fn::Join": [" ", [{'Ref': 'baz'}]]}) {"Fn::Join": [" ", [{'Ref': 'baz'}]]})
def test_join(self): def test_join(self):

View File

@ -236,10 +236,9 @@ class PropertyTest(unittest.TestCase):
map_schema = {'valid': {'Type': 'Boolean'}} map_schema = {'valid': {'Type': 'Boolean'}}
list_schema = {'Type': 'Map', 'Schema': map_schema} list_schema = {'Type': 'Map', 'Schema': map_schema}
p = properties.Property({'Type': 'List', 'Schema': list_schema}) p = properties.Property({'Type': 'List', 'Schema': list_schema})
self.assertEqual(p.validate_data([{'valid': 'TRUE'}, self.assertEqual(p.validate_data(
{'valid': 'False'}]), [{'valid': 'TRUE'}, {'valid': 'False'}]),
[{'valid': True}, [{'valid': True}, {'valid': False}])
{'valid': False}])
def test_list_schema_bad_data(self): def test_list_schema_bad_data(self):
map_schema = {'valid': {'Type': 'Boolean'}} map_schema = {'valid': {'Type': 'Boolean'}}

View File

@ -88,52 +88,44 @@ class QuantumTest(unittest.TestCase):
return stack return stack
def create_net(self, t, stack, resource_name): def create_net(self, t, stack, resource_name):
resource = net.Net('test_net', resource = net.Net('test_net', t['Resources'][resource_name], stack)
t['Resources'][resource_name],
stack)
self.assertEqual(None, resource.create()) self.assertEqual(None, resource.create())
self.assertEqual(net.Net.CREATE_COMPLETE, resource.state) self.assertEqual(net.Net.CREATE_COMPLETE, resource.state)
return resource return resource
def test_validate_properties(self): def test_validate_properties(self):
vs = {'router:external': True} vs = {'router:external': True}
data = { data = {'admin_state_up': False,
'admin_state_up': False, 'value_specs': vs}
'value_specs': vs
}
p = properties.Properties(net.Net.properties_schema, data) p = properties.Properties(net.Net.properties_schema, data)
self.assertEqual(None, qr.validate_properties(p)) self.assertEqual(None, qr.validate_properties(p))
vs['shared'] = True vs['shared'] = True
self.assertEqual('shared not allowed in value_specs', self.assertEqual('shared not allowed in value_specs',
qr.validate_properties(p)) qr.validate_properties(p))
vs.pop('shared') vs.pop('shared')
vs['name'] = 'foo' vs['name'] = 'foo'
self.assertEqual('name not allowed in value_specs', self.assertEqual('name not allowed in value_specs',
qr.validate_properties(p)) qr.validate_properties(p))
vs.pop('name') vs.pop('name')
vs['tenant_id'] = '1234' vs['tenant_id'] = '1234'
self.assertEqual('tenant_id not allowed in value_specs', self.assertEqual('tenant_id not allowed in value_specs',
qr.validate_properties(p)) qr.validate_properties(p))
vs.pop('tenant_id') vs.pop('tenant_id')
vs['foo'] = '1234' vs['foo'] = '1234'
self.assertEqual(None, qr.validate_properties(p)) self.assertEqual(None, qr.validate_properties(p))
def test_prepare_properties(self): def test_prepare_properties(self):
data = { data = {'admin_state_up': False,
'admin_state_up': False, 'value_specs': {'router:external': True}}
'value_specs': {'router:external': True}
}
p = properties.Properties(net.Net.properties_schema, data) p = properties.Properties(net.Net.properties_schema, data)
props = qr.prepare_properties(p, 'resource_name') props = qr.prepare_properties(p, 'resource_name')
self.assertEqual({ self.assertEqual({'name': 'resource_name',
'name': 'resource_name', 'router:external': True,
'router:external': True, 'admin_state_up': False}, props)
'admin_state_up': False
}, props)
def test_net(self): def test_net(self):
fq = FakeQuantum() fq = FakeQuantum()
@ -157,7 +149,7 @@ class QuantumTest(unittest.TestCase):
pass pass
self.assertEqual('fc68ea2c-b60b-4b4f-bd82-94ec81110766', self.assertEqual('fc68ea2c-b60b-4b4f-bd82-94ec81110766',
resource.FnGetAtt('id')) resource.FnGetAtt('id'))
self.assertEqual(net.Net.UPDATE_REPLACE, resource.handle_update()) self.assertEqual(net.Net.UPDATE_REPLACE, resource.handle_update())

View File

@ -99,7 +99,7 @@ class ResourceTest(unittest.TestCase):
tmpl2 = {'Type': 'Foo'} tmpl2 = {'Type': 'Foo'}
tmpl3 = {'Type': 'Bar'} tmpl3 = {'Type': 'Bar'}
stack2 = parser.Stack(None, 'test_stack', parser.Template({}), stack2 = parser.Stack(None, 'test_stack', parser.Template({}),
stack_id=-1) stack_id=-1)
res1 = resource.GenericResource('test_resource', tmpl1, self.stack) res1 = resource.GenericResource('test_resource', tmpl1, self.stack)
res2 = resource.GenericResource('test_resource', tmpl2, stack2) res2 = resource.GenericResource('test_resource', tmpl2, stack2)
res3 = resource.GenericResource('test_resource2', tmpl3, stack2) res3 = resource.GenericResource('test_resource2', tmpl3, stack2)
@ -131,7 +131,7 @@ class MetadataTest(unittest.TestCase):
self.stack = parser.Stack(ctx, 'test_stack', parser.Template({})) self.stack = parser.Stack(ctx, 'test_stack', parser.Template({}))
self.stack.store() self.stack.store()
self.res = resource.GenericResource('metadata_resource', self.res = resource.GenericResource('metadata_resource',
tmpl, self.stack) tmpl, self.stack)
self.res.create() self.res.create()
def tearDown(self): def tearDown(self):

View File

@ -72,8 +72,8 @@ class s3Test(unittest.TestCase):
def create_resource(self, t, stack, resource_name): def create_resource(self, t, stack, resource_name):
resource = s3.S3Bucket('test_resource', resource = s3.S3Bucket('test_resource',
t['Resources'][resource_name], t['Resources'][resource_name],
stack) stack)
self.assertEqual(None, resource.create()) self.assertEqual(None, resource.create())
self.assertEqual(s3.S3Bucket.CREATE_COMPLETE, resource.state) self.assertEqual(s3.S3Bucket.CREATE_COMPLETE, resource.state)
return resource return resource
@ -82,16 +82,18 @@ class s3Test(unittest.TestCase):
def test_create_container_name(self): def test_create_container_name(self):
self.m.UnsetStubs() self.m.UnsetStubs()
self.assertTrue(re.match(self.container_pattern, self.assertTrue(re.match(self.container_pattern,
s3.S3Bucket._create_container_name('test_stack.test_resource'))) s3.S3Bucket._create_container_name(
'test_stack.test_resource')))
@skip_if(skip_test, 'unable to import swiftclient') @skip_if(skip_test, 'unable to import swiftclient')
def test_attributes(self): def test_attributes(self):
swiftclient.Connection.put_container( swiftclient.Connection.put_container(
mox.Regex(self.container_pattern), mox.Regex(self.container_pattern),
{'X-Container-Write': 'test_tenant:test_username', {'X-Container-Write': 'test_tenant:test_username',
'X-Container-Read': 'test_tenant:test_username'}).AndReturn(None) 'X-Container-Read': 'test_tenant:test_username'}
).AndReturn(None)
swiftclient.Connection.get_auth().MultipleTimes().AndReturn( swiftclient.Connection.get_auth().MultipleTimes().AndReturn(
('http://localhost:8080/v_2', None)) ('http://localhost:8080/v_2', None))
swiftclient.Connection.delete_container( swiftclient.Connection.delete_container(
mox.Regex(self.container_pattern)).AndReturn(None) mox.Regex(self.container_pattern)).AndReturn(None)
@ -125,7 +127,7 @@ class s3Test(unittest.TestCase):
swiftclient.Connection.put_container( swiftclient.Connection.put_container(
mox.Regex(self.container_pattern), mox.Regex(self.container_pattern),
{'X-Container-Write': 'test_tenant:test_username', {'X-Container-Write': 'test_tenant:test_username',
'X-Container-Read': '.r:*'}).AndReturn(None) 'X-Container-Read': '.r:*'}).AndReturn(None)
swiftclient.Connection.delete_container( swiftclient.Connection.delete_container(
mox.Regex(self.container_pattern)).AndReturn(None) mox.Regex(self.container_pattern)).AndReturn(None)
@ -143,7 +145,7 @@ class s3Test(unittest.TestCase):
swiftclient.Connection.put_container( swiftclient.Connection.put_container(
mox.Regex(self.container_pattern), mox.Regex(self.container_pattern),
{'X-Container-Write': '.r:*', {'X-Container-Write': '.r:*',
'X-Container-Read': '.r:*'}).AndReturn(None) 'X-Container-Read': '.r:*'}).AndReturn(None)
swiftclient.Connection.delete_container( swiftclient.Connection.delete_container(
mox.Regex(self.container_pattern)).AndReturn(None) mox.Regex(self.container_pattern)).AndReturn(None)
@ -161,7 +163,7 @@ class s3Test(unittest.TestCase):
swiftclient.Connection.put_container( swiftclient.Connection.put_container(
mox.Regex(self.container_pattern), mox.Regex(self.container_pattern),
{'X-Container-Write': 'test_tenant:test_username', {'X-Container-Write': 'test_tenant:test_username',
'X-Container-Read': 'test_tenant'}).AndReturn(None) 'X-Container-Read': 'test_tenant'}).AndReturn(None)
swiftclient.Connection.delete_container( swiftclient.Connection.delete_container(
mox.Regex(self.container_pattern)).AndReturn(None) mox.Regex(self.container_pattern)).AndReturn(None)
@ -199,10 +201,10 @@ class s3Test(unittest.TestCase):
swiftclient.Connection.put_container( swiftclient.Connection.put_container(
mox.Regex(self.container_pattern), mox.Regex(self.container_pattern),
{'X-Container-Write': 'test_tenant:test_username', {'X-Container-Write': 'test_tenant:test_username',
'X-Container-Read': 'test_tenant:test_username'}).AndReturn(None) 'X-Container-Read': 'test_tenant:test_username'}).AndReturn(None)
swiftclient.Connection.delete_container( swiftclient.Connection.delete_container(
mox.Regex(self.container_pattern)).AndRaise( mox.Regex(self.container_pattern)).AndRaise(
swiftclient.ClientException('Test delete failure')) swiftclient.ClientException('Test delete failure'))
self.m.ReplayAll() self.m.ReplayAll()
t = self.load_template() t = self.load_template()
@ -219,7 +221,7 @@ class s3Test(unittest.TestCase):
swiftclient.Connection.put_container( swiftclient.Connection.put_container(
mox.Regex(self.container_pattern), mox.Regex(self.container_pattern),
{'X-Container-Write': 'test_tenant:test_username', {'X-Container-Write': 'test_tenant:test_username',
'X-Container-Read': 'test_tenant:test_username'}).AndReturn(None) 'X-Container-Read': 'test_tenant:test_username'}).AndReturn(None)
# This should not be called # This should not be called
swiftclient.Connection.delete_container( swiftclient.Connection.delete_container(
mox.Regex(self.container_pattern)).AndReturn(None) mox.Regex(self.container_pattern)).AndReturn(None)

View File

@ -37,8 +37,8 @@ class JsonToYamlTest(unittest.TestCase):
template_test_count = 0 template_test_count = 0
for (json_str, for (json_str,
yml_str, yml_str,
file_name) in self.convert_all_json_to_yaml(path): file_name) in self.convert_all_json_to_yaml(path):
self.compare_json_vs_yaml(json_str, yml_str, file_name) self.compare_json_vs_yaml(json_str, yml_str, file_name)
template_test_count += 1 template_test_count += 1
@ -46,20 +46,20 @@ class JsonToYamlTest(unittest.TestCase):
break break
self.assertTrue(template_test_count >= self.expected_test_count, self.assertTrue(template_test_count >= self.expected_test_count,
'Expected at least %d templates to be tested' % 'Expected at least %d templates to be tested' %
self.expected_test_count) self.expected_test_count)
def compare_json_vs_yaml(self, json_str, yml_str, file_name): def compare_json_vs_yaml(self, json_str, yml_str, file_name):
yml = template_format.parse(yml_str) yml = template_format.parse(yml_str)
self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'],
file_name) file_name)
self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name)
del(yml[u'HeatTemplateFormatVersion']) del(yml[u'HeatTemplateFormatVersion'])
jsn = template_format.parse(json_str) jsn = template_format.parse(json_str)
template_format.default_for_missing(jsn, 'AWSTemplateFormatVersion', template_format.default_for_missing(jsn, 'AWSTemplateFormatVersion',
template_format.CFN_VERSIONS) template_format.CFN_VERSIONS)
if u'AWSTemplateFormatVersion' in jsn: if u'AWSTemplateFormatVersion' in jsn:
del(jsn[u'AWSTemplateFormatVersion']) del(jsn[u'AWSTemplateFormatVersion'])
@ -124,7 +124,7 @@ class JsonYamlResolvedCompareTest(unittest.TestCase):
def compare_stacks(self, json_file, yaml_file, parameters): def compare_stacks(self, json_file, yaml_file, parameters):
t1 = self.load_template(json_file) t1 = self.load_template(json_file)
template_format.default_for_missing(t1, 'AWSTemplateFormatVersion', template_format.default_for_missing(t1, 'AWSTemplateFormatVersion',
template_format.CFN_VERSIONS) template_format.CFN_VERSIONS)
del(t1[u'AWSTemplateFormatVersion']) del(t1[u'AWSTemplateFormatVersion'])
t2 = self.load_template(yaml_file) t2 = self.load_template(yaml_file)
@ -143,7 +143,7 @@ class JsonYamlResolvedCompareTest(unittest.TestCase):
self.assertEqual(t1nr, t2nr) self.assertEqual(t1nr, t2nr)
self.assertEquals(set(stack1.resources.keys()), self.assertEquals(set(stack1.resources.keys()),
set(stack2.resources.keys())) set(stack2.resources.keys()))
for key in stack1.resources: for key in stack1.resources:
self.assertEqual(stack1.resources[key].t, stack2.resources[key].t) self.assertEqual(stack1.resources[key].t, stack2.resources[key].t)
@ -152,5 +152,5 @@ class JsonYamlResolvedCompareTest(unittest.TestCase):
def test_wordpress_resolved(self): def test_wordpress_resolved(self):
self.compare_stacks('WordPress_Single_Instance.template', self.compare_stacks('WordPress_Single_Instance.template',
'WordPress_Single_Instance.yaml', 'WordPress_Single_Instance.yaml',
{'KeyName': 'test'}) {'KeyName': 'test'})

View File

@ -68,8 +68,8 @@ class UserTest(unittest.TestCase):
def create_user(self, t, stack, resource_name): def create_user(self, t, stack, resource_name):
resource = user.User(resource_name, resource = user.User(resource_name,
t['Resources'][resource_name], t['Resources'][resource_name],
stack) stack)
self.assertEqual(None, resource.validate()) self.assertEqual(None, resource.validate())
self.assertEqual(None, resource.create()) self.assertEqual(None, resource.create())
self.assertEqual(user.User.CREATE_COMPLETE, resource.state) self.assertEqual(user.User.CREATE_COMPLETE, resource.state)
@ -91,7 +91,7 @@ class UserTest(unittest.TestCase):
self.assertEqual('CREATE_COMPLETE', resource.state) self.assertEqual('CREATE_COMPLETE', resource.state)
self.assertEqual(user.User.UPDATE_REPLACE, self.assertEqual(user.User.UPDATE_REPLACE,
resource.handle_update()) resource.handle_update())
resource.resource_id = None resource.resource_id = None
self.assertEqual(None, resource.delete()) self.assertEqual(None, resource.delete())
@ -113,8 +113,8 @@ class UserTest(unittest.TestCase):
def create_access_key(self, t, stack, resource_name): def create_access_key(self, t, stack, resource_name):
resource = user.AccessKey(resource_name, resource = user.AccessKey(resource_name,
t['Resources'][resource_name], t['Resources'][resource_name],
stack) stack)
self.assertEqual(None, resource.validate()) self.assertEqual(None, resource.validate())
self.assertEqual(None, resource.create()) self.assertEqual(None, resource.create())
self.assertEqual(user.AccessKey.CREATE_COMPLETE, self.assertEqual(user.AccessKey.CREATE_COMPLETE,
@ -138,7 +138,7 @@ class UserTest(unittest.TestCase):
resource = self.create_access_key(t, stack, 'HostKeys') resource = self.create_access_key(t, stack, 'HostKeys')
self.assertEqual(user.AccessKey.UPDATE_REPLACE, self.assertEqual(user.AccessKey.UPDATE_REPLACE,
resource.handle_update()) resource.handle_update())
self.assertEqual(self.fc.access, self.assertEqual(self.fc.access,
resource.resource_id) resource.resource_id)

View File

@ -65,40 +65,40 @@ test_template_ref = '''
"KeyName" : { "KeyName" : {
''' + \ ''' + \
'"Description" : "Name of an existing EC2' + \ '"Description" : "Name of an existing EC2' + \
'KeyPair to enable SSH access to the instances",' + \ 'KeyPair to enable SSH access to the instances",' + \
''' '''
"Type" : "String" "Type" : "String"
} }
}, },
"Resources" : { "Resources" : {
"WikiDatabase": { "WikiDatabase": {
"Type": "AWS::EC2::Instance", "Type": "AWS::EC2::Instance",
"Properties": { "Properties": {
"ImageId": "image_name", "ImageId": "image_name",
"InstanceType": "m1.large", "InstanceType": "m1.large",
"KeyName": { "Ref" : "KeyName" } "KeyName": { "Ref" : "KeyName" }
} }
}, },
"DataVolume" : { "DataVolume" : {
"Type" : "AWS::EC2::Volume", "Type" : "AWS::EC2::Volume",
"Properties" : { "Properties" : {
"Size" : "6", "Size" : "6",
"AvailabilityZone" : "nova" "AvailabilityZone" : "nova"
} }
}, },
"MountPoint" : { "MountPoint" : {
"Type" : "AWS::EC2::VolumeAttachment", "Type" : "AWS::EC2::VolumeAttachment",
"Properties" : { "Properties" : {
"InstanceId" : { "Ref" : "%s" }, "InstanceId" : { "Ref" : "%s" },
"VolumeId" : { "Ref" : "DataVolume" }, "VolumeId" : { "Ref" : "DataVolume" },
"Device" : "/dev/vdb" "Device" : "/dev/vdb"
}
}
} }
} }
} '''
}
'''
test_template_findinmap_valid = ''' test_template_findinmap_valid = '''
{ {
"AWSTemplateFormatVersion" : "2010-09-09", "AWSTemplateFormatVersion" : "2010-09-09",
@ -106,41 +106,41 @@ test_template_findinmap_valid = '''
"Parameters" : { "Parameters" : {
"KeyName" : { "KeyName" : {
''' + \ ''' + \
'"Description" : "Name of an existing EC2 KeyPair to' + \ '"Description" : "Name of an existing EC2 KeyPair to' + \
'enable SSH access to the instances",' + \ 'enable SSH access to the instances",' + \
''' '''
"Type" : "String" "Type" : "String"
} }
}, },
"Resources" : { "Resources" : {
"WikiDatabase": { "WikiDatabase": {
"Type": "AWS::EC2::Instance", "Type": "AWS::EC2::Instance",
"Properties": { "Properties": {
"ImageId": "image_name", "ImageId": "image_name",
"InstanceType": "m1.large", "InstanceType": "m1.large",
"KeyName": { "Ref" : "KeyName" } "KeyName": { "Ref" : "KeyName" }
} }
}, },
"DataVolume" : { "DataVolume" : {
"Type" : "AWS::EC2::Volume", "Type" : "AWS::EC2::Volume",
"Properties" : { "Properties" : {
"Size" : "6", "Size" : "6",
"AvailabilityZone" : "nova" "AvailabilityZone" : "nova"
} }
}, },
"MountPoint" : { "MountPoint" : {
"Type" : "AWS::EC2::VolumeAttachment", "Type" : "AWS::EC2::VolumeAttachment",
"Properties" : { "Properties" : {
"InstanceId" : { "Ref" : "WikiDatabase" }, "InstanceId" : { "Ref" : "WikiDatabase" },
"VolumeId" : { "Ref" : "DataVolume" }, "VolumeId" : { "Ref" : "DataVolume" },
"Device" : "/dev/vdb" "Device" : "/dev/vdb"
}
}
} }
} }
} '''
}
'''
test_template_findinmap_invalid = ''' test_template_findinmap_invalid = '''
{ {
"AWSTemplateFormatVersion" : "2010-09-09", "AWSTemplateFormatVersion" : "2010-09-09",
@ -149,39 +149,39 @@ test_template_findinmap_invalid = '''
"KeyName" : { "KeyName" : {
''' + \ ''' + \
'"Description" : "Name of an existing EC2 KeyPair to enable SSH ' + \ '"Description" : "Name of an existing EC2 KeyPair to enable SSH ' + \
'access to the instances",' + \ 'access to the instances",' + \
''' "Type" : "String" ''' "Type" : "String"
} }
}, },
"Mappings" : { "Mappings" : {
"AWSInstanceType2Arch" : { "AWSInstanceType2Arch" : {
"t1.micro" : { "Arch" : "64" }, "t1.micro" : { "Arch" : "64" },
"m1.small" : { "Arch" : "64" }, "m1.small" : { "Arch" : "64" },
"m1.medium" : { "Arch" : "64" }, "m1.medium" : { "Arch" : "64" },
"m1.large" : { "Arch" : "64" }, "m1.large" : { "Arch" : "64" },
"m1.xlarge" : { "Arch" : "64" }, "m1.xlarge" : { "Arch" : "64" },
"m2.xlarge" : { "Arch" : "64" }, "m2.xlarge" : { "Arch" : "64" },
"m2.2xlarge" : { "Arch" : "64" }, "m2.2xlarge" : { "Arch" : "64" },
"m2.4xlarge" : { "Arch" : "64" }, "m2.4xlarge" : { "Arch" : "64" },
"c1.medium" : { "Arch" : "64" }, "c1.medium" : { "Arch" : "64" },
"c1.xlarge" : { "Arch" : "64" }, "c1.xlarge" : { "Arch" : "64" },
"cc1.4xlarge" : { "Arch" : "64HVM" }, "cc1.4xlarge" : { "Arch" : "64HVM" },
"cc2.8xlarge" : { "Arch" : "64HVM" }, "cc2.8xlarge" : { "Arch" : "64HVM" },
"cg1.4xlarge" : { "Arch" : "64HVM" } "cg1.4xlarge" : { "Arch" : "64HVM" }
} }
}, },
"Resources" : { "Resources" : {
"WikiDatabase": { "WikiDatabase": {
"Type": "AWS::EC2::Instance", "Type": "AWS::EC2::Instance",
"Properties": { "Properties": {
''' + \ ''' + \
'"ImageId" : { "Fn::FindInMap" : [ "DistroArch2AMI", { "Ref" : ' + \ '"ImageId" : { "Fn::FindInMap" : [ "DistroArch2AMI", { "Ref" : ' + \
'"LinuxDistribution" },' + \ '"LinuxDistribution" },' + \
'{ "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : ' + \ '{ "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : ' + \
'"InstanceType" }, "Arch" ] } ] },' + \ '"InstanceType" }, "Arch" ] } ] },' + \
''' '''
"InstanceType": "m1.large", "InstanceType": "m1.large",
"KeyName": { "Ref" : "KeyName"} "KeyName": { "Ref" : "KeyName"}
} }
@ -250,8 +250,7 @@ class validateTest(unittest.TestCase):
self.m.ReplayAll() self.m.ReplayAll()
engine = service.EngineService('a', 't') engine = service.EngineService('a', 't')
res = dict(engine. res = dict(engine.validate_template(None, t))
validate_template(None, t))
print 'res %s' % res print 'res %s' % res
self.assertEqual(res['Description'], 'test.') self.assertEqual(res['Description'], 'test.')
@ -263,8 +262,7 @@ class validateTest(unittest.TestCase):
self.m.ReplayAll() self.m.ReplayAll()
engine = service.EngineService('a', 't') engine = service.EngineService('a', 't')
res = dict(engine. res = dict(engine.validate_template(None, t))
validate_template(None, t))
self.assertNotEqual(res['Description'], 'Successfully validated') self.assertNotEqual(res['Description'], 'Successfully validated')
def test_validate_findinmap_valid(self): def test_validate_findinmap_valid(self):
@ -275,8 +273,7 @@ class validateTest(unittest.TestCase):
self.m.ReplayAll() self.m.ReplayAll()
engine = service.EngineService('a', 't') engine = service.EngineService('a', 't')
res = dict(engine. res = dict(engine.validate_template(None, t))
validate_template(None, t))
self.assertEqual(res['Description'], 'test.') self.assertEqual(res['Description'], 'test.')
def test_validate_findinmap_invalid(self): def test_validate_findinmap_invalid(self):
@ -287,6 +284,5 @@ class validateTest(unittest.TestCase):
self.m.ReplayAll() self.m.ReplayAll()
engine = service.EngineService('a', 't') engine = service.EngineService('a', 't')
res = dict(engine. res = dict(engine.validate_template(None, t))
validate_template(None, t))
self.assertNotEqual(res['Description'], 'Successfully validated') self.assertNotEqual(res['Description'], 'Successfully validated')

View File

@ -91,9 +91,9 @@ class VolumeTest(unittest.TestCase):
# create script # create script
vol.Volume.nova('volume').MultipleTimes().AndReturn(self.fc) vol.Volume.nova('volume').MultipleTimes().AndReturn(self.fc)
self.fc.volumes.create(u'1', self.fc.volumes.create(
display_description='%s.DataVolume' % stack_name, u'1', display_description='%s.DataVolume' % stack_name,
display_name='%s.DataVolume' % stack_name).AndReturn(fv) display_name='%s.DataVolume' % stack_name).AndReturn(fv)
# delete script # delete script
self.fc.volumes.get('vol-123').AndReturn(fv) self.fc.volumes.get('vol-123').AndReturn(fv)
@ -125,9 +125,9 @@ class VolumeTest(unittest.TestCase):
# create script # create script
vol.Volume.nova('volume').AndReturn(self.fc) vol.Volume.nova('volume').AndReturn(self.fc)
self.fc.volumes.create(u'1', self.fc.volumes.create(
display_description='%s.DataVolume' % stack_name, u'1', display_description='%s.DataVolume' % stack_name,
display_name='%s.DataVolume' % stack_name).AndReturn(fv) display_name='%s.DataVolume' % stack_name).AndReturn(fv)
eventlet.sleep(1).AndReturn(None) eventlet.sleep(1).AndReturn(None)
@ -150,17 +150,18 @@ class VolumeTest(unittest.TestCase):
# volume create # volume create
vol.Volume.nova('volume').MultipleTimes().AndReturn(self.fc) vol.Volume.nova('volume').MultipleTimes().AndReturn(self.fc)
self.fc.volumes.create(u'1', self.fc.volumes.create(
display_description='%s.DataVolume' % stack_name, u'1', display_description='%s.DataVolume' % stack_name,
display_name='%s.DataVolume' % stack_name).AndReturn(fv) display_name='%s.DataVolume' % stack_name).AndReturn(fv)
# create script # create script
vol.VolumeAttachment.nova().MultipleTimes().AndReturn(self.fc) vol.VolumeAttachment.nova().MultipleTimes().AndReturn(self.fc)
vol.VolumeAttachment.nova('volume').MultipleTimes().AndReturn(self.fc) vol.VolumeAttachment.nova('volume').MultipleTimes().AndReturn(self.fc)
eventlet.sleep(1).MultipleTimes().AndReturn(None) eventlet.sleep(1).MultipleTimes().AndReturn(None)
self.fc.volumes.create_server_volume(device=u'/dev/vdc', self.fc.volumes.create_server_volume(
server_id=u'WikiDatabase', device=u'/dev/vdc',
volume_id=u'vol-123').AndReturn(fva) server_id=u'WikiDatabase',
volume_id=u'vol-123').AndReturn(fva)
self.fc.volumes.get('vol-123').AndReturn(fva) self.fc.volumes.get('vol-123').AndReturn(fva)
@ -185,17 +186,18 @@ class VolumeTest(unittest.TestCase):
# volume create # volume create
vol.Volume.nova('volume').MultipleTimes().AndReturn(self.fc) vol.Volume.nova('volume').MultipleTimes().AndReturn(self.fc)
self.fc.volumes.create(u'1', self.fc.volumes.create(
display_description='%s.DataVolume' % stack_name, u'1', display_description='%s.DataVolume' % stack_name,
display_name='%s.DataVolume' % stack_name).AndReturn(fv) display_name='%s.DataVolume' % stack_name).AndReturn(fv)
# create script # create script
vol.VolumeAttachment.nova().MultipleTimes().AndReturn(self.fc) vol.VolumeAttachment.nova().MultipleTimes().AndReturn(self.fc)
vol.VolumeAttachment.nova('volume').MultipleTimes().AndReturn(self.fc) vol.VolumeAttachment.nova('volume').MultipleTimes().AndReturn(self.fc)
eventlet.sleep(1).MultipleTimes().AndReturn(None) eventlet.sleep(1).MultipleTimes().AndReturn(None)
self.fc.volumes.create_server_volume(device=u'/dev/vdc', self.fc.volumes.create_server_volume(
server_id=u'WikiDatabase', device=u'/dev/vdc',
volume_id=u'vol-123').AndReturn(fva) server_id=u'WikiDatabase',
volume_id=u'vol-123').AndReturn(fva)
self.fc.volumes.get('vol-123').AndReturn(fva) self.fc.volumes.get('vol-123').AndReturn(fva)

View File

@ -86,9 +86,7 @@ class QuantumTest(unittest.TestCase):
return stack return stack
def create_vpc(self, t, stack, resource_name): def create_vpc(self, t, stack, resource_name):
resource = vpc.VPC('the_vpc', resource = vpc.VPC('the_vpc', t['Resources'][resource_name], stack)
t['Resources'][resource_name],
stack)
self.assertEqual(None, resource.create()) self.assertEqual(None, resource.create())
self.assertEqual(vpc.VPC.CREATE_COMPLETE, resource.state) self.assertEqual(vpc.VPC.CREATE_COMPLETE, resource.state)
return resource return resource

View File

@ -86,13 +86,13 @@ class WaitConditionTest(unittest.TestCase):
wc.WaitCondition._create_timeout().AndReturn(eventlet.Timeout(5)) wc.WaitCondition._create_timeout().AndReturn(eventlet.Timeout(5))
wc.WaitCondition._get_status_reason( wc.WaitCondition._get_status_reason(
mox.IgnoreArg()).AndReturn(('WAITING', '')) mox.IgnoreArg()).AndReturn(('WAITING', ''))
eventlet.sleep(1).AndReturn(None) eventlet.sleep(1).AndReturn(None)
wc.WaitCondition._get_status_reason( wc.WaitCondition._get_status_reason(
mox.IgnoreArg()).AndReturn(('WAITING', '')) mox.IgnoreArg()).AndReturn(('WAITING', ''))
eventlet.sleep(1).AndReturn(None) eventlet.sleep(1).AndReturn(None)
wc.WaitCondition._get_status_reason( wc.WaitCondition._get_status_reason(
mox.IgnoreArg()).AndReturn(('SUCCESS', 'woot toot')) mox.IgnoreArg()).AndReturn(('SUCCESS', 'woot toot'))
self.m.StubOutWithMock(wc.WaitConditionHandle, 'keystone') self.m.StubOutWithMock(wc.WaitConditionHandle, 'keystone')
wc.WaitConditionHandle.keystone().MultipleTimes().AndReturn(self.fc) wc.WaitConditionHandle.keystone().MultipleTimes().AndReturn(self.fc)
@ -124,10 +124,10 @@ class WaitConditionTest(unittest.TestCase):
tmo = eventlet.Timeout(6) tmo = eventlet.Timeout(6)
wc.WaitCondition._create_timeout().AndReturn(tmo) wc.WaitCondition._create_timeout().AndReturn(tmo)
wc.WaitCondition._get_status_reason( wc.WaitCondition._get_status_reason(
mox.IgnoreArg()).AndReturn(('WAITING', '')) mox.IgnoreArg()).AndReturn(('WAITING', ''))
eventlet.sleep(1).AndReturn(None) eventlet.sleep(1).AndReturn(None)
wc.WaitCondition._get_status_reason( wc.WaitCondition._get_status_reason(
mox.IgnoreArg()).AndReturn(('WAITING', '')) mox.IgnoreArg()).AndReturn(('WAITING', ''))
eventlet.sleep(1).AndRaise(tmo) eventlet.sleep(1).AndRaise(tmo)
self.m.StubOutWithMock(wc.WaitConditionHandle, 'keystone') self.m.StubOutWithMock(wc.WaitConditionHandle, 'keystone')
@ -147,7 +147,7 @@ class WaitConditionTest(unittest.TestCase):
self.assertEqual(resource.state, self.assertEqual(resource.state,
'CREATE_FAILED') 'CREATE_FAILED')
self.assertEqual(wc.WaitCondition.UPDATE_REPLACE, self.assertEqual(wc.WaitCondition.UPDATE_REPLACE,
resource.handle_update()) resource.handle_update())
stack.delete() stack.delete()
@ -186,7 +186,7 @@ class WaitConditionHandleTest(unittest.TestCase):
# Stub waitcondition status so all goes CREATE_COMPLETE # Stub waitcondition status so all goes CREATE_COMPLETE
self.m.StubOutWithMock(wc.WaitCondition, '_get_status_reason') self.m.StubOutWithMock(wc.WaitCondition, '_get_status_reason')
wc.WaitCondition._get_status_reason( wc.WaitCondition._get_status_reason(
mox.IgnoreArg()).AndReturn(('SUCCESS', 'woot toot')) mox.IgnoreArg()).AndReturn(('SUCCESS', 'woot toot'))
self.m.StubOutWithMock(wc.WaitCondition, '_create_timeout') self.m.StubOutWithMock(wc.WaitCondition, '_create_timeout')
wc.WaitCondition._create_timeout().AndReturn(eventlet.Timeout(5)) wc.WaitCondition._create_timeout().AndReturn(eventlet.Timeout(5))
@ -210,23 +210,21 @@ class WaitConditionHandleTest(unittest.TestCase):
resource = stack.resources['WaitHandle'] resource = stack.resources['WaitHandle']
self.assertEqual(resource.state, 'CREATE_COMPLETE') self.assertEqual(resource.state, 'CREATE_COMPLETE')
expected_url = "".join( expected_url = "".join([
['http://127.0.0.1:8000/v1/waitcondition/', 'http://127.0.0.1:8000/v1/waitcondition/',
'arn%3Aopenstack%3Aheat%3A%3Atest_tenant%3Astacks%2F', 'arn%3Aopenstack%3Aheat%3A%3Atest_tenant%3Astacks%2F',
'test_stack2%2FSTACKABCD1234%2Fresources%2F', 'test_stack2%2FSTACKABCD1234%2Fresources%2F',
'WaitHandle?', 'WaitHandle?',
'Timestamp=2012-11-29T13%3A49%3A37Z&', 'Timestamp=2012-11-29T13%3A49%3A37Z&',
'SignatureMethod=HmacSHA256&', 'SignatureMethod=HmacSHA256&',
'AWSAccessKeyId=4567&', 'AWSAccessKeyId=4567&',
'SignatureVersion=2&', 'SignatureVersion=2&',
'Signature=', 'Signature=',
'ePyTwmC%2F1kSigeo%2Fha7kP8Avvb45G9Y7WOQWe4F%2BnXM%3D' 'ePyTwmC%2F1kSigeo%2Fha7kP8Avvb45G9Y7WOQWe4F%2BnXM%3D'])
])
self.assertEqual(expected_url, resource.FnGetRefId()) self.assertEqual(expected_url, resource.FnGetRefId())
self.assertEqual(resource.UPDATE_REPLACE, self.assertEqual(resource.UPDATE_REPLACE, resource.handle_update())
resource.handle_update())
stack.delete() stack.delete()

View File

@ -46,16 +46,16 @@ class WatchRuleTest(unittest.TestCase):
ctx = context.get_admin_context() ctx = context.get_admin_context()
tmpl = db_api.raw_template_create(ctx, {'foo': 'bar'}) tmpl = db_api.raw_template_create(ctx, {'foo': 'bar'})
dummy_stack = {'id': '6754d843-bed2-40dc-a325-84882bb90a98', dummy_stack = {'id': '6754d843-bed2-40dc-a325-84882bb90a98',
'name': 'dummystack', 'name': 'dummystack',
'raw_template_id': tmpl.id, 'raw_template_id': tmpl.id,
'user_creds_id': 1, 'user_creds_id': 1,
'username': 'dummyuser', 'username': 'dummyuser',
'owner_id': None, 'owner_id': None,
'status': 'CREATE_COMPLETE', 'status': 'CREATE_COMPLETE',
'status_reason': 'foo status', 'status_reason': 'foo status',
'parameters': {'foo': 'bar'}, 'parameters': {'foo': 'bar'},
'timeout': 60, 'timeout': 60,
'tenant': 123456} 'tenant': 123456}
db_ret = db_api.stack_create(ctx, dummy_stack) db_ret = db_api.stack_create(ctx, dummy_stack)
cls.stack_id = db_ret.id cls.stack_id = db_ret.id
@ -74,13 +74,12 @@ class WatchRuleTest(unittest.TestCase):
self.m.UnsetStubs() self.m.UnsetStubs()
def test_minimum(self): def test_minimum(self):
rule = { rule = {'EvaluationPeriods': '1',
'EvaluationPeriods': '1', 'MetricName': 'test_metric',
'MetricName': 'test_metric', 'Period': '300',
'Period': '300', 'Statistic': 'Minimum',
'Statistic': 'Minimum', 'ComparisonOperator': 'LessThanOrEqualToThreshold',
'ComparisonOperator': 'LessThanOrEqualToThreshold', 'Threshold': '50'}
'Threshold': '50'}
now = timeutils.utcnow() now = timeutils.utcnow()
last = now - datetime.timedelta(seconds=320) last = now - datetime.timedelta(seconds=320)
@ -110,13 +109,12 @@ class WatchRuleTest(unittest.TestCase):
self.assertEqual(new_state, 'ALARM') self.assertEqual(new_state, 'ALARM')
def test_maximum(self): def test_maximum(self):
rule = { rule = {'EvaluationPeriods': '1',
'EvaluationPeriods': '1', 'MetricName': 'test_metric',
'MetricName': 'test_metric', 'Period': '300',
'Period': '300', 'Statistic': 'Maximum',
'Statistic': 'Maximum', 'ComparisonOperator': 'GreaterThanOrEqualToThreshold',
'ComparisonOperator': 'GreaterThanOrEqualToThreshold', 'Threshold': '30'}
'Threshold': '30'}
now = timeutils.utcnow() now = timeutils.utcnow()
last = now - datetime.timedelta(seconds=320) last = now - datetime.timedelta(seconds=320)
@ -149,13 +147,12 @@ class WatchRuleTest(unittest.TestCase):
def test_samplecount(self): def test_samplecount(self):
rule = { rule = {'EvaluationPeriods': '1',
'EvaluationPeriods': '1', 'MetricName': 'test_metric',
'MetricName': 'test_metric', 'Period': '300',
'Period': '300', 'Statistic': 'SampleCount',
'Statistic': 'SampleCount', 'ComparisonOperator': 'GreaterThanOrEqualToThreshold',
'ComparisonOperator': 'GreaterThanOrEqualToThreshold', 'Threshold': '3'}
'Threshold': '3'}
now = timeutils.utcnow() now = timeutils.utcnow()
last = now - datetime.timedelta(seconds=320) last = now - datetime.timedelta(seconds=320)
@ -202,13 +199,12 @@ class WatchRuleTest(unittest.TestCase):
self.assertEqual(new_state, 'NORMAL') self.assertEqual(new_state, 'NORMAL')
def test_sum(self): def test_sum(self):
rule = { rule = {'EvaluationPeriods': '1',
'EvaluationPeriods': '1', 'MetricName': 'test_metric',
'MetricName': 'test_metric', 'Period': '300',
'Period': '300', 'Statistic': 'Sum',
'Statistic': 'Sum', 'ComparisonOperator': 'GreaterThanOrEqualToThreshold',
'ComparisonOperator': 'GreaterThanOrEqualToThreshold', 'Threshold': '100'}
'Threshold': '100'}
now = timeutils.utcnow() now = timeutils.utcnow()
last = now - datetime.timedelta(seconds=320) last = now - datetime.timedelta(seconds=320)
@ -241,13 +237,12 @@ class WatchRuleTest(unittest.TestCase):
self.assertEqual(new_state, 'ALARM') self.assertEqual(new_state, 'ALARM')
def test_ave(self): def test_ave(self):
rule = { rule = {'EvaluationPeriods': '1',
'EvaluationPeriods': '1', 'MetricName': 'test_metric',
'MetricName': 'test_metric', 'Period': '300',
'Period': '300', 'Statistic': 'Average',
'Statistic': 'Average', 'ComparisonOperator': 'GreaterThanThreshold',
'ComparisonOperator': 'GreaterThanThreshold', 'Threshold': '100'}
'Threshold': '100'}
now = timeutils.utcnow() now = timeutils.utcnow()
last = now - datetime.timedelta(seconds=320) last = now - datetime.timedelta(seconds=320)
@ -282,16 +277,15 @@ class WatchRuleTest(unittest.TestCase):
values = {'stack_id': self.stack_id, values = {'stack_id': self.stack_id,
'state': 'NORMAL', 'state': 'NORMAL',
'name': u'HttpFailureAlarm', 'name': u'HttpFailureAlarm',
'rule': { 'rule': {u'EvaluationPeriods': u'1',
u'EvaluationPeriods': u'1', u'AlarmActions': [u'WebServerRestartPolicy'],
u'AlarmActions': [u'WebServerRestartPolicy'], u'AlarmDescription': u'Restart the WikiDatabase',
u'AlarmDescription': u'Restart the WikiDatabase', u'Namespace': u'system/linux',
u'Namespace': u'system/linux', u'Period': u'300',
u'Period': u'300', u'ComparisonOperator': u'GreaterThanThreshold',
u'ComparisonOperator': u'GreaterThanThreshold', u'Statistic': u'SampleCount',
u'Statistic': u'SampleCount', u'Threshold': u'2',
u'Threshold': u'2', u'MetricName': u'ServiceFailure'}}
u'MetricName': u'ServiceFailure'}}
db_ret = db_api.watch_rule_create(self.ctx, values) db_ret = db_api.watch_rule_create(self.ctx, values)
self.assertNotEqual(db_ret, None) self.assertNotEqual(db_ret, None)
values['name'] = 'AnotherWatch' values['name'] = 'AnotherWatch'

View File

@ -73,57 +73,37 @@ class FakeHTTPClient(base_client.HTTPClient):
def get_limits(self, **kw): def get_limits(self, **kw):
return (200, {"limits": { return (200, {"limits": {
"rate": [ "rate": [{"uri": "*",
{ "regex": ".*",
"uri": "*", "limit": [
"regex": ".*", {"value": 10,
"limit": [ "verb": "POST",
{ "remaining": 2,
"value": 10, "unit": "MINUTE",
"verb": "POST", "next-available": "2011-12-15T22:42:45Z"},
"remaining": 2, {"value": 10,
"unit": "MINUTE", "verb": "PUT",
"next-available": "2011-12-15T22:42:45Z" "remaining": 2,
}, "unit": "MINUTE",
{ "next-available": "2011-12-15T22:42:45Z"},
"value": 10, {"value": 100,
"verb": "PUT", "verb": "DELETE",
"remaining": 2, "remaining": 100,
"unit": "MINUTE", "unit": "MINUTE",
"next-available": "2011-12-15T22:42:45Z" "next-available": "2011-12-15T22:42:45Z"}]},
}, {"uri": "*/servers",
{ "regex": "^/servers",
"value": 100, "limit": [{"verb": "POST",
"verb": "DELETE", "value": 25,
"remaining": 100, "remaining": 24,
"unit": "MINUTE", "unit": "DAY",
"next-available": "2011-12-15T22:42:45Z" "next-available":
} "2011-12-15T22:42:45Z"}]}],
] "absolute": {"maxTotalRAMSize": 51200,
}, "maxServerMeta": 5,
{ "maxImageMeta": 5,
"uri": "*/servers", "maxPersonality": 5,
"regex": "^/servers", "maxPersonalitySize": 10240}}})
"limit": [
{
"verb": "POST",
"value": 25,
"remaining": 24,
"unit": "DAY",
"next-available": "2011-12-15T22:42:45Z"
}
]
}
],
"absolute": {
"maxTotalRAMSize": 51200,
"maxServerMeta": 5,
"maxImageMeta": 5,
"maxPersonality": 5,
"maxPersonalitySize": 10240
},
},
})
# #
# Servers # Servers
@ -137,109 +117,67 @@ class FakeHTTPClient(base_client.HTTPClient):
]}) ]})
def get_servers_detail(self, **kw): def get_servers_detail(self, **kw):
return (200, {"servers": [ return (200, {"servers": [{"id": 1234,
{ "name": "sample-server",
"id": 1234, "image": {"id": 2,
"name": "sample-server", "name": "sample image"},
"image": { "flavor": {"id": 1,
"id": 2, "name": "256 MB Server"},
"name": "sample image", "hostId":
}, "e4d909c290d0fb1ca068ffaddf22cbd0",
"flavor": { "status": "BUILD",
"id": 1, "progress": 60,
"name": "256 MB Server", "addresses": {"public": [{"version": 4,
}, "addr":
"hostId": "e4d909c290d0fb1ca068ffaddf22cbd0", "1.2.3.4"},
"status": "BUILD", {"version": 4,
"progress": 60, "addr":
"addresses": { "5.6.7.8"}],
"public": [{ "private": [{"version": 4,
"version": 4, "addr": "10.11.12.13"}]},
"addr": "1.2.3.4", "metadata": {"Server Label": "Web Head 1",
}, "Image Version": "2.1"}},
{ {"id": 5678,
"version": 4, "name": "sample-server2",
"addr": "5.6.7.8", "image": {"id": 2,
}], "name": "sample image"},
"private": [{ "flavor": {"id": 1,
"version": 4, "name": "256 MB Server"},
"addr": "10.11.12.13", "hostId":
}], "9e107d9d372bb6826bd81d3542a419d6",
}, "status": "ACTIVE",
"metadata": { "addresses": {"public": [{"version": 4,
"Server Label": "Web Head 1", "addr":
"Image Version": "2.1" "4.5.6.7"},
} {"version": 4,
}, "addr":
{ "5.6.9.8"}],
"id": 5678, "private": [{"version": 4,
"name": "sample-server2", "addr": "10.13.12.13"}]},
"image": { "metadata": {"Server Label": "DB 1"}},
"id": 2, {"id": 9999,
"name": "sample image", "name": "sample-server3",
}, "image": {"id": 3,
"flavor": { "name": "sample image"},
"id": 1, "flavor": {"id": 3,
"name": "256 MB Server", "name": "m1.large"},
}, "hostId":
"hostId": "9e107d9d372bb6826bd81d3542a419d6", "9e107d9d372bb6826bd81d3542a419d6",
"status": "ACTIVE", "status": "ACTIVE",
"addresses": { "addresses": {
"public": [{ "public": [{"version": 4,
"version": 4, "addr": "4.5.6.7"},
"addr": "4.5.6.7", {"version": 4,
}, "addr": "5.6.9.8"}],
{ "private": [{"version": 4,
"version": 4, "addr": "10.13.12.13"}]},
"addr": "5.6.9.8", "metadata": {"Server Label": "DB 1"}}]})
}],
"private": [{
"version": 4,
"addr": "10.13.12.13",
}],
},
"metadata": {
"Server Label": "DB 1"
}
},
{
"id": 9999,
"name": "sample-server3",
"image": {
"id": 3,
"name": "sample image",
},
"flavor": {
"id": 3,
"name": "m1.large",
},
"hostId": "9e107d9d372bb6826bd81d3542a419d6",
"status": "ACTIVE",
"addresses": {
"public": [{
"version": 4,
"addr": "4.5.6.7",
},
{
"version": 4,
"addr": "5.6.9.8",
}],
"private": [{
"version": 4,
"addr": "10.13.12.13",
}],
},
"metadata": {
"Server Label": "DB 1"
}
}
]})
def post_servers(self, body, **kw): def post_servers(self, body, **kw):
assert body.keys() == ['server'] assert body.keys() == ['server']
fakes.assert_has_keys(body['server'], fakes.assert_has_keys(body['server'],
required=['name', 'imageRef', 'flavorRef'], required=['name', 'imageRef', 'flavorRef'],
optional=['metadata', 'personality']) optional=['metadata', 'personality'])
if 'personality' in body['server']: if 'personality' in body['server']:
for pfile in body['server']['personality']: for pfile in body['server']['personality']:
fakes.assert_has_keys(pfile, required=['path', 'contents']) fakes.assert_has_keys(pfile, required=['path', 'contents'])
@ -326,18 +264,12 @@ class FakeHTTPClient(base_client.HTTPClient):
return (200, 'Fake diagnostics') return (200, 'Fake diagnostics')
def get_servers_1234_actions(self, **kw): def get_servers_1234_actions(self, **kw):
return (200, {'actions': [ return (200, {'actions': [{'action': 'rebuild',
{ 'error': None,
'action': 'rebuild', 'created_at': '2011-12-30 11:45:36'},
'error': None, {'action': 'reboot',
'created_at': '2011-12-30 11:45:36' 'error': 'Failed!',
}, 'created_at': '2011-12-30 11:40:29'}]})
{
'action': 'reboot',
'error': 'Failed!',
'created_at': '2011-12-30 11:40:29'
},
]})
# #
# Server Addresses # Server Addresses
@ -425,9 +357,7 @@ class FakeHTTPClient(base_client.HTTPClient):
# #
def get_os_cloudpipe(self, **kw): def get_os_cloudpipe(self, **kw):
return (200, {'cloudpipes': [ return (200, {'cloudpipes': [{'project_id': 1}]})
{'project_id':1}
]})
def post_os_cloudpipe(self, **ks): def post_os_cloudpipe(self, **ks):
return (202, {'instance_id': '9d5824aa-20e6-4b9f-b967-76a699fc51fd'}) return (202, {'instance_id': '9d5824aa-20e6-4b9f-b967-76a699fc51fd'})
@ -484,22 +414,24 @@ class FakeHTTPClient(base_client.HTTPClient):
]}) ]})
def get_os_floating_ips_1(self, **kw): def get_os_floating_ips_1(self, **kw):
return (200, {'floating_ip': return (200, {'floating_ip': {'id': 1,
{'id': 1, 'fixed_ip': '10.0.0.1', 'ip': '11.0.0.1'} 'fixed_ip': '10.0.0.1',
}) 'ip': '11.0.0.1'}})
def post_os_floating_ips(self, body, **kw): def post_os_floating_ips(self, body, **kw):
return (202, self.get_os_floating_ips_1()[1]) return (202, self.get_os_floating_ips_1()[1])
def post_os_floating_ips(self, body): def post_os_floating_ips(self, body):
if body.get('pool'): if body.get('pool'):
return (200, {'floating_ip': return (200, {'floating_ip': {'id': 1,
{'id': 1, 'fixed_ip': '10.0.0.1', 'ip': '11.0.0.1', 'fixed_ip': '10.0.0.1',
'pool': 'nova'}}) 'ip': '11.0.0.1',
'pool': 'nova'}})
else: else:
return (200, {'floating_ip': return (200, {'floating_ip': {'id': 1,
{'id': 1, 'fixed_ip': '10.0.0.1', 'ip': '11.0.0.1', 'fixed_ip': '10.0.0.1',
'pool': None}}) 'ip': '11.0.0.1',
'pool': None}})
def delete_os_floating_ips_1(self, **kw): def delete_os_floating_ips_1(self, **kw):
return (204, None) return (204, None)
@ -512,42 +444,39 @@ class FakeHTTPClient(base_client.HTTPClient):
def get_os_floating_ip_dns_testdomain_entries(self, **kw): def get_os_floating_ip_dns_testdomain_entries(self, **kw):
if kw.get('ip'): if kw.get('ip'):
return (205, {'dns_entries': return (205, {'dns_entries':
[{'dns_entry': [{'dns_entry': {'ip': kw.get('ip'),
{'ip': kw.get('ip'), 'name': "host1",
'name': "host1", 'type': "A",
'type': "A", 'domain': 'testdomain'}},
'domain': 'testdomain'}}, {'dns_entry': {'ip': kw.get('ip'),
{'dns_entry': 'name': "host2",
{'ip': kw.get('ip'), 'type': "A",
'name': "host2", 'domain': 'testdomain'}}]})
'type': "A",
'domain': 'testdomain'}}]})
else: else:
return (404, None) return (404, None)
def get_os_floating_ip_dns_testdomain_entries_testname(self, **kw): def get_os_floating_ip_dns_testdomain_entries_testname(self, **kw):
return (205, {'dns_entry': return (205, {'dns_entry': {'ip': "10.10.10.10",
{'ip': "10.10.10.10", 'name': 'testname',
'name': 'testname', 'type': "A",
'type': "A", 'domain': 'testdomain'}})
'domain': 'testdomain'}})
def put_os_floating_ip_dns_testdomain(self, body, **kw): def put_os_floating_ip_dns_testdomain(self, body, **kw):
if body['domain_entry']['scope'] == 'private': if body['domain_entry']['scope'] == 'private':
fakes.assert_has_keys(body['domain_entry'], fakes.assert_has_keys(body['domain_entry'],
required=['availability_zone', 'scope']) required=['availability_zone', 'scope'])
elif body['domain_entry']['scope'] == 'public': elif body['domain_entry']['scope'] == 'public':
fakes.assert_has_keys(body['domain_entry'], fakes.assert_has_keys(body['domain_entry'],
required=['project', 'scope']) required=['project', 'scope'])
else: else:
fakes.assert_has_keys(body['domain_entry'], fakes.assert_has_keys(body['domain_entry'],
required=['project', 'scope']) required=['project', 'scope'])
return (205, None) return (205, None)
def put_os_floating_ip_dns_testdomain_entries_testname(self, body, **kw): def put_os_floating_ip_dns_testdomain_entries_testname(self, body, **kw):
fakes.assert_has_keys(body['dns_entry'], fakes.assert_has_keys(body['dns_entry'],
required=['ip', 'dns_type']) required=['ip', 'dns_type'])
return (205, None) return (205, None)
def delete_os_floating_ip_dns_testdomain(self, **kw): def delete_os_floating_ip_dns_testdomain(self, **kw):
@ -560,57 +489,43 @@ class FakeHTTPClient(base_client.HTTPClient):
# Images # Images
# #
def get_images(self, **kw): def get_images(self, **kw):
return (200, {'images': [ return (200, {'images': [{'id': 1, 'name': 'CentOS 5.2'},
{'id': 1, 'name': 'CentOS 5.2'}, {'id': 2, 'name': 'My Server Backup'},
{'id': 2, 'name': 'My Server Backup'}, {'id': 3, 'name': 'F17-x86_64-gold'},
{'id': 3, 'name': 'F17-x86_64-gold'}, {'id': 4, 'name': 'F17-x86_64-cfntools'}]})
{'id': 4, 'name': 'F17-x86_64-cfntools'}
]})
def get_images_detail(self, **kw): def get_images_detail(self, **kw):
return (200, {'images': [ return (200, {'images': [{'id': 1,
{ 'name': 'CentOS 5.2',
'id': 1, "updated": "2010-10-10T12:00:00Z",
'name': 'CentOS 5.2', "created": "2010-08-10T12:00:00Z",
"updated": "2010-10-10T12:00:00Z", "status": "ACTIVE",
"created": "2010-08-10T12:00:00Z", "metadata": {"test_key": "test_value"},
"status": "ACTIVE", "links": {}},
"metadata": { {"id": 743,
"test_key": "test_value", "name": "My Server Backup",
}, "serverId": 1234,
"links": {}, "updated": "2010-10-10T12:00:00Z",
}, "created": "2010-08-10T12:00:00Z",
{ "status": "SAVING",
"id": 743, "progress": 80,
"name": "My Server Backup", "links": {}},
"serverId": 1234, {"id": 744,
"updated": "2010-10-10T12:00:00Z", "name": "F17-x86_64-gold",
"created": "2010-08-10T12:00:00Z", "serverId": 9999,
"status": "SAVING", "updated": "2010-10-10T12:00:00Z",
"progress": 80, "created": "2010-08-10T12:00:00Z",
"links": {}, "status": "SAVING",
}, "progress": 80,
{ "links": {}},
"id": 744, {"id": 745,
"name": "F17-x86_64-gold", "name": "F17-x86_64-cfntools",
"serverId": 9999, "serverId": 9998,
"updated": "2010-10-10T12:00:00Z", "updated": "2010-10-10T12:00:00Z",
"created": "2010-08-10T12:00:00Z", "created": "2010-08-10T12:00:00Z",
"status": "SAVING", "status": "SAVING",
"progress": 80, "progress": 80,
"links": {}, "links": {}}]})
},
{
"id": 745,
"name": "F17-x86_64-cfntools",
"serverId": 9998,
"updated": "2010-10-10T12:00:00Z",
"created": "2010-08-10T12:00:00Z",
"status": "SAVING",
"progress": 80,
"links": {},
}
]})
def get_images_1(self, **kw): def get_images_1(self, **kw):
return (200, {'image': self.get_images_detail()[1]['images'][0]}) return (200, {'image': self.get_images_detail()[1]['images'][0]})
@ -627,8 +542,7 @@ class FakeHTTPClient(base_client.HTTPClient):
assert body.keys() == ['metadata'] assert body.keys() == ['metadata']
fakes.assert_has_keys(body['metadata'], fakes.assert_has_keys(body['metadata'],
required=['test_key']) required=['test_key'])
return (200, return (200, {'metadata': self.get_images_1()[1]['image']['metadata']})
{'metadata': self.get_images_1()[1]['image']['metadata']})
def delete_images_1(self, **kw): def delete_images_1(self, **kw):
return (204, None) return (204, None)
@ -640,9 +554,8 @@ class FakeHTTPClient(base_client.HTTPClient):
# Keypairs # Keypairs
# #
def get_os_keypairs(self, *kw): def get_os_keypairs(self, *kw):
return (200, {"keypairs": [ return (200, {"keypairs": [{'fingerprint': 'FAKE_KEYPAIR',
{'fingerprint': 'FAKE_KEYPAIR', 'name': 'test'} 'name': 'test'}]})
]})
def delete_os_keypairs_test(self, **kw): def delete_os_keypairs_test(self, **kw):
return (202, None) return (202, None)
@ -745,14 +658,16 @@ class FakeHTTPClient(base_client.HTTPClient):
# Security Groups # Security Groups
# #
def get_os_security_groups(self, **kw): def get_os_security_groups(self, **kw):
return (200, {"security_groups": [ return (200, {"security_groups": [{'id': 1,
{'id': 1, 'name': 'test', 'description': 'FAKE_SECURITY_GROUP'} 'name': 'test',
]}) 'description':
'FAKE_SECURITY_GROUP'}]})
def get_os_security_groups_1(self, **kw): def get_os_security_groups_1(self, **kw):
return (200, {"security_group": return (200, {"security_group": {'id': 1,
{'id': 1, 'name': 'test', 'description': 'FAKE_SECURITY_GROUP'} 'name': 'test',
}) 'description':
'FAKE_SECURITY_GROUP'}})
def delete_os_security_groups_1(self, **kw): def delete_os_security_groups_1(self, **kw):
return (202, None) return (202, None)
@ -762,18 +677,20 @@ class FakeHTTPClient(base_client.HTTPClient):
fakes.assert_has_keys(body['security_group'], fakes.assert_has_keys(body['security_group'],
required=['name', 'description']) required=['name', 'description'])
r = {'security_group': r = {'security_group':
self.get_os_security_groups()[1]['security_groups'][0]} self.get_os_security_groups()[1]['security_groups'][0]}
return (202, r) return (202, r)
# #
# Security Group Rules # Security Group Rules
# #
def get_os_security_group_rules(self, **kw): def get_os_security_group_rules(self, **kw):
return (200, {"security_group_rules": [ return (200, {"security_group_rules": [{'id': 1,
{'id': 1, 'parent_group_id': 1, 'group_id': 2, 'parent_group_id': 1,
'ip_protocol': 'TCP', 'from_port': '22', 'to_port': 22, 'group_id': 2,
'cidr': '10.0.0.0/8'} 'ip_protocol': 'TCP',
]}) 'from_port': '22',
'to_port': 22,
'cidr': '10.0.0.0/8'}]})
def delete_os_security_group_rules_1(self, **kw): def delete_os_security_group_rules_1(self, **kw):
return (202, None) return (202, None)
@ -781,11 +698,11 @@ class FakeHTTPClient(base_client.HTTPClient):
def post_os_security_group_rules(self, body, **kw): def post_os_security_group_rules(self, body, **kw):
assert body.keys() == ['security_group_rule'] assert body.keys() == ['security_group_rule']
fakes.assert_has_keys(body['security_group_rule'], fakes.assert_has_keys(body['security_group_rule'],
required=['parent_group_id'], required=['parent_group_id'],
optional=['group_id', 'ip_protocol', 'from_port', optional=['group_id', 'ip_protocol', 'from_port',
'to_port', 'cidr']) 'to_port', 'cidr'])
r = {'security_group_rule': r = {'security_group_rule':
self.get_os_security_group_rules()[1]['security_group_rules'][0]} self.get_os_security_group_rules()[1]['security_group_rules'][0]}
return (202, r) return (202, r)
# #
@ -841,10 +758,10 @@ class FakeHTTPClient(base_client.HTTPClient):
# #
def get_os_aggregates(self, *kw): def get_os_aggregates(self, *kw):
return (200, {"aggregates": [ return (200, {"aggregates": [
{'id':'1', {'id': '1',
'name': 'test', 'name': 'test',
'availability_zone': 'nova1'}, 'availability_zone': 'nova1'},
{'id':'2', {'id': '2',
'name': 'test2', 'name': 'test2',
'availability_zone': 'nova1'}, 'availability_zone': 'nova1'},
]}) ]})