本文整理汇总了Python中botocore.stub.Stubber.add_client_error方法的典型用法代码示例。如果您正苦于以下问题:Python Stubber.add_client_error方法的具体用法?Python Stubber.add_client_error怎么用?Python Stubber.add_client_error使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类botocore.stub.Stubber
的用法示例。
在下文中一共展示了Stubber.add_client_error方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_ensure_cfn_bucket_doesnt_exist_us_west
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import add_client_error [as 别名]
def test_ensure_cfn_bucket_doesnt_exist_us_west(self):
session = get_session("us-west-1")
provider = Provider(session)
action = BaseAction(
context=mock_context("mynamespace"),
provider_builder=MockProviderBuilder(provider, region="us-west-1")
)
stubber = Stubber(action.s3_conn)
stubber.add_client_error(
"head_bucket",
service_error_code="NoSuchBucket",
service_message="Not Found",
http_status_code=404,
)
stubber.add_response(
"create_bucket",
service_response={},
expected_params={
"Bucket": ANY,
"CreateBucketConfiguration": {
"LocationConstraint": "us-west-1",
}
}
)
with stubber:
action.ensure_cfn_bucket()
示例2: TestLogsCommandContext_get_resource_id_from_stack
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import add_client_error [as 别名]
class TestLogsCommandContext_get_resource_id_from_stack(TestCase):
def setUp(self):
self.real_client = botocore.session.get_session().create_client('cloudformation', region_name="us-east-1")
self.cfn_client_stubber = Stubber(self.real_client)
self.logical_id = "name"
self.stack_name = "stackname"
self.physical_id = "myid"
def test_must_get_from_cfn(self):
expected_params = {
"StackName": self.stack_name,
"LogicalResourceId": self.logical_id
}
mock_response = {
"StackResourceDetail": {
"PhysicalResourceId": self.physical_id,
"LogicalResourceId": self.logical_id,
"ResourceType": "AWS::Lambda::Function",
"ResourceStatus": "UPDATE_COMPLETE",
"LastUpdatedTimestamp": "2017-07-28T23:34:13.435Z"
}
}
self.cfn_client_stubber.add_response("describe_stack_resource", mock_response, expected_params)
with self.cfn_client_stubber:
result = LogsCommandContext._get_resource_id_from_stack(self.real_client,
self.stack_name,
self.logical_id)
self.assertEquals(result, self.physical_id)
def test_must_handle_resource_not_found(self):
errmsg = "Something went wrong"
errcode = "SomeException"
self.cfn_client_stubber.add_client_error("describe_stack_resource",
service_error_code=errcode,
service_message=errmsg)
expected_error_msg = "An error occurred ({}) when calling the DescribeStackResource operation: {}".format(
errcode, errmsg)
with self.cfn_client_stubber:
with self.assertRaises(UserException) as context:
LogsCommandContext._get_resource_id_from_stack(self.real_client,
self.stack_name,
self.logical_id)
self.assertEquals(expected_error_msg, str(context.exception))
示例3: test_ensure_cfn_forbidden
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import add_client_error [as 别名]
def test_ensure_cfn_forbidden(self):
session = get_session("us-west-1")
provider = Provider(session)
action = BaseAction(
context=mock_context("mynamespace"),
provider_builder=MockProviderBuilder(provider)
)
stubber = Stubber(action.s3_conn)
stubber.add_client_error(
"head_bucket",
service_error_code="AccessDenied",
service_message="Forbidden",
http_status_code=403,
)
with stubber:
with self.assertRaises(botocore.exceptions.ClientError):
action.ensure_cfn_bucket()
示例4: TestStubber
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import add_client_error [as 别名]
#.........这里部分代码省略.........
# This just ensures that we register at the correct event
# and nothing more
self.event_emitter.register_first.assert_called_with(
'before-parameter-build.*.*', mock.ANY, unique_id=mock.ANY)
self.event_emitter.register.assert_called_with(
'before-call.*.*', mock.ANY, unique_id=mock.ANY)
def test_stubber_unregisters_events(self):
self.event_emitter = mock.Mock()
self.client.meta.events = self.event_emitter
self.stubber.activate()
self.stubber.deactivate()
self.event_emitter.unregister.assert_any_call(
'before-parameter-build.*.*', mock.ANY, unique_id=mock.ANY)
self.event_emitter.unregister.assert_any_call(
'before-call.*.*', mock.ANY, unique_id=mock.ANY)
def test_add_response(self):
response = {'foo': 'bar'}
self.stubber.add_response('foo', response)
with self.assertRaises(AssertionError):
self.stubber.assert_no_pending_responses()
def test_add_response_fails_when_missing_client_method(self):
del self.client.foo
with self.assertRaises(ValueError):
self.stubber.add_response('foo', {})
def test_validates_service_response(self):
self.stubber.add_response('foo', {})
self.assertTrue(self.validate_parameters_mock.called)
def test_validate_ignores_response_metadata(self):
service_response = {'ResponseMetadata': {'foo': 'bar'}}
service_model = ServiceModel({
'documentation': '',
'operations': {
'foo': {
'name': 'foo',
'input': {'shape': 'StringShape'},
'output': {'shape': 'StringShape'}
}
},
'shapes': {
'StringShape': {'type': 'string'}
}
})
op_name = service_model.operation_names[0]
output_shape = service_model.operation_model(op_name).output_shape
self.client.meta.service_model = service_model
self.stubber.add_response('TestOperation', service_response)
self.validate_parameters_mock.assert_called_with(
{}, output_shape)
# Make sure service response hasn't been mutated
self.assertEqual(
service_response, {'ResponseMetadata': {'foo': 'bar'}})
def test_validates_on_empty_output_shape(self):
service_model = ServiceModel({
'documentation': '',
'operations': {
'foo': {
'name': 'foo'
}
}
})
self.client.meta.service_model = service_model
with self.assertRaises(ParamValidationError):
self.stubber.add_response('TestOperation', {'foo': 'bar'})
def test_get_response(self):
service_response = {'bar': 'baz'}
self.stubber.add_response('foo', service_response)
self.stubber.activate()
response = self.emit_get_response_event()
self.assertEqual(response[1], service_response)
self.assertEqual(response[0].status_code, 200)
def test_get_client_error_response(self):
error_code = "foo"
service_message = "bar"
self.stubber.add_client_error('foo', error_code, service_message)
self.stubber.activate()
response = self.emit_get_response_event()
self.assertEqual(response[1]['Error']['Message'], service_message)
self.assertEqual(response[1]['Error']['Code'], error_code)
def test_get_response_errors_with_no_stubs(self):
self.stubber.activate()
with self.assertRaises(StubResponseError):
self.emit_get_response_event()
def test_assert_no_responses_remaining(self):
self.stubber.add_response('foo', {})
with self.assertRaises(AssertionError):
self.stubber.assert_no_pending_responses()
示例5: TestS3Uploader
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import add_client_error [as 别名]
#.........这里部分代码省略.........
self.s3uploader.upload = Mock()
self.s3uploader.upload_with_dedup(filename, extension)
remotepath = "{0}.{1}".format(checksum, extension)
self.s3uploader.upload.assert_called_once_with(filename, remotepath)
def test_file_exists(self):
key = "some/path"
expected_params = {
"Bucket": self.bucket_name,
"Key": key
}
response = {
"AcceptRanges": "bytes",
"ContentType": "text/html",
"LastModified": "Thu, 16 Apr 2015 18:19:14 GMT",
"ContentLength": 77,
"VersionId": "null",
"ETag": "\"30a6ec7e1a9ad79c203d05a589c8b400\"",
"Metadata": {}
}
# Let's pretend file exists
self.s3client_stub.add_response("head_object",
response,
expected_params)
with self.s3client_stub:
self.assertTrue(self.s3uploader.file_exists(key))
# Let's pretend file does not exist
self.s3client_stub.add_client_error(
'head_object', "ClientError", "some error")
with self.s3client_stub:
self.assertFalse(self.s3uploader.file_exists(key))
# Let's pretend some other unknown exception happened
s3mock = Mock()
uploader = S3Uploader(s3mock, self.bucket_name, self.region)
s3mock.head_object = Mock()
s3mock.head_object.side_effect = RuntimeError()
with self.assertRaises(RuntimeError):
uploader.file_exists(key)
def test_file_checksum(self):
num_chars = 4096*5
data = ''.join(random.choice(string.ascii_uppercase)
for _ in range(num_chars)).encode('utf-8')
md5 = hashlib.md5()
md5.update(data)
expected_checksum = md5.hexdigest()
tempdir = tempfile.mkdtemp()
try:
filename = os.path.join(tempdir, 'tempfile')
with open(filename, 'wb') as f:
f.write(data)
actual_checksum = self.s3uploader.file_checksum(filename)
self.assertEqual(expected_checksum, actual_checksum)
finally:
shutil.rmtree(tempdir)
示例6: TestStubber
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import add_client_error [as 别名]
class TestStubber(unittest.TestCase):
def setUp(self):
session = botocore.session.get_session()
config = botocore.client.Config(signature_version=botocore.UNSIGNED)
self.client = session.create_client('s3', config=config)
self.stubber = Stubber(self.client)
def test_stubber_returns_response(self):
service_response = {'ResponseMetadata': {'foo': 'bar'}}
self.stubber.add_response('list_objects', service_response)
self.stubber.activate()
response = self.client.list_objects(Bucket='foo')
self.assertEqual(response, service_response)
def test_activated_stubber_errors_with_no_registered_stubs(self):
self.stubber.activate()
with self.assertRaises(StubResponseError):
self.client.list_objects(Bucket='foo')
def test_stubber_errors_when_stubs_are_used_up(self):
self.stubber.add_response('list_objects', {})
self.stubber.activate()
self.client.list_objects(Bucket='foo')
with self.assertRaises(StubResponseError):
self.client.list_objects(Bucket='foo')
def test_client_error_response(self):
error_code = "AccessDenied"
error_message = "Access Denied"
self.stubber.add_client_error(
'list_objects', error_code, error_message)
self.stubber.activate()
with self.assertRaises(ClientError):
self.client.list_objects(Bucket='foo')
def test_expected_params_success(self):
service_response = {}
expected_params = {'Bucket': 'foo'}
self.stubber.add_response(
'list_objects', service_response, expected_params)
self.stubber.activate()
# This should be called successfully with no errors being thrown
# for mismatching expected params.
response = self.client.list_objects(Bucket='foo')
self.assertEqual(response, service_response)
def test_expected_params_fail(self):
service_response = {}
expected_params = {'Bucket': 'bar'}
self.stubber.add_response(
'list_objects', service_response, expected_params)
self.stubber.activate()
# This should call should raise an for mismatching expected params.
with self.assertRaises(StubResponseError):
self.client.list_objects(Bucket='foo')
def test_expected_params_mixed_with_errors_responses(self):
# Add an error response
error_code = "AccessDenied"
error_message = "Access Denied"
self.stubber.add_client_error(
'list_objects', error_code, error_message)
# Add a response with incorrect expected params
service_response = {}
expected_params = {'Bucket': 'bar'}
self.stubber.add_response(
'list_objects', service_response, expected_params)
self.stubber.activate()
# The first call should throw and error as expected.
with self.assertRaises(ClientError):
self.client.list_objects(Bucket='foo')
# The second call should throw an error for unexpected parameters
with self.assertRaisesRegexp(StubResponseError, 'Expected parameters'):
self.client.list_objects(Bucket='foo')
def test_can_continue_to_call_after_expected_params_fail(self):
service_response = {}
expected_params = {'Bucket': 'bar'}
self.stubber.add_response(
'list_objects', service_response, expected_params)
self.stubber.activate()
# Throw an error for unexpected parameters
with self.assertRaises(StubResponseError):
self.client.list_objects(Bucket='foo')
# The stubber should still have the responses queued up
# even though the original parameters did not match the expected ones.
self.client.list_objects(Bucket='bar')
self.stubber.assert_no_pending_responses()
def test_still_relies_on_param_validation_with_expected_params(self):
#.........这里部分代码省略.........
示例7: TestDynamoDBHandler
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import add_client_error [as 别名]
#.........这里部分代码省略.........
expected_params)
with self.stubber:
try:
DynamodbLookup.handle(base_lookup_key)
except ValueError as e:
self.assertEqual(
'Please make sure to include a dynamodb table name',
str(e))
@mock.patch('stacker.lookups.handlers.dynamodb.get_session',
return_value=SessionStub(client))
def test_dynamodb_missing_table_handler(self, mock_client):
expected_params = {
'Key': {
'TestKey': {'S': 'TestVal'}
},
'ProjectionExpression': 'TestVal,TestMap,String1'
}
base_lookup_key = 'TestKey:TestVal.TestMap[M].String1'
self.stubber.add_response('get_item',
self.get_parameters_response,
expected_params)
with self.stubber:
try:
DynamodbLookup.handle(base_lookup_key)
except ValueError as e:
self.assertEqual(
'Please make sure to include a tablename',
str(e))
@mock.patch('stacker.lookups.handlers.dynamodb.get_session',
return_value=SessionStub(client))
def test_dynamodb_invalid_table_handler(self, mock_client):
expected_params = {
'TableName': 'FakeTable',
'Key': {
'TestKey': {'S': 'TestVal'}
},
'ProjectionExpression': 'TestVal,TestMap,String1'
}
base_lookup_key = '[email protected]:TestVal.TestMap[M].String1'
service_error_code = 'ResourceNotFoundException'
self.stubber.add_client_error('get_item',
service_error_code=service_error_code,
expected_params=expected_params)
with self.stubber:
try:
DynamodbLookup.handle(base_lookup_key)
except ValueError as e:
self.assertEqual(
'Cannot find the dynamodb table: FakeTable',
str(e))
@mock.patch('stacker.lookups.handlers.dynamodb.get_session',
return_value=SessionStub(client))
def test_dynamodb_invalid_partition_key_handler(self, mock_client):
expected_params = {
'TableName': 'TestTable',
'Key': {
'FakeKey': {'S': 'TestVal'}
},
'ProjectionExpression': 'TestVal,TestMap,String1'
}
base_lookup_key = '[email protected]:TestVal.TestMap[M].String1'
service_error_code = 'ValidationException'
self.stubber.add_client_error('get_item',
service_error_code=service_error_code,
expected_params=expected_params)
with self.stubber:
try:
DynamodbLookup.handle(base_lookup_key)
except ValueError as e:
self.assertEqual(
'No dynamodb record matched the partition key: FakeKey',
str(e))
@mock.patch('stacker.lookups.handlers.dynamodb.get_session',
return_value=SessionStub(client))
def test_dynamodb_invalid_partition_val_handler(self, mock_client):
expected_params = {
'TableName': 'TestTable',
'Key': {
'TestKey': {'S': 'FakeVal'}
},
'ProjectionExpression': 'FakeVal,TestMap,String1'
}
empty_response = {'ResponseMetadata': {}}
base_lookup_key = '[email protected]:FakeVal.TestMap[M].String1'
self.stubber.add_response('get_item',
empty_response,
expected_params)
with self.stubber:
try:
DynamodbLookup.handle(base_lookup_key)
except ValueError as e:
self.assertEqual(
'The dynamodb record could not be found using '
'the following key: {\'S\': \'FakeVal\'}',
str(e))
示例8: TestStubber
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import add_client_error [as 别名]
class TestStubber(unittest.TestCase):
def setUp(self):
session = botocore.session.get_session()
config = botocore.config.Config(signature_version=botocore.UNSIGNED)
self.client = session.create_client('s3', config=config)
self.stubber = Stubber(self.client)
def test_stubber_returns_response(self):
service_response = {'ResponseMetadata': {'foo': 'bar'}}
self.stubber.add_response('list_objects', service_response)
self.stubber.activate()
response = self.client.list_objects(Bucket='foo')
self.assertEqual(response, service_response)
def test_context_manager_returns_response(self):
service_response = {'ResponseMetadata': {'foo': 'bar'}}
self.stubber.add_response('list_objects', service_response)
with self.stubber:
response = self.client.list_objects(Bucket='foo')
self.assertEqual(response, service_response)
def test_activated_stubber_errors_with_no_registered_stubs(self):
self.stubber.activate()
# Params one per line for readability.
with self.assertRaisesRegexp(StubResponseError,
"'Bucket': 'asdfasdfasdfasdf',\n"):
self.client.list_objects(
Bucket='asdfasdfasdfasdf',
Delimiter='asdfasdfasdfasdf',
Prefix='asdfasdfasdfasdf',
EncodingType='url')
def test_stubber_errors_when_stubs_are_used_up(self):
self.stubber.add_response('list_objects', {})
self.stubber.activate()
self.client.list_objects(Bucket='foo')
with self.assertRaises(StubResponseError):
self.client.list_objects(Bucket='foo')
def test_client_error_response(self):
error_code = "AccessDenied"
error_message = "Access Denied"
self.stubber.add_client_error(
'list_objects', error_code, error_message)
self.stubber.activate()
with self.assertRaises(ClientError):
self.client.list_objects(Bucket='foo')
def test_expected_params_success(self):
service_response = {}
expected_params = {'Bucket': 'foo'}
self.stubber.add_response(
'list_objects', service_response, expected_params)
self.stubber.activate()
# This should be called successfully with no errors being thrown
# for mismatching expected params.
response = self.client.list_objects(Bucket='foo')
self.assertEqual(response, service_response)
def test_expected_params_fail(self):
service_response = {}
expected_params = {'Bucket': 'bar'}
self.stubber.add_response(
'list_objects', service_response, expected_params)
self.stubber.activate()
# This should call should raise an for mismatching expected params.
with self.assertRaisesRegexp(StubResponseError,
"{'Bucket': 'bar'},\n"):
self.client.list_objects(Bucket='foo')
def test_expected_params_mixed_with_errors_responses(self):
# Add an error response
error_code = "AccessDenied"
error_message = "Access Denied"
self.stubber.add_client_error(
'list_objects', error_code, error_message)
# Add a response with incorrect expected params
service_response = {}
expected_params = {'Bucket': 'bar'}
self.stubber.add_response(
'list_objects', service_response, expected_params)
self.stubber.activate()
# The first call should throw and error as expected.
with self.assertRaises(ClientError):
self.client.list_objects(Bucket='foo')
# The second call should throw an error for unexpected parameters
with self.assertRaisesRegexp(StubResponseError, 'Expected parameters'):
self.client.list_objects(Bucket='foo')
def test_can_continue_to_call_after_expected_params_fail(self):
service_response = {}
expected_params = {'Bucket': 'bar'}
#.........这里部分代码省略.........
示例9: TestStubber
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import add_client_error [as 别名]
class TestStubber(unittest.TestCase):
def setUp(self):
session = botocore.session.get_session()
config = botocore.config.Config(
signature_version=botocore.UNSIGNED,
s3={'addressing_style': 'path'}
)
self.client = session.create_client(
's3', region_name='us-east-1', config=config)
self.stubber = Stubber(self.client)
def test_stubber_returns_response(self):
service_response = {'ResponseMetadata': {'foo': 'bar'}}
self.stubber.add_response('list_objects', service_response)
self.stubber.activate()
response = self.client.list_objects(Bucket='foo')
self.assertEqual(response, service_response)
def test_context_manager_returns_response(self):
service_response = {'ResponseMetadata': {'foo': 'bar'}}
self.stubber.add_response('list_objects', service_response)
with self.stubber:
response = self.client.list_objects(Bucket='foo')
self.assertEqual(response, service_response)
def test_activated_stubber_errors_with_no_registered_stubs(self):
self.stubber.activate()
# Params one per line for readability.
with self.assertRaisesRegexp(UnStubbedResponseError,
"Unexpected API Call"):
self.client.list_objects(
Bucket='asdfasdfasdfasdf',
Delimiter='asdfasdfasdfasdf',
Prefix='asdfasdfasdfasdf',
EncodingType='url')
def test_stubber_errors_when_stubs_are_used_up(self):
self.stubber.add_response('list_objects', {})
self.stubber.activate()
self.client.list_objects(Bucket='foo')
with self.assertRaises(UnStubbedResponseError):
self.client.list_objects(Bucket='foo')
def test_client_error_response(self):
error_code = "AccessDenied"
error_message = "Access Denied"
self.stubber.add_client_error(
'list_objects', error_code, error_message)
self.stubber.activate()
with self.assertRaises(ClientError):
self.client.list_objects(Bucket='foo')
def test_can_add_expected_params_to_client_error(self):
self.stubber.add_client_error(
'list_objects', 'Error', 'error',
expected_params={'Bucket': 'foo'}
)
self.stubber.activate()
with self.assertRaises(ClientError):
self.client.list_objects(Bucket='foo')
def test_can_expected_param_fails_in_client_error(self):
self.stubber.add_client_error(
'list_objects', 'Error', 'error',
expected_params={'Bucket': 'foo'}
)
self.stubber.activate()
# We expect an AssertionError instead of a ClientError
# because we're calling the operation with the wrong
# param value.
with self.assertRaises(AssertionError):
self.client.list_objects(Bucket='wrong-argument-value')
def test_expected_params_success(self):
service_response = {}
expected_params = {'Bucket': 'foo'}
self.stubber.add_response(
'list_objects', service_response, expected_params)
self.stubber.activate()
# This should be called successfully with no errors being thrown
# for mismatching expected params.
response = self.client.list_objects(Bucket='foo')
self.assertEqual(response, service_response)
def test_expected_params_fail(self):
service_response = {}
expected_params = {'Bucket': 'bar'}
self.stubber.add_response(
'list_objects', service_response, expected_params)
self.stubber.activate()
# This should call should raise an for mismatching expected params.
with self.assertRaisesRegexp(StubResponseError,
"{'Bucket': 'bar'},\n"):
self.client.list_objects(Bucket='foo')
def test_expected_params_mixed_with_errors_responses(self):
# Add an error response
#.........这里部分代码省略.........
示例10: TestDeployer
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import add_client_error [as 别名]
class TestDeployer(unittest.TestCase):
def setUp(self):
client = botocore.session.get_session().create_client('cloudformation',
region_name="us-east-1")
self.stub_client = Stubber(client)
self.changeset_prefix = "some-changeset-prefix"
self.deployer = Deployer(client, self.changeset_prefix)
def test_has_stack_success(self):
stack_name = "stack_name"
expected_params = {
"StackName": stack_name
}
response = {
"Stacks": [
make_stack_obj(stack_name)
]
}
self.stub_client.add_response('describe_stacks', response,
expected_params)
with self.stub_client:
response = self.deployer.has_stack(stack_name)
self.assertTrue(response)
def test_has_stack_no_stack(self):
stack_name = "stack_name"
expected_params = {
"StackName": stack_name
}
# Response contains NO stack
no_stack_response = {
"Stacks": []
}
self.stub_client.add_response('describe_stacks', no_stack_response,
expected_params)
with self.stub_client:
response = self.deployer.has_stack(stack_name)
self.assertFalse(response)
# Response is a ClientError with a message that the stack does not exist
self.stub_client.add_client_error('describe_stacks', "ClientError",
"Stack with id {0} does not exist"
.format(stack_name))
with self.stub_client:
response = self.deployer.has_stack(stack_name)
self.assertFalse(response)
def test_has_stack_review_in_progress(self):
stack_name = "stack_name"
expected_params = {
"StackName": stack_name
}
# Response contains NO stack
review_in_progress_response = {
"Stacks": [make_stack_obj(stack_name, "REVIEW_IN_PROGRESS")]
}
self.stub_client.add_response('describe_stacks',
review_in_progress_response,
expected_params)
with self.stub_client:
response = self.deployer.has_stack(stack_name)
self.assertFalse(response)
def test_has_stack_exception(self):
self.stub_client.add_client_error('describe_stacks', "ValidationError",
"Service is bad")
with self.stub_client:
with self.assertRaises(botocore.exceptions.ClientError):
self.deployer.has_stack("stack_name")
def test_create_changeset_success(self):
stack_name = "stack_name"
template = "template"
parameters = [{"ParameterKey": "Key1", "ParameterValue": "Value",
"UsePreviousValue": True}]
capabilities = ["capabilities"]
# Case 1: Stack DOES NOT exist
self.deployer.has_stack = Mock()
self.deployer.has_stack.return_value = False
expected_params = {
"ChangeSetName": botocore.stub.ANY,
"StackName": stack_name,
"TemplateBody": template,
"ChangeSetType": "CREATE",
"Parameters": parameters,
"Capabilities": capabilities,
"Description": botocore.stub.ANY
}
response = {
#.........这里部分代码省略.........
示例11: TestProviderDefaultMode
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import add_client_error [as 别名]
class TestProviderDefaultMode(unittest.TestCase):
def setUp(self):
region = "us-east-1"
self.session = get_session(region=region)
self.provider = Provider(
self.session, region=region, recreate_failed=False)
self.stubber = Stubber(self.provider.cloudformation)
def test_get_stack_stack_does_not_exist(self):
stack_name = "MockStack"
self.stubber.add_client_error(
"describe_stacks",
service_error_code="ValidationError",
service_message="Stack with id %s does not exist" % stack_name,
expected_params={"StackName": stack_name}
)
with self.assertRaises(exceptions.StackDoesNotExist):
with self.stubber:
self.provider.get_stack(stack_name)
def test_get_stack_stack_exists(self):
stack_name = "MockStack"
stack_response = {
"Stacks": [generate_describe_stacks_stack(stack_name)]
}
self.stubber.add_response(
"describe_stacks",
stack_response,
expected_params={"StackName": stack_name}
)
with self.stubber:
response = self.provider.get_stack(stack_name)
self.assertEqual(response["StackName"], stack_name)
def test_select_update_method(self):
for i in [[{'force_interactive': True,
'force_change_set': False},
self.provider.interactive_update_stack],
[{'force_interactive': False,
'force_change_set': False},
self.provider.default_update_stack],
[{'force_interactive': False,
'force_change_set': True},
self.provider.noninteractive_changeset_update],
[{'force_interactive': True,
'force_change_set': True},
self.provider.interactive_update_stack]]:
self.assertEquals(
self.provider.select_update_method(**i[0]),
i[1]
)
def test_prepare_stack_for_update_completed(self):
stack_name = "MockStack"
stack = generate_describe_stacks_stack(
stack_name, stack_status="UPDATE_COMPLETE")
with self.stubber:
self.assertTrue(
self.provider.prepare_stack_for_update(stack, []))
def test_prepare_stack_for_update_in_progress(self):
stack_name = "MockStack"
stack = generate_describe_stacks_stack(
stack_name, stack_status="UPDATE_IN_PROGRESS")
with self.assertRaises(exceptions.StackUpdateBadStatus) as raised:
with self.stubber:
self.provider.prepare_stack_for_update(stack, [])
self.assertIn('in-progress', str(raised.exception))
def test_prepare_stack_for_update_non_recreatable(self):
stack_name = "MockStack"
stack = generate_describe_stacks_stack(
stack_name, stack_status="REVIEW_IN_PROGRESS")
with self.assertRaises(exceptions.StackUpdateBadStatus) as raised:
with self.stubber:
self.provider.prepare_stack_for_update(stack, [])
self.assertIn('Unsupported state', str(raised.exception))
def test_prepare_stack_for_update_disallowed(self):
stack_name = "MockStack"
stack = generate_describe_stacks_stack(
stack_name, stack_status="ROLLBACK_COMPLETE")
with self.assertRaises(exceptions.StackUpdateBadStatus) as raised:
with self.stubber:
self.provider.prepare_stack_for_update(stack, [])
self.assertIn('re-creation is disabled', str(raised.exception))
# Ensure we point out to the user how to enable re-creation
self.assertIn('--recreate-failed', str(raised.exception))
def test_prepare_stack_for_update_bad_tags(self):
#.........这里部分代码省略.........
示例12: TestDeployer
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import add_client_error [as 别名]
class TestDeployer(unittest.TestCase):
def setUp(self):
client = botocore.session.get_session().create_client('cloudformation',
region_name="us-east-1")
self.stub_client = Stubber(client)
self.changeset_prefix = "some-changeset-prefix"
self.deployer = Deployer(client, self.changeset_prefix)
def test_has_stack_success(self):
stack_name = "stack_name"
expected_params = {
"StackName": stack_name
}
response = {
"Stacks": [
make_stack_obj(stack_name)
]
}
self.stub_client.add_response('describe_stacks', response,
expected_params)
with self.stub_client:
response = self.deployer.has_stack(stack_name)
self.assertTrue(response)
def test_has_stack_no_stack(self):
stack_name = "stack_name"
expected_params = {
"StackName": stack_name
}
# Response contains NO stack
no_stack_response = {
"Stacks": []
}
self.stub_client.add_response('describe_stacks', no_stack_response,
expected_params)
with self.stub_client:
response = self.deployer.has_stack(stack_name)
self.assertFalse(response)
# Response is a ClientError with a message that the stack does not exist
self.stub_client.add_client_error('describe_stacks', "ClientError",
"Stack with id {0} does not exist"
.format(stack_name))
with self.stub_client:
response = self.deployer.has_stack(stack_name)
self.assertFalse(response)
def test_has_stack_review_in_progress(self):
stack_name = "stack_name"
expected_params = {
"StackName": stack_name
}
# Response contains NO stack
review_in_progress_response = {
"Stacks": [make_stack_obj(stack_name, "REVIEW_IN_PROGRESS")]
}
self.stub_client.add_response('describe_stacks',
review_in_progress_response,
expected_params)
with self.stub_client:
response = self.deployer.has_stack(stack_name)
self.assertFalse(response)
def test_has_stack_exception(self):
self.stub_client.add_client_error('describe_stacks', "ValidationError",
"Service is bad")
with self.stub_client:
with self.assertRaises(botocore.exceptions.ClientError):
self.deployer.has_stack("stack_name")
def test_create_changeset_success(self):
stack_name = "stack_name"
template = "template"
parameters = [
{"ParameterKey": "Key1", "ParameterValue": "Value"},
{"ParameterKey": "Key2", "UsePreviousValue": True},
{"ParameterKey": "Key3", "UsePreviousValue": False},
]
# Parameters that Use Previous Value will be removed on stack creation
# to either force CloudFormation to use the Default value, or ask user to specify a parameter
filtered_parameters = [
{"ParameterKey": "Key1", "ParameterValue": "Value"},
{"ParameterKey": "Key3", "UsePreviousValue": False},
]
capabilities = ["capabilities"]
role_arn = "arn:aws:iam::1234567890:role"
notification_arns = ["arn:aws:sns:region:1234567890:notify"]
s3_uploader = None
tags = [{"Key":"key1", "Value": "val1"}]
# Case 1: Stack DOES NOT exist
#.........这里部分代码省略.........