本文整理汇总了Python中botocore.stub.Stubber.activate方法的典型用法代码示例。如果您正苦于以下问题:Python Stubber.activate方法的具体用法?Python Stubber.activate怎么用?Python Stubber.activate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类botocore.stub.Stubber
的用法示例。
在下文中一共展示了Stubber.activate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: boto_volume_for_test
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import activate [as 别名]
def boto_volume_for_test(test, cluster_id):
"""
Create an in-memory boto3 Volume, avoiding any AWS API calls.
"""
# Create a session directly rather than allow lazy loading of a default
# session.
region_name = u"some-test-region-1"
s = Boto3Session(
botocore_session=botocore_get_session(),
region_name=region_name,
)
ec2 = s.resource("ec2", region_name=region_name)
stubber = Stubber(ec2.meta.client)
# From this point, any attempt to interact with AWS API should fail with
# botocore.exceptions.StubResponseError
stubber.activate()
volume_id = u"vol-{}".format(random_name(test))
v = ec2.Volume(id=volume_id)
tags = []
if cluster_id is not None:
tags.append(
dict(
Key=CLUSTER_ID_LABEL,
Value=cluster_id,
),
)
# Pre-populate the metadata to prevent any attempt to load the metadata by
# API calls.
v.meta.data = dict(
Tags=tags
)
return v
示例2: create_client_sts_stub
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import activate [as 别名]
def create_client_sts_stub(service, *args, **kwargs):
client = _original_create_client(service, *args, **kwargs)
stub = Stubber(client)
response = self.create_assume_role_response(expected_creds)
self.actual_client_region = client.meta.region_name
stub.add_response('assume_role', response)
stub.activate()
return client
示例3: test_delete_tags
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import activate [as 别名]
def test_delete_tags(self):
stubber = Stubber(self.instance_resource.meta.client)
stubber.add_response('delete_tags', {})
stubber.activate()
response = self.instance_resource.delete_tags(Tags=[{'Key': 'foo'}])
stubber.assert_no_pending_responses()
self.assertEqual(response, {})
stubber.deactivate()
示例4: set_cloudformation_stubber_for_client
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import activate [as 别名]
def set_cloudformation_stubber_for_client(self, redshift_client):
stubber = Stubber(redshift_client)
with open(self.resource_path+'/DescribeSourceClusterResponse.json') as describe_source_response:
describe_source_cluster_response = json.load(describe_source_response)
expected_source_params = {'ClusterIdentifier': 'rscopyunloadtest3-redshiftclustersource-1so4t2ip0ei3a'}
stubber.add_response('describe_clusters', describe_source_cluster_response, expected_source_params)
with open(self.resource_path+'/DescribeTargetClusterResponse.json') as describe_target_response:
describe_target_cluster_response = json.load(describe_target_response)
expected_target_params = {'ClusterIdentifier': 'rscopyunloadtest3-redshiftclustertarget-oaw35zvu02h'}
stubber.add_response('describe_clusters', describe_target_cluster_response, expected_target_params)
stubber.activate()
示例5: test_multipart_download_with_multiple_parts_and_extra_args
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import activate [as 别名]
def test_multipart_download_with_multiple_parts_and_extra_args(self):
client = Session().create_client('s3')
stubber = Stubber(client)
response_body = b'foobarbaz'
response = {'Body': six.BytesIO(response_body)}
expected_params = {
'Range': mock.ANY, 'Bucket': mock.ANY, 'Key': mock.ANY,
'RequestPayer': 'requester'}
stubber.add_response('get_object', response, expected_params)
stubber.activate()
downloader = MultipartDownloader(
client, TransferConfig(), InMemoryOSLayer({}), SequentialExecutor)
downloader.download_file(
'bucket', 'key', 'filename', len(response_body),
{'RequestPayer': 'requester'})
stubber.assert_no_pending_responses()
示例6: create_session
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import activate [as 别名]
def create_session(self, profile=None):
session = Session(profile=profile)
# We have to set bogus credentials here or otherwise we'll trigger
# an early credential chain resolution.
sts = session.create_client(
'sts',
aws_access_key_id='spam',
aws_secret_access_key='eggs',
)
stubber = Stubber(sts)
stubber.activate()
assume_role_provider = AssumeRoleProvider(
load_config=lambda: session.full_config,
client_creator=lambda *args, **kwargs: sts,
cache={},
profile_name=profile,
credential_sourcer=CanonicalNameCredentialSourcer([
self.env_provider, self.container_provider,
self.metadata_provider
])
)
component_name = 'credential_provider'
resolver = session.get_component(component_name)
available_methods = [p.METHOD for p in resolver.providers]
replacements = {
'env': self.env_provider,
'iam-role': self.metadata_provider,
'container-role': self.container_provider,
'assume-role': assume_role_provider
}
for name, provider in replacements.items():
try:
index = available_methods.index(name)
except ValueError:
# The provider isn't in the session
continue
resolver.providers[index] = provider
session.register_component(
'credential_provider', resolver
)
return session, stubber
示例7: _boto3_stubber
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import activate [as 别名]
def _boto3_stubber(service, mocked_requests):
client = boto3.client(service, region)
stubber = Stubber(client)
# Save a ref to the stubber so that we can deactivate it at the end of the test.
created_stubbers.append(stubber)
# Attach mocked requests to the Stubber and activate it.
if not isinstance(mocked_requests, list):
mocked_requests = [mocked_requests]
for mocked_request in mocked_requests:
stubber.add_response(
mocked_request.method, mocked_request.response, expected_params=mocked_request.expected_params
)
stubber.activate()
# Add stubber to the collection of mocked clients. This allows to mock multiple clients.
# Mocking twice the same client will replace the previous one.
mocked_clients[service] = client
return client
示例8: TestRDSPagination
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import activate [as 别名]
class TestRDSPagination(BaseSessionTest):
def setUp(self):
super(TestRDSPagination, self).setUp()
self.region = 'us-west-2'
self.client = self.session.create_client(
'rds', self.region)
self.stubber = Stubber(self.client)
def test_can_specify_zero_marker(self):
service_response = {
'LogFileData': 'foo',
'Marker': '2',
'AdditionalDataPending': True
}
expected_params = {
'DBInstanceIdentifier': 'foo',
'LogFileName': 'bar',
'NumberOfLines': 2,
'Marker': '0'
}
function_name = 'download_db_log_file_portion'
# The stubber will assert that the function is called with the expected
# parameters.
self.stubber.add_response(
function_name, service_response, expected_params)
self.stubber.activate()
try:
paginator = self.client.get_paginator(function_name)
result = paginator.paginate(
DBInstanceIdentifier='foo',
LogFileName='bar',
NumberOfLines=2,
PaginationConfig={
'StartingToken': '0',
'MaxItems': 3
}).build_full_result()
self.assertEqual(result['LogFileData'], 'foo')
self.assertIn('NextToken', result)
except StubAssertionError as e:
self.fail(str(e))
示例9: TestRDS
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import activate [as 别名]
class TestRDS(unittest.TestCase):
def setUp(self):
self.session = botocore.session.get_session()
self.client = self.session.create_client('rds', 'us-west-2')
self.stubber = Stubber(self.client)
self.stubber.activate()
def test_generate_db_auth_token(self):
hostname = 'host.us-east-1.rds.amazonaws.com'
port = 3306
username = 'mySQLUser'
auth_token = self.client.generate_db_auth_token(
DBHostname=hostname, Port=port, DBUsername=username)
endpoint_url = 'host.us-east-1.rds.amazonaws.com:3306'
self.assertIn(endpoint_url, auth_token)
self.assertIn('Action=connect', auth_token)
# Asserts that there is no scheme in the url
self.assertTrue(auth_token.startswith(hostname))
示例10: test_provide_copy_source_client
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import activate [as 别名]
def test_provide_copy_source_client(self):
source_client = self.session.create_client(
's3', 'eu-central-1', aws_access_key_id='foo',
aws_secret_access_key='bar')
source_stubber = Stubber(source_client)
source_stubber.activate()
self.addCleanup(source_stubber.deactivate)
self.add_head_object_response(stubber=source_stubber)
self.add_successful_copy_responses()
call_kwargs = self.create_call_kwargs()
call_kwargs['source_client'] = source_client
future = self.manager.copy(**call_kwargs)
future.result()
# Make sure that all of the responses were properly
# used for both clients.
source_stubber.assert_no_pending_responses()
self.stubber.assert_no_pending_responses()
示例11: TestMturk
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import activate [as 别名]
class TestMturk(BaseSessionTest):
def setUp(self):
super(TestMturk, self).setUp()
self.region = 'us-west-2'
self.client = self.session.create_client(
'mturk', self.region)
self.stubber = Stubber(self.client)
self.stubber.activate()
def tearDown(self):
self.stubber.deactivate()
def test_list_hits_aliased(self):
self.stubber.add_response('list_hits_for_qualification_type', {})
self.stubber.add_response('list_hits_for_qualification_type', {})
params = {'QualificationTypeId': 'foo'}
self.client.list_hi_ts_for_qualification_type(**params)
self.client.list_hits_for_qualification_type(**params)
self.stubber.assert_no_pending_responses()
示例12: TestS3ObjectSummary
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import activate [as 别名]
class TestS3ObjectSummary(unittest.TestCase):
def setUp(self):
self.session = boto3.session.Session(
aws_access_key_id='foo', aws_secret_access_key='bar',
region_name='us-west-2')
self.s3 = self.session.resource('s3')
self.obj_summary = self.s3.ObjectSummary('my_bucket', 'my_key')
self.obj_summary_size = 12
self.stubber = Stubber(self.s3.meta.client)
self.stubber.activate()
self.stubber.add_response(
method='head_object',
service_response={
'ContentLength': self.obj_summary_size, 'ETag': 'my-etag',
'ContentType': 'binary'
},
expected_params={
'Bucket': 'my_bucket',
'Key': 'my_key'
}
)
def tearDown(self):
self.stubber.deactivate()
def test_has_load(self):
self.assertTrue(hasattr(self.obj_summary, 'load'),
'load() was not injected onto ObjectSummary resource.')
def test_autoloads_correctly(self):
# In HeadObject the parameter returned is ContentLength, this
# should get mapped to Size of ListObject since the resource uses
# the shape returned to by ListObjects.
self.assertEqual(self.obj_summary.size, self.obj_summary_size)
def test_cannot_access_other_non_related_parameters(self):
# Even though an HeadObject was used to load this, it should
# only expose the attributes from its shape defined in ListObjects.
self.assertFalse(hasattr(self.obj_summary, 'content_length'))
示例13: TestSagemaker
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import activate [as 别名]
class TestSagemaker(BaseSessionTest):
def setUp(self):
super(TestSagemaker, self).setUp()
self.region = 'us-west-2'
self.client = self.session.create_client(
'sagemaker', self.region)
self.stubber = Stubber(self.client)
self.stubber.activate()
self.hook_calls = []
def _hook(self, **kwargs):
self.hook_calls.append(kwargs['event_name'])
def tearDown(self):
self.stubber.deactivate()
def test_event_with_old_prefix(self):
self.client.meta.events.register(
'provide-client-params.sagemaker.ListEndpoints',
self._hook
)
self.stubber.add_response('list_endpoints', {'Endpoints': []})
self.client.list_endpoints()
self.assertEqual(self.hook_calls, [
'provide-client-params.sagemaker.ListEndpoints'
])
def test_event_with_new_prefix(self):
self.client.meta.events.register(
'provide-client-params.api.sagemaker.ListEndpoints',
self._hook
)
self.stubber.add_response('list_endpoints', {'Endpoints': []})
self.client.list_endpoints()
self.assertEqual(self.hook_calls, [
'provide-client-params.sagemaker.ListEndpoints'
])
示例14: StubbedClientTest
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import activate [as 别名]
class StubbedClientTest(unittest.TestCase):
def setUp(self):
self.session = botocore.session.get_session()
self.region = 'us-west-2'
self.client = self.session.create_client(
's3', self.region, aws_access_key_id='foo',
aws_secret_access_key='bar')
self.stubber = Stubber(self.client)
self.stubber.activate()
def tearDown(self):
self.stubber.deactivate()
def reset_stubber_with_new_client(self, override_client_kwargs):
client_kwargs = {
'service_name': 's3',
'region_name': self.region,
'aws_access_key_id': 'foo',
'aws_secret_access_key': 'bar'
}
client_kwargs.update(override_client_kwargs)
self.client = self.session.create_client(**client_kwargs)
self.stubber = Stubber(self.client)
self.stubber.activate()
示例15: TestSTSPresignedUrl
# 需要导入模块: from botocore.stub import Stubber [as 别名]
# 或者: from botocore.stub.Stubber import activate [as 别名]
class TestSTSPresignedUrl(BaseSessionTest):
def setUp(self):
super(TestSTSPresignedUrl, self).setUp()
self.client = self.session.create_client('sts', 'us-west-2')
# Makes sure that no requests will go through
self.stubber = Stubber(self.client)
self.stubber.activate()
def test_presigned_url_contains_no_content_type(self):
timestamp = datetime(2017, 3, 22, 0, 0)
with mock.patch('botocore.auth.datetime') as _datetime:
_datetime.datetime.utcnow.return_value = timestamp
url = self.client.generate_presigned_url('get_caller_identity', {})
# There should be no 'content-type' in x-amz-signedheaders
expected_url = (
'https://sts.amazonaws.com/?Action=GetCallerIdentity&'
'Version=2011-06-15&X-Amz-Algorithm=AWS4-HMAC-SHA256&'
'X-Amz-Credential=access_key%2F20170322%2Fus-east-1%2Fsts%2F'
'aws4_request&X-Amz-Date=20170322T000000Z&X-Amz-Expires=3600&'
'X-Amz-SignedHeaders=host&X-Amz-Signature=767845d2ee858069a598d5f'
'8b497b75c7d57356885b1b3dba46dbbc0fc62bf5a'
)
assert_url_equal(url, expected_url)