def test_list_instances(self):
        # Setup Expected Response
        next_page_token = ''
        instances_element = {}
        instances = [instances_element]
        expected_response = {
            'next_page_token': next_page_token,
            'instances': instances
        }
        expected_response = spanner_instance_admin_pb2.ListInstancesResponse(
            **expected_response)

        # Mock the API response
        channel = ChannelStub(responses=[expected_response])
        client = spanner_admin_instance_v1.InstanceAdminClient(channel=channel)

        # Setup Request
        parent = client.project_path('[PROJECT]')

        paged_list_response = client.list_instances(parent)
        resources = list(paged_list_response)
        assert len(resources) == 1

        assert expected_response.instances[0] == resources[0]

        assert len(channel.requests) == 1
        expected_request = spanner_instance_admin_pb2.ListInstancesRequest(
            parent=parent)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
Esempio n. 2
0
    def test_list_instances_w_options(self):
        from google.cloud.spanner_admin_instance_v1.gapic import instance_admin_client
        from google.cloud.spanner_admin_instance_v1.proto import (
            spanner_instance_admin_pb2, )

        api = instance_admin_client.InstanceAdminClient(mock.Mock())
        credentials = _make_credentials()
        client = self._make_one(project=self.PROJECT, credentials=credentials)
        client._instance_admin_api = api

        instance_pbs = spanner_instance_admin_pb2.ListInstancesResponse(
            instances=[])

        li_api = api._inner_api_calls["list_instances"] = mock.Mock(
            return_value=instance_pbs)

        token = "token"
        page_size = 42
        list(client.list_instances(page_token=token, page_size=42))

        expected_metadata = [
            ("google-cloud-resource-prefix", client.project_name),
            ("x-goog-request-params", "parent={}".format(client.project_name)),
        ]
        li_api.assert_called_once_with(
            spanner_instance_admin_pb2.ListInstancesRequest(
                parent=self.PATH, page_size=page_size, page_token=token),
            metadata=expected_metadata,
            retry=mock.ANY,
            timeout=mock.ANY,
        )
Esempio n. 3
0
    def test_list_instances(self):
        # Setup Expected Response
        next_page_token = ""
        instances_element = {}
        instances = [instances_element]
        expected_response = {"next_page_token": next_page_token, "instances": instances}
        expected_response = spanner_instance_admin_pb2.ListInstancesResponse(
            **expected_response
        )

        # Mock the API response
        channel = ChannelStub(responses=[expected_response])
        patch = mock.patch("google.api_core.grpc_helpers.create_channel")
        with patch as create_channel:
            create_channel.return_value = channel
            client = spanner_admin_instance_v1.InstanceAdminClient()

        # Setup Request
        parent = client.project_path("[PROJECT]")

        paged_list_response = client.list_instances(parent)
        resources = list(paged_list_response)
        assert len(resources) == 1

        assert expected_response.instances[0] == resources[0]

        assert len(channel.requests) == 1
        expected_request = spanner_instance_admin_pb2.ListInstancesRequest(
            parent=parent
        )
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
    def test_list_instances_w_options(self):
        from google.cloud.spanner_admin_instance_v1.gapic import (
            instance_admin_client)
        from google.cloud.spanner_admin_instance_v1.proto import (
            spanner_instance_admin_pb2)

        api = instance_admin_client.InstanceAdminClient(mock.Mock())
        credentials = _make_credentials()
        client = self._make_one(project=self.PROJECT, credentials=credentials)
        client._instance_admin_api = api

        instance_pbs = (spanner_instance_admin_pb2.ListInstancesResponse(
            instances=[]))

        api._list_instances = mock.Mock(return_value=instance_pbs)

        token = 'token'
        page_size = 42
        list(client.list_instances(page_token=token, page_size=42))

        api._list_instances.assert_called_once_with(
            spanner_instance_admin_pb2.ListInstancesRequest(
                parent=self.PATH, page_size=page_size, page_token=token),
            metadata=[('google-cloud-resource-prefix', client.project_name)],
            retry=mock.ANY,
            timeout=mock.ANY)
