From 347ed657f5f83bc9b83fa14a0bc8a3fabfcd22b3 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 18 Oct 2022 09:05:57 -0400 Subject: [PATCH] feat: Add CloudChannelReportsService to CloudChannel API (#209) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: Add CloudChannelReportsService to CloudChannel API PiperOrigin-RevId: 481642499 Source-Link: https://github.com/googleapis/googleapis/commit/0c78b0c2ef2a623784a6434316c80ee33a33dac1 Source-Link: https://github.com/googleapis/googleapis-gen/commit/d5bf707a1960ad03c96207ffac5a8dec26d6ea5f Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiZDViZjcwN2ExOTYwYWQwM2M5NjIwN2ZmYWM1YThkZWMyNmQ2ZWE1ZiJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot --- .../cloud_channel_reports_service.rst | 10 + docs/channel_v1/services.rst | 1 + google/cloud/channel/__init__.py | 38 + google/cloud/channel_v1/__init__.py | 36 + google/cloud/channel_v1/gapic_metadata.json | 44 + .../cloud_channel_reports_service/__init__.py | 22 + .../async_client.py | 819 +++++ .../cloud_channel_reports_service/client.py | 1055 ++++++ .../cloud_channel_reports_service/pagers.py | 283 ++ .../transports/__init__.py | 34 + .../transports/base.py | 233 ++ .../transports/grpc.py | 439 +++ .../transports/grpc_asyncio.py | 445 +++ .../cloud_channel_service/async_client.py | 3 +- .../services/cloud_channel_service/client.py | 3 +- .../cloud_channel_service/transports/grpc.py | 3 +- .../transports/grpc_asyncio.py | 3 +- google/cloud/channel_v1/types/__init__.py | 30 + .../cloud/channel_v1/types/reports_service.py | 617 ++++ google/cloud/channel_v1/types/service.py | 18 +- ...orts_service_fetch_report_results_async.py | 53 + ...ports_service_fetch_report_results_sync.py | 53 + ...nnel_reports_service_list_reports_async.py | 53 + ...annel_reports_service_list_reports_sync.py | 53 + ...el_reports_service_run_report_job_async.py | 56 + ...nel_reports_service_run_report_job_sync.py | 56 + .../snippet_metadata_channel_v1.json | 475 +++ scripts/fixup_channel_v1_keywords.py | 3 + .../test_cloud_channel_reports_service.py | 3100 +++++++++++++++++ 29 files changed, 8025 insertions(+), 13 deletions(-) create mode 100644 docs/channel_v1/cloud_channel_reports_service.rst create mode 100644 google/cloud/channel_v1/services/cloud_channel_reports_service/__init__.py create mode 100644 google/cloud/channel_v1/services/cloud_channel_reports_service/async_client.py create mode 100644 google/cloud/channel_v1/services/cloud_channel_reports_service/client.py create mode 100644 google/cloud/channel_v1/services/cloud_channel_reports_service/pagers.py create mode 100644 google/cloud/channel_v1/services/cloud_channel_reports_service/transports/__init__.py create mode 100644 google/cloud/channel_v1/services/cloud_channel_reports_service/transports/base.py create mode 100644 google/cloud/channel_v1/services/cloud_channel_reports_service/transports/grpc.py create mode 100644 google/cloud/channel_v1/services/cloud_channel_reports_service/transports/grpc_asyncio.py create mode 100644 google/cloud/channel_v1/types/reports_service.py create mode 100644 samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_fetch_report_results_async.py create mode 100644 samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_fetch_report_results_sync.py create mode 100644 samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_list_reports_async.py create mode 100644 samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_list_reports_sync.py create mode 100644 samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_run_report_job_async.py create mode 100644 samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_run_report_job_sync.py create mode 100644 tests/unit/gapic/channel_v1/test_cloud_channel_reports_service.py diff --git a/docs/channel_v1/cloud_channel_reports_service.rst b/docs/channel_v1/cloud_channel_reports_service.rst new file mode 100644 index 0000000..39e3749 --- /dev/null +++ b/docs/channel_v1/cloud_channel_reports_service.rst @@ -0,0 +1,10 @@ +CloudChannelReportsService +-------------------------------------------- + +.. automodule:: google.cloud.channel_v1.services.cloud_channel_reports_service + :members: + :inherited-members: + +.. automodule:: google.cloud.channel_v1.services.cloud_channel_reports_service.pagers + :members: + :inherited-members: diff --git a/docs/channel_v1/services.rst b/docs/channel_v1/services.rst index afcb3e9..a310f7a 100644 --- a/docs/channel_v1/services.rst +++ b/docs/channel_v1/services.rst @@ -3,4 +3,5 @@ Services for Google Cloud Channel v1 API .. toctree:: :maxdepth: 2 + cloud_channel_reports_service cloud_channel_service diff --git a/google/cloud/channel/__init__.py b/google/cloud/channel/__init__.py index 7d0eb98..0d1b70e 100644 --- a/google/cloud/channel/__init__.py +++ b/google/cloud/channel/__init__.py @@ -14,6 +14,12 @@ # limitations under the License. # +from google.cloud.channel_v1.services.cloud_channel_reports_service.async_client import ( + CloudChannelReportsServiceAsyncClient, +) +from google.cloud.channel_v1.services.cloud_channel_reports_service.client import ( + CloudChannelReportsServiceClient, +) from google.cloud.channel_v1.services.cloud_channel_service.async_client import ( CloudChannelServiceAsyncClient, ) @@ -68,6 +74,22 @@ Product, Sku, ) +from google.cloud.channel_v1.types.reports_service import ( + Column, + DateRange, + FetchReportResultsRequest, + FetchReportResultsResponse, + ListReportsRequest, + ListReportsResponse, + Report, + ReportJob, + ReportResultsMetadata, + ReportStatus, + ReportValue, + Row, + RunReportJobRequest, + RunReportJobResponse, +) from google.cloud.channel_v1.types.repricing import ( ChannelPartnerRepricingConfig, CustomerRepricingConfig, @@ -151,6 +173,8 @@ ) __all__ = ( + "CloudChannelReportsServiceClient", + "CloudChannelReportsServiceAsyncClient", "CloudChannelServiceClient", "CloudChannelServiceAsyncClient", "ChannelPartnerLink", @@ -192,6 +216,20 @@ "Product", "Sku", "MediaType", + "Column", + "DateRange", + "FetchReportResultsRequest", + "FetchReportResultsResponse", + "ListReportsRequest", + "ListReportsResponse", + "Report", + "ReportJob", + "ReportResultsMetadata", + "ReportStatus", + "ReportValue", + "Row", + "RunReportJobRequest", + "RunReportJobResponse", "ChannelPartnerRepricingConfig", "CustomerRepricingConfig", "PercentageAdjustment", diff --git a/google/cloud/channel_v1/__init__.py b/google/cloud/channel_v1/__init__.py index c5f1724..a6e47a6 100644 --- a/google/cloud/channel_v1/__init__.py +++ b/google/cloud/channel_v1/__init__.py @@ -14,6 +14,10 @@ # limitations under the License. # +from .services.cloud_channel_reports_service import ( + CloudChannelReportsServiceAsyncClient, + CloudChannelReportsServiceClient, +) from .services.cloud_channel_service import ( CloudChannelServiceAsyncClient, CloudChannelServiceClient, @@ -55,6 +59,22 @@ ) from .types.operations import OperationMetadata from .types.products import MarketingInfo, Media, MediaType, Product, Sku +from .types.reports_service import ( + Column, + DateRange, + FetchReportResultsRequest, + FetchReportResultsResponse, + ListReportsRequest, + ListReportsResponse, + Report, + ReportJob, + ReportResultsMetadata, + ReportStatus, + ReportValue, + Row, + RunReportJobRequest, + RunReportJobResponse, +) from .types.repricing import ( ChannelPartnerRepricingConfig, CustomerRepricingConfig, @@ -134,6 +154,7 @@ from .types.subscriber_event import CustomerEvent, EntitlementEvent, SubscriberEvent __all__ = ( + "CloudChannelReportsServiceAsyncClient", "CloudChannelServiceAsyncClient", "ActivateEntitlementRequest", "AdminUser", @@ -148,9 +169,11 @@ "ChannelPartnerRepricingConfig", "CheckCloudIdentityAccountsExistRequest", "CheckCloudIdentityAccountsExistResponse", + "CloudChannelReportsServiceClient", "CloudChannelServiceClient", "CloudIdentityCustomerAccount", "CloudIdentityInfo", + "Column", "CommitmentSettings", "Constraints", "ContactInfo", @@ -163,12 +186,15 @@ "CustomerConstraints", "CustomerEvent", "CustomerRepricingConfig", + "DateRange", "DeleteChannelPartnerRepricingConfigRequest", "DeleteCustomerRepricingConfigRequest", "DeleteCustomerRequest", "EduData", "Entitlement", "EntitlementEvent", + "FetchReportResultsRequest", + "FetchReportResultsResponse", "GetChannelPartnerLinkRequest", "GetChannelPartnerRepricingConfigRequest", "GetCustomerRepricingConfigRequest", @@ -193,6 +219,8 @@ "ListPurchasableOffersResponse", "ListPurchasableSkusRequest", "ListPurchasableSkusResponse", + "ListReportsRequest", + "ListReportsResponse", "ListSkusRequest", "ListSkusResponse", "ListSubscribersRequest", @@ -229,9 +257,17 @@ "RegisterSubscriberRequest", "RegisterSubscriberResponse", "RenewalSettings", + "Report", + "ReportJob", + "ReportResultsMetadata", + "ReportStatus", + "ReportValue", "RepricingAdjustment", "RepricingConfig", "ResourceType", + "Row", + "RunReportJobRequest", + "RunReportJobResponse", "Sku", "StartPaidServiceRequest", "SubscriberEvent", diff --git a/google/cloud/channel_v1/gapic_metadata.json b/google/cloud/channel_v1/gapic_metadata.json index 38333bb..aff1a2d 100644 --- a/google/cloud/channel_v1/gapic_metadata.json +++ b/google/cloud/channel_v1/gapic_metadata.json @@ -5,6 +5,50 @@ "protoPackage": "google.cloud.channel.v1", "schema": "1.0", "services": { + "CloudChannelReportsService": { + "clients": { + "grpc": { + "libraryClient": "CloudChannelReportsServiceClient", + "rpcs": { + "FetchReportResults": { + "methods": [ + "fetch_report_results" + ] + }, + "ListReports": { + "methods": [ + "list_reports" + ] + }, + "RunReportJob": { + "methods": [ + "run_report_job" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CloudChannelReportsServiceAsyncClient", + "rpcs": { + "FetchReportResults": { + "methods": [ + "fetch_report_results" + ] + }, + "ListReports": { + "methods": [ + "list_reports" + ] + }, + "RunReportJob": { + "methods": [ + "run_report_job" + ] + } + } + } + } + }, "CloudChannelService": { "clients": { "grpc": { diff --git a/google/cloud/channel_v1/services/cloud_channel_reports_service/__init__.py b/google/cloud/channel_v1/services/cloud_channel_reports_service/__init__.py new file mode 100644 index 0000000..8815a86 --- /dev/null +++ b/google/cloud/channel_v1/services/cloud_channel_reports_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import CloudChannelReportsServiceAsyncClient +from .client import CloudChannelReportsServiceClient + +__all__ = ( + "CloudChannelReportsServiceClient", + "CloudChannelReportsServiceAsyncClient", +) diff --git a/google/cloud/channel_v1/services/cloud_channel_reports_service/async_client.py b/google/cloud/channel_v1/services/cloud_channel_reports_service/async_client.py new file mode 100644 index 0000000..e690456 --- /dev/null +++ b/google/cloud/channel_v1/services/cloud_channel_reports_service/async_client.py @@ -0,0 +1,819 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import pkg_resources + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.longrunning import operations_pb2 + +from google.cloud.channel_v1.services.cloud_channel_reports_service import pagers +from google.cloud.channel_v1.types import operations, reports_service + +from .client import CloudChannelReportsServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, CloudChannelReportsServiceTransport +from .transports.grpc_asyncio import CloudChannelReportsServiceGrpcAsyncIOTransport + + +class CloudChannelReportsServiceAsyncClient: + """CloudChannelReportsService lets Google Cloud resellers and + distributors retrieve and combine a variety of data in Cloud + Channel for multiple products (Google Cloud Platform (GCP), + Google Voice, and Google Workspace.) + """ + + _client: CloudChannelReportsServiceClient + + DEFAULT_ENDPOINT = CloudChannelReportsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CloudChannelReportsServiceClient.DEFAULT_MTLS_ENDPOINT + + report_path = staticmethod(CloudChannelReportsServiceClient.report_path) + parse_report_path = staticmethod(CloudChannelReportsServiceClient.parse_report_path) + report_job_path = staticmethod(CloudChannelReportsServiceClient.report_job_path) + parse_report_job_path = staticmethod( + CloudChannelReportsServiceClient.parse_report_job_path + ) + common_billing_account_path = staticmethod( + CloudChannelReportsServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + CloudChannelReportsServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod( + CloudChannelReportsServiceClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + CloudChannelReportsServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + CloudChannelReportsServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + CloudChannelReportsServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod( + CloudChannelReportsServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + CloudChannelReportsServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + CloudChannelReportsServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + CloudChannelReportsServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CloudChannelReportsServiceAsyncClient: The constructed client. + """ + return CloudChannelReportsServiceClient.from_service_account_info.__func__(CloudChannelReportsServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CloudChannelReportsServiceAsyncClient: The constructed client. + """ + return CloudChannelReportsServiceClient.from_service_account_file.__func__(CloudChannelReportsServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return CloudChannelReportsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CloudChannelReportsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CloudChannelReportsServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(CloudChannelReportsServiceClient).get_transport_class, + type(CloudChannelReportsServiceClient), + ) + + def __init__( + self, + *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, CloudChannelReportsServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the cloud channel reports service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CloudChannelReportsServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CloudChannelReportsServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def run_report_job( + self, + request: Union[reports_service.RunReportJobRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Begins generation of data for a given report. The report + identifier is a UID (for example, ``613bf59q``). + + Possible error codes: + + - PERMISSION_DENIED: The user doesn't have access to this + report. + - INVALID_ARGUMENT: Required request parameters are missing or + invalid. + - NOT_FOUND: The report identifier was not found. + - INTERNAL: Any non-user error related to a technical issue in + the backend. Contact Cloud Channel support. + - UNKNOWN: Any non-user error related to a technical issue in + the backend. Contact Cloud Channel support. + + Return value: The ID of a long-running operation. + + To get the results of the operation, call the GetOperation + method of CloudChannelOperationsService. The Operation metadata + contains an instance of + [OperationMetadata][google.cloud.channel.v1.OperationMetadata]. + + To get the results of report generation, call + [CloudChannelReportsService.FetchReportResults][google.cloud.channel.v1.CloudChannelReportsService.FetchReportResults] + with the + [RunReportJobResponse.report_job][google.cloud.channel.v1.RunReportJobResponse.report_job]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import channel_v1 + + async def sample_run_report_job(): + # Create a client + client = channel_v1.CloudChannelReportsServiceAsyncClient() + + # Initialize request argument(s) + request = channel_v1.RunReportJobRequest( + name="name_value", + ) + + # Make the request + operation = client.run_report_job(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.channel_v1.types.RunReportJobRequest, dict]): + The request object. Request message for + [CloudChannelReportsService.RunReportJob][google.cloud.channel.v1.CloudChannelReportsService.RunReportJob]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.channel_v1.types.RunReportJobResponse` + Response message for + [CloudChannelReportsService.RunReportJob][google.cloud.channel.v1.CloudChannelReportsService.RunReportJob]. + + """ + # Create or coerce a protobuf request object. + request = reports_service.RunReportJobRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.run_report_job, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + reports_service.RunReportJobResponse, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def fetch_report_results( + self, + request: Union[reports_service.FetchReportResultsRequest, dict] = None, + *, + report_job: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.FetchReportResultsAsyncPager: + r"""Retrieves data generated by + [CloudChannelReportsService.RunReportJob][google.cloud.channel.v1.CloudChannelReportsService.RunReportJob]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import channel_v1 + + async def sample_fetch_report_results(): + # Create a client + client = channel_v1.CloudChannelReportsServiceAsyncClient() + + # Initialize request argument(s) + request = channel_v1.FetchReportResultsRequest( + report_job="report_job_value", + ) + + # Make the request + page_result = client.fetch_report_results(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.channel_v1.types.FetchReportResultsRequest, dict]): + The request object. Request message for + [CloudChannelReportsService.FetchReportResults][google.cloud.channel.v1.CloudChannelReportsService.FetchReportResults]. + report_job (:class:`str`): + Required. The report job created by + [CloudChannelReportsService.RunReportJob][google.cloud.channel.v1.CloudChannelReportsService.RunReportJob]. + Report_job uses the format: + accounts/{account_id}/reportJobs/{report_job_id} + + This corresponds to the ``report_job`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.channel_v1.services.cloud_channel_reports_service.pagers.FetchReportResultsAsyncPager: + Response message for [CloudChannelReportsService.FetchReportResults][google.cloud.channel.v1.CloudChannelReportsService.FetchReportResults]. + Contains a tabular representation of the report + results. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([report_job]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = reports_service.FetchReportResultsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if report_job is not None: + request.report_job = report_job + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.fetch_report_results, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("report_job", request.report_job),) + ), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.FetchReportResultsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_reports( + self, + request: Union[reports_service.ListReportsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListReportsAsyncPager: + r"""Lists the reports that RunReportJob can run. These + reports include an ID, a description, and the list of + columns that will be in the result. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import channel_v1 + + async def sample_list_reports(): + # Create a client + client = channel_v1.CloudChannelReportsServiceAsyncClient() + + # Initialize request argument(s) + request = channel_v1.ListReportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_reports(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Union[google.cloud.channel_v1.types.ListReportsRequest, dict]): + The request object. Request message for + [CloudChannelReportsService.ListReports][google.cloud.channel.v1.CloudChannelReportsService.ListReports]. + parent (:class:`str`): + Required. The resource name of the partner account to + list available reports for. Parent uses the format: + accounts/{account_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.channel_v1.services.cloud_channel_reports_service.pagers.ListReportsAsyncPager: + Response message for + [CloudChannelReportsService.ListReports][google.cloud.channel.v1.CloudChannelReportsService.ListReports]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = reports_service.ListReportsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_reports, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListReportsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: operations_pb2.ListOperationsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: operations_pb2.GetOperationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: operations_pb2.DeleteOperationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: operations_pb2.CancelOperationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-channel", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("CloudChannelReportsServiceAsyncClient",) diff --git a/google/cloud/channel_v1/services/cloud_channel_reports_service/client.py b/google/cloud/channel_v1/services/cloud_channel_reports_service/client.py new file mode 100644 index 0000000..5325507 --- /dev/null +++ b/google/cloud/channel_v1/services/cloud_channel_reports_service/client.py @@ -0,0 +1,1055 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore +import pkg_resources + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.longrunning import operations_pb2 + +from google.cloud.channel_v1.services.cloud_channel_reports_service import pagers +from google.cloud.channel_v1.types import operations, reports_service + +from .transports.base import DEFAULT_CLIENT_INFO, CloudChannelReportsServiceTransport +from .transports.grpc import CloudChannelReportsServiceGrpcTransport +from .transports.grpc_asyncio import CloudChannelReportsServiceGrpcAsyncIOTransport + + +class CloudChannelReportsServiceClientMeta(type): + """Metaclass for the CloudChannelReportsService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[CloudChannelReportsServiceTransport]] + _transport_registry["grpc"] = CloudChannelReportsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CloudChannelReportsServiceGrpcAsyncIOTransport + + def get_transport_class( + cls, + label: str = None, + ) -> Type[CloudChannelReportsServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class CloudChannelReportsServiceClient(metaclass=CloudChannelReportsServiceClientMeta): + """CloudChannelReportsService lets Google Cloud resellers and + distributors retrieve and combine a variety of data in Cloud + Channel for multiple products (Google Cloud Platform (GCP), + Google Voice, and Google Workspace.) + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudchannel.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CloudChannelReportsServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CloudChannelReportsServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> CloudChannelReportsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CloudChannelReportsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def report_path( + account: str, + report: str, + ) -> str: + """Returns a fully-qualified report string.""" + return "accounts/{account}/reports/{report}".format( + account=account, + report=report, + ) + + @staticmethod + def parse_report_path(path: str) -> Dict[str, str]: + """Parses a report path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/reports/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def report_job_path( + account: str, + report_job: str, + ) -> str: + """Returns a fully-qualified report_job string.""" + return "accounts/{account}/reportJobs/{report_job}".format( + account=account, + report_job=report_job, + ) + + @staticmethod + def parse_report_job_path(path: str) -> Dict[str, str]: + """Parses a report_job path into its component segments.""" + m = re.match( + r"^accounts/(?P.+?)/reportJobs/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CloudChannelReportsServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the cloud channel reports service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CloudChannelReportsServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( + client_options + ) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CloudChannelReportsServiceTransport): + # transport is a CloudChannelReportsServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def run_report_job( + self, + request: Union[reports_service.RunReportJobRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Begins generation of data for a given report. The report + identifier is a UID (for example, ``613bf59q``). + + Possible error codes: + + - PERMISSION_DENIED: The user doesn't have access to this + report. + - INVALID_ARGUMENT: Required request parameters are missing or + invalid. + - NOT_FOUND: The report identifier was not found. + - INTERNAL: Any non-user error related to a technical issue in + the backend. Contact Cloud Channel support. + - UNKNOWN: Any non-user error related to a technical issue in + the backend. Contact Cloud Channel support. + + Return value: The ID of a long-running operation. + + To get the results of the operation, call the GetOperation + method of CloudChannelOperationsService. The Operation metadata + contains an instance of + [OperationMetadata][google.cloud.channel.v1.OperationMetadata]. + + To get the results of report generation, call + [CloudChannelReportsService.FetchReportResults][google.cloud.channel.v1.CloudChannelReportsService.FetchReportResults] + with the + [RunReportJobResponse.report_job][google.cloud.channel.v1.RunReportJobResponse.report_job]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import channel_v1 + + def sample_run_report_job(): + # Create a client + client = channel_v1.CloudChannelReportsServiceClient() + + # Initialize request argument(s) + request = channel_v1.RunReportJobRequest( + name="name_value", + ) + + # Make the request + operation = client.run_report_job(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.channel_v1.types.RunReportJobRequest, dict]): + The request object. Request message for + [CloudChannelReportsService.RunReportJob][google.cloud.channel.v1.CloudChannelReportsService.RunReportJob]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.channel_v1.types.RunReportJobResponse` + Response message for + [CloudChannelReportsService.RunReportJob][google.cloud.channel.v1.CloudChannelReportsService.RunReportJob]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a reports_service.RunReportJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, reports_service.RunReportJobRequest): + request = reports_service.RunReportJobRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.run_report_job] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + reports_service.RunReportJobResponse, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + def fetch_report_results( + self, + request: Union[reports_service.FetchReportResultsRequest, dict] = None, + *, + report_job: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.FetchReportResultsPager: + r"""Retrieves data generated by + [CloudChannelReportsService.RunReportJob][google.cloud.channel.v1.CloudChannelReportsService.RunReportJob]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import channel_v1 + + def sample_fetch_report_results(): + # Create a client + client = channel_v1.CloudChannelReportsServiceClient() + + # Initialize request argument(s) + request = channel_v1.FetchReportResultsRequest( + report_job="report_job_value", + ) + + # Make the request + page_result = client.fetch_report_results(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.channel_v1.types.FetchReportResultsRequest, dict]): + The request object. Request message for + [CloudChannelReportsService.FetchReportResults][google.cloud.channel.v1.CloudChannelReportsService.FetchReportResults]. + report_job (str): + Required. The report job created by + [CloudChannelReportsService.RunReportJob][google.cloud.channel.v1.CloudChannelReportsService.RunReportJob]. + Report_job uses the format: + accounts/{account_id}/reportJobs/{report_job_id} + + This corresponds to the ``report_job`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.channel_v1.services.cloud_channel_reports_service.pagers.FetchReportResultsPager: + Response message for [CloudChannelReportsService.FetchReportResults][google.cloud.channel.v1.CloudChannelReportsService.FetchReportResults]. + Contains a tabular representation of the report + results. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([report_job]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a reports_service.FetchReportResultsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, reports_service.FetchReportResultsRequest): + request = reports_service.FetchReportResultsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if report_job is not None: + request.report_job = report_job + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.fetch_report_results] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("report_job", request.report_job),) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.FetchReportResultsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_reports( + self, + request: Union[reports_service.ListReportsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListReportsPager: + r"""Lists the reports that RunReportJob can run. These + reports include an ID, a description, and the list of + columns that will be in the result. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import channel_v1 + + def sample_list_reports(): + # Create a client + client = channel_v1.CloudChannelReportsServiceClient() + + # Initialize request argument(s) + request = channel_v1.ListReportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_reports(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.channel_v1.types.ListReportsRequest, dict]): + The request object. Request message for + [CloudChannelReportsService.ListReports][google.cloud.channel.v1.CloudChannelReportsService.ListReports]. + parent (str): + Required. The resource name of the partner account to + list available reports for. Parent uses the format: + accounts/{account_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.channel_v1.services.cloud_channel_reports_service.pagers.ListReportsPager: + Response message for + [CloudChannelReportsService.ListReports][google.cloud.channel.v1.CloudChannelReportsService.ListReports]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a reports_service.ListReportsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, reports_service.ListReportsRequest): + request = reports_service.ListReportsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_reports] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListReportsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: operations_pb2.ListOperationsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_operation( + self, + request: operations_pb2.GetOperationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_operation( + self, + request: operations_pb2.DeleteOperationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: operations_pb2.CancelOperationRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-channel", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("CloudChannelReportsServiceClient",) diff --git a/google/cloud/channel_v1/services/cloud_channel_reports_service/pagers.py b/google/cloud/channel_v1/services/cloud_channel_reports_service/pagers.py new file mode 100644 index 0000000..fa8146d --- /dev/null +++ b/google/cloud/channel_v1/services/cloud_channel_reports_service/pagers.py @@ -0,0 +1,283 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, +) + +from google.cloud.channel_v1.types import reports_service + + +class FetchReportResultsPager: + """A pager for iterating through ``fetch_report_results`` requests. + + This class thinly wraps an initial + :class:`google.cloud.channel_v1.types.FetchReportResultsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``rows`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``FetchReportResults`` requests and continue to iterate + through the ``rows`` field on the + corresponding responses. + + All the usual :class:`google.cloud.channel_v1.types.FetchReportResultsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., reports_service.FetchReportResultsResponse], + request: reports_service.FetchReportResultsRequest, + response: reports_service.FetchReportResultsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.channel_v1.types.FetchReportResultsRequest): + The initial request object. + response (google.cloud.channel_v1.types.FetchReportResultsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = reports_service.FetchReportResultsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[reports_service.FetchReportResultsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[reports_service.Row]: + for page in self.pages: + yield from page.rows + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class FetchReportResultsAsyncPager: + """A pager for iterating through ``fetch_report_results`` requests. + + This class thinly wraps an initial + :class:`google.cloud.channel_v1.types.FetchReportResultsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``rows`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``FetchReportResults`` requests and continue to iterate + through the ``rows`` field on the + corresponding responses. + + All the usual :class:`google.cloud.channel_v1.types.FetchReportResultsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[reports_service.FetchReportResultsResponse]], + request: reports_service.FetchReportResultsRequest, + response: reports_service.FetchReportResultsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.channel_v1.types.FetchReportResultsRequest): + The initial request object. + response (google.cloud.channel_v1.types.FetchReportResultsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = reports_service.FetchReportResultsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[reports_service.FetchReportResultsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[reports_service.Row]: + async def async_generator(): + async for page in self.pages: + for response in page.rows: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListReportsPager: + """A pager for iterating through ``list_reports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.channel_v1.types.ListReportsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``reports`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListReports`` requests and continue to iterate + through the ``reports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.channel_v1.types.ListReportsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., reports_service.ListReportsResponse], + request: reports_service.ListReportsRequest, + response: reports_service.ListReportsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.channel_v1.types.ListReportsRequest): + The initial request object. + response (google.cloud.channel_v1.types.ListReportsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = reports_service.ListReportsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[reports_service.ListReportsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[reports_service.Report]: + for page in self.pages: + yield from page.reports + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListReportsAsyncPager: + """A pager for iterating through ``list_reports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.channel_v1.types.ListReportsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``reports`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListReports`` requests and continue to iterate + through the ``reports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.channel_v1.types.ListReportsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[reports_service.ListReportsResponse]], + request: reports_service.ListReportsRequest, + response: reports_service.ListReportsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.channel_v1.types.ListReportsRequest): + The initial request object. + response (google.cloud.channel_v1.types.ListReportsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = reports_service.ListReportsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[reports_service.ListReportsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[reports_service.Report]: + async def async_generator(): + async for page in self.pages: + for response in page.reports: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/channel_v1/services/cloud_channel_reports_service/transports/__init__.py b/google/cloud/channel_v1/services/cloud_channel_reports_service/transports/__init__.py new file mode 100644 index 0000000..18c348e --- /dev/null +++ b/google/cloud/channel_v1/services/cloud_channel_reports_service/transports/__init__.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import CloudChannelReportsServiceTransport +from .grpc import CloudChannelReportsServiceGrpcTransport +from .grpc_asyncio import CloudChannelReportsServiceGrpcAsyncIOTransport + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[CloudChannelReportsServiceTransport]] +_transport_registry["grpc"] = CloudChannelReportsServiceGrpcTransport +_transport_registry["grpc_asyncio"] = CloudChannelReportsServiceGrpcAsyncIOTransport + +__all__ = ( + "CloudChannelReportsServiceTransport", + "CloudChannelReportsServiceGrpcTransport", + "CloudChannelReportsServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/channel_v1/services/cloud_channel_reports_service/transports/base.py b/google/cloud/channel_v1/services/cloud_channel_reports_service/transports/base.py new file mode 100644 index 0000000..9089d44 --- /dev/null +++ b/google/cloud/channel_v1/services/cloud_channel_reports_service/transports/base.py @@ -0,0 +1,233 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore +import pkg_resources + +from google.cloud.channel_v1.types import reports_service + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-channel", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class CloudChannelReportsServiceTransport(abc.ABC): + """Abstract transport class for CloudChannelReportsService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/apps.reports.usage.readonly",) + + DEFAULT_HOST: str = "cloudchannel.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.run_report_job: gapic_v1.method.wrap_method( + self.run_report_job, + default_timeout=None, + client_info=client_info, + ), + self.fetch_report_results: gapic_v1.method.wrap_method( + self.fetch_report_results, + default_timeout=None, + client_info=client_info, + ), + self.list_reports: gapic_v1.method.wrap_method( + self.list_reports, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def run_report_job( + self, + ) -> Callable[ + [reports_service.RunReportJobRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def fetch_report_results( + self, + ) -> Callable[ + [reports_service.FetchReportResultsRequest], + Union[ + reports_service.FetchReportResultsResponse, + Awaitable[reports_service.FetchReportResultsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_reports( + self, + ) -> Callable[ + [reports_service.ListReportsRequest], + Union[ + reports_service.ListReportsResponse, + Awaitable[reports_service.ListReportsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None,]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("CloudChannelReportsServiceTransport",) diff --git a/google/cloud/channel_v1/services/cloud_channel_reports_service/transports/grpc.py b/google/cloud/channel_v1/services/cloud_channel_reports_service/transports/grpc.py new file mode 100644 index 0000000..3e8a73d --- /dev/null +++ b/google/cloud/channel_v1/services/cloud_channel_reports_service/transports/grpc.py @@ -0,0 +1,439 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import grpc # type: ignore + +from google.cloud.channel_v1.types import reports_service + +from .base import DEFAULT_CLIENT_INFO, CloudChannelReportsServiceTransport + + +class CloudChannelReportsServiceGrpcTransport(CloudChannelReportsServiceTransport): + """gRPC backend transport for CloudChannelReportsService. + + CloudChannelReportsService lets Google Cloud resellers and + distributors retrieve and combine a variety of data in Cloud + Channel for multiple products (Google Cloud Platform (GCP), + Google Voice, and Google Workspace.) + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "cloudchannel.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "cloudchannel.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient(self.grpc_channel) + + # Return the client from cache. + return self._operations_client + + @property + def run_report_job( + self, + ) -> Callable[[reports_service.RunReportJobRequest], operations_pb2.Operation]: + r"""Return a callable for the run report job method over gRPC. + + Begins generation of data for a given report. The report + identifier is a UID (for example, ``613bf59q``). + + Possible error codes: + + - PERMISSION_DENIED: The user doesn't have access to this + report. + - INVALID_ARGUMENT: Required request parameters are missing or + invalid. + - NOT_FOUND: The report identifier was not found. + - INTERNAL: Any non-user error related to a technical issue in + the backend. Contact Cloud Channel support. + - UNKNOWN: Any non-user error related to a technical issue in + the backend. Contact Cloud Channel support. + + Return value: The ID of a long-running operation. + + To get the results of the operation, call the GetOperation + method of CloudChannelOperationsService. The Operation metadata + contains an instance of + [OperationMetadata][google.cloud.channel.v1.OperationMetadata]. + + To get the results of report generation, call + [CloudChannelReportsService.FetchReportResults][google.cloud.channel.v1.CloudChannelReportsService.FetchReportResults] + with the + [RunReportJobResponse.report_job][google.cloud.channel.v1.RunReportJobResponse.report_job]. + + Returns: + Callable[[~.RunReportJobRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "run_report_job" not in self._stubs: + self._stubs["run_report_job"] = self.grpc_channel.unary_unary( + "/google.cloud.channel.v1.CloudChannelReportsService/RunReportJob", + request_serializer=reports_service.RunReportJobRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["run_report_job"] + + @property + def fetch_report_results( + self, + ) -> Callable[ + [reports_service.FetchReportResultsRequest], + reports_service.FetchReportResultsResponse, + ]: + r"""Return a callable for the fetch report results method over gRPC. + + Retrieves data generated by + [CloudChannelReportsService.RunReportJob][google.cloud.channel.v1.CloudChannelReportsService.RunReportJob]. + + Returns: + Callable[[~.FetchReportResultsRequest], + ~.FetchReportResultsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "fetch_report_results" not in self._stubs: + self._stubs["fetch_report_results"] = self.grpc_channel.unary_unary( + "/google.cloud.channel.v1.CloudChannelReportsService/FetchReportResults", + request_serializer=reports_service.FetchReportResultsRequest.serialize, + response_deserializer=reports_service.FetchReportResultsResponse.deserialize, + ) + return self._stubs["fetch_report_results"] + + @property + def list_reports( + self, + ) -> Callable[ + [reports_service.ListReportsRequest], reports_service.ListReportsResponse + ]: + r"""Return a callable for the list reports method over gRPC. + + Lists the reports that RunReportJob can run. These + reports include an ID, a description, and the list of + columns that will be in the result. + + Returns: + Callable[[~.ListReportsRequest], + ~.ListReportsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_reports" not in self._stubs: + self._stubs["list_reports"] = self.grpc_channel.unary_unary( + "/google.cloud.channel.v1.CloudChannelReportsService/ListReports", + request_serializer=reports_service.ListReportsRequest.serialize, + response_deserializer=reports_service.ListReportsResponse.deserialize, + ) + return self._stubs["list_reports"] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("CloudChannelReportsServiceGrpcTransport",) diff --git a/google/cloud/channel_v1/services/cloud_channel_reports_service/transports/grpc_asyncio.py b/google/cloud/channel_v1/services/cloud_channel_reports_service/transports/grpc_asyncio.py new file mode 100644 index 0000000..215ea78 --- /dev/null +++ b/google/cloud/channel_v1/services/cloud_channel_reports_service/transports/grpc_asyncio.py @@ -0,0 +1,445 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.channel_v1.types import reports_service + +from .base import DEFAULT_CLIENT_INFO, CloudChannelReportsServiceTransport +from .grpc import CloudChannelReportsServiceGrpcTransport + + +class CloudChannelReportsServiceGrpcAsyncIOTransport( + CloudChannelReportsServiceTransport +): + """gRPC AsyncIO backend transport for CloudChannelReportsService. + + CloudChannelReportsService lets Google Cloud resellers and + distributors retrieve and combine a variety of data in Cloud + Channel for multiple products (Google Cloud Platform (GCP), + Google Voice, and Google Workspace.) + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "cloudchannel.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "cloudchannel.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def run_report_job( + self, + ) -> Callable[ + [reports_service.RunReportJobRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the run report job method over gRPC. + + Begins generation of data for a given report. The report + identifier is a UID (for example, ``613bf59q``). + + Possible error codes: + + - PERMISSION_DENIED: The user doesn't have access to this + report. + - INVALID_ARGUMENT: Required request parameters are missing or + invalid. + - NOT_FOUND: The report identifier was not found. + - INTERNAL: Any non-user error related to a technical issue in + the backend. Contact Cloud Channel support. + - UNKNOWN: Any non-user error related to a technical issue in + the backend. Contact Cloud Channel support. + + Return value: The ID of a long-running operation. + + To get the results of the operation, call the GetOperation + method of CloudChannelOperationsService. The Operation metadata + contains an instance of + [OperationMetadata][google.cloud.channel.v1.OperationMetadata]. + + To get the results of report generation, call + [CloudChannelReportsService.FetchReportResults][google.cloud.channel.v1.CloudChannelReportsService.FetchReportResults] + with the + [RunReportJobResponse.report_job][google.cloud.channel.v1.RunReportJobResponse.report_job]. + + Returns: + Callable[[~.RunReportJobRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "run_report_job" not in self._stubs: + self._stubs["run_report_job"] = self.grpc_channel.unary_unary( + "/google.cloud.channel.v1.CloudChannelReportsService/RunReportJob", + request_serializer=reports_service.RunReportJobRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["run_report_job"] + + @property + def fetch_report_results( + self, + ) -> Callable[ + [reports_service.FetchReportResultsRequest], + Awaitable[reports_service.FetchReportResultsResponse], + ]: + r"""Return a callable for the fetch report results method over gRPC. + + Retrieves data generated by + [CloudChannelReportsService.RunReportJob][google.cloud.channel.v1.CloudChannelReportsService.RunReportJob]. + + Returns: + Callable[[~.FetchReportResultsRequest], + Awaitable[~.FetchReportResultsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "fetch_report_results" not in self._stubs: + self._stubs["fetch_report_results"] = self.grpc_channel.unary_unary( + "/google.cloud.channel.v1.CloudChannelReportsService/FetchReportResults", + request_serializer=reports_service.FetchReportResultsRequest.serialize, + response_deserializer=reports_service.FetchReportResultsResponse.deserialize, + ) + return self._stubs["fetch_report_results"] + + @property + def list_reports( + self, + ) -> Callable[ + [reports_service.ListReportsRequest], + Awaitable[reports_service.ListReportsResponse], + ]: + r"""Return a callable for the list reports method over gRPC. + + Lists the reports that RunReportJob can run. These + reports include an ID, a description, and the list of + columns that will be in the result. + + Returns: + Callable[[~.ListReportsRequest], + Awaitable[~.ListReportsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_reports" not in self._stubs: + self._stubs["list_reports"] = self.grpc_channel.unary_unary( + "/google.cloud.channel.v1.CloudChannelReportsService/ListReports", + request_serializer=reports_service.ListReportsRequest.serialize, + response_deserializer=reports_service.ListReportsResponse.deserialize, + ) + return self._stubs["list_reports"] + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ("CloudChannelReportsServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/channel_v1/services/cloud_channel_service/async_client.py b/google/cloud/channel_v1/services/cloud_channel_service/async_client.py index 9ecfbbb..3a72240 100644 --- a/google/cloud/channel_v1/services/cloud_channel_service/async_client.py +++ b/google/cloud/channel_v1/services/cloud_channel_service/async_client.py @@ -1348,7 +1348,8 @@ async def list_transferable_offers( - The customer doesn't belong to the reseller and has no auth token. - - The supplied auth token is invalid. + - The customer provided incorrect reseller information when + generating auth token. - The reseller account making the request is different from the reseller account in the query. diff --git a/google/cloud/channel_v1/services/cloud_channel_service/client.py b/google/cloud/channel_v1/services/cloud_channel_service/client.py index 9022bc4..ad0a59c 100644 --- a/google/cloud/channel_v1/services/cloud_channel_service/client.py +++ b/google/cloud/channel_v1/services/cloud_channel_service/client.py @@ -1686,7 +1686,8 @@ def list_transferable_offers( - The customer doesn't belong to the reseller and has no auth token. - - The supplied auth token is invalid. + - The customer provided incorrect reseller information when + generating auth token. - The reseller account making the request is different from the reseller account in the query. diff --git a/google/cloud/channel_v1/services/cloud_channel_service/transports/grpc.py b/google/cloud/channel_v1/services/cloud_channel_service/transports/grpc.py index b2f42c7..0f7126f 100644 --- a/google/cloud/channel_v1/services/cloud_channel_service/transports/grpc.py +++ b/google/cloud/channel_v1/services/cloud_channel_service/transports/grpc.py @@ -716,7 +716,8 @@ def list_transferable_offers( - The customer doesn't belong to the reseller and has no auth token. - - The supplied auth token is invalid. + - The customer provided incorrect reseller information when + generating auth token. - The reseller account making the request is different from the reseller account in the query. diff --git a/google/cloud/channel_v1/services/cloud_channel_service/transports/grpc_asyncio.py b/google/cloud/channel_v1/services/cloud_channel_service/transports/grpc_asyncio.py index 1655b69..503aedd 100644 --- a/google/cloud/channel_v1/services/cloud_channel_service/transports/grpc_asyncio.py +++ b/google/cloud/channel_v1/services/cloud_channel_service/transports/grpc_asyncio.py @@ -729,7 +729,8 @@ def list_transferable_offers( - The customer doesn't belong to the reseller and has no auth token. - - The supplied auth token is invalid. + - The customer provided incorrect reseller information when + generating auth token. - The reseller account making the request is different from the reseller account in the query. diff --git a/google/cloud/channel_v1/types/__init__.py b/google/cloud/channel_v1/types/__init__.py index bdaddfc..3dc7529 100644 --- a/google/cloud/channel_v1/types/__init__.py +++ b/google/cloud/channel_v1/types/__init__.py @@ -50,6 +50,22 @@ ) from .operations import OperationMetadata from .products import MarketingInfo, Media, MediaType, Product, Sku +from .reports_service import ( + Column, + DateRange, + FetchReportResultsRequest, + FetchReportResultsResponse, + ListReportsRequest, + ListReportsResponse, + Report, + ReportJob, + ReportResultsMetadata, + ReportStatus, + ReportValue, + Row, + RunReportJobRequest, + RunReportJobResponse, +) from .repricing import ( ChannelPartnerRepricingConfig, CustomerRepricingConfig, @@ -168,6 +184,20 @@ "Product", "Sku", "MediaType", + "Column", + "DateRange", + "FetchReportResultsRequest", + "FetchReportResultsResponse", + "ListReportsRequest", + "ListReportsResponse", + "Report", + "ReportJob", + "ReportResultsMetadata", + "ReportStatus", + "ReportValue", + "Row", + "RunReportJobRequest", + "RunReportJobResponse", "ChannelPartnerRepricingConfig", "CustomerRepricingConfig", "PercentageAdjustment", diff --git a/google/cloud/channel_v1/types/reports_service.py b/google/cloud/channel_v1/types/reports_service.py new file mode 100644 index 0000000..9ecaaa2 --- /dev/null +++ b/google/cloud/channel_v1/types/reports_service.py @@ -0,0 +1,617 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +from google.type import datetime_pb2 # type: ignore +from google.type import decimal_pb2 # type: ignore +from google.type import money_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.channel.v1", + manifest={ + "RunReportJobRequest", + "RunReportJobResponse", + "FetchReportResultsRequest", + "FetchReportResultsResponse", + "ListReportsRequest", + "ListReportsResponse", + "ReportJob", + "ReportResultsMetadata", + "Column", + "DateRange", + "Row", + "ReportValue", + "ReportStatus", + "Report", + }, +) + + +class RunReportJobRequest(proto.Message): + r"""Request message for + [CloudChannelReportsService.RunReportJob][google.cloud.channel.v1.CloudChannelReportsService.RunReportJob]. + + Attributes: + name (str): + Required. The report's resource name. Specifies the account + and report used to generate report data. The report_id + identifier is a UID (for example, ``613bf59q``). Name uses + the format: accounts/{account_id}/reports/{report_id} + date_range (google.cloud.channel_v1.types.DateRange): + Optional. The range of usage or invoice dates + to include in the result. + filter (str): + Optional. A structured string that defines conditions on + dimension columns to restrict the report output. + + Filters support logical operators (AND, OR, NOT) and + conditional operators (=, !=, <, >, <=, and >=) using + ``column_id`` as keys. + + For example: + ``(customer:"accounts/C123abc/customers/S456def" OR customer:"accounts/C123abc/customers/S789ghi") AND invoice_start_date.year >= 2022`` + language_code (str): + Optional. The BCP-47 language code, such as + "en-US". If specified, the response is + localized to the corresponding language code if + the original data sources support it. + Default is "en-US". + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + date_range = proto.Field( + proto.MESSAGE, + number=2, + message="DateRange", + ) + filter = proto.Field( + proto.STRING, + number=3, + ) + language_code = proto.Field( + proto.STRING, + number=4, + ) + + +class RunReportJobResponse(proto.Message): + r"""Response message for + [CloudChannelReportsService.RunReportJob][google.cloud.channel.v1.CloudChannelReportsService.RunReportJob]. + + Attributes: + report_job (google.cloud.channel_v1.types.ReportJob): + Pass ``report_job.name`` to + [FetchReportResultsRequest.report_job][google.cloud.channel.v1.FetchReportResultsRequest.report_job] + to retrieve the report's results. + report_metadata (google.cloud.channel_v1.types.ReportResultsMetadata): + The metadata for the report's results + (display name, columns, row count, and date + range). If you view this before the operation + finishes, you may see incomplete data. + """ + + report_job = proto.Field( + proto.MESSAGE, + number=1, + message="ReportJob", + ) + report_metadata = proto.Field( + proto.MESSAGE, + number=2, + message="ReportResultsMetadata", + ) + + +class FetchReportResultsRequest(proto.Message): + r"""Request message for + [CloudChannelReportsService.FetchReportResults][google.cloud.channel.v1.CloudChannelReportsService.FetchReportResults]. + + Attributes: + report_job (str): + Required. The report job created by + [CloudChannelReportsService.RunReportJob][google.cloud.channel.v1.CloudChannelReportsService.RunReportJob]. + Report_job uses the format: + accounts/{account_id}/reportJobs/{report_job_id} + page_size (int): + Optional. Requested page size of the report. + The server may return fewer results than + requested. If you don't specify a page size, the + server uses a sensible default (may change over + time). + + The maximum value is 30,000; the server will + change larger values to 30,000. + page_token (str): + Optional. A token that specifies a page of results beyond + the first page. Obtained through + [FetchReportResultsResponse.next_page_token][google.cloud.channel.v1.FetchReportResultsResponse.next_page_token] + of the previous + [CloudChannelReportsService.FetchReportResults][google.cloud.channel.v1.CloudChannelReportsService.FetchReportResults] + call. + """ + + report_job = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class FetchReportResultsResponse(proto.Message): + r"""Response message for + [CloudChannelReportsService.FetchReportResults][google.cloud.channel.v1.CloudChannelReportsService.FetchReportResults]. + Contains a tabular representation of the report results. + + Attributes: + report_metadata (google.cloud.channel_v1.types.ReportResultsMetadata): + The metadata for the report results (display + name, columns, row count, and date ranges). + rows (Sequence[google.cloud.channel_v1.types.Row]): + The report's lists of values. Each row follows the settings + and ordering of the columns from ``report_metadata``. + next_page_token (str): + Pass this token to + [FetchReportResultsRequest.page_token][google.cloud.channel.v1.FetchReportResultsRequest.page_token] + to retrieve the next page of results. + """ + + @property + def raw_page(self): + return self + + report_metadata = proto.Field( + proto.MESSAGE, + number=1, + message="ReportResultsMetadata", + ) + rows = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Row", + ) + next_page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListReportsRequest(proto.Message): + r"""Request message for + [CloudChannelReportsService.ListReports][google.cloud.channel.v1.CloudChannelReportsService.ListReports]. + + Attributes: + parent (str): + Required. The resource name of the partner account to list + available reports for. Parent uses the format: + accounts/{account_id} + page_size (int): + Optional. Requested page size of the report. + The server might return fewer results than + requested. If unspecified, returns 20 reports. + The maximum value is 100. + page_token (str): + Optional. A token that specifies a page of results beyond + the first page. Obtained through + [ListReportsResponse.next_page_token][google.cloud.channel.v1.ListReportsResponse.next_page_token] + of the previous + [CloudChannelReportsService.ListReports][google.cloud.channel.v1.CloudChannelReportsService.ListReports] + call. + language_code (str): + Optional. The BCP-47 language code, such as + "en-US". If specified, the response is + localized to the corresponding language code if + the original data sources support it. + Default is "en-US". + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + language_code = proto.Field( + proto.STRING, + number=4, + ) + + +class ListReportsResponse(proto.Message): + r"""Response message for + [CloudChannelReportsService.ListReports][google.cloud.channel.v1.CloudChannelReportsService.ListReports]. + + Attributes: + reports (Sequence[google.cloud.channel_v1.types.Report]): + The reports available to the partner. + next_page_token (str): + Pass this token to + [FetchReportResultsRequest.page_token][google.cloud.channel.v1.FetchReportResultsRequest.page_token] + to retrieve the next page of results. + """ + + @property + def raw_page(self): + return self + + reports = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Report", + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ReportJob(proto.Message): + r"""The result of a [RunReportJob][] operation. Contains the name to use + in + [FetchReportResultsRequest.report_job][google.cloud.channel.v1.FetchReportResultsRequest.report_job] + and the status of the operation. + + Attributes: + name (str): + Required. The resource name of a report job. Name uses the + format: ``accounts/{account_id}/reportJobs/{report_job_id}`` + report_status (google.cloud.channel_v1.types.ReportStatus): + The current status of report generation. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + report_status = proto.Field( + proto.MESSAGE, + number=2, + message="ReportStatus", + ) + + +class ReportResultsMetadata(proto.Message): + r"""The features describing the data. Returned by + [CloudChannelReportsService.RunReportJob][google.cloud.channel.v1.CloudChannelReportsService.RunReportJob] + and + [CloudChannelReportsService.FetchReportResults][google.cloud.channel.v1.CloudChannelReportsService.FetchReportResults]. + + Attributes: + report (google.cloud.channel_v1.types.Report): + Details of the completed report. + row_count (int): + The total number of rows of data in the final + report. + date_range (google.cloud.channel_v1.types.DateRange): + The date range of reported usage. + preceding_date_range (google.cloud.channel_v1.types.DateRange): + The usage dates immediately preceding ``date_range`` with + the same duration. Use this to calculate trending usage and + costs. This is only populated if you request trending data. + + For example, if ``date_range`` is July 1-15, + ``preceding_date_range`` will be June 16-30. + """ + + report = proto.Field( + proto.MESSAGE, + number=1, + message="Report", + ) + row_count = proto.Field( + proto.INT64, + number=2, + ) + date_range = proto.Field( + proto.MESSAGE, + number=3, + message="DateRange", + ) + preceding_date_range = proto.Field( + proto.MESSAGE, + number=4, + message="DateRange", + ) + + +class Column(proto.Message): + r"""The definition of a report column. Specifies the data + properties in the corresponding position of the report rows. + + Attributes: + column_id (str): + The unique name of the column (for example, customer_domain, + channel_partner, customer_cost). You can use column IDs in + [RunReportJobRequest.filter][google.cloud.channel.v1.RunReportJobRequest.filter]. + To see all reports and their columns, call + [CloudChannelReportsService.ListReports][google.cloud.channel.v1.CloudChannelReportsService.ListReports]. + display_name (str): + The column's display name. + data_type (google.cloud.channel_v1.types.Column.DataType): + The type of the values for this column. + """ + + class DataType(proto.Enum): + r"""Available data types for columns. Corresponds to the fields in the + ReportValue ``oneof`` field. + """ + DATA_TYPE_UNSPECIFIED = 0 + STRING = 1 + INT = 2 + DECIMAL = 3 + MONEY = 4 + DATE = 5 + DATE_TIME = 6 + + column_id = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + data_type = proto.Field( + proto.ENUM, + number=3, + enum=DataType, + ) + + +class DateRange(proto.Message): + r"""A representation of usage or invoice date ranges. + + Attributes: + usage_start_date_time (google.type.datetime_pb2.DateTime): + The earliest usage date time (inclusive). + + If you use time groupings (daily, weekly, etc), each group + uses midnight to midnight (Pacific time). The usage start + date is rounded down to include all usage from the specified + date. We recommend that clients pass + ``usage_start_date_time`` in Pacific time. + usage_end_date_time (google.type.datetime_pb2.DateTime): + The latest usage date time (exclusive). + + If you use time groupings (daily, weekly, etc), each group + uses midnight to midnight (Pacific time). The usage end date + is rounded down to include all usage from the specified + date. We recommend that clients pass + ``usage_start_date_time`` in Pacific time. + invoice_start_date (google.type.date_pb2.Date): + The earliest invoice date (inclusive). + If your product uses monthly invoices, and this + value is not the beginning of a month, this will + adjust the date to the first day of the given + month. + invoice_end_date (google.type.date_pb2.Date): + The latest invoice date (exclusive). + If your product uses monthly invoices, and this + value is not the beginning of a month, this will + adjust the date to the first day of the + following month. + """ + + usage_start_date_time = proto.Field( + proto.MESSAGE, + number=1, + message=datetime_pb2.DateTime, + ) + usage_end_date_time = proto.Field( + proto.MESSAGE, + number=2, + message=datetime_pb2.DateTime, + ) + invoice_start_date = proto.Field( + proto.MESSAGE, + number=3, + message=date_pb2.Date, + ) + invoice_end_date = proto.Field( + proto.MESSAGE, + number=4, + message=date_pb2.Date, + ) + + +class Row(proto.Message): + r"""A row of report values. + + Attributes: + values (Sequence[google.cloud.channel_v1.types.ReportValue]): + The list of values in the row. + """ + + values = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ReportValue", + ) + + +class ReportValue(proto.Message): + r"""A single report value. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + string_value (str): + A value of type ``string``. + + This field is a member of `oneof`_ ``value``. + int_value (int): + A value of type ``int``. + + This field is a member of `oneof`_ ``value``. + decimal_value (google.type.decimal_pb2.Decimal): + A value of type ``google.type.Decimal``, representing + non-integer numeric values. + + This field is a member of `oneof`_ ``value``. + money_value (google.type.money_pb2.Money): + A value of type ``google.type.Money`` (currency code, whole + units, decimal units). + + This field is a member of `oneof`_ ``value``. + date_value (google.type.date_pb2.Date): + A value of type ``google.type.Date`` (year, month, day). + + This field is a member of `oneof`_ ``value``. + date_time_value (google.type.datetime_pb2.DateTime): + A value of type ``google.type.DateTime`` (year, month, day, + hour, minute, second, and UTC offset or timezone.) + + This field is a member of `oneof`_ ``value``. + """ + + string_value = proto.Field( + proto.STRING, + number=1, + oneof="value", + ) + int_value = proto.Field( + proto.INT64, + number=2, + oneof="value", + ) + decimal_value = proto.Field( + proto.MESSAGE, + number=3, + oneof="value", + message=decimal_pb2.Decimal, + ) + money_value = proto.Field( + proto.MESSAGE, + number=4, + oneof="value", + message=money_pb2.Money, + ) + date_value = proto.Field( + proto.MESSAGE, + number=5, + oneof="value", + message=date_pb2.Date, + ) + date_time_value = proto.Field( + proto.MESSAGE, + number=6, + oneof="value", + message=datetime_pb2.DateTime, + ) + + +class ReportStatus(proto.Message): + r"""Status of a report generation process. + + Attributes: + state (google.cloud.channel_v1.types.ReportStatus.State): + The current state of the report generation + process. + start_time (google.protobuf.timestamp_pb2.Timestamp): + The report generation's start time. + end_time (google.protobuf.timestamp_pb2.Timestamp): + The report generation's completion time. + """ + + class State(proto.Enum): + r"""Available states of report generation.""" + STATE_UNSPECIFIED = 0 + STARTED = 1 + WRITING = 2 + AVAILABLE = 3 + FAILED = 4 + + state = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + start_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class Report(proto.Message): + r"""The ID and description of a report that was used to generate + report data. For example, "GCP Daily Spend", "Google Workspace + License Activity", etc. + + Attributes: + name (str): + Required. The report's resource name. Specifies the account + and report used to generate report data. The report_id + identifier is a UID (for example, ``613bf59q``). + + Name uses the format: + accounts/{account_id}/reports/{report_id} + display_name (str): + A human-readable name for this report. + columns (Sequence[google.cloud.channel_v1.types.Column]): + The list of columns included in the report. + This defines the schema of the report results. + description (str): + A description of other aspects of the report, + such as the products it supports. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + columns = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="Column", + ) + description = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/channel_v1/types/service.py b/google/cloud/channel_v1/types/service.py index 2230786..fd0bdc0 100644 --- a/google/cloud/channel_v1/types/service.py +++ b/google/cloud/channel_v1/types/service.py @@ -558,11 +558,11 @@ class ListTransferableSkusRequest(proto.Message): [CloudChannelService.ListTransferableSkus][google.cloud.channel.v1.CloudChannelService.ListTransferableSkus] call. Optional. auth_token (str): - The super admin of the resold customer - generates this token to authorize a reseller to - access their Cloud Identity and purchase - entitlements on their behalf. You can omit this - token after authorization. See + Optional. The super admin of the resold + customer generates this token to authorize a + reseller to access their Cloud Identity and + purchase entitlements on their behalf. You can + omit this token after authorization. See https://support.google.com/a/answer/7643790 for more details. language_code (str): @@ -673,10 +673,10 @@ class ListTransferableOffersRequest(proto.Message): sku (str): Required. The SKU to look up Offers for. language_code (str): - The BCP-47 language code. For example, - "en-US". The response will localize in the - corresponding language code, if specified. The - default value is "en-US". + Optional. The BCP-47 language code. For + example, "en-US". The response will localize in + the corresponding language code, if specified. + The default value is "en-US". """ cloud_identity_id = proto.Field( diff --git a/samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_fetch_report_results_async.py b/samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_fetch_report_results_async.py new file mode 100644 index 0000000..c951243 --- /dev/null +++ b/samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_fetch_report_results_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FetchReportResults +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-channel + + +# [START cloudchannel_v1_generated_CloudChannelReportsService_FetchReportResults_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import channel_v1 + + +async def sample_fetch_report_results(): + # Create a client + client = channel_v1.CloudChannelReportsServiceAsyncClient() + + # Initialize request argument(s) + request = channel_v1.FetchReportResultsRequest( + report_job="report_job_value", + ) + + # Make the request + page_result = client.fetch_report_results(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudchannel_v1_generated_CloudChannelReportsService_FetchReportResults_async] diff --git a/samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_fetch_report_results_sync.py b/samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_fetch_report_results_sync.py new file mode 100644 index 0000000..ee3906a --- /dev/null +++ b/samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_fetch_report_results_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FetchReportResults +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-channel + + +# [START cloudchannel_v1_generated_CloudChannelReportsService_FetchReportResults_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import channel_v1 + + +def sample_fetch_report_results(): + # Create a client + client = channel_v1.CloudChannelReportsServiceClient() + + # Initialize request argument(s) + request = channel_v1.FetchReportResultsRequest( + report_job="report_job_value", + ) + + # Make the request + page_result = client.fetch_report_results(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudchannel_v1_generated_CloudChannelReportsService_FetchReportResults_sync] diff --git a/samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_list_reports_async.py b/samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_list_reports_async.py new file mode 100644 index 0000000..6a86357 --- /dev/null +++ b/samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_list_reports_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListReports +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-channel + + +# [START cloudchannel_v1_generated_CloudChannelReportsService_ListReports_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import channel_v1 + + +async def sample_list_reports(): + # Create a client + client = channel_v1.CloudChannelReportsServiceAsyncClient() + + # Initialize request argument(s) + request = channel_v1.ListReportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_reports(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudchannel_v1_generated_CloudChannelReportsService_ListReports_async] diff --git a/samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_list_reports_sync.py b/samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_list_reports_sync.py new file mode 100644 index 0000000..321436e --- /dev/null +++ b/samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_list_reports_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListReports +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-channel + + +# [START cloudchannel_v1_generated_CloudChannelReportsService_ListReports_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import channel_v1 + + +def sample_list_reports(): + # Create a client + client = channel_v1.CloudChannelReportsServiceClient() + + # Initialize request argument(s) + request = channel_v1.ListReportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_reports(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudchannel_v1_generated_CloudChannelReportsService_ListReports_sync] diff --git a/samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_run_report_job_async.py b/samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_run_report_job_async.py new file mode 100644 index 0000000..77e08d0 --- /dev/null +++ b/samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_run_report_job_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RunReportJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-channel + + +# [START cloudchannel_v1_generated_CloudChannelReportsService_RunReportJob_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import channel_v1 + + +async def sample_run_report_job(): + # Create a client + client = channel_v1.CloudChannelReportsServiceAsyncClient() + + # Initialize request argument(s) + request = channel_v1.RunReportJobRequest( + name="name_value", + ) + + # Make the request + operation = client.run_report_job(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END cloudchannel_v1_generated_CloudChannelReportsService_RunReportJob_async] diff --git a/samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_run_report_job_sync.py b/samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_run_report_job_sync.py new file mode 100644 index 0000000..0ccde93 --- /dev/null +++ b/samples/generated_samples/cloudchannel_v1_generated_cloud_channel_reports_service_run_report_job_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RunReportJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-channel + + +# [START cloudchannel_v1_generated_CloudChannelReportsService_RunReportJob_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import channel_v1 + + +def sample_run_report_job(): + # Create a client + client = channel_v1.CloudChannelReportsServiceClient() + + # Initialize request argument(s) + request = channel_v1.RunReportJobRequest( + name="name_value", + ) + + # Make the request + operation = client.run_report_job(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudchannel_v1_generated_CloudChannelReportsService_RunReportJob_sync] diff --git a/samples/generated_samples/snippet_metadata_channel_v1.json b/samples/generated_samples/snippet_metadata_channel_v1.json index 6ed74d0..44fb553 100644 --- a/samples/generated_samples/snippet_metadata_channel_v1.json +++ b/samples/generated_samples/snippet_metadata_channel_v1.json @@ -10,6 +10,481 @@ "name": "google-cloud-channel" }, "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.channel_v1.CloudChannelReportsServiceAsyncClient", + "shortName": "CloudChannelReportsServiceAsyncClient" + }, + "fullName": "google.cloud.channel_v1.CloudChannelReportsServiceAsyncClient.fetch_report_results", + "method": { + "fullName": "google.cloud.channel.v1.CloudChannelReportsService.FetchReportResults", + "service": { + "fullName": "google.cloud.channel.v1.CloudChannelReportsService", + "shortName": "CloudChannelReportsService" + }, + "shortName": "FetchReportResults" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.channel_v1.types.FetchReportResultsRequest" + }, + { + "name": "report_job", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.channel_v1.services.cloud_channel_reports_service.pagers.FetchReportResultsAsyncPager", + "shortName": "fetch_report_results" + }, + "description": "Sample for FetchReportResults", + "file": "cloudchannel_v1_generated_cloud_channel_reports_service_fetch_report_results_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudchannel_v1_generated_CloudChannelReportsService_FetchReportResults_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudchannel_v1_generated_cloud_channel_reports_service_fetch_report_results_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.channel_v1.CloudChannelReportsServiceClient", + "shortName": "CloudChannelReportsServiceClient" + }, + "fullName": "google.cloud.channel_v1.CloudChannelReportsServiceClient.fetch_report_results", + "method": { + "fullName": "google.cloud.channel.v1.CloudChannelReportsService.FetchReportResults", + "service": { + "fullName": "google.cloud.channel.v1.CloudChannelReportsService", + "shortName": "CloudChannelReportsService" + }, + "shortName": "FetchReportResults" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.channel_v1.types.FetchReportResultsRequest" + }, + { + "name": "report_job", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.channel_v1.services.cloud_channel_reports_service.pagers.FetchReportResultsPager", + "shortName": "fetch_report_results" + }, + "description": "Sample for FetchReportResults", + "file": "cloudchannel_v1_generated_cloud_channel_reports_service_fetch_report_results_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudchannel_v1_generated_CloudChannelReportsService_FetchReportResults_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudchannel_v1_generated_cloud_channel_reports_service_fetch_report_results_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.channel_v1.CloudChannelReportsServiceAsyncClient", + "shortName": "CloudChannelReportsServiceAsyncClient" + }, + "fullName": "google.cloud.channel_v1.CloudChannelReportsServiceAsyncClient.list_reports", + "method": { + "fullName": "google.cloud.channel.v1.CloudChannelReportsService.ListReports", + "service": { + "fullName": "google.cloud.channel.v1.CloudChannelReportsService", + "shortName": "CloudChannelReportsService" + }, + "shortName": "ListReports" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.channel_v1.types.ListReportsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.channel_v1.services.cloud_channel_reports_service.pagers.ListReportsAsyncPager", + "shortName": "list_reports" + }, + "description": "Sample for ListReports", + "file": "cloudchannel_v1_generated_cloud_channel_reports_service_list_reports_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudchannel_v1_generated_CloudChannelReportsService_ListReports_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudchannel_v1_generated_cloud_channel_reports_service_list_reports_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.channel_v1.CloudChannelReportsServiceClient", + "shortName": "CloudChannelReportsServiceClient" + }, + "fullName": "google.cloud.channel_v1.CloudChannelReportsServiceClient.list_reports", + "method": { + "fullName": "google.cloud.channel.v1.CloudChannelReportsService.ListReports", + "service": { + "fullName": "google.cloud.channel.v1.CloudChannelReportsService", + "shortName": "CloudChannelReportsService" + }, + "shortName": "ListReports" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.channel_v1.types.ListReportsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.channel_v1.services.cloud_channel_reports_service.pagers.ListReportsPager", + "shortName": "list_reports" + }, + "description": "Sample for ListReports", + "file": "cloudchannel_v1_generated_cloud_channel_reports_service_list_reports_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudchannel_v1_generated_CloudChannelReportsService_ListReports_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudchannel_v1_generated_cloud_channel_reports_service_list_reports_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.channel_v1.CloudChannelReportsServiceAsyncClient", + "shortName": "CloudChannelReportsServiceAsyncClient" + }, + "fullName": "google.cloud.channel_v1.CloudChannelReportsServiceAsyncClient.run_report_job", + "method": { + "fullName": "google.cloud.channel.v1.CloudChannelReportsService.RunReportJob", + "service": { + "fullName": "google.cloud.channel.v1.CloudChannelReportsService", + "shortName": "CloudChannelReportsService" + }, + "shortName": "RunReportJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.channel_v1.types.RunReportJobRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "run_report_job" + }, + "description": "Sample for RunReportJob", + "file": "cloudchannel_v1_generated_cloud_channel_reports_service_run_report_job_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudchannel_v1_generated_CloudChannelReportsService_RunReportJob_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudchannel_v1_generated_cloud_channel_reports_service_run_report_job_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.channel_v1.CloudChannelReportsServiceClient", + "shortName": "CloudChannelReportsServiceClient" + }, + "fullName": "google.cloud.channel_v1.CloudChannelReportsServiceClient.run_report_job", + "method": { + "fullName": "google.cloud.channel.v1.CloudChannelReportsService.RunReportJob", + "service": { + "fullName": "google.cloud.channel.v1.CloudChannelReportsService", + "shortName": "CloudChannelReportsService" + }, + "shortName": "RunReportJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.channel_v1.types.RunReportJobRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "run_report_job" + }, + "description": "Sample for RunReportJob", + "file": "cloudchannel_v1_generated_cloud_channel_reports_service_run_report_job_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudchannel_v1_generated_CloudChannelReportsService_RunReportJob_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudchannel_v1_generated_cloud_channel_reports_service_run_report_job_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/scripts/fixup_channel_v1_keywords.py b/scripts/fixup_channel_v1_keywords.py index 31f5ad4..643b44c 100644 --- a/scripts/fixup_channel_v1_keywords.py +++ b/scripts/fixup_channel_v1_keywords.py @@ -53,6 +53,7 @@ class channelCallTransformer(cst.CSTTransformer): 'delete_channel_partner_repricing_config': ('name', ), 'delete_customer': ('name', ), 'delete_customer_repricing_config': ('name', ), + 'fetch_report_results': ('report_job', 'page_size', 'page_token', ), 'get_channel_partner_link': ('name', 'view', ), 'get_channel_partner_repricing_config': ('name', ), 'get_customer': ('name', ), @@ -68,6 +69,7 @@ class channelCallTransformer(cst.CSTTransformer): 'list_products': ('account', 'page_size', 'page_token', 'language_code', ), 'list_purchasable_offers': ('customer', 'create_entitlement_purchase', 'change_offer_purchase', 'page_size', 'page_token', 'language_code', ), 'list_purchasable_skus': ('customer', 'create_entitlement_purchase', 'change_offer_purchase', 'page_size', 'page_token', 'language_code', ), + 'list_reports': ('parent', 'page_size', 'page_token', 'language_code', ), 'list_skus': ('parent', 'account', 'page_size', 'page_token', 'language_code', ), 'list_subscribers': ('account', 'page_size', 'page_token', ), 'list_transferable_offers': ('parent', 'sku', 'cloud_identity_id', 'customer_name', 'page_size', 'page_token', 'language_code', ), @@ -75,6 +77,7 @@ class channelCallTransformer(cst.CSTTransformer): 'lookup_offer': ('entitlement', ), 'provision_cloud_identity': ('customer', 'cloud_identity_info', 'user', 'validate_only', ), 'register_subscriber': ('account', 'service_account', ), + 'run_report_job': ('name', 'date_range', 'filter', 'language_code', ), 'start_paid_service': ('name', 'request_id', ), 'suspend_entitlement': ('name', 'request_id', ), 'transfer_entitlements': ('parent', 'entitlements', 'auth_token', 'request_id', ), diff --git a/tests/unit/gapic/channel_v1/test_cloud_channel_reports_service.py b/tests/unit/gapic/channel_v1/test_cloud_channel_reports_service.py new file mode 100644 index 0000000..e646e4b --- /dev/null +++ b/tests/unit/gapic/channel_v1/test_cloud_channel_reports_service.py @@ -0,0 +1,3100 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import math + +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import operation_async # type: ignore +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +from google.type import datetime_pb2 # type: ignore +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest + +from google.cloud.channel_v1.services.cloud_channel_reports_service import ( + CloudChannelReportsServiceAsyncClient, + CloudChannelReportsServiceClient, + pagers, + transports, +) +from google.cloud.channel_v1.types import operations, reports_service + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CloudChannelReportsServiceClient._get_default_mtls_endpoint(None) is None + assert ( + CloudChannelReportsServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + CloudChannelReportsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + CloudChannelReportsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + CloudChannelReportsServiceClient._get_default_mtls_endpoint( + sandbox_mtls_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + CloudChannelReportsServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (CloudChannelReportsServiceClient, "grpc"), + (CloudChannelReportsServiceAsyncClient, "grpc_asyncio"), + ], +) +def test_cloud_channel_reports_service_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ("cloudchannel.googleapis.com:443") + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.CloudChannelReportsServiceGrpcTransport, "grpc"), + (transports.CloudChannelReportsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_cloud_channel_reports_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (CloudChannelReportsServiceClient, "grpc"), + (CloudChannelReportsServiceAsyncClient, "grpc_asyncio"), + ], +) +def test_cloud_channel_reports_service_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ("cloudchannel.googleapis.com:443") + + +def test_cloud_channel_reports_service_client_get_transport_class(): + transport = CloudChannelReportsServiceClient.get_transport_class() + available_transports = [ + transports.CloudChannelReportsServiceGrpcTransport, + ] + assert transport in available_transports + + transport = CloudChannelReportsServiceClient.get_transport_class("grpc") + assert transport == transports.CloudChannelReportsServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + CloudChannelReportsServiceClient, + transports.CloudChannelReportsServiceGrpcTransport, + "grpc", + ), + ( + CloudChannelReportsServiceAsyncClient, + transports.CloudChannelReportsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + CloudChannelReportsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CloudChannelReportsServiceClient), +) +@mock.patch.object( + CloudChannelReportsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CloudChannelReportsServiceAsyncClient), +) +def test_cloud_channel_reports_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object( + CloudChannelReportsServiceClient, "get_transport_class" + ) as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object( + CloudChannelReportsServiceClient, "get_transport_class" + ) as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + CloudChannelReportsServiceClient, + transports.CloudChannelReportsServiceGrpcTransport, + "grpc", + "true", + ), + ( + CloudChannelReportsServiceAsyncClient, + transports.CloudChannelReportsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + CloudChannelReportsServiceClient, + transports.CloudChannelReportsServiceGrpcTransport, + "grpc", + "false", + ), + ( + CloudChannelReportsServiceAsyncClient, + transports.CloudChannelReportsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + CloudChannelReportsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CloudChannelReportsServiceClient), +) +@mock.patch.object( + CloudChannelReportsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CloudChannelReportsServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_cloud_channel_reports_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", + [CloudChannelReportsServiceClient, CloudChannelReportsServiceAsyncClient], +) +@mock.patch.object( + CloudChannelReportsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CloudChannelReportsServiceClient), +) +@mock.patch.object( + CloudChannelReportsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CloudChannelReportsServiceAsyncClient), +) +def test_cloud_channel_reports_service_client_get_mtls_endpoint_and_cert_source( + client_class, +): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + CloudChannelReportsServiceClient, + transports.CloudChannelReportsServiceGrpcTransport, + "grpc", + ), + ( + CloudChannelReportsServiceAsyncClient, + transports.CloudChannelReportsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_cloud_channel_reports_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + CloudChannelReportsServiceClient, + transports.CloudChannelReportsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + CloudChannelReportsServiceAsyncClient, + transports.CloudChannelReportsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_cloud_channel_reports_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_cloud_channel_reports_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.channel_v1.services.cloud_channel_reports_service.transports.CloudChannelReportsServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = CloudChannelReportsServiceClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + CloudChannelReportsServiceClient, + transports.CloudChannelReportsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + CloudChannelReportsServiceAsyncClient, + transports.CloudChannelReportsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_cloud_channel_reports_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudchannel.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/apps.reports.usage.readonly", + ), + scopes=None, + default_host="cloudchannel.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + reports_service.RunReportJobRequest, + dict, + ], +) +def test_run_report_job(request_type, transport: str = "grpc"): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_report_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.run_report_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == reports_service.RunReportJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_run_report_job_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_report_job), "__call__") as call: + client.run_report_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reports_service.RunReportJobRequest() + + +@pytest.mark.asyncio +async def test_run_report_job_async( + transport: str = "grpc_asyncio", request_type=reports_service.RunReportJobRequest +): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_report_job), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.run_report_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == reports_service.RunReportJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_run_report_job_async_from_dict(): + await test_run_report_job_async(request_type=dict) + + +def test_run_report_job_field_headers(): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reports_service.RunReportJobRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_report_job), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.run_report_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_run_report_job_field_headers_async(): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reports_service.RunReportJobRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_report_job), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.run_report_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + reports_service.FetchReportResultsRequest, + dict, + ], +) +def test_fetch_report_results(request_type, transport: str = "grpc"): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_report_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = reports_service.FetchReportResultsResponse( + next_page_token="next_page_token_value", + ) + response = client.fetch_report_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == reports_service.FetchReportResultsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchReportResultsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_fetch_report_results_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_report_results), "__call__" + ) as call: + client.fetch_report_results() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reports_service.FetchReportResultsRequest() + + +@pytest.mark.asyncio +async def test_fetch_report_results_async( + transport: str = "grpc_asyncio", + request_type=reports_service.FetchReportResultsRequest, +): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_report_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + reports_service.FetchReportResultsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.fetch_report_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == reports_service.FetchReportResultsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchReportResultsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_fetch_report_results_async_from_dict(): + await test_fetch_report_results_async(request_type=dict) + + +def test_fetch_report_results_field_headers(): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reports_service.FetchReportResultsRequest() + + request.report_job = "report_job_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_report_results), "__call__" + ) as call: + call.return_value = reports_service.FetchReportResultsResponse() + client.fetch_report_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "report_job=report_job_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_fetch_report_results_field_headers_async(): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reports_service.FetchReportResultsRequest() + + request.report_job = "report_job_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_report_results), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + reports_service.FetchReportResultsResponse() + ) + await client.fetch_report_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "report_job=report_job_value", + ) in kw["metadata"] + + +def test_fetch_report_results_flattened(): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_report_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = reports_service.FetchReportResultsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.fetch_report_results( + report_job="report_job_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].report_job + mock_val = "report_job_value" + assert arg == mock_val + + +def test_fetch_report_results_flattened_error(): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_report_results( + reports_service.FetchReportResultsRequest(), + report_job="report_job_value", + ) + + +@pytest.mark.asyncio +async def test_fetch_report_results_flattened_async(): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_report_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = reports_service.FetchReportResultsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + reports_service.FetchReportResultsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.fetch_report_results( + report_job="report_job_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].report_job + mock_val = "report_job_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_fetch_report_results_flattened_error_async(): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.fetch_report_results( + reports_service.FetchReportResultsRequest(), + report_job="report_job_value", + ) + + +def test_fetch_report_results_pager(transport_name: str = "grpc"): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_report_results), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + reports_service.FetchReportResultsResponse( + rows=[ + reports_service.Row(), + reports_service.Row(), + reports_service.Row(), + ], + next_page_token="abc", + ), + reports_service.FetchReportResultsResponse( + rows=[], + next_page_token="def", + ), + reports_service.FetchReportResultsResponse( + rows=[ + reports_service.Row(), + ], + next_page_token="ghi", + ), + reports_service.FetchReportResultsResponse( + rows=[ + reports_service.Row(), + reports_service.Row(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("report_job", ""),)), + ) + pager = client.fetch_report_results(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, reports_service.Row) for i in results) + + +def test_fetch_report_results_pages(transport_name: str = "grpc"): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_report_results), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + reports_service.FetchReportResultsResponse( + rows=[ + reports_service.Row(), + reports_service.Row(), + reports_service.Row(), + ], + next_page_token="abc", + ), + reports_service.FetchReportResultsResponse( + rows=[], + next_page_token="def", + ), + reports_service.FetchReportResultsResponse( + rows=[ + reports_service.Row(), + ], + next_page_token="ghi", + ), + reports_service.FetchReportResultsResponse( + rows=[ + reports_service.Row(), + reports_service.Row(), + ], + ), + RuntimeError, + ) + pages = list(client.fetch_report_results(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_fetch_report_results_async_pager(): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_report_results), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + reports_service.FetchReportResultsResponse( + rows=[ + reports_service.Row(), + reports_service.Row(), + reports_service.Row(), + ], + next_page_token="abc", + ), + reports_service.FetchReportResultsResponse( + rows=[], + next_page_token="def", + ), + reports_service.FetchReportResultsResponse( + rows=[ + reports_service.Row(), + ], + next_page_token="ghi", + ), + reports_service.FetchReportResultsResponse( + rows=[ + reports_service.Row(), + reports_service.Row(), + ], + ), + RuntimeError, + ) + async_pager = await client.fetch_report_results( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, reports_service.Row) for i in responses) + + +@pytest.mark.asyncio +async def test_fetch_report_results_async_pages(): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_report_results), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + reports_service.FetchReportResultsResponse( + rows=[ + reports_service.Row(), + reports_service.Row(), + reports_service.Row(), + ], + next_page_token="abc", + ), + reports_service.FetchReportResultsResponse( + rows=[], + next_page_token="def", + ), + reports_service.FetchReportResultsResponse( + rows=[ + reports_service.Row(), + ], + next_page_token="ghi", + ), + reports_service.FetchReportResultsResponse( + rows=[ + reports_service.Row(), + reports_service.Row(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.fetch_report_results(request={}) + ).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + reports_service.ListReportsRequest, + dict, + ], +) +def test_list_reports(request_type, transport: str = "grpc"): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_reports), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = reports_service.ListReportsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_reports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == reports_service.ListReportsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReportsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_reports_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_reports), "__call__") as call: + client.list_reports() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reports_service.ListReportsRequest() + + +@pytest.mark.asyncio +async def test_list_reports_async( + transport: str = "grpc_asyncio", request_type=reports_service.ListReportsRequest +): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_reports), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + reports_service.ListReportsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_reports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == reports_service.ListReportsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReportsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_reports_async_from_dict(): + await test_list_reports_async(request_type=dict) + + +def test_list_reports_field_headers(): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reports_service.ListReportsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_reports), "__call__") as call: + call.return_value = reports_service.ListReportsResponse() + client.list_reports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_reports_field_headers_async(): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = reports_service.ListReportsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_reports), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + reports_service.ListReportsResponse() + ) + await client.list_reports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_reports_flattened(): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_reports), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = reports_service.ListReportsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_reports( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_reports_flattened_error(): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_reports( + reports_service.ListReportsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_reports_flattened_async(): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_reports), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = reports_service.ListReportsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + reports_service.ListReportsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_reports( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_reports_flattened_error_async(): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_reports( + reports_service.ListReportsRequest(), + parent="parent_value", + ) + + +def test_list_reports_pager(transport_name: str = "grpc"): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_reports), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + reports_service.ListReportsResponse( + reports=[ + reports_service.Report(), + reports_service.Report(), + reports_service.Report(), + ], + next_page_token="abc", + ), + reports_service.ListReportsResponse( + reports=[], + next_page_token="def", + ), + reports_service.ListReportsResponse( + reports=[ + reports_service.Report(), + ], + next_page_token="ghi", + ), + reports_service.ListReportsResponse( + reports=[ + reports_service.Report(), + reports_service.Report(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_reports(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, reports_service.Report) for i in results) + + +def test_list_reports_pages(transport_name: str = "grpc"): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_reports), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + reports_service.ListReportsResponse( + reports=[ + reports_service.Report(), + reports_service.Report(), + reports_service.Report(), + ], + next_page_token="abc", + ), + reports_service.ListReportsResponse( + reports=[], + next_page_token="def", + ), + reports_service.ListReportsResponse( + reports=[ + reports_service.Report(), + ], + next_page_token="ghi", + ), + reports_service.ListReportsResponse( + reports=[ + reports_service.Report(), + reports_service.Report(), + ], + ), + RuntimeError, + ) + pages = list(client.list_reports(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_reports_async_pager(): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_reports), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + reports_service.ListReportsResponse( + reports=[ + reports_service.Report(), + reports_service.Report(), + reports_service.Report(), + ], + next_page_token="abc", + ), + reports_service.ListReportsResponse( + reports=[], + next_page_token="def", + ), + reports_service.ListReportsResponse( + reports=[ + reports_service.Report(), + ], + next_page_token="ghi", + ), + reports_service.ListReportsResponse( + reports=[ + reports_service.Report(), + reports_service.Report(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_reports( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, reports_service.Report) for i in responses) + + +@pytest.mark.asyncio +async def test_list_reports_async_pages(): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_reports), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + reports_service.ListReportsResponse( + reports=[ + reports_service.Report(), + reports_service.Report(), + reports_service.Report(), + ], + next_page_token="abc", + ), + reports_service.ListReportsResponse( + reports=[], + next_page_token="def", + ), + reports_service.ListReportsResponse( + reports=[ + reports_service.Report(), + ], + next_page_token="ghi", + ), + reports_service.ListReportsResponse( + reports=[ + reports_service.Report(), + reports_service.Report(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_reports(request={}) + ).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CloudChannelReportsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CloudChannelReportsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudChannelReportsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CloudChannelReportsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CloudChannelReportsServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CloudChannelReportsServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CloudChannelReportsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudChannelReportsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudChannelReportsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CloudChannelReportsServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudChannelReportsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CloudChannelReportsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudChannelReportsServiceGrpcTransport, + transports.CloudChannelReportsServiceGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + ], +) +def test_transport_kind(transport_name): + transport = CloudChannelReportsServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CloudChannelReportsServiceGrpcTransport, + ) + + +def test_cloud_channel_reports_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CloudChannelReportsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_cloud_channel_reports_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.channel_v1.services.cloud_channel_reports_service.transports.CloudChannelReportsServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.CloudChannelReportsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "run_report_job", + "fetch_report_results", + "list_reports", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_cloud_channel_reports_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.channel_v1.services.cloud_channel_reports_service.transports.CloudChannelReportsServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudChannelReportsServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/apps.reports.usage.readonly", + ), + quota_project_id="octopus", + ) + + +def test_cloud_channel_reports_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.channel_v1.services.cloud_channel_reports_service.transports.CloudChannelReportsServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudChannelReportsServiceTransport() + adc.assert_called_once() + + +def test_cloud_channel_reports_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CloudChannelReportsServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/apps.reports.usage.readonly", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudChannelReportsServiceGrpcTransport, + transports.CloudChannelReportsServiceGrpcAsyncIOTransport, + ], +) +def test_cloud_channel_reports_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/apps.reports.usage.readonly", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudChannelReportsServiceGrpcTransport, + transports.CloudChannelReportsServiceGrpcAsyncIOTransport, + ], +) +def test_cloud_channel_reports_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CloudChannelReportsServiceGrpcTransport, grpc_helpers), + (transports.CloudChannelReportsServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_cloud_channel_reports_service_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudchannel.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/apps.reports.usage.readonly", + ), + scopes=["1", "2"], + default_host="cloudchannel.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudChannelReportsServiceGrpcTransport, + transports.CloudChannelReportsServiceGrpcAsyncIOTransport, + ], +) +def test_cloud_channel_reports_service_grpc_transport_client_cert_source_for_mtls( + transport_class, +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + ], +) +def test_cloud_channel_reports_service_host_no_port(transport_name): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudchannel.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ("cloudchannel.googleapis.com:443") + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + ], +) +def test_cloud_channel_reports_service_host_with_port(transport_name): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudchannel.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ("cloudchannel.googleapis.com:8000") + + +def test_cloud_channel_reports_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudChannelReportsServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_cloud_channel_reports_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudChannelReportsServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudChannelReportsServiceGrpcTransport, + transports.CloudChannelReportsServiceGrpcAsyncIOTransport, + ], +) +def test_cloud_channel_reports_service_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudChannelReportsServiceGrpcTransport, + transports.CloudChannelReportsServiceGrpcAsyncIOTransport, + ], +) +def test_cloud_channel_reports_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_cloud_channel_reports_service_grpc_lro_client(): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_cloud_channel_reports_service_grpc_lro_async_client(): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_report_path(): + account = "squid" + report = "clam" + expected = "accounts/{account}/reports/{report}".format( + account=account, + report=report, + ) + actual = CloudChannelReportsServiceClient.report_path(account, report) + assert expected == actual + + +def test_parse_report_path(): + expected = { + "account": "whelk", + "report": "octopus", + } + path = CloudChannelReportsServiceClient.report_path(**expected) + + # Check that the path construction is reversible. + actual = CloudChannelReportsServiceClient.parse_report_path(path) + assert expected == actual + + +def test_report_job_path(): + account = "oyster" + report_job = "nudibranch" + expected = "accounts/{account}/reportJobs/{report_job}".format( + account=account, + report_job=report_job, + ) + actual = CloudChannelReportsServiceClient.report_job_path(account, report_job) + assert expected == actual + + +def test_parse_report_job_path(): + expected = { + "account": "cuttlefish", + "report_job": "mussel", + } + path = CloudChannelReportsServiceClient.report_job_path(**expected) + + # Check that the path construction is reversible. + actual = CloudChannelReportsServiceClient.parse_report_job_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = CloudChannelReportsServiceClient.common_billing_account_path( + billing_account + ) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = CloudChannelReportsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CloudChannelReportsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = CloudChannelReportsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = CloudChannelReportsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CloudChannelReportsServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = CloudChannelReportsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = CloudChannelReportsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CloudChannelReportsServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format( + project=project, + ) + actual = CloudChannelReportsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = CloudChannelReportsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CloudChannelReportsServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = CloudChannelReportsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = CloudChannelReportsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CloudChannelReportsServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.CloudChannelReportsServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.CloudChannelReportsServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = CloudChannelReportsServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_delete_operation(transport: str = "grpc"): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc"): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_field_headers(): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_delete_operation_from_dict(): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc"): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_list_operations_field_headers(): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_operations_from_dict(): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = CloudChannelReportsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "grpc", + ] + for transport in transports: + client = CloudChannelReportsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + ( + CloudChannelReportsServiceClient, + transports.CloudChannelReportsServiceGrpcTransport, + ), + ( + CloudChannelReportsServiceAsyncClient, + transports.CloudChannelReportsServiceGrpcAsyncIOTransport, + ), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + )