1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
|
import time
from mock import Mock, call
from tests import unittest
from botocore.awsrequest import AWSRequest
from botocore.client import ClientMeta
from botocore.hooks import HierarchicalEmitter
from botocore.model import ServiceModel
from botocore.exceptions import ConnectionError
from botocore.handlers import inject_api_version_header_if_needed
from botocore.discovery import (
EndpointDiscoveryManager, EndpointDiscoveryHandler,
EndpointDiscoveryRequired, EndpointDiscoveryRefreshFailed,
block_endpoint_discovery_required_operations,
)
class BaseEndpointDiscoveryTest(unittest.TestCase):
def setUp(self):
self.service_description = {
'version': '2.0',
'metadata': {
'apiVersion': '2018-08-31',
'endpointPrefix': 'fooendpoint',
'jsonVersion': '1.1',
'protocol': 'json',
'serviceAbbreviation': 'FooService',
'serviceId': 'FooService',
'serviceFullName': 'AwsFooService',
'signatureVersion': 'v4',
'signingName': 'awsfooservice',
'targetPrefix': 'awsfooservice'
},
'operations': {
'DescribeEndpoints': {
'name': 'DescribeEndpoints',
'http': {
'method': 'POST',
'requestUri': '/'
},
'input': {'shape': 'DescribeEndpointsRequest'},
'output': {'shape': 'DescribeEndpointsResponse'},
'endpointoperation': True
},
'TestDiscoveryRequired': {
'name': 'TestDiscoveryRequired',
'http': {
'method': 'POST',
'requestUri': '/'
},
'input': {'shape': 'TestDiscoveryIdsRequest'},
'output': {'shape': 'EmptyStruct'},
'endpointdiscovery': {'required': True}
},
'TestDiscoveryOptional': {
'name': 'TestDiscoveryOptional',
'http': {
'method': 'POST',
'requestUri': '/'
},
'input': {'shape': 'TestDiscoveryIdsRequest'},
'output': {'shape': 'EmptyStruct'},
'endpointdiscovery': {}
},
'TestDiscovery': {
'name': 'TestDiscovery',
'http': {
'method': 'POST',
'requestUri': '/'
},
'input': {'shape': 'EmptyStruct'},
'output': {'shape': 'EmptyStruct'},
'endpointdiscovery': {}
},
},
'shapes': {
'Boolean': {'type': 'boolean'},
'DescribeEndpointsRequest': {
'type': 'structure',
'members': {
'Operation': {'shape': 'String'},
'Identifiers': {'shape': 'Identifiers'}
}
},
'DescribeEndpointsResponse': {
'type': 'structure',
'required': ['Endpoints'],
'members': {
'Endpoints': {'shape': 'Endpoints'}
}
},
'Endpoint': {
'type': 'structure',
'required': [
'Address',
'CachePeriodInMinutes'
],
'members': {
'Address': {'shape': 'String'},
'CachePeriodInMinutes': {'shape': 'Long'}
}
},
'Endpoints': {
'type': 'list',
'member': {'shape': 'Endpoint'}
},
'Identifiers': {
'type': 'map',
'key': {'shape': 'String'},
'value': {'shape': 'String'}
},
'Long': {'type': 'long'},
'String': {'type': 'string'},
'TestDiscoveryIdsRequest': {
'type': 'structure',
'required': ['Foo', 'Nested'],
'members': {
'Foo': {
'shape': 'String',
'endpointdiscoveryid': True,
},
'Baz': {'shape': 'String'},
'Nested': {'shape': 'Nested'}
}
},
'EmptyStruct': {
'type': 'structure',
'members': {}
},
'Nested': {
'type': 'structure',
'required': 'Bar',
'members': {
'Bar': {
'shape': 'String',
'endpointdiscoveryid': True,
}
}
}
}
}
class TestEndpointDiscoveryManager(BaseEndpointDiscoveryTest):
def setUp(self):
super(TestEndpointDiscoveryManager, self).setUp()
self.construct_manager()
def construct_manager(self, cache=None, time=None, side_effect=None):
self.service_model = ServiceModel(self.service_description)
self.meta = Mock(spec=ClientMeta)
self.meta.service_model = self.service_model
self.client = Mock()
if side_effect is None:
side_effect = [{
'Endpoints': [{
'Address': 'new.com',
'CachePeriodInMinutes': 2,
}]
}]
self.client.describe_endpoints.side_effect = side_effect
self.client.meta = self.meta
self.manager = EndpointDiscoveryManager(
self.client, cache=cache, current_time=time
)
def test_injects_api_version_if_endpoint_operation(self):
model = self.service_model.operation_model('DescribeEndpoints')
params = {'headers': {}}
inject_api_version_header_if_needed(model, params)
self.assertEqual(params['headers'].get('x-amz-api-version'),
'2018-08-31')
def test_no_inject_api_version_if_not_endpoint_operation(self):
model = self.service_model.operation_model('TestDiscoveryRequired')
params = {'headers': {}}
inject_api_version_header_if_needed(model, params)
self.assertNotIn('x-amz-api-version', params['headers'])
def test_gather_identifiers(self):
params = {
'Foo': 'value1',
'Nested': {'Bar': 'value2'}
}
operation = self.service_model.operation_model('TestDiscoveryRequired')
ids = self.manager.gather_identifiers(operation, params)
self.assertEqual(ids, {'Foo': 'value1', 'Bar': 'value2'})
def test_gather_identifiers_none(self):
operation = self.service_model.operation_model('TestDiscovery')
ids = self.manager.gather_identifiers(operation, {})
self.assertEqual(ids, {})
def test_describe_endpoint(self):
kwargs = {
'Operation': 'FooBar',
'Identifiers': {'Foo': 'value1', 'Bar': 'value2'},
}
self.manager.describe_endpoint(**kwargs)
self.client.describe_endpoints.assert_called_with(**kwargs)
def test_describe_endpoint_no_input(self):
describe = self.service_description['operations']['DescribeEndpoints']
del describe['input']
self.construct_manager()
self.manager.describe_endpoint(Operation='FooBar', Identifiers={})
self.client.describe_endpoints.assert_called_with()
def test_describe_endpoint_empty_input(self):
describe = self.service_description['operations']['DescribeEndpoints']
describe['input'] = {'shape': 'EmptyStruct'}
self.construct_manager()
self.manager.describe_endpoint(Operation='FooBar', Identifiers={})
self.client.describe_endpoints.assert_called_with()
def test_describe_endpoint_ids_and_operation(self):
cache = {}
self.construct_manager(cache=cache)
ids = {'Foo': 'value1', 'Bar': 'value2'}
kwargs = {
'Operation': 'TestDiscoveryRequired',
'Identifiers': ids,
}
self.manager.describe_endpoint(**kwargs)
self.client.describe_endpoints.assert_called_with(**kwargs)
key = ((('Bar', 'value2'), ('Foo', 'value1')), 'TestDiscoveryRequired')
self.assertIn(key, cache)
self.assertEqual(cache[key][0]['Address'], 'new.com')
self.manager.describe_endpoint(**kwargs)
call_count = self.client.describe_endpoints.call_count
self.assertEqual(call_count, 1)
def test_describe_endpoint_no_ids_or_operation(self):
cache = {}
describe = self.service_description['operations']['DescribeEndpoints']
describe['input'] = {'shape': 'EmptyStruct'}
self.construct_manager(cache=cache)
self.manager.describe_endpoint(
Operation='TestDiscoveryRequired', Identifiers={}
)
self.client.describe_endpoints.assert_called_with()
key = ()
self.assertIn(key, cache)
self.assertEqual(cache[key][0]['Address'], 'new.com')
self.manager.describe_endpoint(
Operation='TestDiscoveryRequired', Identifiers={}
)
call_count = self.client.describe_endpoints.call_count
self.assertEqual(call_count, 1)
def test_describe_endpoint_expired_entry(self):
current_time = time.time()
key = ()
cache = {
key: [{'Address': 'old.com', 'Expiration': current_time - 10}]
}
self.construct_manager(cache=cache)
kwargs = {
'Identifiers': {},
'Operation': 'TestDiscoveryRequired',
}
self.manager.describe_endpoint(**kwargs)
self.client.describe_endpoints.assert_called_with()
self.assertIn(key, cache)
self.assertEqual(cache[key][0]['Address'], 'new.com')
self.manager.describe_endpoint(**kwargs)
call_count = self.client.describe_endpoints.call_count
self.assertEqual(call_count, 1)
def test_describe_endpoint_cache_expiration(self):
def _time():
return float(0)
cache = {}
self.construct_manager(cache=cache, time=_time)
self.manager.describe_endpoint(
Operation='TestDiscoveryRequired', Identifiers={}
)
key = ()
self.assertIn(key, cache)
self.assertEqual(cache[key][0]['Expiration'], float(120))
def test_delete_endpoints_present(self):
key = ()
cache = {
key: [{'Address': 'old.com', 'Expiration': 0}]
}
self.construct_manager(cache=cache)
kwargs = {
'Identifiers': {},
'Operation': 'TestDiscoveryRequired',
}
self.manager.delete_endpoints(**kwargs)
self.assertEqual(cache, {})
def test_delete_endpoints_absent(self):
cache = {}
self.construct_manager(cache=cache)
kwargs = {
'Identifiers': {},
'Operation': 'TestDiscoveryRequired',
}
self.manager.delete_endpoints(**kwargs)
self.assertEqual(cache, {})
def test_describe_endpoint_optional_fails_no_cache(self):
side_effect = [ConnectionError(error=None)]
self.construct_manager(side_effect=side_effect)
kwargs = {'Operation': 'TestDiscoveryOptional'}
endpoint = self.manager.describe_endpoint(**kwargs)
self.assertIsNone(endpoint)
# This second call should be blocked as we just failed
endpoint = self.manager.describe_endpoint(**kwargs)
self.assertIsNone(endpoint)
self.client.describe_endpoints.call_args_list == [call()]
def test_describe_endpoint_optional_fails_stale_cache(self):
key = ()
cache = {
key: [{'Address': 'old.com', 'Expiration': 0}]
}
side_effect = [ConnectionError(error=None)] * 2
self.construct_manager(cache=cache, side_effect=side_effect)
kwargs = {'Operation': 'TestDiscoveryOptional'}
endpoint = self.manager.describe_endpoint(**kwargs)
self.assertEqual(endpoint, 'old.com')
# This second call shouldn't go through as we just failed
endpoint = self.manager.describe_endpoint(**kwargs)
self.assertEqual(endpoint, 'old.com')
self.client.describe_endpoints.call_args_list == [call()]
def test_describe_endpoint_required_fails_no_cache(self):
side_effect = [ConnectionError(error=None)] * 2
self.construct_manager(side_effect=side_effect)
kwargs = {'Operation': 'TestDiscoveryRequired'}
with self.assertRaises(EndpointDiscoveryRefreshFailed):
self.manager.describe_endpoint(**kwargs)
# This second call should go through, as we have no cache
with self.assertRaises(EndpointDiscoveryRefreshFailed):
self.manager.describe_endpoint(**kwargs)
describe_count = self.client.describe_endpoints.call_count
self.assertEqual(describe_count, 2)
def test_describe_endpoint_required_fails_stale_cache(self):
key = ()
cache = {
key: [{'Address': 'old.com', 'Expiration': 0}]
}
side_effect = [ConnectionError(error=None)] * 2
self.construct_manager(cache=cache, side_effect=side_effect)
kwargs = {'Operation': 'TestDiscoveryRequired'}
endpoint = self.manager.describe_endpoint(**kwargs)
self.assertEqual(endpoint, 'old.com')
# We have a stale endpoint, so this shouldn't fail or force a refresh
endpoint = self.manager.describe_endpoint(**kwargs)
self.assertEqual(endpoint, 'old.com')
self.client.describe_endpoints.call_args_list == [call()]
def test_describe_endpoint_required_force_refresh_success(self):
side_effect = [
ConnectionError(error=None),
{'Endpoints': [{
'Address': 'new.com',
'CachePeriodInMinutes': 2,
}]},
]
self.construct_manager(side_effect=side_effect)
kwargs = {'Operation': 'TestDiscoveryRequired'}
# First call will fail
with self.assertRaises(EndpointDiscoveryRefreshFailed):
self.manager.describe_endpoint(**kwargs)
self.client.describe_endpoints.call_args_list == [call()]
# Force a refresh if the cache is empty but discovery is required
endpoint = self.manager.describe_endpoint(**kwargs)
self.assertEqual(endpoint, 'new.com')
def test_describe_endpoint_retries_after_failing(self):
fake_time = Mock()
fake_time.side_effect = [0, 100, 200]
side_effect = [
ConnectionError(error=None),
{'Endpoints': [{
'Address': 'new.com',
'CachePeriodInMinutes': 2,
}]},
]
self.construct_manager(side_effect=side_effect, time=fake_time)
kwargs = {'Operation': 'TestDiscoveryOptional'}
endpoint = self.manager.describe_endpoint(**kwargs)
self.assertIsNone(endpoint)
self.client.describe_endpoints.call_args_list == [call()]
# Second time should try again as enough time has elapsed
endpoint = self.manager.describe_endpoint(**kwargs)
self.assertEqual(endpoint, 'new.com')
class TestEndpointDiscoveryHandler(BaseEndpointDiscoveryTest):
def setUp(self):
super(TestEndpointDiscoveryHandler, self).setUp()
self.manager = Mock(spec=EndpointDiscoveryManager)
self.handler = EndpointDiscoveryHandler(self.manager)
self.service_model = ServiceModel(self.service_description)
def test_register_handler(self):
events = Mock(spec=HierarchicalEmitter)
self.handler.register(events, 'foo-bar')
events.register.assert_any_call(
'before-parameter-build.foo-bar', self.handler.gather_identifiers
)
events.register.assert_any_call(
'needs-retry.foo-bar', self.handler.handle_retries
)
events.register_first.assert_called_with(
'request-created.foo-bar', self.handler.discover_endpoint
)
def test_discover_endpoint(self):
request = AWSRequest()
request.context = {
'discovery': {'identifiers': {}}
}
self.manager.describe_endpoint.return_value = 'https://new.foo'
self.handler.discover_endpoint(request, 'TestOperation')
self.assertEqual(request.url, 'https://new.foo')
self.manager.describe_endpoint.assert_called_with(
Operation='TestOperation', Identifiers={}
)
def test_discover_endpoint_fails(self):
request = AWSRequest()
request.context = {
'discovery': {'identifiers': {}}
}
request.url = 'old.com'
self.manager.describe_endpoint.return_value = None
self.handler.discover_endpoint(request, 'TestOperation')
self.assertEqual(request.url, 'old.com')
self.manager.describe_endpoint.assert_called_with(
Operation='TestOperation', Identifiers={}
)
def test_discover_endpoint_no_protocol(self):
request = AWSRequest()
request.context = {
'discovery': {'identifiers': {}}
}
self.manager.describe_endpoint.return_value = 'new.foo'
self.handler.discover_endpoint(request, 'TestOperation')
self.assertEqual(request.url, 'https://new.foo')
self.manager.describe_endpoint.assert_called_with(
Operation='TestOperation', Identifiers={}
)
def test_inject_no_context(self):
request = AWSRequest(url='https://original.foo')
self.handler.discover_endpoint(request, 'TestOperation')
self.assertEqual(request.url, 'https://original.foo')
self.manager.describe_endpoint.assert_not_called()
def test_gather_identifiers(self):
context = {}
params = {
'Foo': 'value1',
'Nested': {'Bar': 'value2'}
}
ids = {
'Foo': 'value1',
'Bar': 'value2'
}
model = self.service_model.operation_model('TestDiscoveryRequired')
self.manager.gather_identifiers.return_value = ids
self.handler.gather_identifiers(params, model, context)
self.assertEqual(context['discovery']['identifiers'], ids)
def test_gather_identifiers_not_discoverable(self):
context = {}
model = self.service_model.operation_model('DescribeEndpoints')
self.handler.gather_identifiers({}, model, context)
self.assertEqual(context, {})
def test_discovery_disabled_but_required(self):
model = self.service_model.operation_model('TestDiscoveryRequired')
with self.assertRaises(EndpointDiscoveryRequired):
block_endpoint_discovery_required_operations(model)
def test_discovery_disabled_but_optional(self):
context = {}
model = self.service_model.operation_model('TestDiscoveryOptional')
block_endpoint_discovery_required_operations(model, context=context)
self.assertEqual(context, {})
def test_does_not_retry_no_response(self):
retry = self.handler.handle_retries(None, None, None)
self.assertIsNone(retry)
def test_does_not_retry_other_errors(self):
parsed_response = {
'ResponseMetadata': {'HTTPStatusCode': 200}
}
response = (None, parsed_response)
retry = self.handler.handle_retries(None, response, None)
self.assertIsNone(retry)
def test_does_not_retry_if_no_context(self):
request_dict = {'context': {}}
parsed_response = {
'ResponseMetadata': {'HTTPStatusCode': 421}
}
response = (None, parsed_response)
retry = self.handler.handle_retries(request_dict, response, None)
self.assertIsNone(retry)
def _assert_retries(self, parsed_response):
request_dict = {
'context': {
'discovery': {'identifiers': {}}
}
}
response = (None, parsed_response)
model = self.service_model.operation_model('TestDiscoveryOptional')
retry = self.handler.handle_retries(request_dict, response, model)
self.assertEqual(retry, 0)
self.manager.delete_endpoints.assert_called_with(
Operation='TestDiscoveryOptional', Identifiers={}
)
def test_retries_421_status_code(self):
parsed_response = {
'ResponseMetadata': {'HTTPStatusCode': 421}
}
self._assert_retries(parsed_response)
def test_retries_invalid_endpoint_exception(self):
parsed_response = {'Error': {'Code': 'InvalidEndpointException'}}
self._assert_retries(parsed_response)
|