Example #1
0
    def test_generate_id_token(self):
        # Setup Expected Response
        token = "token110541305"
        expected_response = {"token": token}
        expected_response = common_pb2.GenerateIdTokenResponse(**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 = iam_credentials_v1.IAMCredentialsClient()

        # Setup Request
        name = client.service_account_path("[PROJECT]", "[SERVICE_ACCOUNT]")
        audience = "audience975628804"

        response = client.generate_id_token(name, audience)
        assert expected_response == response

        assert len(channel.requests) == 1
        expected_request = common_pb2.GenerateIdTokenRequest(
            name=name, audience=audience
        )
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
    def generate_id_token(
        self,
        name,
        audience,
        delegates=None,
        include_email=None,
        retry=google.api_core.gapic_v1.method.DEFAULT,
        timeout=google.api_core.gapic_v1.method.DEFAULT,
        metadata=None,
    ):
        """
        Generates an OpenID Connect ID token for a service account.

        Example:
            >>> from google.cloud import iam_credentials_v1
            >>>
            >>> client = iam_credentials_v1.IAMCredentialsClient()
            >>>
            >>> name = client.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]')
            >>>
            >>> # TODO: Initialize `audience`:
            >>> audience = ''
            >>>
            >>> response = client.generate_id_token(name, audience)

        Args:
            name (str): The resource name of the service account for which the credentials are
                requested, in the following format:
                ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``.
            audience (str): The audience for the token, such as the API or account that this token
                grants access to.
            delegates (list[str]): The sequence of service accounts in a delegation chain. Each service
                account must be granted the ``roles/iam.serviceAccountTokenCreator``
                role on its next service account in the chain. The last service account
                in the chain must be granted the
                ``roles/iam.serviceAccountTokenCreator`` role on the service account
                that is specified in the ``name`` field of the request.

                The delegates must have the following format:
                ``projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}``
            include_email (bool): Include the service account email in the token. If set to ``true``, the
                token will contain ``email`` and ``email_verified`` claims.
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will
                be retried using a default configuration.
            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.cloud.iam_credentials_v1.types.GenerateIdTokenResponse` instance.

        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 "generate_id_token" not in self._inner_api_calls:
            self._inner_api_calls[
                "generate_id_token"] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.generate_id_token,
                    default_retry=self._method_configs["GenerateIdToken"].
                    retry,
                    default_timeout=self._method_configs["GenerateIdToken"].
                    timeout,
                    client_info=self._client_info,
                )

        request = common_pb2.GenerateIdTokenRequest(
            name=name,
            audience=audience,
            delegates=delegates,
            include_email=include_email,
        )
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        try:
            routing_header = [("name", name)]
        except AttributeError:
            pass
        else:
            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
                routing_header)
            metadata.append(routing_metadata)

        return self._inner_api_calls["generate_id_token"](request,
                                                          retry=retry,
                                                          timeout=timeout,
                                                          metadata=metadata)