Esempio n. 5
0
    def test_list_instances(self):
        from google.cloud.spanner_admin_instance_v1.gapic import instance_admin_client
        from google.cloud.spanner_admin_instance_v1.proto import (
            spanner_instance_admin_pb2,
        )
        from google.cloud.spanner_v1.client import Instance

        api = instance_admin_client.InstanceAdminClient(mock.Mock())
        credentials = _make_credentials()
        client = self._make_one(project=self.PROJECT, credentials=credentials)
        client._instance_admin_api = api

        instance_pbs = spanner_instance_admin_pb2.ListInstancesResponse(
            instances=[
                spanner_instance_admin_pb2.Instance(
                    name=self.INSTANCE_NAME,
                    config=self.CONFIGURATION_NAME,
                    display_name=self.DISPLAY_NAME,
                    node_count=self.NODE_COUNT,
                )
            ]
        )

        li_api = api._inner_api_calls["list_instances"] = mock.Mock(
            return_value=instance_pbs
        )

        response = client.list_instances()
        instances = list(response)

        instance = instances[0]
        self.assertIsInstance(instance, Instance)
        self.assertEqual(instance.name, self.INSTANCE_NAME)
        self.assertEqual(instance.configuration_name, self.CONFIGURATION_NAME)
        self.assertEqual(instance.display_name, self.DISPLAY_NAME)
        self.assertEqual(instance.node_count, self.NODE_COUNT)

        expected_metadata = [
            ("google-cloud-resource-prefix", client.project_name),
            ("x-goog-request-params", "parent={}".format(client.project_name)),
        ]
        li_api.assert_called_once_with(
            spanner_instance_admin_pb2.ListInstancesRequest(parent=self.PATH),
            metadata=expected_metadata,
            retry=mock.ANY,
            timeout=mock.ANY,
        )
    def test_list_instances(self, mock_create_stub):
        # Mock gRPC layer
        grpc_stub = mock.Mock()
        mock_create_stub.return_value = grpc_stub

        client = spanner_admin_instance_v1.InstanceAdminClient()

        # Mock request
        parent = client.project_path('[PROJECT]')

        # Mock response
        next_page_token = ''
        instances_element = {}
        instances = [instances_element]
        expected_response = {
            'next_page_token': next_page_token,
            'instances': instances
        }
        expected_response = spanner_instance_admin_pb2.ListInstancesResponse(
            **expected_response)
        grpc_stub.ListInstances.return_value = expected_response

        paged_list_response = client.list_instances(parent)
        resources = list(paged_list_response)
        self.assertEqual(1, len(resources))
        self.assertEqual(expected_response.instances[0], resources[0])

        grpc_stub.ListInstances.assert_called_once()
        args, kwargs = grpc_stub.ListInstances.call_args
        self.assertEqual(len(args), 2)
        self.assertEqual(len(kwargs), 1)
        self.assertIn('metadata', kwargs)
        actual_request = args[0]

        expected_request = spanner_instance_admin_pb2.ListInstancesRequest(
            parent=parent)
        self.assertEqual(expected_request, actual_request)
Esempio n. 7
0
    def list_instances(self,
                       parent,
                       page_size=None,
                       filter_=None,
                       retry=google.api_core.gapic_v1.method.DEFAULT,
                       timeout=google.api_core.gapic_v1.method.DEFAULT,
                       metadata=None):
        """
        Lists all instances in the given project.

        Example:
            >>> from google.cloud import spanner_admin_instance_v1
            >>>
            >>> client = spanner_admin_instance_v1.InstanceAdminClient()
            >>>
            >>> parent = client.project_path('[PROJECT]')
            >>>
            >>>
            >>> # Iterate over all results
            >>> for element in client.list_instances(parent):
            ...     # process element
            ...     pass
            >>>
            >>> # Or iterate over results one page at a time
            >>> for page in client.list_instances(parent, options=CallOptions(page_token=INITIAL_PAGE)):
            ...     for element in page:
            ...         # process element
            ...         pass

        Args:
            parent (str): Required. The name of the project for which a list of instances is
                requested. Values are of the form ``projects/<project>``.
            page_size (int): The maximum number of resources contained in the
                underlying API response. If page streaming is performed per-
                resource, this parameter does not affect the return value. If page
                streaming is performed per-page, this determines the maximum number
                of resources in a page.
            filter_ (str): An expression for filtering the results of the request. Filter rules are
                case insensitive. The fields eligible for filtering are:

                  * ``name``
                  * ``display_name``
                  * ``labels.key`` where key is the name of a label

                Some examples of using filters are:

                  * ``name:*`` --> The instance has a name.
                  * ``name:Howl`` --> The instance's name contains the string \"howl\".
                  * ``name:HOWL`` --> Equivalent to above.
                  * ``NAME:howl`` --> Equivalent to above.
                  * ``labels.env:*`` --> The instance has the label \"env\".
                  * ``labels.env:dev`` --> The instance has the label \"env\" and the value of the label contains the string \"dev\".
                  * ``name:howl labels.env:dev`` --> The instance's name contains \"howl\" and it has the label \"env\" with its value containing \"dev\".

            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.

        Returns:
            A :class:`~google.gax.PageIterator` instance. By default, this
            is an iterable of :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` instances.
            This object can also be configured to iterate over the pages
            of the response through the `options` parameter.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        request = spanner_instance_admin_pb2.ListInstancesRequest(
            parent=parent,
            page_size=page_size,
            filter=filter_,
        )
        iterator = google.api_core.page_iterator.GRPCIterator(
            client=None,
            method=functools.partial(self._list_instances,
                                     retry=retry,
                                     timeout=timeout,
                                     metadata=metadata),
            request=request,
            items_field='instances',
            request_token_field='page_token',
            response_token_field='next_page_token',
        )
        return iterator
    def list_instances(self,
                       parent,
                       page_size=None,
                       filter_=None,
                       options=None):
        """
        Lists all instances in the given project.

        Example:
            >>> from google.cloud import spanner_admin_instance_v1
            >>> from google.gax import CallOptions, INITIAL_PAGE
            >>>
            >>> client = spanner_admin_instance_v1.InstanceAdminClient()
            >>>
            >>> parent = client.project_path('[PROJECT]')
            >>>
            >>>
            >>> # Iterate over all results
            >>> for element in client.list_instances(parent):
            ...     # process element
            ...     pass
            >>>
            >>> # Or iterate over results one page at a time
            >>> for page in client.list_instances(parent, options=CallOptions(page_token=INITIAL_PAGE)):
            ...     for element in page:
            ...         # process element
            ...         pass

        Args:
            parent (str): Required. The name of the project for which a list of instances is
                requested. Values are of the form ``projects/<project>``.
            page_size (int): The maximum number of resources contained in the
                underlying API response. If page streaming is performed per-
                resource, this parameter does not affect the return value. If page
                streaming is performed per-page, this determines the maximum number
                of resources in a page.
            filter_ (str): An expression for filtering the results of the request. Filter rules are
                case insensitive. The fields eligible for filtering are:

                  * name
                  * display_name
                  * labels.key where key is the name of a label

                Some examples of using filters are:

                  * name:* --> The instance has a name.
                  * name:Howl --> The instance's name contains the string \"howl\".
                  * name:HOWL --> Equivalent to above.
                  * NAME:howl --> Equivalent to above.
                  * labels.env:* --> The instance has the label \"env\".
                  * labels.env:dev --> The instance has the label \"env\" and the value of
                    the label contains the string \"dev\".
                  * name:howl labels.env:dev --> The instance's name contains \"howl\" and
                    it has the label \"env\" with its value containing \"dev\".

            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.gax.PageIterator` instance. By default, this
            is an iterable of :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` instances.
            This object can also be configured to iterate over the pages
            of the response through the `options` parameter.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_instance_admin_pb2.ListInstancesRequest(
            parent=parent, page_size=page_size, filter=filter_)
        return self._list_instances(request, options)
