Example #1
0
    def setUp(self):
        super(TestResourceFactory, self).setUp()
        self.factory = ResourceFactory()
        self.load = self.factory.load_from_definition

        # Don't do version lookups on the filesystem, instead always return
        # a set date and mock calls to ``open`` when required.
        self.version_patch = mock.patch(
            'boto3.resources.factory.get_latest_version')
        self.version_mock = self.version_patch.start()
        self.version_mock.return_value = '2014-01-01'
Example #2
0
class BaseTestResourceFactory(BaseTestCase):
    def setUp(self):
        super(BaseTestResourceFactory, self).setUp()
        self.emitter = mock.Mock()
        self.factory = ResourceFactory(self.emitter)

    def load(self,
             resource_name,
             resource_json_definition=None,
             resource_json_definitions=None,
             service_model=None):
        if resource_json_definition is None:
            resource_json_definition = {}
        if resource_json_definitions is None:
            resource_json_definitions = {}
        service_context = ServiceContext(
            service_name='test',
            resource_json_definitions=resource_json_definitions,
            service_model=service_model,
            service_waiter_model=None)

        return self.factory.load_from_definition(
            resource_name=resource_name,
            single_resource_json_definition=resource_json_definition,
            service_context=service_context)
Example #3
0
    def setUp(self):
        super(TestResourceHandler, self).setUp()
        self.identifier_path = ''
        self.factory = ResourceFactory(mock.Mock())
        self.resource_defs = {
            'Frob': {
                'shape': 'Frob',
                'identifiers': [{
                    'name': 'Id'
                }]
            }
        }
        self.service_model = mock.Mock()
        shape = mock.Mock()
        shape.members = {}
        self.service_model.shape_for.return_value = shape

        frobs = mock.Mock()
        frobs.type_name = 'list'
        container = mock.Mock()
        container.type_name = 'structure'
        container.members = {'Frobs': frobs}
        self.output_shape = mock.Mock()
        self.output_shape.type_name = 'structure'
        self.output_shape.members = {'Container': container}
        operation_model = mock.Mock()
        operation_model.output_shape = self.output_shape
        self.service_model.operation_model.return_value = operation_model

        self.parent = mock.Mock()
        self.parent.meta = ResourceMeta('test', client=mock.Mock())
        self.params = {}
Example #4
0
    def _get_resource_list(self, search_path, response):
        request_resource_def = {
            'type':
            'Frob',
            'identifiers': [
                {
                    'target': 'Id',
                    'sourceType': 'responsePath',
                    'source': 'Container.Frobs[].Id'
                },
            ]
        }
        factory = ResourceFactory()
        resource_defs = {
            'Frob': {
                'shape': 'Frob',
                'identifiers': [{
                    'name': 'Id'
                }]
            }
        }
        service_model = mock.Mock()
        shape = mock.Mock()
        shape.members = {}
        service_model.shape_for.return_value = shape
        parent = mock.Mock()
        parent.meta = {
            'service_name': 'test',
            'client': mock.Mock(),
        }
        params = {}

        handler = ResourceHandler(search_path, factory, resource_defs,
                                  service_model, request_resource_def)
        return handler(parent, params, response)
    def setUp(self):
        super(TestCollectionFactory, self).setUp()

        self.client = mock.Mock()
        self.client.can_paginate.return_value = False
        self.parent = mock.Mock()
        self.parent.meta = ResourceMeta('test', client=self.client)
        self.resource_factory = ResourceFactory()
        self.service_model = ServiceModel({})

        self.factory = CollectionFactory()
        self.load = self.factory.load_from_definition