Esempio n. 9
0
    def list_instances(
        self,
        parent,
        page_size=None,
        filter_=None,
        retry=google.api_core.gapic_v1.method.DEFAULT,
        timeout=google.api_core.gapic_v1.method.DEFAULT,
        metadata=None,
    ):
        """
        Lists all instances in the given project.

        Example:
            >>> from google.cloud import spanner_admin_instance_v1
            >>>
            >>> client = spanner_admin_instance_v1.InstanceAdminClient()
            >>>
            >>> parent = client.project_path('[PROJECT]')
            >>>
            >>> # Iterate over all results
            >>> for element in client.list_instances(parent):
            ...     # process element
            ...     pass
            >>>
            >>>
            >>> # Alternatively:
            >>>
            >>> # Iterate over results one page at a time
            >>> for page in client.list_instances(parent).pages:
            ...     for element in page:
            ...         # process element
            ...         pass

        Args:
            parent (str): Required. The name of the project for which a list of instances is
                requested. Values are of the form ``projects/<project>``.
            page_size (int): The maximum number of resources contained in the
                underlying API response. If page streaming is performed per-
                resource, this parameter does not affect the return value. If page
                streaming is performed per-page, this determines the maximum number
                of resources in a page.
            filter_ (str): An expression for filtering the results of the request. Filter rules are
                case insensitive. The fields eligible for filtering are:

                -  ``name``
                -  ``display_name``
                -  ``labels.key`` where key is the name of a label

                Some examples of using filters are:

                -  ``name:*`` --> The instance has a name.
                -  ``name:Howl`` --> The instance's name contains the string "howl".
                -  ``name:HOWL`` --> Equivalent to above.
                -  ``NAME:howl`` --> Equivalent to above.
                -  ``labels.env:*`` --> The instance has the label "env".
                -  ``labels.env:dev`` --> The instance has the label "env" and the value
                   of the label contains the string "dev".
                -  ``name:howl labels.env:dev`` --> The instance's name contains "howl"
                   and it has the label "env" with its value containing "dev".
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.gax.PageIterator` instance. By default, this
            is an iterable of :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` instances.
            This object can also be configured to iterate over the pages
            of the response through the `options` parameter.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        # Wrap the transport method to add retry and timeout logic.
        if "list_instances" not in self._inner_api_calls:
            self._inner_api_calls[
                "list_instances"
            ] = google.api_core.gapic_v1.method.wrap_method(
                self.transport.list_instances,
                default_retry=self._method_configs["ListInstances"].retry,
                default_timeout=self._method_configs["ListInstances"].timeout,
                client_info=self._client_info,
            )

        request = spanner_instance_admin_pb2.ListInstancesRequest(
            parent=parent, page_size=page_size, filter=filter_
        )
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        try:
            routing_header = [("parent", parent)]
        except AttributeError:
            pass
        else:
            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
                routing_header
            )
            metadata.append(routing_metadata)

        iterator = google.api_core.page_iterator.GRPCIterator(
            client=None,
            method=functools.partial(
                self._inner_api_calls["list_instances"],
                retry=retry,
                timeout=timeout,
                metadata=metadata,
            ),
            request=request,
            items_field="instances",
            request_token_field="page_token",
            response_token_field="next_page_token",
        )
        return iterator