Example #6
0
    def __init__(self,
                 aws_access_key_id=None,
                 aws_secret_access_key=None,
                 aws_session_token=None,
                 region_name=None,
                 botocore_session=None,
                 profile_name=None):
        if botocore_session is not None:
            self._session = botocore_session
        else:
            # Create a new default session
            self._session = botocore.session.get_session()

        # Setup custom user-agent string if it isn't already customized
        if self._session.user_agent_name == 'Botocore':
            botocore_info = 'Botocore/{0}'.format(
                self._session.user_agent_version)
            if self._session.user_agent_extra:
                self._session.user_agent_extra += ' ' + botocore_info
            else:
                self._session.user_agent_extra = botocore_info
            self._session.user_agent_name = 'Boto3'
            self._session.user_agent_version = boto3.__version__

        if profile_name is not None:
            self._session.set_config_variable('profile', profile_name)

        if aws_access_key_id or aws_secret_access_key or aws_session_token:
            self._session.set_credentials(aws_access_key_id,
                                          aws_secret_access_key,
                                          aws_session_token)

        if region_name is not None:
            self._session.set_config_variable('region', region_name)

        self.resource_factory = ResourceFactory(
            self._session.get_component('event_emitter'))
        self._setup_loader()
Example #7
0
    def setUp(self):
        super(TestResourceCollection, self).setUp()

        # Minimal definition so things like repr work
        self.collection_def = {
            'request': {
                'operation': 'TestOperation'
            },
            'resource': {
                'type': 'Frob'
            }
        }
        self.client = mock.Mock()
        self.client.can_paginate.return_value = False
        self.parent = mock.Mock()
        self.parent.meta = ResourceMeta('test', client=self.client)
        self.factory = ResourceFactory(mock.Mock())
        self.service_model = ServiceModel({})
Example #8
0
 def setUp(self):
     super(BaseTestResourceFactory, self).setUp()
     self.emitter = mock.Mock()
     self.factory = ResourceFactory(self.emitter)
Example #9
0
class TestResourceFactory(BaseTestCase):
    def setUp(self):
        super(TestResourceFactory, self).setUp()
        self.factory = ResourceFactory()
        self.load = self.factory.load_from_definition

        # Don't do version lookups on the filesystem, instead always return
        # a set date and mock calls to ``open`` when required.
        self.version_patch = mock.patch(
            'boto3.resources.factory.get_latest_version')
        self.version_mock = self.version_patch.start()
        self.version_mock.return_value = '2014-01-01'

    def tearDown(self):
        super(TestResourceFactory, self).tearDown()
        self.version_patch.stop()

    def test_create_service_calls_load(self):
        self.factory.load_from_definition = mock.Mock()
        with mock.patch('boto3.resources.factory.open',
                        mock.mock_open(read_data='{}'),
                        create=True):
            self.factory.create_class('test')

            self.assertTrue(self.factory.load_from_definition.called,
                            'Class was not loaded from definition')
            self.factory.load_from_definition.assert_called_with(
                'test', 'test', {}, {}, None)

    def test_create_resource_calls_load(self):
        self.factory.load_from_definition = mock.Mock()
        with mock.patch('boto3.resources.factory.open',
                        mock.mock_open(read_data='{}'),
                        create=True):
            self.factory.create_class('test', 'Queue')

            self.assertTrue(self.factory.load_from_definition.called,
                            'Class was not loaded from definition')
            self.factory.load_from_definition.assert_called_with(
                'test', 'Queue', {}, {}, None)

    def test_get_service_returns_resource_class(self):
        TestResource = self.load('test', 'test', {}, {}, None)

        self.assertIn(ServiceResource, TestResource.__bases__,
                      'Did not return a ServiceResource subclass for service')

    def test_get_resource_returns_resource_class(self):
        QueueResource = self.load('test', 'Queue', {}, {}, None)

        self.assertIn(
            ServiceResource, QueueResource.__bases__,
            'Did not return a ServiceResource subclass for resource')

    def test_factory_sets_service_name(self):
        QueueResource = self.load('test', 'Queue', {}, {}, None)

        self.assertEqual(QueueResource.meta['service_name'], 'test',
                         'Service name not set')

    def test_factory_sets_identifiers(self):
        model = {
            'identifiers': [
                {
                    'name': 'QueueUrl'
                },
                {
                    'name': 'ReceiptHandle'
                },
            ],
        }

        MessageResource = self.load('test', 'Message', model, {}, None)

        self.assertTrue('identifiers' in MessageResource.meta,
                        'Class has no identifiers')
        self.assertIn('queue_url', MessageResource.meta['identifiers'],
                      'Missing queue_url identifier from model')
        self.assertIn('receipt_handle', MessageResource.meta['identifiers'],
                      'Missing receipt_handle identifier from model')

    def test_factory_creates_dangling_resources(self):
        defs = {'Queue': {}, 'Message': {}}

        TestResource = self.load('test', 'test', {}, defs, None)

        self.assertTrue(hasattr(TestResource, 'Queue'),
                        'Missing Queue class from model')
        self.assertTrue(hasattr(TestResource, 'Message'),
                        'Missing Message class from model')

    def test_factory_creates_properties(self):
        model = {
            'shape': 'TestShape',
            'load': {
                'request': {
                    'operation': 'DescribeTest',
                }
            }
        }
        shape = mock.Mock()
        shape.members = {
            'ETag': None,
            'LastModified': None,
        }
        service_model = mock.Mock()
        service_model.shape_for.return_value = shape

        TestResource = self.load('test', 'test', model, {}, service_model)

        self.assertTrue(hasattr(TestResource, 'e_tag'),
                        'ETag shape member not available on resource')
        self.assertTrue(hasattr(TestResource, 'last_modified'),
                        'LastModified shape member not available on resource')

    def test_factory_fails_on_clobber_identifier(self):
        model = {'identifiers': [{'name': 'Meta'}]}

        # This fails because each resource has a `meta` defined.
        with self.assertRaises(ValueError):
            self.load('test', 'test', model, {}, None)

    def test_factory_fails_on_clobber_action(self):
        model = {
            'identifiers': [{
                'name': 'Test'
            }],
            'actions': {
                'Test': {
                    'request': {
                        'operation': 'GetTest'
                    }
                }
            }
        }

        # This fails because the resource has an identifier
        # that would be clobbered by the action name.
        with self.assertRaises(ValueError):
            self.load('test', 'test', model, {}, None)

    def test_can_instantiate_service_resource(self):
        TestResource = self.load('test', 'test', {}, {}, None)
        resource = TestResource()

        self.assertIsInstance(resource, ServiceResource,
                              'Object is not an instance of ServiceResource')

    def test_dangling_resources_create_resource_instance(self):
        defs = {'Queue': {'identifiers': [{'name': 'Url'}]}}

        resource = self.load('test', 'test', {}, defs, None)()
        q = resource.Queue('test')

        self.assertIsInstance(
            q, ServiceResource,
            'Dangling resource instance not a ServiceResource')

    def test_dangling_resource_create_with_kwarg(self):
        defs = {'Queue': {'identifiers': [{'name': 'Url'}]}}

        resource = self.load('test', 'test', {}, defs, None)()
        q = resource.Queue(url='test')

        self.assertIsInstance(
            q, ServiceResource,
            'Dangling resource created with kwargs is not a ServiceResource')

    def test_dangling_resource_shares_client(self):
        defs = {'Queue': {'identifiers': [{'name': 'Url'}]}}

        resource = self.load('test', 'test', {}, defs, None)()
        q = resource.Queue('test')

        self.assertEqual(
            resource.meta['client'], q.meta['client'],
            'Client was not shared to dangling resource instance')

    def test_dangling_resource_requires_identifier(self):
        defs = {'Queue': {'identifiers': [{'name': 'Url'}]}}

        resource = self.load('test', 'test', {}, defs, None)()

        with self.assertRaises(ValueError):
            resource.Queue()

    def test_dangling_resource_raises_for_unknown_arg(self):
        defs = {'Queue': {'identifiers': [{'name': 'Url'}]}}

        resource = self.load('test', 'test', {}, defs, None)()

        with self.assertRaises(ValueError):
            resource.Queue(url='foo', bar='baz')

    def test_non_service_resource_missing_defs(self):
        # Only services should get dangling defs
        defs = {
            'Queue': {
                'identifiers': [{
                    'name': 'Url'
                }]
            },
            'Message': {
                'identifiers': [{
                    'name': 'QueueUrl'
                }, {
                    'name': 'ReceiptHandle'
                }]
            }
        }

        model = defs['Queue']

        queue = self.load('test', 'Queue', model, defs, None)('url')

        self.assertTrue(not hasattr(queue, 'Queue'))
        self.assertTrue(not hasattr(queue, 'Message'))

    def test_subresource_requires_only_identifier(self):
        defs = {
            'Queue': {
                'identifiers': [{
                    'name': 'Url'
                }],
                'subResources': {
                    'resources': ['Message'],
                    'identifiers': {
                        'Url': 'QueueUrl'
                    }
                }
            },
            'Message': {
                'identifiers': [{
                    'name': 'QueueUrl'
                }, {
                    'name': 'ReceiptHandle'
                }]
            }
        }

        model = defs['Queue']

        queue = self.load('test', 'Queue', model, defs, None)('url')

        # Let's create a message and only give it a receipt handle
        # The required queue_url identifier should be set from the
        # queue itself.
        message = queue.Message('receipt')

        self.assertEqual(
            message.queue_url, 'url',
            'Wrong queue URL set on the message resource instance')
        self.assertEqual(
            message.receipt_handle, 'receipt',
            'Wrong receipt handle set on the message resource instance')

    @mock.patch('boto3.resources.factory.ServiceAction')
    def test_resource_calls_action(self, action_cls):
        model = {
            'actions': {
                'GetMessageStatus': {
                    'request': {
                        'operation': 'DescribeMessageStatus'
                    }
                }
            }
        }

        action = action_cls.return_value

        queue = self.load('test', 'Queue', model, {}, None)()
        queue.get_message_status('arg1', arg2=2)

        action.assert_called_with(queue, 'arg1', arg2=2)

    @mock.patch('boto3.resources.factory.ServiceAction')
    def test_resource_lazy_loads_properties(self, action_cls):
        model = {
            'shape': 'TestShape',
            'identifiers': [{
                'name': 'Url'
            }],
            'load': {
                'request': {
                    'operation': 'DescribeTest',
                }
            }
        }
        shape = mock.Mock()
        shape.members = {
            'Url': None,
            'ETag': None,
            'LastModified': None,
        }
        service_model = mock.Mock()
        service_model.shape_for.return_value = shape

        action = action_cls.return_value
        action.return_value = {'ETag': 'tag', 'LastModified': 'never'}

        resource = self.load('test', 'test', model, {}, service_model)('url')

        # Accessing an identifier should not call load, even if it's in
        # the shape members.
        resource.url
        action.assert_not_called()

        # Accessing a property should call load
        self.assertEqual(resource.e_tag, 'tag',
                         'ETag property returned wrong value')
        action.assert_called_once()

        # Both params should have been loaded into the data bag
        self.assertIn('ETag', resource.meta['data'])
        self.assertIn('LastModified', resource.meta['data'])

        # Accessing another property should use cached value
        # instead of making a second call.
        self.assertEqual(resource.last_modified, 'never',
                         'LastModified property returned wrong value')
        action.assert_called_once()

    @mock.patch('boto3.resources.factory.ServiceAction')
    def test_resource_lazy_properties_missing_load(self, action_cls):
        model = {
            'shape': 'TestShape',
            'identifiers': [{
                'name': 'Url'
            }]
            # Note the lack of a `load` method. These resources
            # are usually loaded via a call on a parent resource.
        }
        shape = mock.Mock()
        shape.members = {
            'Url': None,
            'ETag': None,
            'LastModified': None,
        }
        service_model = mock.Mock()
        service_model.shape_for.return_value = shape

        action = action_cls.return_value
        action.return_value = {'ETag': 'tag', 'LastModified': 'never'}

        resource = self.load('test', 'test', model, {}, service_model)('url')

        with self.assertRaises(ResourceLoadException):
            resource.last_modified
Example #10
0
class AWS_Session(object):
    """
    A session stores configuration state and allows you to create service
    clients and resources.

    :type aws_access_key_id: string
    :param aws_access_key_id: AWS access key ID
    :type aws_secret_access_key: string
    :param aws_secret_access_key: AWS secret access key
    :type aws_session_token: string
    :param aws_session_token: AWS temporary session token
    :type region_name: string
    :param region_name: Default region when creating new connections
    :type botocore_session: botocore.session.Session
    :param botocore_session: Use this Botocore session instead of creating
                             a new default one.
    :type profile_name: string
    :param profile_name: The name of a profile to use. If not given, then
                         the default profile is used.
    """
    def __init__(self,
                 aws_access_key_id=None,
                 aws_secret_access_key=None,
                 aws_session_token=None,
                 region_name=None,
                 botocore_session=None,
                 profile_name=None):
        if botocore_session is not None:
            self._session = botocore_session
        else:
            # Create a new default session
            self._session = botocore.session.get_session()

        # Setup custom user-agent string if it isn't already customized
        if self._session.user_agent_name == 'Botocore':
            botocore_info = 'Botocore/{0}'.format(
                self._session.user_agent_version)
            if self._session.user_agent_extra:
                self._session.user_agent_extra += ' ' + botocore_info
            else:
                self._session.user_agent_extra = botocore_info
            self._session.user_agent_name = 'Boto3'
            self._session.user_agent_version = boto3.__version__

        if profile_name is not None:
            self._session.set_config_variable('profile', profile_name)

        if aws_access_key_id or aws_secret_access_key or aws_session_token:
            self._session.set_credentials(aws_access_key_id,
                                          aws_secret_access_key,
                                          aws_session_token)

        if region_name is not None:
            self._session.set_config_variable('region', region_name)

        self.resource_factory = ResourceFactory(
            self._session.get_component('event_emitter'))
        self._setup_loader()

    def __repr__(self):
        return '{0}(region_name={1})'.format(
            self.__class__.__name__,
            repr(self._session.get_config_variable('region')))

    @property
    def profile_name(self):
        """
        The **read-only** profile name.
        """
        return self._session.profile or 'default'

    @property
    def region_name(self):
        """
        The **read-only** region name.
        """
        return self._session.get_config_variable('region')

    @property
    def events(self):
        """
        The event emitter for a session
        """
        return self._session.get_component('event_emitter')

    @property
    def available_profiles(self):
        """
        The profiles available to the session credentials
        """
        return self._session.available_profiles

    def _setup_loader(self):
        """
        Setup loader paths so that we can load resources.
        """
        self._loader = self._session.get_component('data_loader')
        self._loader.search_paths.append(
            os.path.join(os.path.dirname(__file__), 'data'))

    def get_available_services(self):
        """
        Get a list of available services that can be loaded as low-level
        clients via :py:meth:`Session.client`.

        :rtype: list
        :return: List of service names
        """
        return self._session.get_available_services()

    def get_available_resources(self):
        """
        Get a list of available services that can be loaded as resource
        clients via :py:meth:`Session.resource`.

        :rtype: list
        :return: List of service names
        """
        return self._loader.list_available_services(type_name='resources-1')

    def get_available_partitions(self):
        """Lists the available partitions

        :rtype: list
        :return: Returns a list of partition names (e.g., ["aws", "aws-cn"])
        """
        return self._session.get_available_partitions()

    def get_available_regions(self,
                              service_name,
                              partition_name='aws',
                              allow_non_regional=False):
        """Lists the region and endpoint names of a particular partition.

        :type service_name: string
        :param service_name: Name of a service to list endpoint for (e.g., s3).

        :type partition_name: string
        :param partition_name: Name of the partition to limit endpoints to.
            (e.g., aws for the public AWS endpoints, aws-cn for AWS China
            endpoints, aws-us-gov for AWS GovCloud (US) Endpoints, etc.)

        :type allow_non_regional: bool
        :param allow_non_regional: Set to True to include endpoints that are
             not regional endpoints (e.g., s3-external-1,
             fips-us-gov-west-1, etc).

        :return: Returns a list of endpoint names (e.g., ["us-east-1"]).
        """
        return self._session.get_available_regions(
            service_name=service_name,
            partition_name=partition_name,
            allow_non_regional=allow_non_regional)

    def get_credentials(self):
        """
        Return the :class:`botocore.credential.Credential` object
        associated with this session.  If the credentials have not
        yet been loaded, this will attempt to load them.  If they
        have already been loaded, this will return the cached
        credentials.
        """
        return self._session.get_credentials()

    def client(self,
               service_name,
               region_name=None,
               api_version=None,
               use_ssl=True,
               verify=None,
               endpoint_url=None,
               aws_access_key_id=None,
               aws_secret_access_key=None,
               aws_session_token=None,
               config=None):
        """
        Create a low-level service client by name.

        :type service_name: string
        :param service_name: The name of a service, e.g. 's3' or 'ec2'. You
            can get a list of available services via
            :py:meth:`get_available_services`.

        :type region_name: string
        :param region_name: The name of the region associated with the client.
            A client is associated with a single region.

        :type api_version: string
        :param api_version: The API version to use.  By default, botocore will
            use the latest API version when creating a client.  You only need
            to specify this parameter if you want to use a previous API version
            of the client.

        :type use_ssl: boolean
        :param use_ssl: Whether or not to use SSL.  By default, SSL is used.
            Note that not all services support non-ssl connections.

        :type verify: boolean/string
        :param verify: Whether or not to verify SSL certificates.  By default
            SSL certificates are verified.  You can provide the following
            values:

            * False - do not validate SSL certificates.  SSL will still be
              used (unless use_ssl is False), but SSL certificates
              will not be verified.
            * path/to/cert/bundle.pem - A filename of the CA cert bundle to
              uses.  You can specify this argument if you want to use a
              different CA cert bundle than the one used by botocore.

        :type endpoint_url: string
        :param endpoint_url: The complete URL to use for the constructed
            client. Normally, botocore will automatically construct the
            appropriate URL to use when communicating with a service.  You
            can specify a complete URL (including the "http/https" scheme)
            to override this behavior.  If this value is provided,
            then ``use_ssl`` is ignored.

        :type aws_access_key_id: string
        :param aws_access_key_id: The access key to use when creating
            the client.  This is entirely optional, and if not provided,
            the credentials configured for the session will automatically
            be used.  You only need to provide this argument if you want
            to override the credentials used for this specific client.

        :type aws_secret_access_key: string
        :param aws_secret_access_key: The secret key to use when creating
            the client.  Same semantics as aws_access_key_id above.

        :type aws_session_token: string
        :param aws_session_token: The session token to use when creating
            the client.  Same semantics as aws_access_key_id above.

        :type config: botocore.client.Config
        :param config: Advanced client configuration options. If region_name
            is specified in the client config, its value will take precedence
            over environment variables and configuration values, but not over
            a region_name value passed explicitly to the method. See
            `botocore config documentation
            <https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html>`_
            for more details.

        :return: Service client instance

        """
        return self._session.create_client(
            service_name,
            region_name=region_name,
            api_version=api_version,
            use_ssl=use_ssl,
            verify=verify,
            endpoint_url=endpoint_url,
            aws_access_key_id=aws_access_key_id,
            aws_secret_access_key=aws_secret_access_key,
            aws_session_token=aws_session_token,
            config=config)

    def resource(self,
                 service_name,
                 region_name=None,
                 api_version=None,
                 use_ssl=True,
                 verify=None,
                 endpoint_url=None,
                 aws_access_key_id=None,
                 aws_secret_access_key=None,
                 aws_session_token=None,
                 config=None):
        """
        Create a resource service client by name.

        :type service_name: string
        :param service_name: The name of a service, e.g. 's3' or 'ec2'. You
            can get a list of available services via
            :py:meth:`get_available_resources`.

        :type region_name: string
        :param region_name: The name of the region associated with the client.
            A client is associated with a single region.

        :type api_version: string
        :param api_version: The API version to use.  By default, botocore will
            use the latest API version when creating a client.  You only need
            to specify this parameter if you want to use a previous API version
            of the client.

        :type use_ssl: boolean
        :param use_ssl: Whether or not to use SSL.  By default, SSL is used.
            Note that not all services support non-ssl connections.

        :type verify: boolean/string
        :param verify: Whether or not to verify SSL certificates.  By default
            SSL certificates are verified.  You can provide the following
            values:

            * False - do not validate SSL certificates.  SSL will still be
              used (unless use_ssl is False), but SSL certificates
              will not be verified.
            * path/to/cert/bundle.pem - A filename of the CA cert bundle to
              uses.  You can specify this argument if you want to use a
              different CA cert bundle than the one used by botocore.

        :type endpoint_url: string
        :param endpoint_url: The complete URL to use for the constructed
            client. Normally, botocore will automatically construct the
            appropriate URL to use when communicating with a service.  You
            can specify a complete URL (including the "http/https" scheme)
            to override this behavior.  If this value is provided,
            then ``use_ssl`` is ignored.

        :type aws_access_key_id: string
        :param aws_access_key_id: The access key to use when creating
            the client.  This is entirely optional, and if not provided,
            the credentials configured for the session will automatically
            be used.  You only need to provide this argument if you want
            to override the credentials used for this specific client.

        :type aws_secret_access_key: string
        :param aws_secret_access_key: The secret key to use when creating
            the client.  Same semantics as aws_access_key_id above.

        :type aws_session_token: string
        :param aws_session_token: The session token to use when creating
            the client.  Same semantics as aws_access_key_id above.

        :type config: botocore.client.Config
        :param config: Advanced client configuration options. If region_name
            is specified in the client config, its value will take precedence
            over environment variables and configuration values, but not over
            a region_name value passed explicitly to the method.  If
            user_agent_extra is specified in the client config, it overrides
            the default user_agent_extra provided by the resource API. See
            `botocore config documentation
            <https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html>`_
            for more details.

        :return: Subclass of :py:class:`~boto3.resources.base.ServiceResource`
        """
        try:
            resource_model = self._loader.load_service_model(
                service_name, 'resources-1', api_version)
        except UnknownServiceError:
            available = self.get_available_resources()
            has_low_level_client = (service_name
                                    in self.get_available_services())
            raise ResourceNotExistsError(service_name, available,
                                         has_low_level_client)
        except DataNotFoundError:
            # This is because we've provided an invalid API version.
            available_api_versions = self._loader.list_api_versions(
                service_name, 'resources-1')
            raise UnknownAPIVersionError(service_name, api_version,
                                         ', '.join(available_api_versions))

        if api_version is None:
            # Even though botocore's load_service_model() can handle
            # using the latest api_version if not provided, we need
            # to track this api_version in boto3 in order to ensure
            # we're pairing a resource model with a client model
            # of the same API version.  It's possible for the latest
            # API version of a resource model in boto3 to not be
            # the same API version as a service model in botocore.
            # So we need to look up the api_version if one is not
            # provided to ensure we load the same API version of the
            # client.
            #
            # Note: This is relying on the fact that
            #   loader.load_service_model(..., api_version=None)
            # and loader.determine_latest_version(..., 'resources-1')
            # both load the same api version of the file.
            api_version = self._loader.determine_latest_version(
                service_name, 'resources-1')

        # Creating a new resource instance requires the low-level client
        # and service model, the resource version and resource JSON data.
        # We pass these to the factory and get back a class, which is
        # instantiated on top of the low-level client.
        if config is not None:
            if config.user_agent_extra is None:
                config = copy.deepcopy(config)
                config.user_agent_extra = 'Resource'
        else:
            config = Config(user_agent_extra='Resource')
        client = self.client(service_name,
                             region_name=region_name,
                             api_version=api_version,
                             use_ssl=use_ssl,
                             verify=verify,
                             endpoint_url=endpoint_url,
                             aws_access_key_id=aws_access_key_id,
                             aws_secret_access_key=aws_secret_access_key,
                             aws_session_token=aws_session_token,
                             config=config)
        service_model = client.meta.service_model

        # Create a ServiceContext object to serve as a reference to
        # important read-only information about the general service.
        service_context = boto3.utils.ServiceContext(
            service_name=service_name,
            service_model=service_model,
            resource_json_definitions=resource_model['resources'],
            service_waiter_model=boto3.utils.LazyLoadedWaiterModel(
                self._session, service_name, api_version))

        # Create the service resource class.
        cls = self.resource_factory.load_from_definition(
            resource_name=service_name,
            single_resource_json_definition=resource_model['service'],
            service_context=service_context)

        return cls(client=client)
Example #11
0
 def setUp(self):
     super(TestResourceFactory, self).setUp()
     self.factory = ResourceFactory()
     self.load = self.factory.load_from_definition
Example #12
0
 def setUp(self):
     super(BaseTestResourceFactory, self).setUp()
     self.emitter = mock.Mock()
     self.factory = ResourceFactory(self.emitter)
     self.load = self.factory.load_from_definition