diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 2567653c..0b768450 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:87eee22d276554e4e52863ec9b1cb6a7245815dfae20439712bf644348215a5a + digest: sha256:424d88d5d08ddd955782a4359559dc536e658db1a77416c9a4fff79df9519ad2 diff --git a/.kokoro/samples/lint/common.cfg b/.kokoro/samples/lint/common.cfg index ceb20370..9123caa6 100644 --- a/.kokoro/samples/lint/common.cfg +++ b/.kokoro/samples/lint/common.cfg @@ -31,4 +31,4 @@ gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" # Use the trampoline script to run in docker. -build_file: "python-logging/.kokoro/trampoline.sh" \ No newline at end of file +build_file: "python-logging/.kokoro/trampoline_v2.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.10/common.cfg b/.kokoro/samples/python3.10/common.cfg new file mode 100644 index 00000000..61142a00 --- /dev/null +++ b/.kokoro/samples/python3.10/common.cfg @@ -0,0 +1,40 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Build logs will be here +action { + define_artifacts { + regex: "**/*sponge_log.xml" + } +} + +# Specify which tests to run +env_vars: { + key: "RUN_TESTS_SESSION" + value: "py-3.10" +} + +# Declare build specific Cloud project. +env_vars: { + key: "BUILD_SPECIFIC_GCLOUD_PROJECT" + value: "python-docs-samples-tests-310" +} + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/python-logging/.kokoro/test-samples.sh" +} + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker" +} + +# Download secrets for samples +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "python-logging/.kokoro/trampoline_v2.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.10/continuous.cfg b/.kokoro/samples/python3.10/continuous.cfg new file mode 100644 index 00000000..a1c8d975 --- /dev/null +++ b/.kokoro/samples/python3.10/continuous.cfg @@ -0,0 +1,6 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} \ No newline at end of file diff --git a/.kokoro/samples/python3.10/periodic-head.cfg b/.kokoro/samples/python3.10/periodic-head.cfg new file mode 100644 index 00000000..7e2973e3 --- /dev/null +++ b/.kokoro/samples/python3.10/periodic-head.cfg @@ -0,0 +1,11 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/python-logging/.kokoro/test-samples-against-head.sh" +} diff --git a/.kokoro/samples/python3.10/periodic.cfg b/.kokoro/samples/python3.10/periodic.cfg new file mode 100644 index 00000000..71cd1e59 --- /dev/null +++ b/.kokoro/samples/python3.10/periodic.cfg @@ -0,0 +1,6 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "False" +} diff --git a/.kokoro/samples/python3.10/presubmit.cfg b/.kokoro/samples/python3.10/presubmit.cfg new file mode 100644 index 00000000..a1c8d975 --- /dev/null +++ b/.kokoro/samples/python3.10/presubmit.cfg @@ -0,0 +1,6 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} \ No newline at end of file diff --git a/.kokoro/samples/python3.6/common.cfg b/.kokoro/samples/python3.6/common.cfg index 1bfa98c1..792a4d14 100644 --- a/.kokoro/samples/python3.6/common.cfg +++ b/.kokoro/samples/python3.6/common.cfg @@ -37,4 +37,4 @@ gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" # Use the trampoline script to run in docker. -build_file: "python-logging/.kokoro/trampoline.sh" \ No newline at end of file +build_file: "python-logging/.kokoro/trampoline_v2.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.6/periodic.cfg b/.kokoro/samples/python3.6/periodic.cfg index 50fec964..71cd1e59 100644 --- a/.kokoro/samples/python3.6/periodic.cfg +++ b/.kokoro/samples/python3.6/periodic.cfg @@ -3,4 +3,4 @@ env_vars: { key: "INSTALL_LIBRARY_FROM_SOURCE" value: "False" -} \ No newline at end of file +} diff --git a/.kokoro/samples/python3.7/common.cfg b/.kokoro/samples/python3.7/common.cfg index 0f8e2c95..3ba076fe 100644 --- a/.kokoro/samples/python3.7/common.cfg +++ b/.kokoro/samples/python3.7/common.cfg @@ -37,4 +37,4 @@ gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" # Use the trampoline script to run in docker. -build_file: "python-logging/.kokoro/trampoline.sh" \ No newline at end of file +build_file: "python-logging/.kokoro/trampoline_v2.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.7/periodic.cfg b/.kokoro/samples/python3.7/periodic.cfg index 50fec964..71cd1e59 100644 --- a/.kokoro/samples/python3.7/periodic.cfg +++ b/.kokoro/samples/python3.7/periodic.cfg @@ -3,4 +3,4 @@ env_vars: { key: "INSTALL_LIBRARY_FROM_SOURCE" value: "False" -} \ No newline at end of file +} diff --git a/.kokoro/samples/python3.8/common.cfg b/.kokoro/samples/python3.8/common.cfg index 6c1d661d..14475165 100644 --- a/.kokoro/samples/python3.8/common.cfg +++ b/.kokoro/samples/python3.8/common.cfg @@ -37,4 +37,4 @@ gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" # Use the trampoline script to run in docker. -build_file: "python-logging/.kokoro/trampoline.sh" \ No newline at end of file +build_file: "python-logging/.kokoro/trampoline_v2.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.8/periodic.cfg b/.kokoro/samples/python3.8/periodic.cfg index 50fec964..71cd1e59 100644 --- a/.kokoro/samples/python3.8/periodic.cfg +++ b/.kokoro/samples/python3.8/periodic.cfg @@ -3,4 +3,4 @@ env_vars: { key: "INSTALL_LIBRARY_FROM_SOURCE" value: "False" -} \ No newline at end of file +} diff --git a/.kokoro/samples/python3.9/common.cfg b/.kokoro/samples/python3.9/common.cfg index d4c52134..f6f6943a 100644 --- a/.kokoro/samples/python3.9/common.cfg +++ b/.kokoro/samples/python3.9/common.cfg @@ -37,4 +37,4 @@ gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" # Use the trampoline script to run in docker. -build_file: "python-logging/.kokoro/trampoline.sh" \ No newline at end of file +build_file: "python-logging/.kokoro/trampoline_v2.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.9/periodic.cfg b/.kokoro/samples/python3.9/periodic.cfg index 50fec964..71cd1e59 100644 --- a/.kokoro/samples/python3.9/periodic.cfg +++ b/.kokoro/samples/python3.9/periodic.cfg @@ -3,4 +3,4 @@ env_vars: { key: "INSTALL_LIBRARY_FROM_SOURCE" value: "False" -} \ No newline at end of file +} diff --git a/.kokoro/test-samples-against-head.sh b/.kokoro/test-samples-against-head.sh index 635a5ace..ba3a707b 100755 --- a/.kokoro/test-samples-against-head.sh +++ b/.kokoro/test-samples-against-head.sh @@ -23,6 +23,4 @@ set -eo pipefail # Enables `**` to include files nested inside sub-folders shopt -s globstar -cd github/python-logging - exec .kokoro/test-samples-impl.sh diff --git a/.kokoro/test-samples.sh b/.kokoro/test-samples.sh index 0f5f8d40..11c042d3 100755 --- a/.kokoro/test-samples.sh +++ b/.kokoro/test-samples.sh @@ -24,8 +24,6 @@ set -eo pipefail # Enables `**` to include files nested inside sub-folders shopt -s globstar -cd github/python-logging - # Run periodic samples tests at latest release if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then # preserving the test runner implementation. diff --git a/.trampolinerc b/.trampolinerc index 6f984309..a51abf0b 100644 --- a/.trampolinerc +++ b/.trampolinerc @@ -21,9 +21,22 @@ required_envvars+=() pass_down_envvars+=( "ENVIRONMENT" "RUNTIME" + "NOX_SESSION" + ############### + # Docs builds + ############### "STAGING_BUCKET" "V2_STAGING_BUCKET" - "NOX_SESSION" + ################## + # Samples builds + ################## + "INSTALL_LIBRARY_FROM_SOURCE" + "RUN_TESTS_SESSION" + "BUILD_SPECIFIC_GCLOUD_PROJECT" + # Target directories. + "RUN_TESTS_DIRS" + # The nox session to run. + "RUN_TESTS_SESSION" ) # Prevent unintentional override on the default image. diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 2a720ed4..1839c49a 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.6, 3.7, 3.8 and 3.9 on both UNIX and Windows. + 3.6, 3.7, 3.8, 3.9 and 3.10 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.9 -- -k + $ nox -s unit-3.10 -- -k .. note:: @@ -113,9 +113,9 @@ Coding Style export GOOGLE_CLOUD_TESTING_BRANCH="main" By doing this, you are specifying the location of the most up-to-date - version of ``python-logging``. The the suggested remote name ``upstream`` - should point to the official ``googleapis`` checkout and the - the branch should be the main branch on that remote (``main``). + version of ``python-logging``. The + remote name ``upstream`` should point to the official ``googleapis`` + checkout and the branch should be the default branch on that remote (``main``). - This repository contains configuration for the `pre-commit `__ tool, which automates checking @@ -225,11 +225,13 @@ We support: - `Python 3.7`_ - `Python 3.8`_ - `Python 3.9`_ +- `Python 3.10`_ .. _Python 3.6: https://docs.python.org/3.6/ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ .. _Python 3.9: https://docs.python.org/3.9/ +.. _Python 3.10: https://docs.python.org/3.10/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/docs/conf.py b/docs/conf.py index d6e9cca6..743981d3 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -76,8 +76,8 @@ # The encoding of source files. # source_encoding = 'utf-8-sig' -# The master toctree document. -master_doc = "index" +# The root toctree document. +root_doc = "index" # General information about the project. project = "google-cloud-logging" @@ -280,7 +280,7 @@ # author, documentclass [howto, manual, or own class]). latex_documents = [ ( - master_doc, + root_doc, "google-cloud-logging.tex", "google-cloud-logging Documentation", author, @@ -315,7 +315,7 @@ # (source start file, name, description, authors, manual section). man_pages = [ ( - master_doc, + root_doc, "google-cloud-logging", "google-cloud-logging Documentation", [author], @@ -334,7 +334,7 @@ # dir menu entry, description, category) texinfo_documents = [ ( - master_doc, + root_doc, "google-cloud-logging", "google-cloud-logging Documentation", author, diff --git a/google/cloud/logging_v2/services/config_service_v2/client.py b/google/cloud/logging_v2/services/config_service_v2/client.py index 2ef4f49b..d14827a1 100644 --- a/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/google/cloud/logging_v2/services/config_service_v2/client.py @@ -17,7 +17,7 @@ from distutils import util import os import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore @@ -405,7 +405,7 @@ def __init__( def list_buckets( self, - request: logging_config.ListBucketsRequest = None, + request: Union[logging_config.ListBucketsRequest, dict] = None, *, parent: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -415,7 +415,7 @@ def list_buckets( r"""Lists buckets. Args: - request (google.cloud.logging_v2.types.ListBucketsRequest): + request (Union[google.cloud.logging_v2.types.ListBucketsRequest, dict]): The request object. The parameters to `ListBuckets`. parent (str): Required. The parent resource whose buckets are to be @@ -494,7 +494,7 @@ def list_buckets( def get_bucket( self, - request: logging_config.GetBucketRequest = None, + request: Union[logging_config.GetBucketRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -503,7 +503,7 @@ def get_bucket( r"""Gets a bucket. Args: - request (google.cloud.logging_v2.types.GetBucketRequest): + request (Union[google.cloud.logging_v2.types.GetBucketRequest, dict]): The request object. The parameters to `GetBucket`. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -541,7 +541,7 @@ def get_bucket( def create_bucket( self, - request: logging_config.CreateBucketRequest = None, + request: Union[logging_config.CreateBucketRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -552,7 +552,7 @@ def create_bucket( cannot be changed. Args: - request (google.cloud.logging_v2.types.CreateBucketRequest): + request (Union[google.cloud.logging_v2.types.CreateBucketRequest, dict]): The request object. The parameters to `CreateBucket`. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -590,7 +590,7 @@ def create_bucket( def update_bucket( self, - request: logging_config.UpdateBucketRequest = None, + request: Union[logging_config.UpdateBucketRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -609,7 +609,7 @@ def update_bucket( A buckets region may not be modified after it is created. Args: - request (google.cloud.logging_v2.types.UpdateBucketRequest): + request (Union[google.cloud.logging_v2.types.UpdateBucketRequest, dict]): The request object. The parameters to `UpdateBucket`. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -647,7 +647,7 @@ def update_bucket( def delete_bucket( self, - request: logging_config.DeleteBucketRequest = None, + request: Union[logging_config.DeleteBucketRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -658,7 +658,7 @@ def delete_bucket( the bucket will be permanently deleted. Args: - request (google.cloud.logging_v2.types.DeleteBucketRequest): + request (Union[google.cloud.logging_v2.types.DeleteBucketRequest, dict]): The request object. The parameters to `DeleteBucket`. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -691,7 +691,7 @@ def delete_bucket( def undelete_bucket( self, - request: logging_config.UndeleteBucketRequest = None, + request: Union[logging_config.UndeleteBucketRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -701,7 +701,7 @@ def undelete_bucket( may be undeleted within the grace period of 7 days. Args: - request (google.cloud.logging_v2.types.UndeleteBucketRequest): + request (Union[google.cloud.logging_v2.types.UndeleteBucketRequest, dict]): The request object. The parameters to `UndeleteBucket`. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -734,7 +734,7 @@ def undelete_bucket( def list_views( self, - request: logging_config.ListViewsRequest = None, + request: Union[logging_config.ListViewsRequest, dict] = None, *, parent: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -744,7 +744,7 @@ def list_views( r"""Lists views on a bucket. Args: - request (google.cloud.logging_v2.types.ListViewsRequest): + request (Union[google.cloud.logging_v2.types.ListViewsRequest, dict]): The request object. The parameters to `ListViews`. parent (str): Required. The bucket whose views are to be listed: @@ -815,7 +815,7 @@ def list_views( def get_view( self, - request: logging_config.GetViewRequest = None, + request: Union[logging_config.GetViewRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -824,7 +824,7 @@ def get_view( r"""Gets a view. Args: - request (google.cloud.logging_v2.types.GetViewRequest): + request (Union[google.cloud.logging_v2.types.GetViewRequest, dict]): The request object. The parameters to `GetView`. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -864,7 +864,7 @@ def get_view( def create_view( self, - request: logging_config.CreateViewRequest = None, + request: Union[logging_config.CreateViewRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -874,7 +874,7 @@ def create_view( contain a maximum of 50 views. Args: - request (google.cloud.logging_v2.types.CreateViewRequest): + request (Union[google.cloud.logging_v2.types.CreateViewRequest, dict]): The request object. The parameters to `CreateView`. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -914,7 +914,7 @@ def create_view( def update_view( self, - request: logging_config.UpdateViewRequest = None, + request: Union[logging_config.UpdateViewRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -924,7 +924,7 @@ def update_view( existing view with values from the new view: ``filter``. Args: - request (google.cloud.logging_v2.types.UpdateViewRequest): + request (Union[google.cloud.logging_v2.types.UpdateViewRequest, dict]): The request object. The parameters to `UpdateView`. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -964,7 +964,7 @@ def update_view( def delete_view( self, - request: logging_config.DeleteViewRequest = None, + request: Union[logging_config.DeleteViewRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -973,7 +973,7 @@ def delete_view( r"""Deletes a view from a bucket. Args: - request (google.cloud.logging_v2.types.DeleteViewRequest): + request (Union[google.cloud.logging_v2.types.DeleteViewRequest, dict]): The request object. The parameters to `DeleteView`. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -1006,7 +1006,7 @@ def delete_view( def list_sinks( self, - request: logging_config.ListSinksRequest = None, + request: Union[logging_config.ListSinksRequest, dict] = None, *, parent: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -1016,7 +1016,7 @@ def list_sinks( r"""Lists sinks. Args: - request (google.cloud.logging_v2.types.ListSinksRequest): + request (Union[google.cloud.logging_v2.types.ListSinksRequest, dict]): The request object. The parameters to `ListSinks`. parent (str): Required. The parent resource whose sinks are to be @@ -1091,7 +1091,7 @@ def list_sinks( def get_sink( self, - request: logging_config.GetSinkRequest = None, + request: Union[logging_config.GetSinkRequest, dict] = None, *, sink_name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -1101,7 +1101,7 @@ def get_sink( r"""Gets a sink. Args: - request (google.cloud.logging_v2.types.GetSinkRequest): + request (Union[google.cloud.logging_v2.types.GetSinkRequest, dict]): The request object. The parameters to `GetSink`. sink_name (str): Required. The resource name of the sink: @@ -1178,7 +1178,7 @@ def get_sink( def create_sink( self, - request: logging_config.CreateSinkRequest = None, + request: Union[logging_config.CreateSinkRequest, dict] = None, *, parent: str = None, sink: logging_config.LogSink = None, @@ -1193,7 +1193,7 @@ def create_sink( entries only from the resource owning the sink. Args: - request (google.cloud.logging_v2.types.CreateSinkRequest): + request (Union[google.cloud.logging_v2.types.CreateSinkRequest, dict]): The request object. The parameters to `CreateSink`. parent (str): Required. The resource in which to create the sink: @@ -1278,7 +1278,7 @@ def create_sink( def update_sink( self, - request: logging_config.UpdateSinkRequest = None, + request: Union[logging_config.UpdateSinkRequest, dict] = None, *, sink_name: str = None, sink: logging_config.LogSink = None, @@ -1295,7 +1295,7 @@ def update_sink( the ``unique_writer_identity`` field. Args: - request (google.cloud.logging_v2.types.UpdateSinkRequest): + request (Union[google.cloud.logging_v2.types.UpdateSinkRequest, dict]): The request object. The parameters to `UpdateSink`. sink_name (str): Required. The full resource name of the sink to update, @@ -1404,7 +1404,7 @@ def update_sink( def delete_sink( self, - request: logging_config.DeleteSinkRequest = None, + request: Union[logging_config.DeleteSinkRequest, dict] = None, *, sink_name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -1415,7 +1415,7 @@ def delete_sink( then that service account is also deleted. Args: - request (google.cloud.logging_v2.types.DeleteSinkRequest): + request (Union[google.cloud.logging_v2.types.DeleteSinkRequest, dict]): The request object. The parameters to `DeleteSink`. sink_name (str): Required. The full resource name of the sink to delete, @@ -1479,7 +1479,7 @@ def delete_sink( def list_exclusions( self, - request: logging_config.ListExclusionsRequest = None, + request: Union[logging_config.ListExclusionsRequest, dict] = None, *, parent: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -1489,7 +1489,7 @@ def list_exclusions( r"""Lists all the exclusions in a parent resource. Args: - request (google.cloud.logging_v2.types.ListExclusionsRequest): + request (Union[google.cloud.logging_v2.types.ListExclusionsRequest, dict]): The request object. The parameters to `ListExclusions`. parent (str): Required. The parent resource whose exclusions are to be @@ -1564,7 +1564,7 @@ def list_exclusions( def get_exclusion( self, - request: logging_config.GetExclusionRequest = None, + request: Union[logging_config.GetExclusionRequest, dict] = None, *, name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -1574,7 +1574,7 @@ def get_exclusion( r"""Gets the description of an exclusion. Args: - request (google.cloud.logging_v2.types.GetExclusionRequest): + request (Union[google.cloud.logging_v2.types.GetExclusionRequest, dict]): The request object. The parameters to `GetExclusion`. name (str): Required. The resource name of an existing exclusion: @@ -1652,7 +1652,7 @@ def get_exclusion( def create_exclusion( self, - request: logging_config.CreateExclusionRequest = None, + request: Union[logging_config.CreateExclusionRequest, dict] = None, *, parent: str = None, exclusion: logging_config.LogExclusion = None, @@ -1666,7 +1666,7 @@ def create_exclusion( resource. Args: - request (google.cloud.logging_v2.types.CreateExclusionRequest): + request (Union[google.cloud.logging_v2.types.CreateExclusionRequest, dict]): The request object. The parameters to `CreateExclusion`. parent (str): Required. The parent resource in which to create the @@ -1755,7 +1755,7 @@ def create_exclusion( def update_exclusion( self, - request: logging_config.UpdateExclusionRequest = None, + request: Union[logging_config.UpdateExclusionRequest, dict] = None, *, name: str = None, exclusion: logging_config.LogExclusion = None, @@ -1768,7 +1768,7 @@ def update_exclusion( exclusion. Args: - request (google.cloud.logging_v2.types.UpdateExclusionRequest): + request (Union[google.cloud.logging_v2.types.UpdateExclusionRequest, dict]): The request object. The parameters to `UpdateExclusion`. name (str): Required. The resource name of the exclusion to update: @@ -1872,7 +1872,7 @@ def update_exclusion( def delete_exclusion( self, - request: logging_config.DeleteExclusionRequest = None, + request: Union[logging_config.DeleteExclusionRequest, dict] = None, *, name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -1882,7 +1882,7 @@ def delete_exclusion( r"""Deletes an exclusion. Args: - request (google.cloud.logging_v2.types.DeleteExclusionRequest): + request (Union[google.cloud.logging_v2.types.DeleteExclusionRequest, dict]): The request object. The parameters to `DeleteExclusion`. name (str): Required. The resource name of an existing exclusion to @@ -1945,7 +1945,7 @@ def delete_exclusion( def get_cmek_settings( self, - request: logging_config.GetCmekSettingsRequest = None, + request: Union[logging_config.GetCmekSettingsRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -1962,7 +1962,7 @@ def get_cmek_settings( for more information. Args: - request (google.cloud.logging_v2.types.GetCmekSettingsRequest): + request (Union[google.cloud.logging_v2.types.GetCmekSettingsRequest, dict]): The request object. The parameters to [GetCmekSettings][google.logging.v2.ConfigServiceV2.GetCmekSettings]. See [Enabling CMEK for Logs @@ -2016,7 +2016,7 @@ def get_cmek_settings( def update_cmek_settings( self, - request: logging_config.UpdateCmekSettingsRequest = None, + request: Union[logging_config.UpdateCmekSettingsRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -2039,7 +2039,7 @@ def update_cmek_settings( for more information. Args: - request (google.cloud.logging_v2.types.UpdateCmekSettingsRequest): + request (Union[google.cloud.logging_v2.types.UpdateCmekSettingsRequest, dict]): The request object. The parameters to [UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings]. See [Enabling CMEK for Logs diff --git a/google/cloud/logging_v2/services/config_service_v2/pagers.py b/google/cloud/logging_v2/services/config_service_v2/pagers.py index 6d8e11fb..b0be053e 100644 --- a/google/cloud/logging_v2/services/config_service_v2/pagers.py +++ b/google/cloud/logging_v2/services/config_service_v2/pagers.py @@ -15,13 +15,13 @@ # from typing import ( Any, - AsyncIterable, + AsyncIterator, Awaitable, Callable, - Iterable, Sequence, Tuple, Optional, + Iterator, ) from google.cloud.logging_v2.types import logging_config @@ -74,14 +74,14 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - def pages(self) -> Iterable[logging_config.ListBucketsResponse]: + def pages(self) -> Iterator[logging_config.ListBucketsResponse]: 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) -> Iterable[logging_config.LogBucket]: + def __iter__(self) -> Iterator[logging_config.LogBucket]: for page in self.pages: yield from page.buckets @@ -136,14 +136,14 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - async def pages(self) -> AsyncIterable[logging_config.ListBucketsResponse]: + async def pages(self) -> AsyncIterator[logging_config.ListBucketsResponse]: 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) -> AsyncIterable[logging_config.LogBucket]: + def __aiter__(self) -> AsyncIterator[logging_config.LogBucket]: async def async_generator(): async for page in self.pages: for response in page.buckets: @@ -202,14 +202,14 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - def pages(self) -> Iterable[logging_config.ListViewsResponse]: + def pages(self) -> Iterator[logging_config.ListViewsResponse]: 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) -> Iterable[logging_config.LogView]: + def __iter__(self) -> Iterator[logging_config.LogView]: for page in self.pages: yield from page.views @@ -264,14 +264,14 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - async def pages(self) -> AsyncIterable[logging_config.ListViewsResponse]: + async def pages(self) -> AsyncIterator[logging_config.ListViewsResponse]: 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) -> AsyncIterable[logging_config.LogView]: + def __aiter__(self) -> AsyncIterator[logging_config.LogView]: async def async_generator(): async for page in self.pages: for response in page.views: @@ -330,14 +330,14 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - def pages(self) -> Iterable[logging_config.ListSinksResponse]: + def pages(self) -> Iterator[logging_config.ListSinksResponse]: 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) -> Iterable[logging_config.LogSink]: + def __iter__(self) -> Iterator[logging_config.LogSink]: for page in self.pages: yield from page.sinks @@ -392,14 +392,14 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - async def pages(self) -> AsyncIterable[logging_config.ListSinksResponse]: + async def pages(self) -> AsyncIterator[logging_config.ListSinksResponse]: 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) -> AsyncIterable[logging_config.LogSink]: + def __aiter__(self) -> AsyncIterator[logging_config.LogSink]: async def async_generator(): async for page in self.pages: for response in page.sinks: @@ -458,14 +458,14 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - def pages(self) -> Iterable[logging_config.ListExclusionsResponse]: + def pages(self) -> Iterator[logging_config.ListExclusionsResponse]: 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) -> Iterable[logging_config.LogExclusion]: + def __iter__(self) -> Iterator[logging_config.LogExclusion]: for page in self.pages: yield from page.exclusions @@ -520,14 +520,14 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - async def pages(self) -> AsyncIterable[logging_config.ListExclusionsResponse]: + async def pages(self) -> AsyncIterator[logging_config.ListExclusionsResponse]: 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) -> AsyncIterable[logging_config.LogExclusion]: + def __aiter__(self) -> AsyncIterator[logging_config.LogExclusion]: async def async_generator(): async for page in self.pages: for response in page.exclusions: diff --git a/google/cloud/logging_v2/services/config_service_v2/transports/base.py b/google/cloud/logging_v2/services/config_service_v2/transports/base.py index e191687e..1ffcb227 100644 --- a/google/cloud/logging_v2/services/config_service_v2/transports/base.py +++ b/google/cloud/logging_v2/services/config_service_v2/transports/base.py @@ -121,7 +121,7 @@ def __init__( **scopes_kwargs, quota_project_id=quota_project_id ) - # If the credentials is service account credentials, then always try to use self signed JWT. + # 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) diff --git a/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py b/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py index ccd766fa..7fb2560b 100644 --- a/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py +++ b/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py @@ -81,16 +81,16 @@ def __init__( 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 applicatin default SSL credentials. + ``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 grpc channel. It is ignored if ``channel`` is provided. + 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 mutual TLS channel. It is + 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. diff --git a/google/cloud/logging_v2/services/config_service_v2/transports/grpc_asyncio.py b/google/cloud/logging_v2/services/config_service_v2/transports/grpc_asyncio.py index 3b8139e1..9a844e7c 100644 --- a/google/cloud/logging_v2/services/config_service_v2/transports/grpc_asyncio.py +++ b/google/cloud/logging_v2/services/config_service_v2/transports/grpc_asyncio.py @@ -128,16 +128,16 @@ def __init__( 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 applicatin default SSL credentials. + ``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 grpc channel. It is ignored if ``channel`` is provided. + 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 mutual TLS channel. It is + 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. diff --git a/google/cloud/logging_v2/services/logging_service_v2/client.py b/google/cloud/logging_v2/services/logging_service_v2/client.py index c5dba2d0..73909c7f 100644 --- a/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -17,17 +17,7 @@ from distutils import util import os import re -from typing import ( - Callable, - Dict, - Optional, - Iterable, - Iterator, - Sequence, - Tuple, - Type, - Union, -) +from typing import Dict, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore @@ -359,7 +349,7 @@ def __init__( def delete_log( self, - request: logging.DeleteLogRequest = None, + request: Union[logging.DeleteLogRequest, dict] = None, *, log_name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -373,7 +363,7 @@ def delete_log( with a timestamp before the operation will be deleted. Args: - request (google.cloud.logging_v2.types.DeleteLogRequest): + request (Union[google.cloud.logging_v2.types.DeleteLogRequest, dict]): The request object. The parameters to DeleteLog. log_name (str): Required. The resource name of the log to delete: @@ -438,7 +428,7 @@ def delete_log( def write_log_entries( self, - request: logging.WriteLogEntriesRequest = None, + request: Union[logging.WriteLogEntriesRequest, dict] = None, *, log_name: str = None, resource: monitored_resource_pb2.MonitoredResource = None, @@ -457,7 +447,7 @@ def write_log_entries( organizations, billing accounts or folders) Args: - request (google.cloud.logging_v2.types.WriteLogEntriesRequest): + request (Union[google.cloud.logging_v2.types.WriteLogEntriesRequest, dict]): The request object. The parameters to WriteLogEntries. log_name (str): Optional. A default log resource name that is assigned @@ -596,7 +586,7 @@ def write_log_entries( def list_log_entries( self, - request: logging.ListLogEntriesRequest = None, + request: Union[logging.ListLogEntriesRequest, dict] = None, *, resource_names: Sequence[str] = None, filter: str = None, @@ -611,7 +601,7 @@ def list_log_entries( Logs `__. Args: - request (google.cloud.logging_v2.types.ListLogEntriesRequest): + request (Union[google.cloud.logging_v2.types.ListLogEntriesRequest, dict]): The request object. The parameters to `ListLogEntries`. resource_names (Sequence[str]): Required. Names of one or more parent resources from @@ -720,7 +710,7 @@ def list_log_entries( def list_monitored_resource_descriptors( self, - request: logging.ListMonitoredResourceDescriptorsRequest = None, + request: Union[logging.ListMonitoredResourceDescriptorsRequest, dict] = None, *, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -730,7 +720,7 @@ def list_monitored_resource_descriptors( used by Logging. Args: - request (google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsRequest): + request (Union[google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsRequest, dict]): The request object. The parameters to ListMonitoredResourceDescriptors retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -776,7 +766,7 @@ def list_monitored_resource_descriptors( def list_logs( self, - request: logging.ListLogsRequest = None, + request: Union[logging.ListLogsRequest, dict] = None, *, parent: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -788,7 +778,7 @@ def list_logs( listed. Args: - request (google.cloud.logging_v2.types.ListLogsRequest): + request (Union[google.cloud.logging_v2.types.ListLogsRequest, dict]): The request object. The parameters to ListLogs. parent (str): Required. The resource name that owns the logs: diff --git a/google/cloud/logging_v2/services/logging_service_v2/pagers.py b/google/cloud/logging_v2/services/logging_service_v2/pagers.py index b06007cb..ca4d01fa 100644 --- a/google/cloud/logging_v2/services/logging_service_v2/pagers.py +++ b/google/cloud/logging_v2/services/logging_service_v2/pagers.py @@ -15,13 +15,13 @@ # from typing import ( Any, - AsyncIterable, + AsyncIterator, Awaitable, Callable, - Iterable, Sequence, Tuple, Optional, + Iterator, ) from google.api import monitored_resource_pb2 # type: ignore @@ -76,14 +76,14 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - def pages(self) -> Iterable[logging.ListLogEntriesResponse]: + def pages(self) -> Iterator[logging.ListLogEntriesResponse]: 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) -> Iterable[log_entry.LogEntry]: + def __iter__(self) -> Iterator[log_entry.LogEntry]: for page in self.pages: yield from page.entries @@ -138,14 +138,14 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - async def pages(self) -> AsyncIterable[logging.ListLogEntriesResponse]: + async def pages(self) -> AsyncIterator[logging.ListLogEntriesResponse]: 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) -> AsyncIterable[log_entry.LogEntry]: + def __aiter__(self) -> AsyncIterator[log_entry.LogEntry]: async def async_generator(): async for page in self.pages: for response in page.entries: @@ -204,14 +204,14 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - def pages(self) -> Iterable[logging.ListMonitoredResourceDescriptorsResponse]: + def pages(self) -> Iterator[logging.ListMonitoredResourceDescriptorsResponse]: 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) -> Iterable[monitored_resource_pb2.MonitoredResourceDescriptor]: + def __iter__(self) -> Iterator[monitored_resource_pb2.MonitoredResourceDescriptor]: for page in self.pages: yield from page.resource_descriptors @@ -270,7 +270,7 @@ def __getattr__(self, name: str) -> Any: @property async def pages( self, - ) -> AsyncIterable[logging.ListMonitoredResourceDescriptorsResponse]: + ) -> AsyncIterator[logging.ListMonitoredResourceDescriptorsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token @@ -279,7 +279,7 @@ async def pages( def __aiter__( self, - ) -> AsyncIterable[monitored_resource_pb2.MonitoredResourceDescriptor]: + ) -> AsyncIterator[monitored_resource_pb2.MonitoredResourceDescriptor]: async def async_generator(): async for page in self.pages: for response in page.resource_descriptors: @@ -338,14 +338,14 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - def pages(self) -> Iterable[logging.ListLogsResponse]: + def pages(self) -> Iterator[logging.ListLogsResponse]: 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) -> Iterable[str]: + def __iter__(self) -> Iterator[str]: for page in self.pages: yield from page.log_names @@ -400,14 +400,14 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - async def pages(self) -> AsyncIterable[logging.ListLogsResponse]: + async def pages(self) -> AsyncIterator[logging.ListLogsResponse]: 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) -> AsyncIterable[str]: + def __aiter__(self) -> AsyncIterator[str]: async def async_generator(): async for page in self.pages: for response in page.log_names: diff --git a/google/cloud/logging_v2/services/logging_service_v2/transports/base.py b/google/cloud/logging_v2/services/logging_service_v2/transports/base.py index fb5e3c8b..05c273d6 100644 --- a/google/cloud/logging_v2/services/logging_service_v2/transports/base.py +++ b/google/cloud/logging_v2/services/logging_service_v2/transports/base.py @@ -122,7 +122,7 @@ def __init__( **scopes_kwargs, quota_project_id=quota_project_id ) - # If the credentials is service account credentials, then always try to use self signed JWT. + # 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) diff --git a/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py b/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py index fddf0398..a1031e93 100644 --- a/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py +++ b/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py @@ -81,16 +81,16 @@ def __init__( 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 applicatin default SSL credentials. + ``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 grpc channel. It is ignored if ``channel`` is provided. + 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 mutual TLS channel. It is + 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. diff --git a/google/cloud/logging_v2/services/logging_service_v2/transports/grpc_asyncio.py b/google/cloud/logging_v2/services/logging_service_v2/transports/grpc_asyncio.py index 3e158cd6..a71fb28f 100644 --- a/google/cloud/logging_v2/services/logging_service_v2/transports/grpc_asyncio.py +++ b/google/cloud/logging_v2/services/logging_service_v2/transports/grpc_asyncio.py @@ -128,16 +128,16 @@ def __init__( 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 applicatin default SSL credentials. + ``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 grpc channel. It is ignored if ``channel`` is provided. + 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 mutual TLS channel. It is + 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. diff --git a/google/cloud/logging_v2/services/metrics_service_v2/client.py b/google/cloud/logging_v2/services/metrics_service_v2/client.py index 9749b5ef..7d1e2a21 100644 --- a/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -17,7 +17,7 @@ from distutils import util import os import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore @@ -352,7 +352,7 @@ def __init__( def list_log_metrics( self, - request: logging_metrics.ListLogMetricsRequest = None, + request: Union[logging_metrics.ListLogMetricsRequest, dict] = None, *, parent: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -362,7 +362,7 @@ def list_log_metrics( r"""Lists logs-based metrics. Args: - request (google.cloud.logging_v2.types.ListLogMetricsRequest): + request (Union[google.cloud.logging_v2.types.ListLogMetricsRequest, dict]): The request object. The parameters to ListLogMetrics. parent (str): Required. The name of the project containing the @@ -434,7 +434,7 @@ def list_log_metrics( def get_log_metric( self, - request: logging_metrics.GetLogMetricRequest = None, + request: Union[logging_metrics.GetLogMetricRequest, dict] = None, *, metric_name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -444,7 +444,7 @@ def get_log_metric( r"""Gets a logs-based metric. Args: - request (google.cloud.logging_v2.types.GetLogMetricRequest): + request (Union[google.cloud.logging_v2.types.GetLogMetricRequest, dict]): The request object. The parameters to GetLogMetric. metric_name (str): Required. The resource name of the desired metric: @@ -518,7 +518,7 @@ def get_log_metric( def create_log_metric( self, - request: logging_metrics.CreateLogMetricRequest = None, + request: Union[logging_metrics.CreateLogMetricRequest, dict] = None, *, parent: str = None, metric: logging_metrics.LogMetric = None, @@ -529,7 +529,7 @@ def create_log_metric( r"""Creates a logs-based metric. Args: - request (google.cloud.logging_v2.types.CreateLogMetricRequest): + request (Union[google.cloud.logging_v2.types.CreateLogMetricRequest, dict]): The request object. The parameters to CreateLogMetric. parent (str): Required. The resource name of the project in which to @@ -614,7 +614,7 @@ def create_log_metric( def update_log_metric( self, - request: logging_metrics.UpdateLogMetricRequest = None, + request: Union[logging_metrics.UpdateLogMetricRequest, dict] = None, *, metric_name: str = None, metric: logging_metrics.LogMetric = None, @@ -625,7 +625,7 @@ def update_log_metric( r"""Creates or updates a logs-based metric. Args: - request (google.cloud.logging_v2.types.UpdateLogMetricRequest): + request (Union[google.cloud.logging_v2.types.UpdateLogMetricRequest, dict]): The request object. The parameters to UpdateLogMetric. metric_name (str): Required. The resource name of the metric to update: @@ -711,7 +711,7 @@ def update_log_metric( def delete_log_metric( self, - request: logging_metrics.DeleteLogMetricRequest = None, + request: Union[logging_metrics.DeleteLogMetricRequest, dict] = None, *, metric_name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, @@ -721,7 +721,7 @@ def delete_log_metric( r"""Deletes a logs-based metric. Args: - request (google.cloud.logging_v2.types.DeleteLogMetricRequest): + request (Union[google.cloud.logging_v2.types.DeleteLogMetricRequest, dict]): The request object. The parameters to DeleteLogMetric. metric_name (str): Required. The resource name of the metric to delete: diff --git a/google/cloud/logging_v2/services/metrics_service_v2/pagers.py b/google/cloud/logging_v2/services/metrics_service_v2/pagers.py index 8ff178d2..7026e385 100644 --- a/google/cloud/logging_v2/services/metrics_service_v2/pagers.py +++ b/google/cloud/logging_v2/services/metrics_service_v2/pagers.py @@ -15,13 +15,13 @@ # from typing import ( Any, - AsyncIterable, + AsyncIterator, Awaitable, Callable, - Iterable, Sequence, Tuple, Optional, + Iterator, ) from google.cloud.logging_v2.types import logging_metrics @@ -74,14 +74,14 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - def pages(self) -> Iterable[logging_metrics.ListLogMetricsResponse]: + def pages(self) -> Iterator[logging_metrics.ListLogMetricsResponse]: 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) -> Iterable[logging_metrics.LogMetric]: + def __iter__(self) -> Iterator[logging_metrics.LogMetric]: for page in self.pages: yield from page.metrics @@ -136,14 +136,14 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - async def pages(self) -> AsyncIterable[logging_metrics.ListLogMetricsResponse]: + async def pages(self) -> AsyncIterator[logging_metrics.ListLogMetricsResponse]: 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) -> AsyncIterable[logging_metrics.LogMetric]: + def __aiter__(self) -> AsyncIterator[logging_metrics.LogMetric]: async def async_generator(): async for page in self.pages: for response in page.metrics: diff --git a/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py b/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py index f62eb004..1ce8b3a6 100644 --- a/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py +++ b/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py @@ -122,7 +122,7 @@ def __init__( **scopes_kwargs, quota_project_id=quota_project_id ) - # If the credentials is service account credentials, then always try to use self signed JWT. + # 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) diff --git a/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py b/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py index 6a7a2c6a..49e7263d 100644 --- a/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py +++ b/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py @@ -81,16 +81,16 @@ def __init__( 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 applicatin default SSL credentials. + ``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 grpc channel. It is ignored if ``channel`` is provided. + 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 mutual TLS channel. It is + 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. diff --git a/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc_asyncio.py b/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc_asyncio.py index d2d9b618..9ddc1975 100644 --- a/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc_asyncio.py +++ b/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc_asyncio.py @@ -128,16 +128,16 @@ def __init__( 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 applicatin default SSL credentials. + ``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 grpc channel. It is ignored if ``channel`` is provided. + 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 mutual TLS channel. It is + 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. diff --git a/noxfile.py b/noxfile.py index 9e49bd0d..63e5d4aa 100644 --- a/noxfile.py +++ b/noxfile.py @@ -29,7 +29,7 @@ DEFAULT_PYTHON_VERSION = "3.8" SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] -UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] +UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8", "3.9", "3.10"] CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() @@ -84,18 +84,18 @@ def default(session): constraints_path = str( CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" ) - session.install("asyncmock", "pytest-asyncio", "-c", constraints_path) - session.install( "mock", + "asyncmock", "pytest", "pytest-cov", - "flask", - "webob", - "django", + "pytest-asyncio", "-c", constraints_path, ) + session.install("flask", "-c", constraints_path) + session.install("webob", "-c", constraints_path) + session.install("django", "-c", constraints_path) session.install("-e", ".", "-c", constraints_path) diff --git a/owl-bot-staging/v2/.coveragerc b/owl-bot-staging/v2/.coveragerc deleted file mode 100644 index b38d22e2..00000000 --- a/owl-bot-staging/v2/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/logging/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v2/MANIFEST.in b/owl-bot-staging/v2/MANIFEST.in deleted file mode 100644 index f8c276f2..00000000 --- a/owl-bot-staging/v2/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/logging *.py -recursive-include google/cloud/logging_v2 *.py diff --git a/owl-bot-staging/v2/README.rst b/owl-bot-staging/v2/README.rst deleted file mode 100644 index 56aa7d0a..00000000 --- a/owl-bot-staging/v2/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Logging API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Logging API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v2/docs/conf.py b/owl-bot-staging/v2/docs/conf.py deleted file mode 100644 index eb678377..00000000 --- a/owl-bot-staging/v2/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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. -# -# -# google-cloud-logging documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-logging" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-logging-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - master_doc, - "google-cloud-logging.tex", - u"google-cloud-logging Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - master_doc, - "google-cloud-logging", - u"Google Cloud Logging Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - master_doc, - "google-cloud-logging", - u"google-cloud-logging Documentation", - author, - "google-cloud-logging", - "GAPIC library for Google Cloud Logging API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v2/docs/index.rst b/owl-bot-staging/v2/docs/index.rst deleted file mode 100644 index 6a485964..00000000 --- a/owl-bot-staging/v2/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - logging_v2/services - logging_v2/types diff --git a/owl-bot-staging/v2/docs/logging_v2/config_service_v2.rst b/owl-bot-staging/v2/docs/logging_v2/config_service_v2.rst deleted file mode 100644 index f7c0a770..00000000 --- a/owl-bot-staging/v2/docs/logging_v2/config_service_v2.rst +++ /dev/null @@ -1,10 +0,0 @@ -ConfigServiceV2 ---------------------------------- - -.. automodule:: google.cloud.logging_v2.services.config_service_v2 - :members: - :inherited-members: - -.. automodule:: google.cloud.logging_v2.services.config_service_v2.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/logging_v2/logging_service_v2.rst b/owl-bot-staging/v2/docs/logging_v2/logging_service_v2.rst deleted file mode 100644 index f41c0c89..00000000 --- a/owl-bot-staging/v2/docs/logging_v2/logging_service_v2.rst +++ /dev/null @@ -1,10 +0,0 @@ -LoggingServiceV2 ----------------------------------- - -.. automodule:: google.cloud.logging_v2.services.logging_service_v2 - :members: - :inherited-members: - -.. automodule:: google.cloud.logging_v2.services.logging_service_v2.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/logging_v2/metrics_service_v2.rst b/owl-bot-staging/v2/docs/logging_v2/metrics_service_v2.rst deleted file mode 100644 index fd4d9bc7..00000000 --- a/owl-bot-staging/v2/docs/logging_v2/metrics_service_v2.rst +++ /dev/null @@ -1,10 +0,0 @@ -MetricsServiceV2 ----------------------------------- - -.. automodule:: google.cloud.logging_v2.services.metrics_service_v2 - :members: - :inherited-members: - -.. automodule:: google.cloud.logging_v2.services.metrics_service_v2.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v2/docs/logging_v2/services.rst b/owl-bot-staging/v2/docs/logging_v2/services.rst deleted file mode 100644 index d7a0471b..00000000 --- a/owl-bot-staging/v2/docs/logging_v2/services.rst +++ /dev/null @@ -1,8 +0,0 @@ -Services for Google Cloud Logging v2 API -======================================== -.. toctree:: - :maxdepth: 2 - - config_service_v2 - logging_service_v2 - metrics_service_v2 diff --git a/owl-bot-staging/v2/docs/logging_v2/types.rst b/owl-bot-staging/v2/docs/logging_v2/types.rst deleted file mode 100644 index 843c0dc3..00000000 --- a/owl-bot-staging/v2/docs/logging_v2/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Logging v2 API -===================================== - -.. automodule:: google.cloud.logging_v2.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v2/google/cloud/logging/__init__.py b/owl-bot-staging/v2/google/cloud/logging/__init__.py deleted file mode 100644 index 16e3d0cc..00000000 --- a/owl-bot-staging/v2/google/cloud/logging/__init__.py +++ /dev/null @@ -1,143 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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.cloud.logging_v2.services.config_service_v2.client import ConfigServiceV2Client -from google.cloud.logging_v2.services.config_service_v2.async_client import ConfigServiceV2AsyncClient -from google.cloud.logging_v2.services.logging_service_v2.client import LoggingServiceV2Client -from google.cloud.logging_v2.services.logging_service_v2.async_client import LoggingServiceV2AsyncClient -from google.cloud.logging_v2.services.metrics_service_v2.client import MetricsServiceV2Client -from google.cloud.logging_v2.services.metrics_service_v2.async_client import MetricsServiceV2AsyncClient - -from google.cloud.logging_v2.types.log_entry import LogEntry -from google.cloud.logging_v2.types.log_entry import LogEntryOperation -from google.cloud.logging_v2.types.log_entry import LogEntrySourceLocation -from google.cloud.logging_v2.types.logging import DeleteLogRequest -from google.cloud.logging_v2.types.logging import ListLogEntriesRequest -from google.cloud.logging_v2.types.logging import ListLogEntriesResponse -from google.cloud.logging_v2.types.logging import ListLogsRequest -from google.cloud.logging_v2.types.logging import ListLogsResponse -from google.cloud.logging_v2.types.logging import ListMonitoredResourceDescriptorsRequest -from google.cloud.logging_v2.types.logging import ListMonitoredResourceDescriptorsResponse -from google.cloud.logging_v2.types.logging import TailLogEntriesRequest -from google.cloud.logging_v2.types.logging import TailLogEntriesResponse -from google.cloud.logging_v2.types.logging import WriteLogEntriesPartialErrors -from google.cloud.logging_v2.types.logging import WriteLogEntriesRequest -from google.cloud.logging_v2.types.logging import WriteLogEntriesResponse -from google.cloud.logging_v2.types.logging_config import BigQueryOptions -from google.cloud.logging_v2.types.logging_config import CmekSettings -from google.cloud.logging_v2.types.logging_config import CreateBucketRequest -from google.cloud.logging_v2.types.logging_config import CreateExclusionRequest -from google.cloud.logging_v2.types.logging_config import CreateSinkRequest -from google.cloud.logging_v2.types.logging_config import CreateViewRequest -from google.cloud.logging_v2.types.logging_config import DeleteBucketRequest -from google.cloud.logging_v2.types.logging_config import DeleteExclusionRequest -from google.cloud.logging_v2.types.logging_config import DeleteSinkRequest -from google.cloud.logging_v2.types.logging_config import DeleteViewRequest -from google.cloud.logging_v2.types.logging_config import GetBucketRequest -from google.cloud.logging_v2.types.logging_config import GetCmekSettingsRequest -from google.cloud.logging_v2.types.logging_config import GetExclusionRequest -from google.cloud.logging_v2.types.logging_config import GetSinkRequest -from google.cloud.logging_v2.types.logging_config import GetViewRequest -from google.cloud.logging_v2.types.logging_config import ListBucketsRequest -from google.cloud.logging_v2.types.logging_config import ListBucketsResponse -from google.cloud.logging_v2.types.logging_config import ListExclusionsRequest -from google.cloud.logging_v2.types.logging_config import ListExclusionsResponse -from google.cloud.logging_v2.types.logging_config import ListSinksRequest -from google.cloud.logging_v2.types.logging_config import ListSinksResponse -from google.cloud.logging_v2.types.logging_config import ListViewsRequest -from google.cloud.logging_v2.types.logging_config import ListViewsResponse -from google.cloud.logging_v2.types.logging_config import LogBucket -from google.cloud.logging_v2.types.logging_config import LogExclusion -from google.cloud.logging_v2.types.logging_config import LogSink -from google.cloud.logging_v2.types.logging_config import LogView -from google.cloud.logging_v2.types.logging_config import UndeleteBucketRequest -from google.cloud.logging_v2.types.logging_config import UpdateBucketRequest -from google.cloud.logging_v2.types.logging_config import UpdateCmekSettingsRequest -from google.cloud.logging_v2.types.logging_config import UpdateExclusionRequest -from google.cloud.logging_v2.types.logging_config import UpdateSinkRequest -from google.cloud.logging_v2.types.logging_config import UpdateViewRequest -from google.cloud.logging_v2.types.logging_config import LifecycleState -from google.cloud.logging_v2.types.logging_metrics import CreateLogMetricRequest -from google.cloud.logging_v2.types.logging_metrics import DeleteLogMetricRequest -from google.cloud.logging_v2.types.logging_metrics import GetLogMetricRequest -from google.cloud.logging_v2.types.logging_metrics import ListLogMetricsRequest -from google.cloud.logging_v2.types.logging_metrics import ListLogMetricsResponse -from google.cloud.logging_v2.types.logging_metrics import LogMetric -from google.cloud.logging_v2.types.logging_metrics import UpdateLogMetricRequest - -__all__ = ('ConfigServiceV2Client', - 'ConfigServiceV2AsyncClient', - 'LoggingServiceV2Client', - 'LoggingServiceV2AsyncClient', - 'MetricsServiceV2Client', - 'MetricsServiceV2AsyncClient', - 'LogEntry', - 'LogEntryOperation', - 'LogEntrySourceLocation', - 'DeleteLogRequest', - 'ListLogEntriesRequest', - 'ListLogEntriesResponse', - 'ListLogsRequest', - 'ListLogsResponse', - 'ListMonitoredResourceDescriptorsRequest', - 'ListMonitoredResourceDescriptorsResponse', - 'TailLogEntriesRequest', - 'TailLogEntriesResponse', - 'WriteLogEntriesPartialErrors', - 'WriteLogEntriesRequest', - 'WriteLogEntriesResponse', - 'BigQueryOptions', - 'CmekSettings', - 'CreateBucketRequest', - 'CreateExclusionRequest', - 'CreateSinkRequest', - 'CreateViewRequest', - 'DeleteBucketRequest', - 'DeleteExclusionRequest', - 'DeleteSinkRequest', - 'DeleteViewRequest', - 'GetBucketRequest', - 'GetCmekSettingsRequest', - 'GetExclusionRequest', - 'GetSinkRequest', - 'GetViewRequest', - 'ListBucketsRequest', - 'ListBucketsResponse', - 'ListExclusionsRequest', - 'ListExclusionsResponse', - 'ListSinksRequest', - 'ListSinksResponse', - 'ListViewsRequest', - 'ListViewsResponse', - 'LogBucket', - 'LogExclusion', - 'LogSink', - 'LogView', - 'UndeleteBucketRequest', - 'UpdateBucketRequest', - 'UpdateCmekSettingsRequest', - 'UpdateExclusionRequest', - 'UpdateSinkRequest', - 'UpdateViewRequest', - 'LifecycleState', - 'CreateLogMetricRequest', - 'DeleteLogMetricRequest', - 'GetLogMetricRequest', - 'ListLogMetricsRequest', - 'ListLogMetricsResponse', - 'LogMetric', - 'UpdateLogMetricRequest', -) diff --git a/owl-bot-staging/v2/google/cloud/logging/py.typed b/owl-bot-staging/v2/google/cloud/logging/py.typed deleted file mode 100644 index 6c7420d0..00000000 --- a/owl-bot-staging/v2/google/cloud/logging/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-logging package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/__init__.py b/owl-bot-staging/v2/google/cloud/logging_v2/__init__.py deleted file mode 100644 index 1dc1e1ea..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/__init__.py +++ /dev/null @@ -1,144 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 .services.config_service_v2 import ConfigServiceV2Client -from .services.config_service_v2 import ConfigServiceV2AsyncClient -from .services.logging_service_v2 import LoggingServiceV2Client -from .services.logging_service_v2 import LoggingServiceV2AsyncClient -from .services.metrics_service_v2 import MetricsServiceV2Client -from .services.metrics_service_v2 import MetricsServiceV2AsyncClient - -from .types.log_entry import LogEntry -from .types.log_entry import LogEntryOperation -from .types.log_entry import LogEntrySourceLocation -from .types.logging import DeleteLogRequest -from .types.logging import ListLogEntriesRequest -from .types.logging import ListLogEntriesResponse -from .types.logging import ListLogsRequest -from .types.logging import ListLogsResponse -from .types.logging import ListMonitoredResourceDescriptorsRequest -from .types.logging import ListMonitoredResourceDescriptorsResponse -from .types.logging import TailLogEntriesRequest -from .types.logging import TailLogEntriesResponse -from .types.logging import WriteLogEntriesPartialErrors -from .types.logging import WriteLogEntriesRequest -from .types.logging import WriteLogEntriesResponse -from .types.logging_config import BigQueryOptions -from .types.logging_config import CmekSettings -from .types.logging_config import CreateBucketRequest -from .types.logging_config import CreateExclusionRequest -from .types.logging_config import CreateSinkRequest -from .types.logging_config import CreateViewRequest -from .types.logging_config import DeleteBucketRequest -from .types.logging_config import DeleteExclusionRequest -from .types.logging_config import DeleteSinkRequest -from .types.logging_config import DeleteViewRequest -from .types.logging_config import GetBucketRequest -from .types.logging_config import GetCmekSettingsRequest -from .types.logging_config import GetExclusionRequest -from .types.logging_config import GetSinkRequest -from .types.logging_config import GetViewRequest -from .types.logging_config import ListBucketsRequest -from .types.logging_config import ListBucketsResponse -from .types.logging_config import ListExclusionsRequest -from .types.logging_config import ListExclusionsResponse -from .types.logging_config import ListSinksRequest -from .types.logging_config import ListSinksResponse -from .types.logging_config import ListViewsRequest -from .types.logging_config import ListViewsResponse -from .types.logging_config import LogBucket -from .types.logging_config import LogExclusion -from .types.logging_config import LogSink -from .types.logging_config import LogView -from .types.logging_config import UndeleteBucketRequest -from .types.logging_config import UpdateBucketRequest -from .types.logging_config import UpdateCmekSettingsRequest -from .types.logging_config import UpdateExclusionRequest -from .types.logging_config import UpdateSinkRequest -from .types.logging_config import UpdateViewRequest -from .types.logging_config import LifecycleState -from .types.logging_metrics import CreateLogMetricRequest -from .types.logging_metrics import DeleteLogMetricRequest -from .types.logging_metrics import GetLogMetricRequest -from .types.logging_metrics import ListLogMetricsRequest -from .types.logging_metrics import ListLogMetricsResponse -from .types.logging_metrics import LogMetric -from .types.logging_metrics import UpdateLogMetricRequest - -__all__ = ( - 'ConfigServiceV2AsyncClient', - 'LoggingServiceV2AsyncClient', - 'MetricsServiceV2AsyncClient', -'BigQueryOptions', -'CmekSettings', -'ConfigServiceV2Client', -'CreateBucketRequest', -'CreateExclusionRequest', -'CreateLogMetricRequest', -'CreateSinkRequest', -'CreateViewRequest', -'DeleteBucketRequest', -'DeleteExclusionRequest', -'DeleteLogMetricRequest', -'DeleteLogRequest', -'DeleteSinkRequest', -'DeleteViewRequest', -'GetBucketRequest', -'GetCmekSettingsRequest', -'GetExclusionRequest', -'GetLogMetricRequest', -'GetSinkRequest', -'GetViewRequest', -'LifecycleState', -'ListBucketsRequest', -'ListBucketsResponse', -'ListExclusionsRequest', -'ListExclusionsResponse', -'ListLogEntriesRequest', -'ListLogEntriesResponse', -'ListLogMetricsRequest', -'ListLogMetricsResponse', -'ListLogsRequest', -'ListLogsResponse', -'ListMonitoredResourceDescriptorsRequest', -'ListMonitoredResourceDescriptorsResponse', -'ListSinksRequest', -'ListSinksResponse', -'ListViewsRequest', -'ListViewsResponse', -'LogBucket', -'LogEntry', -'LogEntryOperation', -'LogEntrySourceLocation', -'LogExclusion', -'LogMetric', -'LogSink', -'LogView', -'LoggingServiceV2Client', -'MetricsServiceV2Client', -'TailLogEntriesRequest', -'TailLogEntriesResponse', -'UndeleteBucketRequest', -'UpdateBucketRequest', -'UpdateCmekSettingsRequest', -'UpdateExclusionRequest', -'UpdateLogMetricRequest', -'UpdateSinkRequest', -'UpdateViewRequest', -'WriteLogEntriesPartialErrors', -'WriteLogEntriesRequest', -'WriteLogEntriesResponse', -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/gapic_metadata.json b/owl-bot-staging/v2/google/cloud/logging_v2/gapic_metadata.json deleted file mode 100644 index da4eefd4..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/gapic_metadata.json +++ /dev/null @@ -1,391 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.logging_v2", - "protoPackage": "google.logging.v2", - "schema": "1.0", - "services": { - "ConfigServiceV2": { - "clients": { - "grpc": { - "libraryClient": "ConfigServiceV2Client", - "rpcs": { - "CreateBucket": { - "methods": [ - "create_bucket" - ] - }, - "CreateExclusion": { - "methods": [ - "create_exclusion" - ] - }, - "CreateSink": { - "methods": [ - "create_sink" - ] - }, - "CreateView": { - "methods": [ - "create_view" - ] - }, - "DeleteBucket": { - "methods": [ - "delete_bucket" - ] - }, - "DeleteExclusion": { - "methods": [ - "delete_exclusion" - ] - }, - "DeleteSink": { - "methods": [ - "delete_sink" - ] - }, - "DeleteView": { - "methods": [ - "delete_view" - ] - }, - "GetBucket": { - "methods": [ - "get_bucket" - ] - }, - "GetCmekSettings": { - "methods": [ - "get_cmek_settings" - ] - }, - "GetExclusion": { - "methods": [ - "get_exclusion" - ] - }, - "GetSink": { - "methods": [ - "get_sink" - ] - }, - "GetView": { - "methods": [ - "get_view" - ] - }, - "ListBuckets": { - "methods": [ - "list_buckets" - ] - }, - "ListExclusions": { - "methods": [ - "list_exclusions" - ] - }, - "ListSinks": { - "methods": [ - "list_sinks" - ] - }, - "ListViews": { - "methods": [ - "list_views" - ] - }, - "UndeleteBucket": { - "methods": [ - "undelete_bucket" - ] - }, - "UpdateBucket": { - "methods": [ - "update_bucket" - ] - }, - "UpdateCmekSettings": { - "methods": [ - "update_cmek_settings" - ] - }, - "UpdateExclusion": { - "methods": [ - "update_exclusion" - ] - }, - "UpdateSink": { - "methods": [ - "update_sink" - ] - }, - "UpdateView": { - "methods": [ - "update_view" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ConfigServiceV2AsyncClient", - "rpcs": { - "CreateBucket": { - "methods": [ - "create_bucket" - ] - }, - "CreateExclusion": { - "methods": [ - "create_exclusion" - ] - }, - "CreateSink": { - "methods": [ - "create_sink" - ] - }, - "CreateView": { - "methods": [ - "create_view" - ] - }, - "DeleteBucket": { - "methods": [ - "delete_bucket" - ] - }, - "DeleteExclusion": { - "methods": [ - "delete_exclusion" - ] - }, - "DeleteSink": { - "methods": [ - "delete_sink" - ] - }, - "DeleteView": { - "methods": [ - "delete_view" - ] - }, - "GetBucket": { - "methods": [ - "get_bucket" - ] - }, - "GetCmekSettings": { - "methods": [ - "get_cmek_settings" - ] - }, - "GetExclusion": { - "methods": [ - "get_exclusion" - ] - }, - "GetSink": { - "methods": [ - "get_sink" - ] - }, - "GetView": { - "methods": [ - "get_view" - ] - }, - "ListBuckets": { - "methods": [ - "list_buckets" - ] - }, - "ListExclusions": { - "methods": [ - "list_exclusions" - ] - }, - "ListSinks": { - "methods": [ - "list_sinks" - ] - }, - "ListViews": { - "methods": [ - "list_views" - ] - }, - "UndeleteBucket": { - "methods": [ - "undelete_bucket" - ] - }, - "UpdateBucket": { - "methods": [ - "update_bucket" - ] - }, - "UpdateCmekSettings": { - "methods": [ - "update_cmek_settings" - ] - }, - "UpdateExclusion": { - "methods": [ - "update_exclusion" - ] - }, - "UpdateSink": { - "methods": [ - "update_sink" - ] - }, - "UpdateView": { - "methods": [ - "update_view" - ] - } - } - } - } - }, - "LoggingServiceV2": { - "clients": { - "grpc": { - "libraryClient": "LoggingServiceV2Client", - "rpcs": { - "DeleteLog": { - "methods": [ - "delete_log" - ] - }, - "ListLogEntries": { - "methods": [ - "list_log_entries" - ] - }, - "ListLogs": { - "methods": [ - "list_logs" - ] - }, - "ListMonitoredResourceDescriptors": { - "methods": [ - "list_monitored_resource_descriptors" - ] - }, - "TailLogEntries": { - "methods": [ - "tail_log_entries" - ] - }, - "WriteLogEntries": { - "methods": [ - "write_log_entries" - ] - } - } - }, - "grpc-async": { - "libraryClient": "LoggingServiceV2AsyncClient", - "rpcs": { - "DeleteLog": { - "methods": [ - "delete_log" - ] - }, - "ListLogEntries": { - "methods": [ - "list_log_entries" - ] - }, - "ListLogs": { - "methods": [ - "list_logs" - ] - }, - "ListMonitoredResourceDescriptors": { - "methods": [ - "list_monitored_resource_descriptors" - ] - }, - "TailLogEntries": { - "methods": [ - "tail_log_entries" - ] - }, - "WriteLogEntries": { - "methods": [ - "write_log_entries" - ] - } - } - } - } - }, - "MetricsServiceV2": { - "clients": { - "grpc": { - "libraryClient": "MetricsServiceV2Client", - "rpcs": { - "CreateLogMetric": { - "methods": [ - "create_log_metric" - ] - }, - "DeleteLogMetric": { - "methods": [ - "delete_log_metric" - ] - }, - "GetLogMetric": { - "methods": [ - "get_log_metric" - ] - }, - "ListLogMetrics": { - "methods": [ - "list_log_metrics" - ] - }, - "UpdateLogMetric": { - "methods": [ - "update_log_metric" - ] - } - } - }, - "grpc-async": { - "libraryClient": "MetricsServiceV2AsyncClient", - "rpcs": { - "CreateLogMetric": { - "methods": [ - "create_log_metric" - ] - }, - "DeleteLogMetric": { - "methods": [ - "delete_log_metric" - ] - }, - "GetLogMetric": { - "methods": [ - "get_log_metric" - ] - }, - "ListLogMetrics": { - "methods": [ - "list_log_metrics" - ] - }, - "UpdateLogMetric": { - "methods": [ - "update_log_metric" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/py.typed b/owl-bot-staging/v2/google/cloud/logging_v2/py.typed deleted file mode 100644 index 6c7420d0..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-logging package uses inline types. diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/__init__.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/__init__.py deleted file mode 100644 index 4de65971..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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. -# diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/__init__.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/__init__.py deleted file mode 100644 index 2b27a12e..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 .client import ConfigServiceV2Client -from .async_client import ConfigServiceV2AsyncClient - -__all__ = ( - 'ConfigServiceV2Client', - 'ConfigServiceV2AsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/async_client.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/async_client.py deleted file mode 100644 index 82e84aab..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/async_client.py +++ /dev/null @@ -1,2016 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.logging_v2.services.config_service_v2 import pagers -from google.cloud.logging_v2.types import logging_config -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ConfigServiceV2Transport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ConfigServiceV2GrpcAsyncIOTransport -from .client import ConfigServiceV2Client - - -class ConfigServiceV2AsyncClient: - """Service for configuring sinks used to route log entries.""" - - _client: ConfigServiceV2Client - - DEFAULT_ENDPOINT = ConfigServiceV2Client.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ConfigServiceV2Client.DEFAULT_MTLS_ENDPOINT - - cmek_settings_path = staticmethod(ConfigServiceV2Client.cmek_settings_path) - parse_cmek_settings_path = staticmethod(ConfigServiceV2Client.parse_cmek_settings_path) - log_bucket_path = staticmethod(ConfigServiceV2Client.log_bucket_path) - parse_log_bucket_path = staticmethod(ConfigServiceV2Client.parse_log_bucket_path) - log_exclusion_path = staticmethod(ConfigServiceV2Client.log_exclusion_path) - parse_log_exclusion_path = staticmethod(ConfigServiceV2Client.parse_log_exclusion_path) - log_sink_path = staticmethod(ConfigServiceV2Client.log_sink_path) - parse_log_sink_path = staticmethod(ConfigServiceV2Client.parse_log_sink_path) - log_view_path = staticmethod(ConfigServiceV2Client.log_view_path) - parse_log_view_path = staticmethod(ConfigServiceV2Client.parse_log_view_path) - common_billing_account_path = staticmethod(ConfigServiceV2Client.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ConfigServiceV2Client.parse_common_billing_account_path) - common_folder_path = staticmethod(ConfigServiceV2Client.common_folder_path) - parse_common_folder_path = staticmethod(ConfigServiceV2Client.parse_common_folder_path) - common_organization_path = staticmethod(ConfigServiceV2Client.common_organization_path) - parse_common_organization_path = staticmethod(ConfigServiceV2Client.parse_common_organization_path) - common_project_path = staticmethod(ConfigServiceV2Client.common_project_path) - parse_common_project_path = staticmethod(ConfigServiceV2Client.parse_common_project_path) - common_location_path = staticmethod(ConfigServiceV2Client.common_location_path) - parse_common_location_path = staticmethod(ConfigServiceV2Client.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: - ConfigServiceV2AsyncClient: The constructed client. - """ - return ConfigServiceV2Client.from_service_account_info.__func__(ConfigServiceV2AsyncClient, 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: - ConfigServiceV2AsyncClient: The constructed client. - """ - return ConfigServiceV2Client.from_service_account_file.__func__(ConfigServiceV2AsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> ConfigServiceV2Transport: - """Returns the transport used by the client instance. - - Returns: - ConfigServiceV2Transport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ConfigServiceV2Client).get_transport_class, type(ConfigServiceV2Client)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ConfigServiceV2Transport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the config service v2 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, ~.ConfigServiceV2Transport]): 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 = ConfigServiceV2Client( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_buckets(self, - request: logging_config.ListBucketsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListBucketsAsyncPager: - r"""Lists buckets. - - Args: - request (:class:`google.cloud.logging_v2.types.ListBucketsRequest`): - The request object. The parameters to `ListBuckets`. - parent (:class:`str`): - Required. The parent resource whose buckets are to be - listed: - - :: - - "projects/[PROJECT_ID]/locations/[LOCATION_ID]" - "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" - "folders/[FOLDER_ID]/locations/[LOCATION_ID]" - - Note: The locations portion of the resource must be - specified, but supplying the character ``-`` in place of - [LOCATION_ID] will return all buckets. - - 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.logging_v2.services.config_service_v2.pagers.ListBucketsAsyncPager: - The response from ListBuckets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = logging_config.ListBucketsRequest(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_buckets, - 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.ListBucketsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_bucket(self, - request: logging_config.GetBucketRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogBucket: - r"""Gets a bucket. - - Args: - request (:class:`google.cloud.logging_v2.types.GetBucketRequest`): - The request object. The parameters to `GetBucket`. - 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.logging_v2.types.LogBucket: - Describes a repository of logs. - """ - # Create or coerce a protobuf request object. - request = logging_config.GetBucketRequest(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.get_bucket, - 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 create_bucket(self, - request: logging_config.CreateBucketRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogBucket: - r"""Creates a bucket that can be used to store log - entries. Once a bucket has been created, the region - cannot be changed. - - Args: - request (:class:`google.cloud.logging_v2.types.CreateBucketRequest`): - The request object. The parameters to `CreateBucket`. - 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.logging_v2.types.LogBucket: - Describes a repository of logs. - """ - # Create or coerce a protobuf request object. - request = logging_config.CreateBucketRequest(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.create_bucket, - 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, - ) - - # Done; return the response. - return response - - async def update_bucket(self, - request: logging_config.UpdateBucketRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogBucket: - r"""Updates a bucket. This method replaces the following fields in - the existing bucket with values from the new bucket: - ``retention_period`` - - If the retention period is decreased and the bucket is locked, - FAILED_PRECONDITION will be returned. - - If the bucket has a LifecycleState of DELETE_REQUESTED, - FAILED_PRECONDITION will be returned. - - A buckets region may not be modified after it is created. - - Args: - request (:class:`google.cloud.logging_v2.types.UpdateBucketRequest`): - The request object. The parameters to `UpdateBucket`. - 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.logging_v2.types.LogBucket: - Describes a repository of logs. - """ - # Create or coerce a protobuf request object. - request = logging_config.UpdateBucketRequest(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.update_bucket, - 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_bucket(self, - request: logging_config.DeleteBucketRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a bucket. Moves the bucket to the DELETE_REQUESTED - state. After 7 days, the bucket will be purged and all logs in - the bucket will be permanently deleted. - - Args: - request (:class:`google.cloud.logging_v2.types.DeleteBucketRequest`): - The request object. The parameters to `DeleteBucket`. - 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. - """ - # Create or coerce a protobuf request object. - request = logging_config.DeleteBucketRequest(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.delete_bucket, - 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 undelete_bucket(self, - request: logging_config.UndeleteBucketRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Undeletes a bucket. A bucket that has been deleted - may be undeleted within the grace period of 7 days. - - Args: - request (:class:`google.cloud.logging_v2.types.UndeleteBucketRequest`): - The request object. The parameters to `UndeleteBucket`. - 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. - """ - # Create or coerce a protobuf request object. - request = logging_config.UndeleteBucketRequest(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.undelete_bucket, - 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 list_views(self, - request: logging_config.ListViewsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListViewsAsyncPager: - r"""Lists views on a bucket. - - Args: - request (:class:`google.cloud.logging_v2.types.ListViewsRequest`): - The request object. The parameters to `ListViews`. - parent (:class:`str`): - Required. The bucket whose views are to be listed: - - :: - - "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_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.logging_v2.services.config_service_v2.pagers.ListViewsAsyncPager: - The response from ListViews. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = logging_config.ListViewsRequest(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_views, - 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.ListViewsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_view(self, - request: logging_config.GetViewRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogView: - r"""Gets a view. - - Args: - request (:class:`google.cloud.logging_v2.types.GetViewRequest`): - The request object. The parameters to `GetView`. - 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.logging_v2.types.LogView: - Describes a view over logs in a - bucket. - - """ - # Create or coerce a protobuf request object. - request = logging_config.GetViewRequest(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.get_view, - 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 create_view(self, - request: logging_config.CreateViewRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogView: - r"""Creates a view over logs in a bucket. A bucket may - contain a maximum of 50 views. - - Args: - request (:class:`google.cloud.logging_v2.types.CreateViewRequest`): - The request object. The parameters to `CreateView`. - 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.logging_v2.types.LogView: - Describes a view over logs in a - bucket. - - """ - # Create or coerce a protobuf request object. - request = logging_config.CreateViewRequest(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.create_view, - 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, - ) - - # Done; return the response. - return response - - async def update_view(self, - request: logging_config.UpdateViewRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogView: - r"""Updates a view. This method replaces the following fields in the - existing view with values from the new view: ``filter``. - - Args: - request (:class:`google.cloud.logging_v2.types.UpdateViewRequest`): - The request object. The parameters to `UpdateView`. - 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.logging_v2.types.LogView: - Describes a view over logs in a - bucket. - - """ - # Create or coerce a protobuf request object. - request = logging_config.UpdateViewRequest(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.update_view, - 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_view(self, - request: logging_config.DeleteViewRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a view from a bucket. - - Args: - request (:class:`google.cloud.logging_v2.types.DeleteViewRequest`): - The request object. The parameters to `DeleteView`. - 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. - """ - # Create or coerce a protobuf request object. - request = logging_config.DeleteViewRequest(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.delete_view, - 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 list_sinks(self, - request: logging_config.ListSinksRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSinksAsyncPager: - r"""Lists sinks. - - Args: - request (:class:`google.cloud.logging_v2.types.ListSinksRequest`): - The request object. The parameters to `ListSinks`. - parent (:class:`str`): - Required. The parent resource whose sinks are to be - listed: - - :: - - "projects/[PROJECT_ID]" - "organizations/[ORGANIZATION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]" - "folders/[FOLDER_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.logging_v2.services.config_service_v2.pagers.ListSinksAsyncPager: - Result returned from ListSinks. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = logging_config.ListSinksRequest(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_sinks, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - 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.ListSinksAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_sink(self, - request: logging_config.GetSinkRequest = None, - *, - sink_name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogSink: - r"""Gets a sink. - - Args: - request (:class:`google.cloud.logging_v2.types.GetSinkRequest`): - The request object. The parameters to `GetSink`. - sink_name (:class:`str`): - Required. The resource name of the sink: - - :: - - "projects/[PROJECT_ID]/sinks/[SINK_ID]" - "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - "folders/[FOLDER_ID]/sinks/[SINK_ID]" - - Example: ``"projects/my-project-id/sinks/my-sink-id"``. - - This corresponds to the ``sink_name`` 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.logging_v2.types.LogSink: - Describes a sink used to export log - entries to one of the following - destinations in any project: a Cloud - Storage bucket, a BigQuery dataset, or a - Cloud Pub/Sub topic. A logs filter - controls which log entries are exported. - The sink must be created within a - project, organization, billing account, - or folder. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([sink_name]) - 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 = logging_config.GetSinkRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if sink_name is not None: - request.sink_name = sink_name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_sink, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - 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(( - ("sink_name", request.sink_name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_sink(self, - request: logging_config.CreateSinkRequest = None, - *, - parent: str = None, - sink: logging_config.LogSink = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogSink: - r"""Creates a sink that exports specified log entries to a - destination. The export of newly-ingested log entries begins - immediately, unless the sink's ``writer_identity`` is not - permitted to write to the destination. A sink can export log - entries only from the resource owning the sink. - - Args: - request (:class:`google.cloud.logging_v2.types.CreateSinkRequest`): - The request object. The parameters to `CreateSink`. - parent (:class:`str`): - Required. The resource in which to create the sink: - - :: - - "projects/[PROJECT_ID]" - "organizations/[ORGANIZATION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]" - "folders/[FOLDER_ID]" - - Examples: ``"projects/my-logging-project"``, - ``"organizations/123456789"``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - sink (:class:`google.cloud.logging_v2.types.LogSink`): - Required. The new sink, whose ``name`` parameter is a - sink identifier that is not already in use. - - This corresponds to the ``sink`` 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.logging_v2.types.LogSink: - Describes a sink used to export log - entries to one of the following - destinations in any project: a Cloud - Storage bucket, a BigQuery dataset, or a - Cloud Pub/Sub topic. A logs filter - controls which log entries are exported. - The sink must be created within a - project, organization, billing account, - or folder. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, sink]) - 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 = logging_config.CreateSinkRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if sink is not None: - request.sink = sink - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_sink, - default_timeout=120.0, - 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, - ) - - # Done; return the response. - return response - - async def update_sink(self, - request: logging_config.UpdateSinkRequest = None, - *, - sink_name: str = None, - sink: logging_config.LogSink = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogSink: - r"""Updates a sink. This method replaces the following fields in the - existing sink with values from the new sink: ``destination``, - and ``filter``. - - The updated sink might also have a new ``writer_identity``; see - the ``unique_writer_identity`` field. - - Args: - request (:class:`google.cloud.logging_v2.types.UpdateSinkRequest`): - The request object. The parameters to `UpdateSink`. - sink_name (:class:`str`): - Required. The full resource name of the sink to update, - including the parent resource and the sink identifier: - - :: - - "projects/[PROJECT_ID]/sinks/[SINK_ID]" - "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - "folders/[FOLDER_ID]/sinks/[SINK_ID]" - - Example: ``"projects/my-project-id/sinks/my-sink-id"``. - - This corresponds to the ``sink_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - sink (:class:`google.cloud.logging_v2.types.LogSink`): - Required. The updated sink, whose name is the same - identifier that appears as part of ``sink_name``. - - This corresponds to the ``sink`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. Field mask that specifies the fields in - ``sink`` that need an update. A sink field will be - overwritten if, and only if, it is in the update mask. - ``name`` and output only fields cannot be updated. - - An empty updateMask is temporarily treated as using the - following mask for backwards compatibility purposes: - destination,filter,includeChildren At some point in the - future, behavior will be removed and specifying an empty - updateMask will be an error. - - For a detailed ``FieldMask`` definition, see - https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask - - Example: ``updateMask=filter``. - - This corresponds to the ``update_mask`` 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.logging_v2.types.LogSink: - Describes a sink used to export log - entries to one of the following - destinations in any project: a Cloud - Storage bucket, a BigQuery dataset, or a - Cloud Pub/Sub topic. A logs filter - controls which log entries are exported. - The sink must be created within a - project, organization, billing account, - or folder. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([sink_name, sink, update_mask]) - 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 = logging_config.UpdateSinkRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if sink_name is not None: - request.sink_name = sink_name - if sink is not None: - request.sink = sink - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_sink, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - 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(( - ("sink_name", request.sink_name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_sink(self, - request: logging_config.DeleteSinkRequest = None, - *, - sink_name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a sink. If the sink has a unique ``writer_identity``, - then that service account is also deleted. - - Args: - request (:class:`google.cloud.logging_v2.types.DeleteSinkRequest`): - The request object. The parameters to `DeleteSink`. - sink_name (:class:`str`): - Required. The full resource name of the sink to delete, - including the parent resource and the sink identifier: - - :: - - "projects/[PROJECT_ID]/sinks/[SINK_ID]" - "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - "folders/[FOLDER_ID]/sinks/[SINK_ID]" - - Example: ``"projects/my-project-id/sinks/my-sink-id"``. - - This corresponds to the ``sink_name`` 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. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([sink_name]) - 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 = logging_config.DeleteSinkRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if sink_name is not None: - request.sink_name = sink_name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_sink, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - 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(( - ("sink_name", request.sink_name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def list_exclusions(self, - request: logging_config.ListExclusionsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListExclusionsAsyncPager: - r"""Lists all the exclusions in a parent resource. - - Args: - request (:class:`google.cloud.logging_v2.types.ListExclusionsRequest`): - The request object. The parameters to `ListExclusions`. - parent (:class:`str`): - Required. The parent resource whose exclusions are to be - listed. - - :: - - "projects/[PROJECT_ID]" - "organizations/[ORGANIZATION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]" - "folders/[FOLDER_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.logging_v2.services.config_service_v2.pagers.ListExclusionsAsyncPager: - Result returned from ListExclusions. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = logging_config.ListExclusionsRequest(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_exclusions, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - 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.ListExclusionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_exclusion(self, - request: logging_config.GetExclusionRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogExclusion: - r"""Gets the description of an exclusion. - - Args: - request (:class:`google.cloud.logging_v2.types.GetExclusionRequest`): - The request object. The parameters to `GetExclusion`. - name (:class:`str`): - Required. The resource name of an existing exclusion: - - :: - - "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" - "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" - "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" - - Example: - ``"projects/my-project-id/exclusions/my-exclusion-id"``. - - This corresponds to the ``name`` 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.logging_v2.types.LogExclusion: - Specifies a set of log entries that - are not to be stored in Logging. If your - GCP resource receives a large volume of - logs, you can use exclusions to reduce - your chargeable logs. Exclusions are - processed after log sinks, so you can - export log entries before they are - excluded. Note that organization-level - and folder-level exclusions don't apply - to child resources, and that you can't - exclude audit log entries. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - 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 = logging_config.GetExclusionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_exclusion, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - 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 create_exclusion(self, - request: logging_config.CreateExclusionRequest = None, - *, - parent: str = None, - exclusion: logging_config.LogExclusion = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogExclusion: - r"""Creates a new exclusion in a specified parent - resource. Only log entries belonging to that resource - can be excluded. You can have up to 10 exclusions in a - resource. - - Args: - request (:class:`google.cloud.logging_v2.types.CreateExclusionRequest`): - The request object. The parameters to `CreateExclusion`. - parent (:class:`str`): - Required. The parent resource in which to create the - exclusion: - - :: - - "projects/[PROJECT_ID]" - "organizations/[ORGANIZATION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]" - "folders/[FOLDER_ID]" - - Examples: ``"projects/my-logging-project"``, - ``"organizations/123456789"``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - exclusion (:class:`google.cloud.logging_v2.types.LogExclusion`): - Required. The new exclusion, whose ``name`` parameter is - an exclusion name that is not already used in the parent - resource. - - This corresponds to the ``exclusion`` 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.logging_v2.types.LogExclusion: - Specifies a set of log entries that - are not to be stored in Logging. If your - GCP resource receives a large volume of - logs, you can use exclusions to reduce - your chargeable logs. Exclusions are - processed after log sinks, so you can - export log entries before they are - excluded. Note that organization-level - and folder-level exclusions don't apply - to child resources, and that you can't - exclude audit log entries. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, exclusion]) - 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 = logging_config.CreateExclusionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if exclusion is not None: - request.exclusion = exclusion - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_exclusion, - default_timeout=120.0, - 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, - ) - - # Done; return the response. - return response - - async def update_exclusion(self, - request: logging_config.UpdateExclusionRequest = None, - *, - name: str = None, - exclusion: logging_config.LogExclusion = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogExclusion: - r"""Changes one or more properties of an existing - exclusion. - - Args: - request (:class:`google.cloud.logging_v2.types.UpdateExclusionRequest`): - The request object. The parameters to `UpdateExclusion`. - name (:class:`str`): - Required. The resource name of the exclusion to update: - - :: - - "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" - "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" - "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" - - Example: - ``"projects/my-project-id/exclusions/my-exclusion-id"``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - exclusion (:class:`google.cloud.logging_v2.types.LogExclusion`): - Required. New values for the existing exclusion. Only - the fields specified in ``update_mask`` are relevant. - - This corresponds to the ``exclusion`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. A non-empty list of fields to change in the - existing exclusion. New values for the fields are taken - from the corresponding fields in the - [LogExclusion][google.logging.v2.LogExclusion] included - in this request. Fields not mentioned in ``update_mask`` - are not changed and are ignored in the request. - - For example, to change the filter and description of an - exclusion, specify an ``update_mask`` of - ``"filter,description"``. - - This corresponds to the ``update_mask`` 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.logging_v2.types.LogExclusion: - Specifies a set of log entries that - are not to be stored in Logging. If your - GCP resource receives a large volume of - logs, you can use exclusions to reduce - your chargeable logs. Exclusions are - processed after log sinks, so you can - export log entries before they are - excluded. Note that organization-level - and folder-level exclusions don't apply - to child resources, and that you can't - exclude audit log entries. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, exclusion, update_mask]) - 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 = logging_config.UpdateExclusionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if exclusion is not None: - request.exclusion = exclusion - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_exclusion, - default_timeout=120.0, - 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_exclusion(self, - request: logging_config.DeleteExclusionRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an exclusion. - - Args: - request (:class:`google.cloud.logging_v2.types.DeleteExclusionRequest`): - The request object. The parameters to `DeleteExclusion`. - name (:class:`str`): - Required. The resource name of an existing exclusion to - delete: - - :: - - "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" - "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" - "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" - - Example: - ``"projects/my-project-id/exclusions/my-exclusion-id"``. - - This corresponds to the ``name`` 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. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - 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 = logging_config.DeleteExclusionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_exclusion, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - 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 get_cmek_settings(self, - request: logging_config.GetCmekSettingsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.CmekSettings: - r"""Gets the Logs Router CMEK settings for the given resource. - - Note: CMEK for the Logs Router can currently only be configured - for GCP organizations. Once configured, it applies to all - projects and folders in the GCP organization. - - See `Enabling CMEK for Logs - Router `__ - for more information. - - Args: - request (:class:`google.cloud.logging_v2.types.GetCmekSettingsRequest`): - The request object. The parameters to - [GetCmekSettings][google.logging.v2.ConfigServiceV2.GetCmekSettings]. - See [Enabling CMEK for Logs - Router](https://cloud.google.com/logging/docs/routing/managed- - encryption) for more information. - 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.logging_v2.types.CmekSettings: - Describes the customer-managed encryption key (CMEK) settings associated with - a project, folder, organization, billing account, or - flexible resource. - - Note: CMEK for the Logs Router can currently only be - configured for GCP organizations. Once configured, it - applies to all projects and folders in the GCP - organization. - - See [Enabling CMEK for Logs - Router](\ https://cloud.google.com/logging/docs/routing/managed-encryption) - for more information. - - """ - # Create or coerce a protobuf request object. - request = logging_config.GetCmekSettingsRequest(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.get_cmek_settings, - 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 update_cmek_settings(self, - request: logging_config.UpdateCmekSettingsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.CmekSettings: - r"""Updates the Logs Router CMEK settings for the given resource. - - Note: CMEK for the Logs Router can currently only be configured - for GCP organizations. Once configured, it applies to all - projects and folders in the GCP organization. - - [UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings] - will fail if 1) ``kms_key_name`` is invalid, or 2) the - associated service account does not have the required - ``roles/cloudkms.cryptoKeyEncrypterDecrypter`` role assigned for - the key, or 3) access to the key is disabled. - - See `Enabling CMEK for Logs - Router `__ - for more information. - - Args: - request (:class:`google.cloud.logging_v2.types.UpdateCmekSettingsRequest`): - The request object. The parameters to - [UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings]. - See [Enabling CMEK for Logs - Router](https://cloud.google.com/logging/docs/routing/managed- - encryption) for more information. - 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.logging_v2.types.CmekSettings: - Describes the customer-managed encryption key (CMEK) settings associated with - a project, folder, organization, billing account, or - flexible resource. - - Note: CMEK for the Logs Router can currently only be - configured for GCP organizations. Once configured, it - applies to all projects and folders in the GCP - organization. - - See [Enabling CMEK for Logs - Router](\ https://cloud.google.com/logging/docs/routing/managed-encryption) - for more information. - - """ - # Create or coerce a protobuf request object. - request = logging_config.UpdateCmekSettingsRequest(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.update_cmek_settings, - 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-logging", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ConfigServiceV2AsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/client.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/client.py deleted file mode 100644 index acf10f22..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/client.py +++ /dev/null @@ -1,2198 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 distutils import util -import os -import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.logging_v2.services.config_service_v2 import pagers -from google.cloud.logging_v2.types import logging_config -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ConfigServiceV2Transport, DEFAULT_CLIENT_INFO -from .transports.grpc import ConfigServiceV2GrpcTransport -from .transports.grpc_asyncio import ConfigServiceV2GrpcAsyncIOTransport - - -class ConfigServiceV2ClientMeta(type): - """Metaclass for the ConfigServiceV2 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[ConfigServiceV2Transport]] - _transport_registry["grpc"] = ConfigServiceV2GrpcTransport - _transport_registry["grpc_asyncio"] = ConfigServiceV2GrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ConfigServiceV2Transport]: - """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 ConfigServiceV2Client(metaclass=ConfigServiceV2ClientMeta): - """Service for configuring sinks used to route log entries.""" - - @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 = "logging.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: - ConfigServiceV2Client: 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: - ConfigServiceV2Client: 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) -> ConfigServiceV2Transport: - """Returns the transport used by the client instance. - - Returns: - ConfigServiceV2Transport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def cmek_settings_path(project: str,) -> str: - """Returns a fully-qualified cmek_settings string.""" - return "projects/{project}/cmekSettings".format(project=project, ) - - @staticmethod - def parse_cmek_settings_path(path: str) -> Dict[str,str]: - """Parses a cmek_settings path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/cmekSettings$", path) - return m.groupdict() if m else {} - - @staticmethod - def log_bucket_path(project: str,location: str,bucket: str,) -> str: - """Returns a fully-qualified log_bucket string.""" - return "projects/{project}/locations/{location}/buckets/{bucket}".format(project=project, location=location, bucket=bucket, ) - - @staticmethod - def parse_log_bucket_path(path: str) -> Dict[str,str]: - """Parses a log_bucket path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def log_exclusion_path(project: str,exclusion: str,) -> str: - """Returns a fully-qualified log_exclusion string.""" - return "projects/{project}/exclusions/{exclusion}".format(project=project, exclusion=exclusion, ) - - @staticmethod - def parse_log_exclusion_path(path: str) -> Dict[str,str]: - """Parses a log_exclusion path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/exclusions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def log_sink_path(project: str,sink: str,) -> str: - """Returns a fully-qualified log_sink string.""" - return "projects/{project}/sinks/{sink}".format(project=project, sink=sink, ) - - @staticmethod - def parse_log_sink_path(path: str) -> Dict[str,str]: - """Parses a log_sink path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/sinks/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def log_view_path(project: str,location: str,bucket: str,view: str,) -> str: - """Returns a fully-qualified log_view string.""" - return "projects/{project}/locations/{location}/buckets/{bucket}/views/{view}".format(project=project, location=location, bucket=bucket, view=view, ) - - @staticmethod - def parse_log_view_path(path: str) -> Dict[str,str]: - """Parses a log_view path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/buckets/(?P.+?)/views/(?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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ConfigServiceV2Transport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the config service v2 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, ConfigServiceV2Transport]): 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() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # 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, ConfigServiceV2Transport): - # transport is a ConfigServiceV2Transport instance. - if credentials or client_options.credentials_file: - 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: - 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=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), - ) - - def list_buckets(self, - request: Union[logging_config.ListBucketsRequest, dict] = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListBucketsPager: - r"""Lists buckets. - - Args: - request (Union[google.cloud.logging_v2.types.ListBucketsRequest, dict]): - The request object. The parameters to `ListBuckets`. - parent (str): - Required. The parent resource whose buckets are to be - listed: - - :: - - "projects/[PROJECT_ID]/locations/[LOCATION_ID]" - "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" - "folders/[FOLDER_ID]/locations/[LOCATION_ID]" - - Note: The locations portion of the resource must be - specified, but supplying the character ``-`` in place of - [LOCATION_ID] will return all buckets. - - 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.logging_v2.services.config_service_v2.pagers.ListBucketsPager: - The response from ListBuckets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 logging_config.ListBucketsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.ListBucketsRequest): - request = logging_config.ListBucketsRequest(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_buckets] - - # 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.ListBucketsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_bucket(self, - request: Union[logging_config.GetBucketRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogBucket: - r"""Gets a bucket. - - Args: - request (Union[google.cloud.logging_v2.types.GetBucketRequest, dict]): - The request object. The parameters to `GetBucket`. - 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.logging_v2.types.LogBucket: - Describes a repository of logs. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a logging_config.GetBucketRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.GetBucketRequest): - request = logging_config.GetBucketRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_bucket] - - # 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 create_bucket(self, - request: Union[logging_config.CreateBucketRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogBucket: - r"""Creates a bucket that can be used to store log - entries. Once a bucket has been created, the region - cannot be changed. - - Args: - request (Union[google.cloud.logging_v2.types.CreateBucketRequest, dict]): - The request object. The parameters to `CreateBucket`. - 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.logging_v2.types.LogBucket: - Describes a repository of logs. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a logging_config.CreateBucketRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.CreateBucketRequest): - request = logging_config.CreateBucketRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_bucket] - - # 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, - ) - - # Done; return the response. - return response - - def update_bucket(self, - request: Union[logging_config.UpdateBucketRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogBucket: - r"""Updates a bucket. This method replaces the following fields in - the existing bucket with values from the new bucket: - ``retention_period`` - - If the retention period is decreased and the bucket is locked, - FAILED_PRECONDITION will be returned. - - If the bucket has a LifecycleState of DELETE_REQUESTED, - FAILED_PRECONDITION will be returned. - - A buckets region may not be modified after it is created. - - Args: - request (Union[google.cloud.logging_v2.types.UpdateBucketRequest, dict]): - The request object. The parameters to `UpdateBucket`. - 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.logging_v2.types.LogBucket: - Describes a repository of logs. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a logging_config.UpdateBucketRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.UpdateBucketRequest): - request = logging_config.UpdateBucketRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_bucket] - - # 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_bucket(self, - request: Union[logging_config.DeleteBucketRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a bucket. Moves the bucket to the DELETE_REQUESTED - state. After 7 days, the bucket will be purged and all logs in - the bucket will be permanently deleted. - - Args: - request (Union[google.cloud.logging_v2.types.DeleteBucketRequest, dict]): - The request object. The parameters to `DeleteBucket`. - 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. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a logging_config.DeleteBucketRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.DeleteBucketRequest): - request = logging_config.DeleteBucketRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_bucket] - - # 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 undelete_bucket(self, - request: Union[logging_config.UndeleteBucketRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Undeletes a bucket. A bucket that has been deleted - may be undeleted within the grace period of 7 days. - - Args: - request (Union[google.cloud.logging_v2.types.UndeleteBucketRequest, dict]): - The request object. The parameters to `UndeleteBucket`. - 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. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a logging_config.UndeleteBucketRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.UndeleteBucketRequest): - request = logging_config.UndeleteBucketRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.undelete_bucket] - - # 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 list_views(self, - request: Union[logging_config.ListViewsRequest, dict] = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListViewsPager: - r"""Lists views on a bucket. - - Args: - request (Union[google.cloud.logging_v2.types.ListViewsRequest, dict]): - The request object. The parameters to `ListViews`. - parent (str): - Required. The bucket whose views are to be listed: - - :: - - "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_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.logging_v2.services.config_service_v2.pagers.ListViewsPager: - The response from ListViews. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 logging_config.ListViewsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.ListViewsRequest): - request = logging_config.ListViewsRequest(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_views] - - # 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.ListViewsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_view(self, - request: Union[logging_config.GetViewRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogView: - r"""Gets a view. - - Args: - request (Union[google.cloud.logging_v2.types.GetViewRequest, dict]): - The request object. The parameters to `GetView`. - 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.logging_v2.types.LogView: - Describes a view over logs in a - bucket. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a logging_config.GetViewRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.GetViewRequest): - request = logging_config.GetViewRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_view] - - # 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 create_view(self, - request: Union[logging_config.CreateViewRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogView: - r"""Creates a view over logs in a bucket. A bucket may - contain a maximum of 50 views. - - Args: - request (Union[google.cloud.logging_v2.types.CreateViewRequest, dict]): - The request object. The parameters to `CreateView`. - 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.logging_v2.types.LogView: - Describes a view over logs in a - bucket. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a logging_config.CreateViewRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.CreateViewRequest): - request = logging_config.CreateViewRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_view] - - # 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, - ) - - # Done; return the response. - return response - - def update_view(self, - request: Union[logging_config.UpdateViewRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogView: - r"""Updates a view. This method replaces the following fields in the - existing view with values from the new view: ``filter``. - - Args: - request (Union[google.cloud.logging_v2.types.UpdateViewRequest, dict]): - The request object. The parameters to `UpdateView`. - 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.logging_v2.types.LogView: - Describes a view over logs in a - bucket. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a logging_config.UpdateViewRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.UpdateViewRequest): - request = logging_config.UpdateViewRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_view] - - # 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_view(self, - request: Union[logging_config.DeleteViewRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a view from a bucket. - - Args: - request (Union[google.cloud.logging_v2.types.DeleteViewRequest, dict]): - The request object. The parameters to `DeleteView`. - 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. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a logging_config.DeleteViewRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.DeleteViewRequest): - request = logging_config.DeleteViewRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_view] - - # 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 list_sinks(self, - request: Union[logging_config.ListSinksRequest, dict] = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSinksPager: - r"""Lists sinks. - - Args: - request (Union[google.cloud.logging_v2.types.ListSinksRequest, dict]): - The request object. The parameters to `ListSinks`. - parent (str): - Required. The parent resource whose sinks are to be - listed: - - :: - - "projects/[PROJECT_ID]" - "organizations/[ORGANIZATION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]" - "folders/[FOLDER_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.logging_v2.services.config_service_v2.pagers.ListSinksPager: - Result returned from ListSinks. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 logging_config.ListSinksRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.ListSinksRequest): - request = logging_config.ListSinksRequest(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_sinks] - - # 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.ListSinksPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_sink(self, - request: Union[logging_config.GetSinkRequest, dict] = None, - *, - sink_name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogSink: - r"""Gets a sink. - - Args: - request (Union[google.cloud.logging_v2.types.GetSinkRequest, dict]): - The request object. The parameters to `GetSink`. - sink_name (str): - Required. The resource name of the sink: - - :: - - "projects/[PROJECT_ID]/sinks/[SINK_ID]" - "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - "folders/[FOLDER_ID]/sinks/[SINK_ID]" - - Example: ``"projects/my-project-id/sinks/my-sink-id"``. - - This corresponds to the ``sink_name`` 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.logging_v2.types.LogSink: - Describes a sink used to export log - entries to one of the following - destinations in any project: a Cloud - Storage bucket, a BigQuery dataset, or a - Cloud Pub/Sub topic. A logs filter - controls which log entries are exported. - The sink must be created within a - project, organization, billing account, - or folder. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([sink_name]) - 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 logging_config.GetSinkRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.GetSinkRequest): - request = logging_config.GetSinkRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if sink_name is not None: - request.sink_name = sink_name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_sink] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("sink_name", request.sink_name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_sink(self, - request: Union[logging_config.CreateSinkRequest, dict] = None, - *, - parent: str = None, - sink: logging_config.LogSink = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogSink: - r"""Creates a sink that exports specified log entries to a - destination. The export of newly-ingested log entries begins - immediately, unless the sink's ``writer_identity`` is not - permitted to write to the destination. A sink can export log - entries only from the resource owning the sink. - - Args: - request (Union[google.cloud.logging_v2.types.CreateSinkRequest, dict]): - The request object. The parameters to `CreateSink`. - parent (str): - Required. The resource in which to create the sink: - - :: - - "projects/[PROJECT_ID]" - "organizations/[ORGANIZATION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]" - "folders/[FOLDER_ID]" - - Examples: ``"projects/my-logging-project"``, - ``"organizations/123456789"``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - sink (google.cloud.logging_v2.types.LogSink): - Required. The new sink, whose ``name`` parameter is a - sink identifier that is not already in use. - - This corresponds to the ``sink`` 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.logging_v2.types.LogSink: - Describes a sink used to export log - entries to one of the following - destinations in any project: a Cloud - Storage bucket, a BigQuery dataset, or a - Cloud Pub/Sub topic. A logs filter - controls which log entries are exported. - The sink must be created within a - project, organization, billing account, - or folder. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, sink]) - 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 logging_config.CreateSinkRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.CreateSinkRequest): - request = logging_config.CreateSinkRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if sink is not None: - request.sink = sink - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_sink] - - # 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, - ) - - # Done; return the response. - return response - - def update_sink(self, - request: Union[logging_config.UpdateSinkRequest, dict] = None, - *, - sink_name: str = None, - sink: logging_config.LogSink = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogSink: - r"""Updates a sink. This method replaces the following fields in the - existing sink with values from the new sink: ``destination``, - and ``filter``. - - The updated sink might also have a new ``writer_identity``; see - the ``unique_writer_identity`` field. - - Args: - request (Union[google.cloud.logging_v2.types.UpdateSinkRequest, dict]): - The request object. The parameters to `UpdateSink`. - sink_name (str): - Required. The full resource name of the sink to update, - including the parent resource and the sink identifier: - - :: - - "projects/[PROJECT_ID]/sinks/[SINK_ID]" - "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - "folders/[FOLDER_ID]/sinks/[SINK_ID]" - - Example: ``"projects/my-project-id/sinks/my-sink-id"``. - - This corresponds to the ``sink_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - sink (google.cloud.logging_v2.types.LogSink): - Required. The updated sink, whose name is the same - identifier that appears as part of ``sink_name``. - - This corresponds to the ``sink`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask that specifies the fields in - ``sink`` that need an update. A sink field will be - overwritten if, and only if, it is in the update mask. - ``name`` and output only fields cannot be updated. - - An empty updateMask is temporarily treated as using the - following mask for backwards compatibility purposes: - destination,filter,includeChildren At some point in the - future, behavior will be removed and specifying an empty - updateMask will be an error. - - For a detailed ``FieldMask`` definition, see - https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask - - Example: ``updateMask=filter``. - - This corresponds to the ``update_mask`` 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.logging_v2.types.LogSink: - Describes a sink used to export log - entries to one of the following - destinations in any project: a Cloud - Storage bucket, a BigQuery dataset, or a - Cloud Pub/Sub topic. A logs filter - controls which log entries are exported. - The sink must be created within a - project, organization, billing account, - or folder. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([sink_name, sink, update_mask]) - 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 logging_config.UpdateSinkRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.UpdateSinkRequest): - request = logging_config.UpdateSinkRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if sink_name is not None: - request.sink_name = sink_name - if sink is not None: - request.sink = sink - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_sink] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("sink_name", request.sink_name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_sink(self, - request: Union[logging_config.DeleteSinkRequest, dict] = None, - *, - sink_name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a sink. If the sink has a unique ``writer_identity``, - then that service account is also deleted. - - Args: - request (Union[google.cloud.logging_v2.types.DeleteSinkRequest, dict]): - The request object. The parameters to `DeleteSink`. - sink_name (str): - Required. The full resource name of the sink to delete, - including the parent resource and the sink identifier: - - :: - - "projects/[PROJECT_ID]/sinks/[SINK_ID]" - "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - "folders/[FOLDER_ID]/sinks/[SINK_ID]" - - Example: ``"projects/my-project-id/sinks/my-sink-id"``. - - This corresponds to the ``sink_name`` 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. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([sink_name]) - 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 logging_config.DeleteSinkRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.DeleteSinkRequest): - request = logging_config.DeleteSinkRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if sink_name is not None: - request.sink_name = sink_name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_sink] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("sink_name", request.sink_name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def list_exclusions(self, - request: Union[logging_config.ListExclusionsRequest, dict] = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListExclusionsPager: - r"""Lists all the exclusions in a parent resource. - - Args: - request (Union[google.cloud.logging_v2.types.ListExclusionsRequest, dict]): - The request object. The parameters to `ListExclusions`. - parent (str): - Required. The parent resource whose exclusions are to be - listed. - - :: - - "projects/[PROJECT_ID]" - "organizations/[ORGANIZATION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]" - "folders/[FOLDER_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.logging_v2.services.config_service_v2.pagers.ListExclusionsPager: - Result returned from ListExclusions. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 logging_config.ListExclusionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.ListExclusionsRequest): - request = logging_config.ListExclusionsRequest(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_exclusions] - - # 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.ListExclusionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_exclusion(self, - request: Union[logging_config.GetExclusionRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogExclusion: - r"""Gets the description of an exclusion. - - Args: - request (Union[google.cloud.logging_v2.types.GetExclusionRequest, dict]): - The request object. The parameters to `GetExclusion`. - name (str): - Required. The resource name of an existing exclusion: - - :: - - "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" - "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" - "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" - - Example: - ``"projects/my-project-id/exclusions/my-exclusion-id"``. - - This corresponds to the ``name`` 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.logging_v2.types.LogExclusion: - Specifies a set of log entries that - are not to be stored in Logging. If your - GCP resource receives a large volume of - logs, you can use exclusions to reduce - your chargeable logs. Exclusions are - processed after log sinks, so you can - export log entries before they are - excluded. Note that organization-level - and folder-level exclusions don't apply - to child resources, and that you can't - exclude audit log entries. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - 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 logging_config.GetExclusionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.GetExclusionRequest): - request = logging_config.GetExclusionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_exclusion] - - # 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 create_exclusion(self, - request: Union[logging_config.CreateExclusionRequest, dict] = None, - *, - parent: str = None, - exclusion: logging_config.LogExclusion = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogExclusion: - r"""Creates a new exclusion in a specified parent - resource. Only log entries belonging to that resource - can be excluded. You can have up to 10 exclusions in a - resource. - - Args: - request (Union[google.cloud.logging_v2.types.CreateExclusionRequest, dict]): - The request object. The parameters to `CreateExclusion`. - parent (str): - Required. The parent resource in which to create the - exclusion: - - :: - - "projects/[PROJECT_ID]" - "organizations/[ORGANIZATION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]" - "folders/[FOLDER_ID]" - - Examples: ``"projects/my-logging-project"``, - ``"organizations/123456789"``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - exclusion (google.cloud.logging_v2.types.LogExclusion): - Required. The new exclusion, whose ``name`` parameter is - an exclusion name that is not already used in the parent - resource. - - This corresponds to the ``exclusion`` 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.logging_v2.types.LogExclusion: - Specifies a set of log entries that - are not to be stored in Logging. If your - GCP resource receives a large volume of - logs, you can use exclusions to reduce - your chargeable logs. Exclusions are - processed after log sinks, so you can - export log entries before they are - excluded. Note that organization-level - and folder-level exclusions don't apply - to child resources, and that you can't - exclude audit log entries. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, exclusion]) - 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 logging_config.CreateExclusionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.CreateExclusionRequest): - request = logging_config.CreateExclusionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if exclusion is not None: - request.exclusion = exclusion - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_exclusion] - - # 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, - ) - - # Done; return the response. - return response - - def update_exclusion(self, - request: Union[logging_config.UpdateExclusionRequest, dict] = None, - *, - name: str = None, - exclusion: logging_config.LogExclusion = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.LogExclusion: - r"""Changes one or more properties of an existing - exclusion. - - Args: - request (Union[google.cloud.logging_v2.types.UpdateExclusionRequest, dict]): - The request object. The parameters to `UpdateExclusion`. - name (str): - Required. The resource name of the exclusion to update: - - :: - - "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" - "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" - "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" - - Example: - ``"projects/my-project-id/exclusions/my-exclusion-id"``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - exclusion (google.cloud.logging_v2.types.LogExclusion): - Required. New values for the existing exclusion. Only - the fields specified in ``update_mask`` are relevant. - - This corresponds to the ``exclusion`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. A non-empty list of fields to change in the - existing exclusion. New values for the fields are taken - from the corresponding fields in the - [LogExclusion][google.logging.v2.LogExclusion] included - in this request. Fields not mentioned in ``update_mask`` - are not changed and are ignored in the request. - - For example, to change the filter and description of an - exclusion, specify an ``update_mask`` of - ``"filter,description"``. - - This corresponds to the ``update_mask`` 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.logging_v2.types.LogExclusion: - Specifies a set of log entries that - are not to be stored in Logging. If your - GCP resource receives a large volume of - logs, you can use exclusions to reduce - your chargeable logs. Exclusions are - processed after log sinks, so you can - export log entries before they are - excluded. Note that organization-level - and folder-level exclusions don't apply - to child resources, and that you can't - exclude audit log entries. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, exclusion, update_mask]) - 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 logging_config.UpdateExclusionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.UpdateExclusionRequest): - request = logging_config.UpdateExclusionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if exclusion is not None: - request.exclusion = exclusion - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_exclusion] - - # 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_exclusion(self, - request: Union[logging_config.DeleteExclusionRequest, dict] = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an exclusion. - - Args: - request (Union[google.cloud.logging_v2.types.DeleteExclusionRequest, dict]): - The request object. The parameters to `DeleteExclusion`. - name (str): - Required. The resource name of an existing exclusion to - delete: - - :: - - "projects/[PROJECT_ID]/exclusions/[EXCLUSION_ID]" - "organizations/[ORGANIZATION_ID]/exclusions/[EXCLUSION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/exclusions/[EXCLUSION_ID]" - "folders/[FOLDER_ID]/exclusions/[EXCLUSION_ID]" - - Example: - ``"projects/my-project-id/exclusions/my-exclusion-id"``. - - This corresponds to the ``name`` 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. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - 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 logging_config.DeleteExclusionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.DeleteExclusionRequest): - request = logging_config.DeleteExclusionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_exclusion] - - # 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 get_cmek_settings(self, - request: Union[logging_config.GetCmekSettingsRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.CmekSettings: - r"""Gets the Logs Router CMEK settings for the given resource. - - Note: CMEK for the Logs Router can currently only be configured - for GCP organizations. Once configured, it applies to all - projects and folders in the GCP organization. - - See `Enabling CMEK for Logs - Router `__ - for more information. - - Args: - request (Union[google.cloud.logging_v2.types.GetCmekSettingsRequest, dict]): - The request object. The parameters to - [GetCmekSettings][google.logging.v2.ConfigServiceV2.GetCmekSettings]. - See [Enabling CMEK for Logs - Router](https://cloud.google.com/logging/docs/routing/managed- - encryption) for more information. - 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.logging_v2.types.CmekSettings: - Describes the customer-managed encryption key (CMEK) settings associated with - a project, folder, organization, billing account, or - flexible resource. - - Note: CMEK for the Logs Router can currently only be - configured for GCP organizations. Once configured, it - applies to all projects and folders in the GCP - organization. - - See [Enabling CMEK for Logs - Router](\ https://cloud.google.com/logging/docs/routing/managed-encryption) - for more information. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a logging_config.GetCmekSettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.GetCmekSettingsRequest): - request = logging_config.GetCmekSettingsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_cmek_settings] - - # 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 update_cmek_settings(self, - request: Union[logging_config.UpdateCmekSettingsRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_config.CmekSettings: - r"""Updates the Logs Router CMEK settings for the given resource. - - Note: CMEK for the Logs Router can currently only be configured - for GCP organizations. Once configured, it applies to all - projects and folders in the GCP organization. - - [UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings] - will fail if 1) ``kms_key_name`` is invalid, or 2) the - associated service account does not have the required - ``roles/cloudkms.cryptoKeyEncrypterDecrypter`` role assigned for - the key, or 3) access to the key is disabled. - - See `Enabling CMEK for Logs - Router `__ - for more information. - - Args: - request (Union[google.cloud.logging_v2.types.UpdateCmekSettingsRequest, dict]): - The request object. The parameters to - [UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings]. - See [Enabling CMEK for Logs - Router](https://cloud.google.com/logging/docs/routing/managed- - encryption) for more information. - 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.logging_v2.types.CmekSettings: - Describes the customer-managed encryption key (CMEK) settings associated with - a project, folder, organization, billing account, or - flexible resource. - - Note: CMEK for the Logs Router can currently only be - configured for GCP organizations. Once configured, it - applies to all projects and folders in the GCP - organization. - - See [Enabling CMEK for Logs - Router](\ https://cloud.google.com/logging/docs/routing/managed-encryption) - for more information. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a logging_config.UpdateCmekSettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_config.UpdateCmekSettingsRequest): - request = logging_config.UpdateCmekSettingsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_cmek_settings] - - # 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-logging", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ConfigServiceV2Client", -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/pagers.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/pagers.py deleted file mode 100644 index 43e0084a..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/pagers.py +++ /dev/null @@ -1,506 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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, Sequence, Tuple, Optional, Iterator - -from google.cloud.logging_v2.types import logging_config - - -class ListBucketsPager: - """A pager for iterating through ``list_buckets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.logging_v2.types.ListBucketsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``buckets`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListBuckets`` requests and continue to iterate - through the ``buckets`` field on the - corresponding responses. - - All the usual :class:`google.cloud.logging_v2.types.ListBucketsResponse` - 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[..., logging_config.ListBucketsResponse], - request: logging_config.ListBucketsRequest, - response: logging_config.ListBucketsResponse, - *, - 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.logging_v2.types.ListBucketsRequest): - The initial request object. - response (google.cloud.logging_v2.types.ListBucketsResponse): - 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 = logging_config.ListBucketsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[logging_config.ListBucketsResponse]: - 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[logging_config.LogBucket]: - for page in self.pages: - yield from page.buckets - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListBucketsAsyncPager: - """A pager for iterating through ``list_buckets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.logging_v2.types.ListBucketsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``buckets`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListBuckets`` requests and continue to iterate - through the ``buckets`` field on the - corresponding responses. - - All the usual :class:`google.cloud.logging_v2.types.ListBucketsResponse` - 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[logging_config.ListBucketsResponse]], - request: logging_config.ListBucketsRequest, - response: logging_config.ListBucketsResponse, - *, - 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.logging_v2.types.ListBucketsRequest): - The initial request object. - response (google.cloud.logging_v2.types.ListBucketsResponse): - 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 = logging_config.ListBucketsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[logging_config.ListBucketsResponse]: - 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[logging_config.LogBucket]: - async def async_generator(): - async for page in self.pages: - for response in page.buckets: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListViewsPager: - """A pager for iterating through ``list_views`` requests. - - This class thinly wraps an initial - :class:`google.cloud.logging_v2.types.ListViewsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``views`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListViews`` requests and continue to iterate - through the ``views`` field on the - corresponding responses. - - All the usual :class:`google.cloud.logging_v2.types.ListViewsResponse` - 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[..., logging_config.ListViewsResponse], - request: logging_config.ListViewsRequest, - response: logging_config.ListViewsResponse, - *, - 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.logging_v2.types.ListViewsRequest): - The initial request object. - response (google.cloud.logging_v2.types.ListViewsResponse): - 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 = logging_config.ListViewsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[logging_config.ListViewsResponse]: - 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[logging_config.LogView]: - for page in self.pages: - yield from page.views - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListViewsAsyncPager: - """A pager for iterating through ``list_views`` requests. - - This class thinly wraps an initial - :class:`google.cloud.logging_v2.types.ListViewsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``views`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListViews`` requests and continue to iterate - through the ``views`` field on the - corresponding responses. - - All the usual :class:`google.cloud.logging_v2.types.ListViewsResponse` - 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[logging_config.ListViewsResponse]], - request: logging_config.ListViewsRequest, - response: logging_config.ListViewsResponse, - *, - 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.logging_v2.types.ListViewsRequest): - The initial request object. - response (google.cloud.logging_v2.types.ListViewsResponse): - 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 = logging_config.ListViewsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[logging_config.ListViewsResponse]: - 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[logging_config.LogView]: - async def async_generator(): - async for page in self.pages: - for response in page.views: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSinksPager: - """A pager for iterating through ``list_sinks`` requests. - - This class thinly wraps an initial - :class:`google.cloud.logging_v2.types.ListSinksResponse` object, and - provides an ``__iter__`` method to iterate through its - ``sinks`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSinks`` requests and continue to iterate - through the ``sinks`` field on the - corresponding responses. - - All the usual :class:`google.cloud.logging_v2.types.ListSinksResponse` - 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[..., logging_config.ListSinksResponse], - request: logging_config.ListSinksRequest, - response: logging_config.ListSinksResponse, - *, - 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.logging_v2.types.ListSinksRequest): - The initial request object. - response (google.cloud.logging_v2.types.ListSinksResponse): - 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 = logging_config.ListSinksRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[logging_config.ListSinksResponse]: - 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[logging_config.LogSink]: - for page in self.pages: - yield from page.sinks - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSinksAsyncPager: - """A pager for iterating through ``list_sinks`` requests. - - This class thinly wraps an initial - :class:`google.cloud.logging_v2.types.ListSinksResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``sinks`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSinks`` requests and continue to iterate - through the ``sinks`` field on the - corresponding responses. - - All the usual :class:`google.cloud.logging_v2.types.ListSinksResponse` - 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[logging_config.ListSinksResponse]], - request: logging_config.ListSinksRequest, - response: logging_config.ListSinksResponse, - *, - 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.logging_v2.types.ListSinksRequest): - The initial request object. - response (google.cloud.logging_v2.types.ListSinksResponse): - 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 = logging_config.ListSinksRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[logging_config.ListSinksResponse]: - 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[logging_config.LogSink]: - async def async_generator(): - async for page in self.pages: - for response in page.sinks: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListExclusionsPager: - """A pager for iterating through ``list_exclusions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.logging_v2.types.ListExclusionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``exclusions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListExclusions`` requests and continue to iterate - through the ``exclusions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.logging_v2.types.ListExclusionsResponse` - 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[..., logging_config.ListExclusionsResponse], - request: logging_config.ListExclusionsRequest, - response: logging_config.ListExclusionsResponse, - *, - 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.logging_v2.types.ListExclusionsRequest): - The initial request object. - response (google.cloud.logging_v2.types.ListExclusionsResponse): - 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 = logging_config.ListExclusionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[logging_config.ListExclusionsResponse]: - 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[logging_config.LogExclusion]: - for page in self.pages: - yield from page.exclusions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListExclusionsAsyncPager: - """A pager for iterating through ``list_exclusions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.logging_v2.types.ListExclusionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``exclusions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListExclusions`` requests and continue to iterate - through the ``exclusions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.logging_v2.types.ListExclusionsResponse` - 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[logging_config.ListExclusionsResponse]], - request: logging_config.ListExclusionsRequest, - response: logging_config.ListExclusionsResponse, - *, - 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.logging_v2.types.ListExclusionsRequest): - The initial request object. - response (google.cloud.logging_v2.types.ListExclusionsResponse): - 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 = logging_config.ListExclusionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[logging_config.ListExclusionsResponse]: - 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[logging_config.LogExclusion]: - async def async_generator(): - async for page in self.pages: - for response in page.exclusions: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/transports/__init__.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/transports/__init__.py deleted file mode 100644 index 6e18c331..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 ConfigServiceV2Transport -from .grpc import ConfigServiceV2GrpcTransport -from .grpc_asyncio import ConfigServiceV2GrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ConfigServiceV2Transport]] -_transport_registry['grpc'] = ConfigServiceV2GrpcTransport -_transport_registry['grpc_asyncio'] = ConfigServiceV2GrpcAsyncIOTransport - -__all__ = ( - 'ConfigServiceV2Transport', - 'ConfigServiceV2GrpcTransport', - 'ConfigServiceV2GrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/transports/base.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/transports/base.py deleted file mode 100644 index e7f0db9d..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/transports/base.py +++ /dev/null @@ -1,536 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.logging_v2.types import logging_config -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-logging', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class ConfigServiceV2Transport(abc.ABC): - """Abstract transport class for ConfigServiceV2.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - ) - - DEFAULT_HOST: str = 'logging.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, - **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. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, 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) - - # 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 - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_buckets: gapic_v1.method.wrap_method( - self.list_buckets, - default_timeout=None, - client_info=client_info, - ), - self.get_bucket: gapic_v1.method.wrap_method( - self.get_bucket, - default_timeout=None, - client_info=client_info, - ), - self.create_bucket: gapic_v1.method.wrap_method( - self.create_bucket, - default_timeout=None, - client_info=client_info, - ), - self.update_bucket: gapic_v1.method.wrap_method( - self.update_bucket, - default_timeout=None, - client_info=client_info, - ), - self.delete_bucket: gapic_v1.method.wrap_method( - self.delete_bucket, - default_timeout=None, - client_info=client_info, - ), - self.undelete_bucket: gapic_v1.method.wrap_method( - self.undelete_bucket, - default_timeout=None, - client_info=client_info, - ), - self.list_views: gapic_v1.method.wrap_method( - self.list_views, - default_timeout=None, - client_info=client_info, - ), - self.get_view: gapic_v1.method.wrap_method( - self.get_view, - default_timeout=None, - client_info=client_info, - ), - self.create_view: gapic_v1.method.wrap_method( - self.create_view, - default_timeout=None, - client_info=client_info, - ), - self.update_view: gapic_v1.method.wrap_method( - self.update_view, - default_timeout=None, - client_info=client_info, - ), - self.delete_view: gapic_v1.method.wrap_method( - self.delete_view, - default_timeout=None, - client_info=client_info, - ), - self.list_sinks: gapic_v1.method.wrap_method( - self.list_sinks, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_sink: gapic_v1.method.wrap_method( - self.get_sink, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_sink: gapic_v1.method.wrap_method( - self.create_sink, - default_timeout=120.0, - client_info=client_info, - ), - self.update_sink: gapic_v1.method.wrap_method( - self.update_sink, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_sink: gapic_v1.method.wrap_method( - self.delete_sink, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_exclusions: gapic_v1.method.wrap_method( - self.list_exclusions, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_exclusion: gapic_v1.method.wrap_method( - self.get_exclusion, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_exclusion: gapic_v1.method.wrap_method( - self.create_exclusion, - default_timeout=120.0, - client_info=client_info, - ), - self.update_exclusion: gapic_v1.method.wrap_method( - self.update_exclusion, - default_timeout=120.0, - client_info=client_info, - ), - self.delete_exclusion: gapic_v1.method.wrap_method( - self.delete_exclusion, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_cmek_settings: gapic_v1.method.wrap_method( - self.get_cmek_settings, - default_timeout=None, - client_info=client_info, - ), - self.update_cmek_settings: gapic_v1.method.wrap_method( - self.update_cmek_settings, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def list_buckets(self) -> Callable[ - [logging_config.ListBucketsRequest], - Union[ - logging_config.ListBucketsResponse, - Awaitable[logging_config.ListBucketsResponse] - ]]: - raise NotImplementedError() - - @property - def get_bucket(self) -> Callable[ - [logging_config.GetBucketRequest], - Union[ - logging_config.LogBucket, - Awaitable[logging_config.LogBucket] - ]]: - raise NotImplementedError() - - @property - def create_bucket(self) -> Callable[ - [logging_config.CreateBucketRequest], - Union[ - logging_config.LogBucket, - Awaitable[logging_config.LogBucket] - ]]: - raise NotImplementedError() - - @property - def update_bucket(self) -> Callable[ - [logging_config.UpdateBucketRequest], - Union[ - logging_config.LogBucket, - Awaitable[logging_config.LogBucket] - ]]: - raise NotImplementedError() - - @property - def delete_bucket(self) -> Callable[ - [logging_config.DeleteBucketRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def undelete_bucket(self) -> Callable[ - [logging_config.UndeleteBucketRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_views(self) -> Callable[ - [logging_config.ListViewsRequest], - Union[ - logging_config.ListViewsResponse, - Awaitable[logging_config.ListViewsResponse] - ]]: - raise NotImplementedError() - - @property - def get_view(self) -> Callable[ - [logging_config.GetViewRequest], - Union[ - logging_config.LogView, - Awaitable[logging_config.LogView] - ]]: - raise NotImplementedError() - - @property - def create_view(self) -> Callable[ - [logging_config.CreateViewRequest], - Union[ - logging_config.LogView, - Awaitable[logging_config.LogView] - ]]: - raise NotImplementedError() - - @property - def update_view(self) -> Callable[ - [logging_config.UpdateViewRequest], - Union[ - logging_config.LogView, - Awaitable[logging_config.LogView] - ]]: - raise NotImplementedError() - - @property - def delete_view(self) -> Callable[ - [logging_config.DeleteViewRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_sinks(self) -> Callable[ - [logging_config.ListSinksRequest], - Union[ - logging_config.ListSinksResponse, - Awaitable[logging_config.ListSinksResponse] - ]]: - raise NotImplementedError() - - @property - def get_sink(self) -> Callable[ - [logging_config.GetSinkRequest], - Union[ - logging_config.LogSink, - Awaitable[logging_config.LogSink] - ]]: - raise NotImplementedError() - - @property - def create_sink(self) -> Callable[ - [logging_config.CreateSinkRequest], - Union[ - logging_config.LogSink, - Awaitable[logging_config.LogSink] - ]]: - raise NotImplementedError() - - @property - def update_sink(self) -> Callable[ - [logging_config.UpdateSinkRequest], - Union[ - logging_config.LogSink, - Awaitable[logging_config.LogSink] - ]]: - raise NotImplementedError() - - @property - def delete_sink(self) -> Callable[ - [logging_config.DeleteSinkRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_exclusions(self) -> Callable[ - [logging_config.ListExclusionsRequest], - Union[ - logging_config.ListExclusionsResponse, - Awaitable[logging_config.ListExclusionsResponse] - ]]: - raise NotImplementedError() - - @property - def get_exclusion(self) -> Callable[ - [logging_config.GetExclusionRequest], - Union[ - logging_config.LogExclusion, - Awaitable[logging_config.LogExclusion] - ]]: - raise NotImplementedError() - - @property - def create_exclusion(self) -> Callable[ - [logging_config.CreateExclusionRequest], - Union[ - logging_config.LogExclusion, - Awaitable[logging_config.LogExclusion] - ]]: - raise NotImplementedError() - - @property - def update_exclusion(self) -> Callable[ - [logging_config.UpdateExclusionRequest], - Union[ - logging_config.LogExclusion, - Awaitable[logging_config.LogExclusion] - ]]: - raise NotImplementedError() - - @property - def delete_exclusion(self) -> Callable[ - [logging_config.DeleteExclusionRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_cmek_settings(self) -> Callable[ - [logging_config.GetCmekSettingsRequest], - Union[ - logging_config.CmekSettings, - Awaitable[logging_config.CmekSettings] - ]]: - raise NotImplementedError() - - @property - def update_cmek_settings(self) -> Callable[ - [logging_config.UpdateCmekSettingsRequest], - Union[ - logging_config.CmekSettings, - Awaitable[logging_config.CmekSettings] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'ConfigServiceV2Transport', -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py deleted file mode 100644 index 94e4af68..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/transports/grpc.py +++ /dev/null @@ -1,878 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.logging_v2.types import logging_config -from google.protobuf import empty_pb2 # type: ignore -from .base import ConfigServiceV2Transport, DEFAULT_CLIENT_INFO - - -class ConfigServiceV2GrpcTransport(ConfigServiceV2Transport): - """gRPC backend transport for ConfigServiceV2. - - Service for configuring sinks used to route log entries. - - 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 = 'logging.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, - ) -> 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] = {} - - 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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 = 'logging.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 list_buckets(self) -> Callable[ - [logging_config.ListBucketsRequest], - logging_config.ListBucketsResponse]: - r"""Return a callable for the list buckets method over gRPC. - - Lists buckets. - - Returns: - Callable[[~.ListBucketsRequest], - ~.ListBucketsResponse]: - 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_buckets' not in self._stubs: - self._stubs['list_buckets'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/ListBuckets', - request_serializer=logging_config.ListBucketsRequest.serialize, - response_deserializer=logging_config.ListBucketsResponse.deserialize, - ) - return self._stubs['list_buckets'] - - @property - def get_bucket(self) -> Callable[ - [logging_config.GetBucketRequest], - logging_config.LogBucket]: - r"""Return a callable for the get bucket method over gRPC. - - Gets a bucket. - - Returns: - Callable[[~.GetBucketRequest], - ~.LogBucket]: - 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 'get_bucket' not in self._stubs: - self._stubs['get_bucket'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetBucket', - request_serializer=logging_config.GetBucketRequest.serialize, - response_deserializer=logging_config.LogBucket.deserialize, - ) - return self._stubs['get_bucket'] - - @property - def create_bucket(self) -> Callable[ - [logging_config.CreateBucketRequest], - logging_config.LogBucket]: - r"""Return a callable for the create bucket method over gRPC. - - Creates a bucket that can be used to store log - entries. Once a bucket has been created, the region - cannot be changed. - - Returns: - Callable[[~.CreateBucketRequest], - ~.LogBucket]: - 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 'create_bucket' not in self._stubs: - self._stubs['create_bucket'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CreateBucket', - request_serializer=logging_config.CreateBucketRequest.serialize, - response_deserializer=logging_config.LogBucket.deserialize, - ) - return self._stubs['create_bucket'] - - @property - def update_bucket(self) -> Callable[ - [logging_config.UpdateBucketRequest], - logging_config.LogBucket]: - r"""Return a callable for the update bucket method over gRPC. - - Updates a bucket. This method replaces the following fields in - the existing bucket with values from the new bucket: - ``retention_period`` - - If the retention period is decreased and the bucket is locked, - FAILED_PRECONDITION will be returned. - - If the bucket has a LifecycleState of DELETE_REQUESTED, - FAILED_PRECONDITION will be returned. - - A buckets region may not be modified after it is created. - - Returns: - Callable[[~.UpdateBucketRequest], - ~.LogBucket]: - 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 'update_bucket' not in self._stubs: - self._stubs['update_bucket'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateBucket', - request_serializer=logging_config.UpdateBucketRequest.serialize, - response_deserializer=logging_config.LogBucket.deserialize, - ) - return self._stubs['update_bucket'] - - @property - def delete_bucket(self) -> Callable[ - [logging_config.DeleteBucketRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete bucket method over gRPC. - - Deletes a bucket. Moves the bucket to the DELETE_REQUESTED - state. After 7 days, the bucket will be purged and all logs in - the bucket will be permanently deleted. - - Returns: - Callable[[~.DeleteBucketRequest], - ~.Empty]: - 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 'delete_bucket' not in self._stubs: - self._stubs['delete_bucket'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/DeleteBucket', - request_serializer=logging_config.DeleteBucketRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_bucket'] - - @property - def undelete_bucket(self) -> Callable[ - [logging_config.UndeleteBucketRequest], - empty_pb2.Empty]: - r"""Return a callable for the undelete bucket method over gRPC. - - Undeletes a bucket. A bucket that has been deleted - may be undeleted within the grace period of 7 days. - - Returns: - Callable[[~.UndeleteBucketRequest], - ~.Empty]: - 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 'undelete_bucket' not in self._stubs: - self._stubs['undelete_bucket'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UndeleteBucket', - request_serializer=logging_config.UndeleteBucketRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['undelete_bucket'] - - @property - def list_views(self) -> Callable[ - [logging_config.ListViewsRequest], - logging_config.ListViewsResponse]: - r"""Return a callable for the list views method over gRPC. - - Lists views on a bucket. - - Returns: - Callable[[~.ListViewsRequest], - ~.ListViewsResponse]: - 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_views' not in self._stubs: - self._stubs['list_views'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/ListViews', - request_serializer=logging_config.ListViewsRequest.serialize, - response_deserializer=logging_config.ListViewsResponse.deserialize, - ) - return self._stubs['list_views'] - - @property - def get_view(self) -> Callable[ - [logging_config.GetViewRequest], - logging_config.LogView]: - r"""Return a callable for the get view method over gRPC. - - Gets a view. - - Returns: - Callable[[~.GetViewRequest], - ~.LogView]: - 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 'get_view' not in self._stubs: - self._stubs['get_view'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetView', - request_serializer=logging_config.GetViewRequest.serialize, - response_deserializer=logging_config.LogView.deserialize, - ) - return self._stubs['get_view'] - - @property - def create_view(self) -> Callable[ - [logging_config.CreateViewRequest], - logging_config.LogView]: - r"""Return a callable for the create view method over gRPC. - - Creates a view over logs in a bucket. A bucket may - contain a maximum of 50 views. - - Returns: - Callable[[~.CreateViewRequest], - ~.LogView]: - 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 'create_view' not in self._stubs: - self._stubs['create_view'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CreateView', - request_serializer=logging_config.CreateViewRequest.serialize, - response_deserializer=logging_config.LogView.deserialize, - ) - return self._stubs['create_view'] - - @property - def update_view(self) -> Callable[ - [logging_config.UpdateViewRequest], - logging_config.LogView]: - r"""Return a callable for the update view method over gRPC. - - Updates a view. This method replaces the following fields in the - existing view with values from the new view: ``filter``. - - Returns: - Callable[[~.UpdateViewRequest], - ~.LogView]: - 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 'update_view' not in self._stubs: - self._stubs['update_view'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateView', - request_serializer=logging_config.UpdateViewRequest.serialize, - response_deserializer=logging_config.LogView.deserialize, - ) - return self._stubs['update_view'] - - @property - def delete_view(self) -> Callable[ - [logging_config.DeleteViewRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete view method over gRPC. - - Deletes a view from a bucket. - - Returns: - Callable[[~.DeleteViewRequest], - ~.Empty]: - 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 'delete_view' not in self._stubs: - self._stubs['delete_view'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/DeleteView', - request_serializer=logging_config.DeleteViewRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_view'] - - @property - def list_sinks(self) -> Callable[ - [logging_config.ListSinksRequest], - logging_config.ListSinksResponse]: - r"""Return a callable for the list sinks method over gRPC. - - Lists sinks. - - Returns: - Callable[[~.ListSinksRequest], - ~.ListSinksResponse]: - 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_sinks' not in self._stubs: - self._stubs['list_sinks'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/ListSinks', - request_serializer=logging_config.ListSinksRequest.serialize, - response_deserializer=logging_config.ListSinksResponse.deserialize, - ) - return self._stubs['list_sinks'] - - @property - def get_sink(self) -> Callable[ - [logging_config.GetSinkRequest], - logging_config.LogSink]: - r"""Return a callable for the get sink method over gRPC. - - Gets a sink. - - Returns: - Callable[[~.GetSinkRequest], - ~.LogSink]: - 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 'get_sink' not in self._stubs: - self._stubs['get_sink'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetSink', - request_serializer=logging_config.GetSinkRequest.serialize, - response_deserializer=logging_config.LogSink.deserialize, - ) - return self._stubs['get_sink'] - - @property - def create_sink(self) -> Callable[ - [logging_config.CreateSinkRequest], - logging_config.LogSink]: - r"""Return a callable for the create sink method over gRPC. - - Creates a sink that exports specified log entries to a - destination. The export of newly-ingested log entries begins - immediately, unless the sink's ``writer_identity`` is not - permitted to write to the destination. A sink can export log - entries only from the resource owning the sink. - - Returns: - Callable[[~.CreateSinkRequest], - ~.LogSink]: - 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 'create_sink' not in self._stubs: - self._stubs['create_sink'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CreateSink', - request_serializer=logging_config.CreateSinkRequest.serialize, - response_deserializer=logging_config.LogSink.deserialize, - ) - return self._stubs['create_sink'] - - @property - def update_sink(self) -> Callable[ - [logging_config.UpdateSinkRequest], - logging_config.LogSink]: - r"""Return a callable for the update sink method over gRPC. - - Updates a sink. This method replaces the following fields in the - existing sink with values from the new sink: ``destination``, - and ``filter``. - - The updated sink might also have a new ``writer_identity``; see - the ``unique_writer_identity`` field. - - Returns: - Callable[[~.UpdateSinkRequest], - ~.LogSink]: - 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 'update_sink' not in self._stubs: - self._stubs['update_sink'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateSink', - request_serializer=logging_config.UpdateSinkRequest.serialize, - response_deserializer=logging_config.LogSink.deserialize, - ) - return self._stubs['update_sink'] - - @property - def delete_sink(self) -> Callable[ - [logging_config.DeleteSinkRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete sink method over gRPC. - - Deletes a sink. If the sink has a unique ``writer_identity``, - then that service account is also deleted. - - Returns: - Callable[[~.DeleteSinkRequest], - ~.Empty]: - 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 'delete_sink' not in self._stubs: - self._stubs['delete_sink'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/DeleteSink', - request_serializer=logging_config.DeleteSinkRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_sink'] - - @property - def list_exclusions(self) -> Callable[ - [logging_config.ListExclusionsRequest], - logging_config.ListExclusionsResponse]: - r"""Return a callable for the list exclusions method over gRPC. - - Lists all the exclusions in a parent resource. - - Returns: - Callable[[~.ListExclusionsRequest], - ~.ListExclusionsResponse]: - 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_exclusions' not in self._stubs: - self._stubs['list_exclusions'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/ListExclusions', - request_serializer=logging_config.ListExclusionsRequest.serialize, - response_deserializer=logging_config.ListExclusionsResponse.deserialize, - ) - return self._stubs['list_exclusions'] - - @property - def get_exclusion(self) -> Callable[ - [logging_config.GetExclusionRequest], - logging_config.LogExclusion]: - r"""Return a callable for the get exclusion method over gRPC. - - Gets the description of an exclusion. - - Returns: - Callable[[~.GetExclusionRequest], - ~.LogExclusion]: - 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 'get_exclusion' not in self._stubs: - self._stubs['get_exclusion'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetExclusion', - request_serializer=logging_config.GetExclusionRequest.serialize, - response_deserializer=logging_config.LogExclusion.deserialize, - ) - return self._stubs['get_exclusion'] - - @property - def create_exclusion(self) -> Callable[ - [logging_config.CreateExclusionRequest], - logging_config.LogExclusion]: - r"""Return a callable for the create exclusion method over gRPC. - - Creates a new exclusion in a specified parent - resource. Only log entries belonging to that resource - can be excluded. You can have up to 10 exclusions in a - resource. - - Returns: - Callable[[~.CreateExclusionRequest], - ~.LogExclusion]: - 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 'create_exclusion' not in self._stubs: - self._stubs['create_exclusion'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CreateExclusion', - request_serializer=logging_config.CreateExclusionRequest.serialize, - response_deserializer=logging_config.LogExclusion.deserialize, - ) - return self._stubs['create_exclusion'] - - @property - def update_exclusion(self) -> Callable[ - [logging_config.UpdateExclusionRequest], - logging_config.LogExclusion]: - r"""Return a callable for the update exclusion method over gRPC. - - Changes one or more properties of an existing - exclusion. - - Returns: - Callable[[~.UpdateExclusionRequest], - ~.LogExclusion]: - 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 'update_exclusion' not in self._stubs: - self._stubs['update_exclusion'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateExclusion', - request_serializer=logging_config.UpdateExclusionRequest.serialize, - response_deserializer=logging_config.LogExclusion.deserialize, - ) - return self._stubs['update_exclusion'] - - @property - def delete_exclusion(self) -> Callable[ - [logging_config.DeleteExclusionRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete exclusion method over gRPC. - - Deletes an exclusion. - - Returns: - Callable[[~.DeleteExclusionRequest], - ~.Empty]: - 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 'delete_exclusion' not in self._stubs: - self._stubs['delete_exclusion'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/DeleteExclusion', - request_serializer=logging_config.DeleteExclusionRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_exclusion'] - - @property - def get_cmek_settings(self) -> Callable[ - [logging_config.GetCmekSettingsRequest], - logging_config.CmekSettings]: - r"""Return a callable for the get cmek settings method over gRPC. - - Gets the Logs Router CMEK settings for the given resource. - - Note: CMEK for the Logs Router can currently only be configured - for GCP organizations. Once configured, it applies to all - projects and folders in the GCP organization. - - See `Enabling CMEK for Logs - Router `__ - for more information. - - Returns: - Callable[[~.GetCmekSettingsRequest], - ~.CmekSettings]: - 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 'get_cmek_settings' not in self._stubs: - self._stubs['get_cmek_settings'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetCmekSettings', - request_serializer=logging_config.GetCmekSettingsRequest.serialize, - response_deserializer=logging_config.CmekSettings.deserialize, - ) - return self._stubs['get_cmek_settings'] - - @property - def update_cmek_settings(self) -> Callable[ - [logging_config.UpdateCmekSettingsRequest], - logging_config.CmekSettings]: - r"""Return a callable for the update cmek settings method over gRPC. - - Updates the Logs Router CMEK settings for the given resource. - - Note: CMEK for the Logs Router can currently only be configured - for GCP organizations. Once configured, it applies to all - projects and folders in the GCP organization. - - [UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings] - will fail if 1) ``kms_key_name`` is invalid, or 2) the - associated service account does not have the required - ``roles/cloudkms.cryptoKeyEncrypterDecrypter`` role assigned for - the key, or 3) access to the key is disabled. - - See `Enabling CMEK for Logs - Router `__ - for more information. - - Returns: - Callable[[~.UpdateCmekSettingsRequest], - ~.CmekSettings]: - 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 'update_cmek_settings' not in self._stubs: - self._stubs['update_cmek_settings'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateCmekSettings', - request_serializer=logging_config.UpdateCmekSettingsRequest.serialize, - response_deserializer=logging_config.CmekSettings.deserialize, - ) - return self._stubs['update_cmek_settings'] - - -__all__ = ( - 'ConfigServiceV2GrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/transports/grpc_asyncio.py deleted file mode 100644 index 78e442d8..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/config_service_v2/transports/grpc_asyncio.py +++ /dev/null @@ -1,882 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.logging_v2.types import logging_config -from google.protobuf import empty_pb2 # type: ignore -from .base import ConfigServiceV2Transport, DEFAULT_CLIENT_INFO -from .grpc import ConfigServiceV2GrpcTransport - - -class ConfigServiceV2GrpcAsyncIOTransport(ConfigServiceV2Transport): - """gRPC AsyncIO backend transport for ConfigServiceV2. - - Service for configuring sinks used to route log entries. - - 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 = 'logging.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 = 'logging.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, - ) -> 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] = {} - - 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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 list_buckets(self) -> Callable[ - [logging_config.ListBucketsRequest], - Awaitable[logging_config.ListBucketsResponse]]: - r"""Return a callable for the list buckets method over gRPC. - - Lists buckets. - - Returns: - Callable[[~.ListBucketsRequest], - Awaitable[~.ListBucketsResponse]]: - 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_buckets' not in self._stubs: - self._stubs['list_buckets'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/ListBuckets', - request_serializer=logging_config.ListBucketsRequest.serialize, - response_deserializer=logging_config.ListBucketsResponse.deserialize, - ) - return self._stubs['list_buckets'] - - @property - def get_bucket(self) -> Callable[ - [logging_config.GetBucketRequest], - Awaitable[logging_config.LogBucket]]: - r"""Return a callable for the get bucket method over gRPC. - - Gets a bucket. - - Returns: - Callable[[~.GetBucketRequest], - Awaitable[~.LogBucket]]: - 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 'get_bucket' not in self._stubs: - self._stubs['get_bucket'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetBucket', - request_serializer=logging_config.GetBucketRequest.serialize, - response_deserializer=logging_config.LogBucket.deserialize, - ) - return self._stubs['get_bucket'] - - @property - def create_bucket(self) -> Callable[ - [logging_config.CreateBucketRequest], - Awaitable[logging_config.LogBucket]]: - r"""Return a callable for the create bucket method over gRPC. - - Creates a bucket that can be used to store log - entries. Once a bucket has been created, the region - cannot be changed. - - Returns: - Callable[[~.CreateBucketRequest], - Awaitable[~.LogBucket]]: - 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 'create_bucket' not in self._stubs: - self._stubs['create_bucket'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CreateBucket', - request_serializer=logging_config.CreateBucketRequest.serialize, - response_deserializer=logging_config.LogBucket.deserialize, - ) - return self._stubs['create_bucket'] - - @property - def update_bucket(self) -> Callable[ - [logging_config.UpdateBucketRequest], - Awaitable[logging_config.LogBucket]]: - r"""Return a callable for the update bucket method over gRPC. - - Updates a bucket. This method replaces the following fields in - the existing bucket with values from the new bucket: - ``retention_period`` - - If the retention period is decreased and the bucket is locked, - FAILED_PRECONDITION will be returned. - - If the bucket has a LifecycleState of DELETE_REQUESTED, - FAILED_PRECONDITION will be returned. - - A buckets region may not be modified after it is created. - - Returns: - Callable[[~.UpdateBucketRequest], - Awaitable[~.LogBucket]]: - 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 'update_bucket' not in self._stubs: - self._stubs['update_bucket'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateBucket', - request_serializer=logging_config.UpdateBucketRequest.serialize, - response_deserializer=logging_config.LogBucket.deserialize, - ) - return self._stubs['update_bucket'] - - @property - def delete_bucket(self) -> Callable[ - [logging_config.DeleteBucketRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete bucket method over gRPC. - - Deletes a bucket. Moves the bucket to the DELETE_REQUESTED - state. After 7 days, the bucket will be purged and all logs in - the bucket will be permanently deleted. - - Returns: - Callable[[~.DeleteBucketRequest], - Awaitable[~.Empty]]: - 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 'delete_bucket' not in self._stubs: - self._stubs['delete_bucket'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/DeleteBucket', - request_serializer=logging_config.DeleteBucketRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_bucket'] - - @property - def undelete_bucket(self) -> Callable[ - [logging_config.UndeleteBucketRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the undelete bucket method over gRPC. - - Undeletes a bucket. A bucket that has been deleted - may be undeleted within the grace period of 7 days. - - Returns: - Callable[[~.UndeleteBucketRequest], - Awaitable[~.Empty]]: - 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 'undelete_bucket' not in self._stubs: - self._stubs['undelete_bucket'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UndeleteBucket', - request_serializer=logging_config.UndeleteBucketRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['undelete_bucket'] - - @property - def list_views(self) -> Callable[ - [logging_config.ListViewsRequest], - Awaitable[logging_config.ListViewsResponse]]: - r"""Return a callable for the list views method over gRPC. - - Lists views on a bucket. - - Returns: - Callable[[~.ListViewsRequest], - Awaitable[~.ListViewsResponse]]: - 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_views' not in self._stubs: - self._stubs['list_views'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/ListViews', - request_serializer=logging_config.ListViewsRequest.serialize, - response_deserializer=logging_config.ListViewsResponse.deserialize, - ) - return self._stubs['list_views'] - - @property - def get_view(self) -> Callable[ - [logging_config.GetViewRequest], - Awaitable[logging_config.LogView]]: - r"""Return a callable for the get view method over gRPC. - - Gets a view. - - Returns: - Callable[[~.GetViewRequest], - Awaitable[~.LogView]]: - 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 'get_view' not in self._stubs: - self._stubs['get_view'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetView', - request_serializer=logging_config.GetViewRequest.serialize, - response_deserializer=logging_config.LogView.deserialize, - ) - return self._stubs['get_view'] - - @property - def create_view(self) -> Callable[ - [logging_config.CreateViewRequest], - Awaitable[logging_config.LogView]]: - r"""Return a callable for the create view method over gRPC. - - Creates a view over logs in a bucket. A bucket may - contain a maximum of 50 views. - - Returns: - Callable[[~.CreateViewRequest], - Awaitable[~.LogView]]: - 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 'create_view' not in self._stubs: - self._stubs['create_view'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CreateView', - request_serializer=logging_config.CreateViewRequest.serialize, - response_deserializer=logging_config.LogView.deserialize, - ) - return self._stubs['create_view'] - - @property - def update_view(self) -> Callable[ - [logging_config.UpdateViewRequest], - Awaitable[logging_config.LogView]]: - r"""Return a callable for the update view method over gRPC. - - Updates a view. This method replaces the following fields in the - existing view with values from the new view: ``filter``. - - Returns: - Callable[[~.UpdateViewRequest], - Awaitable[~.LogView]]: - 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 'update_view' not in self._stubs: - self._stubs['update_view'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateView', - request_serializer=logging_config.UpdateViewRequest.serialize, - response_deserializer=logging_config.LogView.deserialize, - ) - return self._stubs['update_view'] - - @property - def delete_view(self) -> Callable[ - [logging_config.DeleteViewRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete view method over gRPC. - - Deletes a view from a bucket. - - Returns: - Callable[[~.DeleteViewRequest], - Awaitable[~.Empty]]: - 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 'delete_view' not in self._stubs: - self._stubs['delete_view'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/DeleteView', - request_serializer=logging_config.DeleteViewRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_view'] - - @property - def list_sinks(self) -> Callable[ - [logging_config.ListSinksRequest], - Awaitable[logging_config.ListSinksResponse]]: - r"""Return a callable for the list sinks method over gRPC. - - Lists sinks. - - Returns: - Callable[[~.ListSinksRequest], - Awaitable[~.ListSinksResponse]]: - 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_sinks' not in self._stubs: - self._stubs['list_sinks'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/ListSinks', - request_serializer=logging_config.ListSinksRequest.serialize, - response_deserializer=logging_config.ListSinksResponse.deserialize, - ) - return self._stubs['list_sinks'] - - @property - def get_sink(self) -> Callable[ - [logging_config.GetSinkRequest], - Awaitable[logging_config.LogSink]]: - r"""Return a callable for the get sink method over gRPC. - - Gets a sink. - - Returns: - Callable[[~.GetSinkRequest], - Awaitable[~.LogSink]]: - 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 'get_sink' not in self._stubs: - self._stubs['get_sink'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetSink', - request_serializer=logging_config.GetSinkRequest.serialize, - response_deserializer=logging_config.LogSink.deserialize, - ) - return self._stubs['get_sink'] - - @property - def create_sink(self) -> Callable[ - [logging_config.CreateSinkRequest], - Awaitable[logging_config.LogSink]]: - r"""Return a callable for the create sink method over gRPC. - - Creates a sink that exports specified log entries to a - destination. The export of newly-ingested log entries begins - immediately, unless the sink's ``writer_identity`` is not - permitted to write to the destination. A sink can export log - entries only from the resource owning the sink. - - Returns: - Callable[[~.CreateSinkRequest], - Awaitable[~.LogSink]]: - 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 'create_sink' not in self._stubs: - self._stubs['create_sink'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CreateSink', - request_serializer=logging_config.CreateSinkRequest.serialize, - response_deserializer=logging_config.LogSink.deserialize, - ) - return self._stubs['create_sink'] - - @property - def update_sink(self) -> Callable[ - [logging_config.UpdateSinkRequest], - Awaitable[logging_config.LogSink]]: - r"""Return a callable for the update sink method over gRPC. - - Updates a sink. This method replaces the following fields in the - existing sink with values from the new sink: ``destination``, - and ``filter``. - - The updated sink might also have a new ``writer_identity``; see - the ``unique_writer_identity`` field. - - Returns: - Callable[[~.UpdateSinkRequest], - Awaitable[~.LogSink]]: - 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 'update_sink' not in self._stubs: - self._stubs['update_sink'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateSink', - request_serializer=logging_config.UpdateSinkRequest.serialize, - response_deserializer=logging_config.LogSink.deserialize, - ) - return self._stubs['update_sink'] - - @property - def delete_sink(self) -> Callable[ - [logging_config.DeleteSinkRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete sink method over gRPC. - - Deletes a sink. If the sink has a unique ``writer_identity``, - then that service account is also deleted. - - Returns: - Callable[[~.DeleteSinkRequest], - Awaitable[~.Empty]]: - 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 'delete_sink' not in self._stubs: - self._stubs['delete_sink'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/DeleteSink', - request_serializer=logging_config.DeleteSinkRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_sink'] - - @property - def list_exclusions(self) -> Callable[ - [logging_config.ListExclusionsRequest], - Awaitable[logging_config.ListExclusionsResponse]]: - r"""Return a callable for the list exclusions method over gRPC. - - Lists all the exclusions in a parent resource. - - Returns: - Callable[[~.ListExclusionsRequest], - Awaitable[~.ListExclusionsResponse]]: - 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_exclusions' not in self._stubs: - self._stubs['list_exclusions'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/ListExclusions', - request_serializer=logging_config.ListExclusionsRequest.serialize, - response_deserializer=logging_config.ListExclusionsResponse.deserialize, - ) - return self._stubs['list_exclusions'] - - @property - def get_exclusion(self) -> Callable[ - [logging_config.GetExclusionRequest], - Awaitable[logging_config.LogExclusion]]: - r"""Return a callable for the get exclusion method over gRPC. - - Gets the description of an exclusion. - - Returns: - Callable[[~.GetExclusionRequest], - Awaitable[~.LogExclusion]]: - 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 'get_exclusion' not in self._stubs: - self._stubs['get_exclusion'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetExclusion', - request_serializer=logging_config.GetExclusionRequest.serialize, - response_deserializer=logging_config.LogExclusion.deserialize, - ) - return self._stubs['get_exclusion'] - - @property - def create_exclusion(self) -> Callable[ - [logging_config.CreateExclusionRequest], - Awaitable[logging_config.LogExclusion]]: - r"""Return a callable for the create exclusion method over gRPC. - - Creates a new exclusion in a specified parent - resource. Only log entries belonging to that resource - can be excluded. You can have up to 10 exclusions in a - resource. - - Returns: - Callable[[~.CreateExclusionRequest], - Awaitable[~.LogExclusion]]: - 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 'create_exclusion' not in self._stubs: - self._stubs['create_exclusion'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/CreateExclusion', - request_serializer=logging_config.CreateExclusionRequest.serialize, - response_deserializer=logging_config.LogExclusion.deserialize, - ) - return self._stubs['create_exclusion'] - - @property - def update_exclusion(self) -> Callable[ - [logging_config.UpdateExclusionRequest], - Awaitable[logging_config.LogExclusion]]: - r"""Return a callable for the update exclusion method over gRPC. - - Changes one or more properties of an existing - exclusion. - - Returns: - Callable[[~.UpdateExclusionRequest], - Awaitable[~.LogExclusion]]: - 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 'update_exclusion' not in self._stubs: - self._stubs['update_exclusion'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateExclusion', - request_serializer=logging_config.UpdateExclusionRequest.serialize, - response_deserializer=logging_config.LogExclusion.deserialize, - ) - return self._stubs['update_exclusion'] - - @property - def delete_exclusion(self) -> Callable[ - [logging_config.DeleteExclusionRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete exclusion method over gRPC. - - Deletes an exclusion. - - Returns: - Callable[[~.DeleteExclusionRequest], - Awaitable[~.Empty]]: - 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 'delete_exclusion' not in self._stubs: - self._stubs['delete_exclusion'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/DeleteExclusion', - request_serializer=logging_config.DeleteExclusionRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_exclusion'] - - @property - def get_cmek_settings(self) -> Callable[ - [logging_config.GetCmekSettingsRequest], - Awaitable[logging_config.CmekSettings]]: - r"""Return a callable for the get cmek settings method over gRPC. - - Gets the Logs Router CMEK settings for the given resource. - - Note: CMEK for the Logs Router can currently only be configured - for GCP organizations. Once configured, it applies to all - projects and folders in the GCP organization. - - See `Enabling CMEK for Logs - Router `__ - for more information. - - Returns: - Callable[[~.GetCmekSettingsRequest], - Awaitable[~.CmekSettings]]: - 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 'get_cmek_settings' not in self._stubs: - self._stubs['get_cmek_settings'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/GetCmekSettings', - request_serializer=logging_config.GetCmekSettingsRequest.serialize, - response_deserializer=logging_config.CmekSettings.deserialize, - ) - return self._stubs['get_cmek_settings'] - - @property - def update_cmek_settings(self) -> Callable[ - [logging_config.UpdateCmekSettingsRequest], - Awaitable[logging_config.CmekSettings]]: - r"""Return a callable for the update cmek settings method over gRPC. - - Updates the Logs Router CMEK settings for the given resource. - - Note: CMEK for the Logs Router can currently only be configured - for GCP organizations. Once configured, it applies to all - projects and folders in the GCP organization. - - [UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings] - will fail if 1) ``kms_key_name`` is invalid, or 2) the - associated service account does not have the required - ``roles/cloudkms.cryptoKeyEncrypterDecrypter`` role assigned for - the key, or 3) access to the key is disabled. - - See `Enabling CMEK for Logs - Router `__ - for more information. - - Returns: - Callable[[~.UpdateCmekSettingsRequest], - Awaitable[~.CmekSettings]]: - 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 'update_cmek_settings' not in self._stubs: - self._stubs['update_cmek_settings'] = self.grpc_channel.unary_unary( - '/google.logging.v2.ConfigServiceV2/UpdateCmekSettings', - request_serializer=logging_config.UpdateCmekSettingsRequest.serialize, - response_deserializer=logging_config.CmekSettings.deserialize, - ) - return self._stubs['update_cmek_settings'] - - -__all__ = ( - 'ConfigServiceV2GrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/__init__.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/__init__.py deleted file mode 100644 index ed08d188..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 .client import LoggingServiceV2Client -from .async_client import LoggingServiceV2AsyncClient - -__all__ = ( - 'LoggingServiceV2Client', - 'LoggingServiceV2AsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/async_client.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/async_client.py deleted file mode 100644 index dd9cbb78..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/async_client.py +++ /dev/null @@ -1,781 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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, AsyncIterable, Awaitable, AsyncIterator, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api import monitored_resource_pb2 # type: ignore -from google.cloud.logging_v2.services.logging_service_v2 import pagers -from google.cloud.logging_v2.types import log_entry -from google.cloud.logging_v2.types import logging -from .transports.base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import LoggingServiceV2GrpcAsyncIOTransport -from .client import LoggingServiceV2Client - - -class LoggingServiceV2AsyncClient: - """Service for ingesting and querying logs.""" - - _client: LoggingServiceV2Client - - DEFAULT_ENDPOINT = LoggingServiceV2Client.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = LoggingServiceV2Client.DEFAULT_MTLS_ENDPOINT - - log_path = staticmethod(LoggingServiceV2Client.log_path) - parse_log_path = staticmethod(LoggingServiceV2Client.parse_log_path) - common_billing_account_path = staticmethod(LoggingServiceV2Client.common_billing_account_path) - parse_common_billing_account_path = staticmethod(LoggingServiceV2Client.parse_common_billing_account_path) - common_folder_path = staticmethod(LoggingServiceV2Client.common_folder_path) - parse_common_folder_path = staticmethod(LoggingServiceV2Client.parse_common_folder_path) - common_organization_path = staticmethod(LoggingServiceV2Client.common_organization_path) - parse_common_organization_path = staticmethod(LoggingServiceV2Client.parse_common_organization_path) - common_project_path = staticmethod(LoggingServiceV2Client.common_project_path) - parse_common_project_path = staticmethod(LoggingServiceV2Client.parse_common_project_path) - common_location_path = staticmethod(LoggingServiceV2Client.common_location_path) - parse_common_location_path = staticmethod(LoggingServiceV2Client.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: - LoggingServiceV2AsyncClient: The constructed client. - """ - return LoggingServiceV2Client.from_service_account_info.__func__(LoggingServiceV2AsyncClient, 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: - LoggingServiceV2AsyncClient: The constructed client. - """ - return LoggingServiceV2Client.from_service_account_file.__func__(LoggingServiceV2AsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> LoggingServiceV2Transport: - """Returns the transport used by the client instance. - - Returns: - LoggingServiceV2Transport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(LoggingServiceV2Client).get_transport_class, type(LoggingServiceV2Client)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, LoggingServiceV2Transport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the logging service v2 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, ~.LoggingServiceV2Transport]): 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 = LoggingServiceV2Client( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def delete_log(self, - request: logging.DeleteLogRequest = None, - *, - log_name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes all the log entries in a log. The log - reappears if it receives new entries. Log entries - written shortly before the delete operation might not be - deleted. Entries received after the delete operation - with a timestamp before the operation will be deleted. - - Args: - request (:class:`google.cloud.logging_v2.types.DeleteLogRequest`): - The request object. The parameters to DeleteLog. - log_name (:class:`str`): - Required. The resource name of the log to delete: - - :: - - "projects/[PROJECT_ID]/logs/[LOG_ID]" - "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" - "folders/[FOLDER_ID]/logs/[LOG_ID]" - - ``[LOG_ID]`` must be URL-encoded. For example, - ``"projects/my-project-id/logs/syslog"``, - ``"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"``. - For more information about log names, see - [LogEntry][google.logging.v2.LogEntry]. - - This corresponds to the ``log_name`` 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. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([log_name]) - 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 = logging.DeleteLogRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if log_name is not None: - request.log_name = log_name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_log, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - 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(( - ("log_name", request.log_name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def write_log_entries(self, - request: logging.WriteLogEntriesRequest = None, - *, - log_name: str = None, - resource: monitored_resource_pb2.MonitoredResource = None, - labels: Sequence[logging.WriteLogEntriesRequest.LabelsEntry] = None, - entries: Sequence[log_entry.LogEntry] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging.WriteLogEntriesResponse: - r"""Writes log entries to Logging. This API method is the - only way to send log entries to Logging. This method is - used, directly or indirectly, by the Logging agent - (fluentd) and all logging libraries configured to use - Logging. A single request may contain log entries for a - maximum of 1000 different resources (projects, - organizations, billing accounts or folders) - - Args: - request (:class:`google.cloud.logging_v2.types.WriteLogEntriesRequest`): - The request object. The parameters to WriteLogEntries. - log_name (:class:`str`): - Optional. A default log resource name that is assigned - to all log entries in ``entries`` that do not specify a - value for ``log_name``: - - :: - - "projects/[PROJECT_ID]/logs/[LOG_ID]" - "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" - "folders/[FOLDER_ID]/logs/[LOG_ID]" - - ``[LOG_ID]`` must be URL-encoded. For example: - - :: - - "projects/my-project-id/logs/syslog" - "organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity" - - The permission ``logging.logEntries.create`` is needed - on each project, organization, billing account, or - folder that is receiving new log entries, whether the - resource is specified in ``logName`` or in an individual - log entry. - - This corresponds to the ``log_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - resource (:class:`google.api.monitored_resource_pb2.MonitoredResource`): - Optional. A default monitored resource object that is - assigned to all log entries in ``entries`` that do not - specify a value for ``resource``. Example: - - :: - - { "type": "gce_instance", - "labels": { - "zone": "us-central1-a", "instance_id": "00000000000000000000" }} - - See [LogEntry][google.logging.v2.LogEntry]. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - labels (:class:`Sequence[google.cloud.logging_v2.types.WriteLogEntriesRequest.LabelsEntry]`): - Optional. Default labels that are added to the - ``labels`` field of all log entries in ``entries``. If a - log entry already has a label with the same key as a - label in this parameter, then the log entry's label is - not changed. See [LogEntry][google.logging.v2.LogEntry]. - - This corresponds to the ``labels`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entries (:class:`Sequence[google.cloud.logging_v2.types.LogEntry]`): - Required. The log entries to send to Logging. The order - of log entries in this list does not matter. Values - supplied in this method's ``log_name``, ``resource``, - and ``labels`` fields are copied into those log entries - in this list that do not include values for their - corresponding fields. For more information, see the - [LogEntry][google.logging.v2.LogEntry] type. - - If the ``timestamp`` or ``insert_id`` fields are missing - in log entries, then this method supplies the current - time or a unique identifier, respectively. The supplied - values are chosen so that, among the log entries that - did not supply their own values, the entries earlier in - the list will sort before the entries later in the list. - See the ``entries.list`` method. - - Log entries with timestamps that are more than the `logs - retention - period `__ - in the past or more than 24 hours in the future will not - be available when calling ``entries.list``. However, - those log entries can still be `exported with - LogSinks `__. - - To improve throughput and to avoid exceeding the `quota - limit `__ - for calls to ``entries.write``, you should try to - include several log entries in this list, rather than - calling this method for each individual log entry. - - This corresponds to the ``entries`` 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.logging_v2.types.WriteLogEntriesResponse: - Result returned from WriteLogEntries. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([log_name, resource, labels, entries]) - 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 = logging.WriteLogEntriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if log_name is not None: - request.log_name = log_name - if resource is not None: - request.resource = resource - - if labels: - request.labels.update(labels) - if entries: - request.entries.extend(entries) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.write_log_entries, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_log_entries(self, - request: logging.ListLogEntriesRequest = None, - *, - resource_names: Sequence[str] = None, - filter: str = None, - order_by: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListLogEntriesAsyncPager: - r"""Lists log entries. Use this method to retrieve log entries that - originated from a project/folder/organization/billing account. - For ways to export log entries, see `Exporting - Logs `__. - - Args: - request (:class:`google.cloud.logging_v2.types.ListLogEntriesRequest`): - The request object. The parameters to `ListLogEntries`. - resource_names (:class:`Sequence[str]`): - Required. Names of one or more parent resources from - which to retrieve log entries: - - :: - - "projects/[PROJECT_ID]" - "organizations/[ORGANIZATION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]" - "folders/[FOLDER_ID]" - - May alternatively be one or more views - projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID] - organization/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID] - billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID] - folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID] - - Projects listed in the ``project_ids`` field are added - to this list. - - This corresponds to the ``resource_names`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - Optional. A filter that chooses which log entries to - return. See `Advanced Logs - Queries `__. - Only log entries that match the filter are returned. An - empty filter matches all log entries in the resources - listed in ``resource_names``. Referencing a parent - resource that is not listed in ``resource_names`` will - cause the filter to return no results. The maximum - length of the filter is 20000 characters. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - order_by (:class:`str`): - Optional. How the results should be sorted. Presently, - the only permitted values are ``"timestamp asc"`` - (default) and ``"timestamp desc"``. The first option - returns entries in order of increasing values of - ``LogEntry.timestamp`` (oldest first), and the second - option returns entries in order of decreasing timestamps - (newest first). Entries with equal timestamps are - returned in order of their ``insert_id`` values. - - This corresponds to the ``order_by`` 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.logging_v2.services.logging_service_v2.pagers.ListLogEntriesAsyncPager: - Result returned from ListLogEntries. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource_names, filter, order_by]) - 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 = logging.ListLogEntriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if filter is not None: - request.filter = filter - if order_by is not None: - request.order_by = order_by - if resource_names: - request.resource_names.extend(resource_names) - - # 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_log_entries, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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.ListLogEntriesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_monitored_resource_descriptors(self, - request: logging.ListMonitoredResourceDescriptorsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListMonitoredResourceDescriptorsAsyncPager: - r"""Lists the descriptors for monitored resource types - used by Logging. - - Args: - request (:class:`google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsRequest`): - The request object. The parameters to - ListMonitoredResourceDescriptors - 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.logging_v2.services.logging_service_v2.pagers.ListMonitoredResourceDescriptorsAsyncPager: - Result returned from - ListMonitoredResourceDescriptors. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - request = logging.ListMonitoredResourceDescriptorsRequest(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.list_monitored_resource_descriptors, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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.ListMonitoredResourceDescriptorsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_logs(self, - request: logging.ListLogsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListLogsAsyncPager: - r"""Lists the logs in projects, organizations, folders, - or billing accounts. Only logs that have entries are - listed. - - Args: - request (:class:`google.cloud.logging_v2.types.ListLogsRequest`): - The request object. The parameters to ListLogs. - parent (:class:`str`): - Required. The resource name that owns the logs: - - :: - - "projects/[PROJECT_ID]" - "organizations/[ORGANIZATION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]" - "folders/[FOLDER_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.logging_v2.services.logging_service_v2.pagers.ListLogsAsyncPager: - Result returned from ListLogs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = logging.ListLogsRequest(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_logs, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - 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.ListLogsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def tail_log_entries(self, - requests: AsyncIterator[logging.TailLogEntriesRequest] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Awaitable[AsyncIterable[logging.TailLogEntriesResponse]]: - r"""Streaming read of log entries as they are ingested. - Until the stream is terminated, it will continue reading - logs. - - Args: - requests (AsyncIterator[`google.cloud.logging_v2.types.TailLogEntriesRequest`]): - The request object AsyncIterator. The parameters to `TailLogEntries`. - 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: - AsyncIterable[google.cloud.logging_v2.types.TailLogEntriesResponse]: - Result returned from TailLogEntries. - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.tail_log_entries, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=3600.0, - ), - default_timeout=3600.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-logging", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "LoggingServiceV2AsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/client.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/client.py deleted file mode 100644 index 35494597..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/client.py +++ /dev/null @@ -1,920 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 distutils import util -import os -import re -from typing import Dict, Optional, Iterable, Iterator, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api import monitored_resource_pb2 # type: ignore -from google.cloud.logging_v2.services.logging_service_v2 import pagers -from google.cloud.logging_v2.types import log_entry -from google.cloud.logging_v2.types import logging -from .transports.base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO -from .transports.grpc import LoggingServiceV2GrpcTransport -from .transports.grpc_asyncio import LoggingServiceV2GrpcAsyncIOTransport - - -class LoggingServiceV2ClientMeta(type): - """Metaclass for the LoggingServiceV2 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[LoggingServiceV2Transport]] - _transport_registry["grpc"] = LoggingServiceV2GrpcTransport - _transport_registry["grpc_asyncio"] = LoggingServiceV2GrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[LoggingServiceV2Transport]: - """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 LoggingServiceV2Client(metaclass=LoggingServiceV2ClientMeta): - """Service for ingesting and querying logs.""" - - @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 = "logging.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: - LoggingServiceV2Client: 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: - LoggingServiceV2Client: 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) -> LoggingServiceV2Transport: - """Returns the transport used by the client instance. - - Returns: - LoggingServiceV2Transport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def log_path(project: str,log: str,) -> str: - """Returns a fully-qualified log string.""" - return "projects/{project}/logs/{log}".format(project=project, log=log, ) - - @staticmethod - def parse_log_path(path: str) -> Dict[str,str]: - """Parses a log path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/logs/(?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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, LoggingServiceV2Transport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the logging service v2 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, LoggingServiceV2Transport]): 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() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # 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, LoggingServiceV2Transport): - # transport is a LoggingServiceV2Transport instance. - if credentials or client_options.credentials_file: - 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: - 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=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), - ) - - def delete_log(self, - request: Union[logging.DeleteLogRequest, dict] = None, - *, - log_name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes all the log entries in a log. The log - reappears if it receives new entries. Log entries - written shortly before the delete operation might not be - deleted. Entries received after the delete operation - with a timestamp before the operation will be deleted. - - Args: - request (Union[google.cloud.logging_v2.types.DeleteLogRequest, dict]): - The request object. The parameters to DeleteLog. - log_name (str): - Required. The resource name of the log to delete: - - :: - - "projects/[PROJECT_ID]/logs/[LOG_ID]" - "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" - "folders/[FOLDER_ID]/logs/[LOG_ID]" - - ``[LOG_ID]`` must be URL-encoded. For example, - ``"projects/my-project-id/logs/syslog"``, - ``"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"``. - For more information about log names, see - [LogEntry][google.logging.v2.LogEntry]. - - This corresponds to the ``log_name`` 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. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([log_name]) - 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 logging.DeleteLogRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging.DeleteLogRequest): - request = logging.DeleteLogRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if log_name is not None: - request.log_name = log_name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_log] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("log_name", request.log_name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def write_log_entries(self, - request: Union[logging.WriteLogEntriesRequest, dict] = None, - *, - log_name: str = None, - resource: monitored_resource_pb2.MonitoredResource = None, - labels: Sequence[logging.WriteLogEntriesRequest.LabelsEntry] = None, - entries: Sequence[log_entry.LogEntry] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging.WriteLogEntriesResponse: - r"""Writes log entries to Logging. This API method is the - only way to send log entries to Logging. This method is - used, directly or indirectly, by the Logging agent - (fluentd) and all logging libraries configured to use - Logging. A single request may contain log entries for a - maximum of 1000 different resources (projects, - organizations, billing accounts or folders) - - Args: - request (Union[google.cloud.logging_v2.types.WriteLogEntriesRequest, dict]): - The request object. The parameters to WriteLogEntries. - log_name (str): - Optional. A default log resource name that is assigned - to all log entries in ``entries`` that do not specify a - value for ``log_name``: - - :: - - "projects/[PROJECT_ID]/logs/[LOG_ID]" - "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" - "folders/[FOLDER_ID]/logs/[LOG_ID]" - - ``[LOG_ID]`` must be URL-encoded. For example: - - :: - - "projects/my-project-id/logs/syslog" - "organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity" - - The permission ``logging.logEntries.create`` is needed - on each project, organization, billing account, or - folder that is receiving new log entries, whether the - resource is specified in ``logName`` or in an individual - log entry. - - This corresponds to the ``log_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - resource (google.api.monitored_resource_pb2.MonitoredResource): - Optional. A default monitored resource object that is - assigned to all log entries in ``entries`` that do not - specify a value for ``resource``. Example: - - :: - - { "type": "gce_instance", - "labels": { - "zone": "us-central1-a", "instance_id": "00000000000000000000" }} - - See [LogEntry][google.logging.v2.LogEntry]. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - labels (Sequence[google.cloud.logging_v2.types.WriteLogEntriesRequest.LabelsEntry]): - Optional. Default labels that are added to the - ``labels`` field of all log entries in ``entries``. If a - log entry already has a label with the same key as a - label in this parameter, then the log entry's label is - not changed. See [LogEntry][google.logging.v2.LogEntry]. - - This corresponds to the ``labels`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entries (Sequence[google.cloud.logging_v2.types.LogEntry]): - Required. The log entries to send to Logging. The order - of log entries in this list does not matter. Values - supplied in this method's ``log_name``, ``resource``, - and ``labels`` fields are copied into those log entries - in this list that do not include values for their - corresponding fields. For more information, see the - [LogEntry][google.logging.v2.LogEntry] type. - - If the ``timestamp`` or ``insert_id`` fields are missing - in log entries, then this method supplies the current - time or a unique identifier, respectively. The supplied - values are chosen so that, among the log entries that - did not supply their own values, the entries earlier in - the list will sort before the entries later in the list. - See the ``entries.list`` method. - - Log entries with timestamps that are more than the `logs - retention - period `__ - in the past or more than 24 hours in the future will not - be available when calling ``entries.list``. However, - those log entries can still be `exported with - LogSinks `__. - - To improve throughput and to avoid exceeding the `quota - limit `__ - for calls to ``entries.write``, you should try to - include several log entries in this list, rather than - calling this method for each individual log entry. - - This corresponds to the ``entries`` 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.logging_v2.types.WriteLogEntriesResponse: - Result returned from WriteLogEntries. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([log_name, resource, labels, entries]) - 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 logging.WriteLogEntriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging.WriteLogEntriesRequest): - request = logging.WriteLogEntriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if log_name is not None: - request.log_name = log_name - if resource is not None: - request.resource = resource - if labels is not None: - request.labels = labels - if entries is not None: - request.entries = entries - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.write_log_entries] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_log_entries(self, - request: Union[logging.ListLogEntriesRequest, dict] = None, - *, - resource_names: Sequence[str] = None, - filter: str = None, - order_by: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListLogEntriesPager: - r"""Lists log entries. Use this method to retrieve log entries that - originated from a project/folder/organization/billing account. - For ways to export log entries, see `Exporting - Logs `__. - - Args: - request (Union[google.cloud.logging_v2.types.ListLogEntriesRequest, dict]): - The request object. The parameters to `ListLogEntries`. - resource_names (Sequence[str]): - Required. Names of one or more parent resources from - which to retrieve log entries: - - :: - - "projects/[PROJECT_ID]" - "organizations/[ORGANIZATION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]" - "folders/[FOLDER_ID]" - - May alternatively be one or more views - projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID] - organization/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID] - billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID] - folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID] - - Projects listed in the ``project_ids`` field are added - to this list. - - This corresponds to the ``resource_names`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - Optional. A filter that chooses which log entries to - return. See `Advanced Logs - Queries `__. - Only log entries that match the filter are returned. An - empty filter matches all log entries in the resources - listed in ``resource_names``. Referencing a parent - resource that is not listed in ``resource_names`` will - cause the filter to return no results. The maximum - length of the filter is 20000 characters. - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - order_by (str): - Optional. How the results should be sorted. Presently, - the only permitted values are ``"timestamp asc"`` - (default) and ``"timestamp desc"``. The first option - returns entries in order of increasing values of - ``LogEntry.timestamp`` (oldest first), and the second - option returns entries in order of decreasing timestamps - (newest first). Entries with equal timestamps are - returned in order of their ``insert_id`` values. - - This corresponds to the ``order_by`` 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.logging_v2.services.logging_service_v2.pagers.ListLogEntriesPager: - Result returned from ListLogEntries. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource_names, filter, order_by]) - 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 logging.ListLogEntriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging.ListLogEntriesRequest): - request = logging.ListLogEntriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if resource_names is not None: - request.resource_names = resource_names - if filter is not None: - request.filter = filter - if order_by is not None: - request.order_by = order_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_log_entries] - - # 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.ListLogEntriesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_monitored_resource_descriptors(self, - request: Union[logging.ListMonitoredResourceDescriptorsRequest, dict] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListMonitoredResourceDescriptorsPager: - r"""Lists the descriptors for monitored resource types - used by Logging. - - Args: - request (Union[google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsRequest, dict]): - The request object. The parameters to - ListMonitoredResourceDescriptors - 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.logging_v2.services.logging_service_v2.pagers.ListMonitoredResourceDescriptorsPager: - Result returned from - ListMonitoredResourceDescriptors. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a logging.ListMonitoredResourceDescriptorsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging.ListMonitoredResourceDescriptorsRequest): - request = logging.ListMonitoredResourceDescriptorsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_monitored_resource_descriptors] - - # 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.ListMonitoredResourceDescriptorsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_logs(self, - request: Union[logging.ListLogsRequest, dict] = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListLogsPager: - r"""Lists the logs in projects, organizations, folders, - or billing accounts. Only logs that have entries are - listed. - - Args: - request (Union[google.cloud.logging_v2.types.ListLogsRequest, dict]): - The request object. The parameters to ListLogs. - parent (str): - Required. The resource name that owns the logs: - - :: - - "projects/[PROJECT_ID]" - "organizations/[ORGANIZATION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]" - "folders/[FOLDER_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.logging_v2.services.logging_service_v2.pagers.ListLogsPager: - Result returned from ListLogs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 logging.ListLogsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging.ListLogsRequest): - request = logging.ListLogsRequest(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_logs] - - # 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.ListLogsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def tail_log_entries(self, - requests: Iterator[logging.TailLogEntriesRequest] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Iterable[logging.TailLogEntriesResponse]: - r"""Streaming read of log entries as they are ingested. - Until the stream is terminated, it will continue reading - logs. - - Args: - requests (Iterator[google.cloud.logging_v2.types.TailLogEntriesRequest]): - The request object iterator. The parameters to `TailLogEntries`. - 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: - Iterable[google.cloud.logging_v2.types.TailLogEntriesResponse]: - Result returned from TailLogEntries. - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.tail_log_entries] - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-logging", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "LoggingServiceV2Client", -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/pagers.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/pagers.py deleted file mode 100644 index 95adb7e9..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/pagers.py +++ /dev/null @@ -1,386 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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, Sequence, Tuple, Optional, Iterator - -from google.api import monitored_resource_pb2 # type: ignore -from google.cloud.logging_v2.types import log_entry -from google.cloud.logging_v2.types import logging - - -class ListLogEntriesPager: - """A pager for iterating through ``list_log_entries`` requests. - - This class thinly wraps an initial - :class:`google.cloud.logging_v2.types.ListLogEntriesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``entries`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListLogEntries`` requests and continue to iterate - through the ``entries`` field on the - corresponding responses. - - All the usual :class:`google.cloud.logging_v2.types.ListLogEntriesResponse` - 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[..., logging.ListLogEntriesResponse], - request: logging.ListLogEntriesRequest, - response: logging.ListLogEntriesResponse, - *, - 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.logging_v2.types.ListLogEntriesRequest): - The initial request object. - response (google.cloud.logging_v2.types.ListLogEntriesResponse): - 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 = logging.ListLogEntriesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[logging.ListLogEntriesResponse]: - 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[log_entry.LogEntry]: - for page in self.pages: - yield from page.entries - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListLogEntriesAsyncPager: - """A pager for iterating through ``list_log_entries`` requests. - - This class thinly wraps an initial - :class:`google.cloud.logging_v2.types.ListLogEntriesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``entries`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListLogEntries`` requests and continue to iterate - through the ``entries`` field on the - corresponding responses. - - All the usual :class:`google.cloud.logging_v2.types.ListLogEntriesResponse` - 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[logging.ListLogEntriesResponse]], - request: logging.ListLogEntriesRequest, - response: logging.ListLogEntriesResponse, - *, - 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.logging_v2.types.ListLogEntriesRequest): - The initial request object. - response (google.cloud.logging_v2.types.ListLogEntriesResponse): - 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 = logging.ListLogEntriesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[logging.ListLogEntriesResponse]: - 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[log_entry.LogEntry]: - async def async_generator(): - async for page in self.pages: - for response in page.entries: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMonitoredResourceDescriptorsPager: - """A pager for iterating through ``list_monitored_resource_descriptors`` requests. - - This class thinly wraps an initial - :class:`google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``resource_descriptors`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListMonitoredResourceDescriptors`` requests and continue to iterate - through the ``resource_descriptors`` field on the - corresponding responses. - - All the usual :class:`google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsResponse` - 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[..., logging.ListMonitoredResourceDescriptorsResponse], - request: logging.ListMonitoredResourceDescriptorsRequest, - response: logging.ListMonitoredResourceDescriptorsResponse, - *, - 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.logging_v2.types.ListMonitoredResourceDescriptorsRequest): - The initial request object. - response (google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsResponse): - 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 = logging.ListMonitoredResourceDescriptorsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[logging.ListMonitoredResourceDescriptorsResponse]: - 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[monitored_resource_pb2.MonitoredResourceDescriptor]: - for page in self.pages: - yield from page.resource_descriptors - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMonitoredResourceDescriptorsAsyncPager: - """A pager for iterating through ``list_monitored_resource_descriptors`` requests. - - This class thinly wraps an initial - :class:`google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``resource_descriptors`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListMonitoredResourceDescriptors`` requests and continue to iterate - through the ``resource_descriptors`` field on the - corresponding responses. - - All the usual :class:`google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsResponse` - 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[logging.ListMonitoredResourceDescriptorsResponse]], - request: logging.ListMonitoredResourceDescriptorsRequest, - response: logging.ListMonitoredResourceDescriptorsResponse, - *, - 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.logging_v2.types.ListMonitoredResourceDescriptorsRequest): - The initial request object. - response (google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsResponse): - 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 = logging.ListMonitoredResourceDescriptorsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[logging.ListMonitoredResourceDescriptorsResponse]: - 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[monitored_resource_pb2.MonitoredResourceDescriptor]: - async def async_generator(): - async for page in self.pages: - for response in page.resource_descriptors: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListLogsPager: - """A pager for iterating through ``list_logs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.logging_v2.types.ListLogsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``log_names`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListLogs`` requests and continue to iterate - through the ``log_names`` field on the - corresponding responses. - - All the usual :class:`google.cloud.logging_v2.types.ListLogsResponse` - 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[..., logging.ListLogsResponse], - request: logging.ListLogsRequest, - response: logging.ListLogsResponse, - *, - 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.logging_v2.types.ListLogsRequest): - The initial request object. - response (google.cloud.logging_v2.types.ListLogsResponse): - 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 = logging.ListLogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[logging.ListLogsResponse]: - 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[str]: - for page in self.pages: - yield from page.log_names - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListLogsAsyncPager: - """A pager for iterating through ``list_logs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.logging_v2.types.ListLogsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``log_names`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListLogs`` requests and continue to iterate - through the ``log_names`` field on the - corresponding responses. - - All the usual :class:`google.cloud.logging_v2.types.ListLogsResponse` - 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[logging.ListLogsResponse]], - request: logging.ListLogsRequest, - response: logging.ListLogsResponse, - *, - 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.logging_v2.types.ListLogsRequest): - The initial request object. - response (google.cloud.logging_v2.types.ListLogsResponse): - 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 = logging.ListLogsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[logging.ListLogsResponse]: - 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[str]: - async def async_generator(): - async for page in self.pages: - for response in page.log_names: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/transports/__init__.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/transports/__init__.py deleted file mode 100644 index 46e9a1fc..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 LoggingServiceV2Transport -from .grpc import LoggingServiceV2GrpcTransport -from .grpc_asyncio import LoggingServiceV2GrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[LoggingServiceV2Transport]] -_transport_registry['grpc'] = LoggingServiceV2GrpcTransport -_transport_registry['grpc_asyncio'] = LoggingServiceV2GrpcAsyncIOTransport - -__all__ = ( - 'LoggingServiceV2Transport', - 'LoggingServiceV2GrpcTransport', - 'LoggingServiceV2GrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/transports/base.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/transports/base.py deleted file mode 100644 index 222ed3c1..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/transports/base.py +++ /dev/null @@ -1,291 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.logging_v2.types import logging -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-logging', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class LoggingServiceV2Transport(abc.ABC): - """Abstract transport class for LoggingServiceV2.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', - ) - - DEFAULT_HOST: str = 'logging.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, - **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. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, 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) - - # 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 - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.delete_log: gapic_v1.method.wrap_method( - self.delete_log, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.write_log_entries: gapic_v1.method.wrap_method( - self.write_log_entries, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_log_entries: gapic_v1.method.wrap_method( - self.list_log_entries, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_monitored_resource_descriptors: gapic_v1.method.wrap_method( - self.list_monitored_resource_descriptors, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_logs: gapic_v1.method.wrap_method( - self.list_logs, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.tail_log_entries: gapic_v1.method.wrap_method( - self.tail_log_entries, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=3600.0, - ), - default_timeout=3600.0, - client_info=client_info, - ), - } - - @property - def delete_log(self) -> Callable[ - [logging.DeleteLogRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def write_log_entries(self) -> Callable[ - [logging.WriteLogEntriesRequest], - Union[ - logging.WriteLogEntriesResponse, - Awaitable[logging.WriteLogEntriesResponse] - ]]: - raise NotImplementedError() - - @property - def list_log_entries(self) -> Callable[ - [logging.ListLogEntriesRequest], - Union[ - logging.ListLogEntriesResponse, - Awaitable[logging.ListLogEntriesResponse] - ]]: - raise NotImplementedError() - - @property - def list_monitored_resource_descriptors(self) -> Callable[ - [logging.ListMonitoredResourceDescriptorsRequest], - Union[ - logging.ListMonitoredResourceDescriptorsResponse, - Awaitable[logging.ListMonitoredResourceDescriptorsResponse] - ]]: - raise NotImplementedError() - - @property - def list_logs(self) -> Callable[ - [logging.ListLogsRequest], - Union[ - logging.ListLogsResponse, - Awaitable[logging.ListLogsResponse] - ]]: - raise NotImplementedError() - - @property - def tail_log_entries(self) -> Callable[ - [logging.TailLogEntriesRequest], - Union[ - logging.TailLogEntriesResponse, - Awaitable[logging.TailLogEntriesResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'LoggingServiceV2Transport', -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py deleted file mode 100644 index f66cb54a..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/transports/grpc.py +++ /dev/null @@ -1,402 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.logging_v2.types import logging -from google.protobuf import empty_pb2 # type: ignore -from .base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO - - -class LoggingServiceV2GrpcTransport(LoggingServiceV2Transport): - """gRPC backend transport for LoggingServiceV2. - - Service for ingesting and querying logs. - - 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 = 'logging.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, - ) -> 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] = {} - - 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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 = 'logging.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 delete_log(self) -> Callable[ - [logging.DeleteLogRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete log method over gRPC. - - Deletes all the log entries in a log. The log - reappears if it receives new entries. Log entries - written shortly before the delete operation might not be - deleted. Entries received after the delete operation - with a timestamp before the operation will be deleted. - - Returns: - Callable[[~.DeleteLogRequest], - ~.Empty]: - 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 'delete_log' not in self._stubs: - self._stubs['delete_log'] = self.grpc_channel.unary_unary( - '/google.logging.v2.LoggingServiceV2/DeleteLog', - request_serializer=logging.DeleteLogRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_log'] - - @property - def write_log_entries(self) -> Callable[ - [logging.WriteLogEntriesRequest], - logging.WriteLogEntriesResponse]: - r"""Return a callable for the write log entries method over gRPC. - - Writes log entries to Logging. This API method is the - only way to send log entries to Logging. This method is - used, directly or indirectly, by the Logging agent - (fluentd) and all logging libraries configured to use - Logging. A single request may contain log entries for a - maximum of 1000 different resources (projects, - organizations, billing accounts or folders) - - Returns: - Callable[[~.WriteLogEntriesRequest], - ~.WriteLogEntriesResponse]: - 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 'write_log_entries' not in self._stubs: - self._stubs['write_log_entries'] = self.grpc_channel.unary_unary( - '/google.logging.v2.LoggingServiceV2/WriteLogEntries', - request_serializer=logging.WriteLogEntriesRequest.serialize, - response_deserializer=logging.WriteLogEntriesResponse.deserialize, - ) - return self._stubs['write_log_entries'] - - @property - def list_log_entries(self) -> Callable[ - [logging.ListLogEntriesRequest], - logging.ListLogEntriesResponse]: - r"""Return a callable for the list log entries method over gRPC. - - Lists log entries. Use this method to retrieve log entries that - originated from a project/folder/organization/billing account. - For ways to export log entries, see `Exporting - Logs `__. - - Returns: - Callable[[~.ListLogEntriesRequest], - ~.ListLogEntriesResponse]: - 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_log_entries' not in self._stubs: - self._stubs['list_log_entries'] = self.grpc_channel.unary_unary( - '/google.logging.v2.LoggingServiceV2/ListLogEntries', - request_serializer=logging.ListLogEntriesRequest.serialize, - response_deserializer=logging.ListLogEntriesResponse.deserialize, - ) - return self._stubs['list_log_entries'] - - @property - def list_monitored_resource_descriptors(self) -> Callable[ - [logging.ListMonitoredResourceDescriptorsRequest], - logging.ListMonitoredResourceDescriptorsResponse]: - r"""Return a callable for the list monitored resource - descriptors method over gRPC. - - Lists the descriptors for monitored resource types - used by Logging. - - Returns: - Callable[[~.ListMonitoredResourceDescriptorsRequest], - ~.ListMonitoredResourceDescriptorsResponse]: - 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_monitored_resource_descriptors' not in self._stubs: - self._stubs['list_monitored_resource_descriptors'] = self.grpc_channel.unary_unary( - '/google.logging.v2.LoggingServiceV2/ListMonitoredResourceDescriptors', - request_serializer=logging.ListMonitoredResourceDescriptorsRequest.serialize, - response_deserializer=logging.ListMonitoredResourceDescriptorsResponse.deserialize, - ) - return self._stubs['list_monitored_resource_descriptors'] - - @property - def list_logs(self) -> Callable[ - [logging.ListLogsRequest], - logging.ListLogsResponse]: - r"""Return a callable for the list logs method over gRPC. - - Lists the logs in projects, organizations, folders, - or billing accounts. Only logs that have entries are - listed. - - Returns: - Callable[[~.ListLogsRequest], - ~.ListLogsResponse]: - 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_logs' not in self._stubs: - self._stubs['list_logs'] = self.grpc_channel.unary_unary( - '/google.logging.v2.LoggingServiceV2/ListLogs', - request_serializer=logging.ListLogsRequest.serialize, - response_deserializer=logging.ListLogsResponse.deserialize, - ) - return self._stubs['list_logs'] - - @property - def tail_log_entries(self) -> Callable[ - [logging.TailLogEntriesRequest], - logging.TailLogEntriesResponse]: - r"""Return a callable for the tail log entries method over gRPC. - - Streaming read of log entries as they are ingested. - Until the stream is terminated, it will continue reading - logs. - - Returns: - Callable[[~.TailLogEntriesRequest], - ~.TailLogEntriesResponse]: - 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 'tail_log_entries' not in self._stubs: - self._stubs['tail_log_entries'] = self.grpc_channel.stream_stream( - '/google.logging.v2.LoggingServiceV2/TailLogEntries', - request_serializer=logging.TailLogEntriesRequest.serialize, - response_deserializer=logging.TailLogEntriesResponse.deserialize, - ) - return self._stubs['tail_log_entries'] - - -__all__ = ( - 'LoggingServiceV2GrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/transports/grpc_asyncio.py deleted file mode 100644 index a19007ab..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/logging_service_v2/transports/grpc_asyncio.py +++ /dev/null @@ -1,406 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.logging_v2.types import logging -from google.protobuf import empty_pb2 # type: ignore -from .base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO -from .grpc import LoggingServiceV2GrpcTransport - - -class LoggingServiceV2GrpcAsyncIOTransport(LoggingServiceV2Transport): - """gRPC AsyncIO backend transport for LoggingServiceV2. - - Service for ingesting and querying logs. - - 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 = 'logging.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 = 'logging.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, - ) -> 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] = {} - - 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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 delete_log(self) -> Callable[ - [logging.DeleteLogRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete log method over gRPC. - - Deletes all the log entries in a log. The log - reappears if it receives new entries. Log entries - written shortly before the delete operation might not be - deleted. Entries received after the delete operation - with a timestamp before the operation will be deleted. - - Returns: - Callable[[~.DeleteLogRequest], - Awaitable[~.Empty]]: - 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 'delete_log' not in self._stubs: - self._stubs['delete_log'] = self.grpc_channel.unary_unary( - '/google.logging.v2.LoggingServiceV2/DeleteLog', - request_serializer=logging.DeleteLogRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_log'] - - @property - def write_log_entries(self) -> Callable[ - [logging.WriteLogEntriesRequest], - Awaitable[logging.WriteLogEntriesResponse]]: - r"""Return a callable for the write log entries method over gRPC. - - Writes log entries to Logging. This API method is the - only way to send log entries to Logging. This method is - used, directly or indirectly, by the Logging agent - (fluentd) and all logging libraries configured to use - Logging. A single request may contain log entries for a - maximum of 1000 different resources (projects, - organizations, billing accounts or folders) - - Returns: - Callable[[~.WriteLogEntriesRequest], - Awaitable[~.WriteLogEntriesResponse]]: - 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 'write_log_entries' not in self._stubs: - self._stubs['write_log_entries'] = self.grpc_channel.unary_unary( - '/google.logging.v2.LoggingServiceV2/WriteLogEntries', - request_serializer=logging.WriteLogEntriesRequest.serialize, - response_deserializer=logging.WriteLogEntriesResponse.deserialize, - ) - return self._stubs['write_log_entries'] - - @property - def list_log_entries(self) -> Callable[ - [logging.ListLogEntriesRequest], - Awaitable[logging.ListLogEntriesResponse]]: - r"""Return a callable for the list log entries method over gRPC. - - Lists log entries. Use this method to retrieve log entries that - originated from a project/folder/organization/billing account. - For ways to export log entries, see `Exporting - Logs `__. - - Returns: - Callable[[~.ListLogEntriesRequest], - Awaitable[~.ListLogEntriesResponse]]: - 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_log_entries' not in self._stubs: - self._stubs['list_log_entries'] = self.grpc_channel.unary_unary( - '/google.logging.v2.LoggingServiceV2/ListLogEntries', - request_serializer=logging.ListLogEntriesRequest.serialize, - response_deserializer=logging.ListLogEntriesResponse.deserialize, - ) - return self._stubs['list_log_entries'] - - @property - def list_monitored_resource_descriptors(self) -> Callable[ - [logging.ListMonitoredResourceDescriptorsRequest], - Awaitable[logging.ListMonitoredResourceDescriptorsResponse]]: - r"""Return a callable for the list monitored resource - descriptors method over gRPC. - - Lists the descriptors for monitored resource types - used by Logging. - - Returns: - Callable[[~.ListMonitoredResourceDescriptorsRequest], - Awaitable[~.ListMonitoredResourceDescriptorsResponse]]: - 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_monitored_resource_descriptors' not in self._stubs: - self._stubs['list_monitored_resource_descriptors'] = self.grpc_channel.unary_unary( - '/google.logging.v2.LoggingServiceV2/ListMonitoredResourceDescriptors', - request_serializer=logging.ListMonitoredResourceDescriptorsRequest.serialize, - response_deserializer=logging.ListMonitoredResourceDescriptorsResponse.deserialize, - ) - return self._stubs['list_monitored_resource_descriptors'] - - @property - def list_logs(self) -> Callable[ - [logging.ListLogsRequest], - Awaitable[logging.ListLogsResponse]]: - r"""Return a callable for the list logs method over gRPC. - - Lists the logs in projects, organizations, folders, - or billing accounts. Only logs that have entries are - listed. - - Returns: - Callable[[~.ListLogsRequest], - Awaitable[~.ListLogsResponse]]: - 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_logs' not in self._stubs: - self._stubs['list_logs'] = self.grpc_channel.unary_unary( - '/google.logging.v2.LoggingServiceV2/ListLogs', - request_serializer=logging.ListLogsRequest.serialize, - response_deserializer=logging.ListLogsResponse.deserialize, - ) - return self._stubs['list_logs'] - - @property - def tail_log_entries(self) -> Callable[ - [logging.TailLogEntriesRequest], - Awaitable[logging.TailLogEntriesResponse]]: - r"""Return a callable for the tail log entries method over gRPC. - - Streaming read of log entries as they are ingested. - Until the stream is terminated, it will continue reading - logs. - - Returns: - Callable[[~.TailLogEntriesRequest], - Awaitable[~.TailLogEntriesResponse]]: - 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 'tail_log_entries' not in self._stubs: - self._stubs['tail_log_entries'] = self.grpc_channel.stream_stream( - '/google.logging.v2.LoggingServiceV2/TailLogEntries', - request_serializer=logging.TailLogEntriesRequest.serialize, - response_deserializer=logging.TailLogEntriesResponse.deserialize, - ) - return self._stubs['tail_log_entries'] - - -__all__ = ( - 'LoggingServiceV2GrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/__init__.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/__init__.py deleted file mode 100644 index 1b5d1805..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 .client import MetricsServiceV2Client -from .async_client import MetricsServiceV2AsyncClient - -__all__ = ( - 'MetricsServiceV2Client', - 'MetricsServiceV2AsyncClient', -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/async_client.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/async_client.py deleted file mode 100644 index 764f44f6..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/async_client.py +++ /dev/null @@ -1,640 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api import distribution_pb2 # type: ignore -from google.api import metric_pb2 # type: ignore -from google.cloud.logging_v2.services.metrics_service_v2 import pagers -from google.cloud.logging_v2.types import logging_metrics -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import MetricsServiceV2GrpcAsyncIOTransport -from .client import MetricsServiceV2Client - - -class MetricsServiceV2AsyncClient: - """Service for configuring logs-based metrics.""" - - _client: MetricsServiceV2Client - - DEFAULT_ENDPOINT = MetricsServiceV2Client.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = MetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT - - log_metric_path = staticmethod(MetricsServiceV2Client.log_metric_path) - parse_log_metric_path = staticmethod(MetricsServiceV2Client.parse_log_metric_path) - common_billing_account_path = staticmethod(MetricsServiceV2Client.common_billing_account_path) - parse_common_billing_account_path = staticmethod(MetricsServiceV2Client.parse_common_billing_account_path) - common_folder_path = staticmethod(MetricsServiceV2Client.common_folder_path) - parse_common_folder_path = staticmethod(MetricsServiceV2Client.parse_common_folder_path) - common_organization_path = staticmethod(MetricsServiceV2Client.common_organization_path) - parse_common_organization_path = staticmethod(MetricsServiceV2Client.parse_common_organization_path) - common_project_path = staticmethod(MetricsServiceV2Client.common_project_path) - parse_common_project_path = staticmethod(MetricsServiceV2Client.parse_common_project_path) - common_location_path = staticmethod(MetricsServiceV2Client.common_location_path) - parse_common_location_path = staticmethod(MetricsServiceV2Client.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: - MetricsServiceV2AsyncClient: The constructed client. - """ - return MetricsServiceV2Client.from_service_account_info.__func__(MetricsServiceV2AsyncClient, 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: - MetricsServiceV2AsyncClient: The constructed client. - """ - return MetricsServiceV2Client.from_service_account_file.__func__(MetricsServiceV2AsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> MetricsServiceV2Transport: - """Returns the transport used by the client instance. - - Returns: - MetricsServiceV2Transport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(MetricsServiceV2Client).get_transport_class, type(MetricsServiceV2Client)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, MetricsServiceV2Transport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the metrics service v2 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, ~.MetricsServiceV2Transport]): 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 = MetricsServiceV2Client( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_log_metrics(self, - request: logging_metrics.ListLogMetricsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListLogMetricsAsyncPager: - r"""Lists logs-based metrics. - - Args: - request (:class:`google.cloud.logging_v2.types.ListLogMetricsRequest`): - The request object. The parameters to ListLogMetrics. - parent (:class:`str`): - Required. The name of the project containing the - metrics: - - :: - - "projects/[PROJECT_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.logging_v2.services.metrics_service_v2.pagers.ListLogMetricsAsyncPager: - Result returned from ListLogMetrics. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = logging_metrics.ListLogMetricsRequest(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_log_metrics, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - 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.ListLogMetricsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_log_metric(self, - request: logging_metrics.GetLogMetricRequest = None, - *, - metric_name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_metrics.LogMetric: - r"""Gets a logs-based metric. - - Args: - request (:class:`google.cloud.logging_v2.types.GetLogMetricRequest`): - The request object. The parameters to GetLogMetric. - metric_name (:class:`str`): - Required. The resource name of the desired metric: - - :: - - "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - - This corresponds to the ``metric_name`` 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.logging_v2.types.LogMetric: - Describes a logs-based metric. The - value of the metric is the number of log - entries that match a logs filter in a - given time interval. - Logs-based metrics can also be used to - extract values from logs and create a - distribution of the values. The - distribution records the statistics of - the extracted values along with an - optional histogram of the values as - specified by the bucket options. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([metric_name]) - 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 = logging_metrics.GetLogMetricRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if metric_name is not None: - request.metric_name = metric_name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_log_metric, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - 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(( - ("metric_name", request.metric_name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_log_metric(self, - request: logging_metrics.CreateLogMetricRequest = None, - *, - parent: str = None, - metric: logging_metrics.LogMetric = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_metrics.LogMetric: - r"""Creates a logs-based metric. - - Args: - request (:class:`google.cloud.logging_v2.types.CreateLogMetricRequest`): - The request object. The parameters to CreateLogMetric. - parent (:class:`str`): - Required. The resource name of the project in which to - create the metric: - - :: - - "projects/[PROJECT_ID]" - - The new metric must be provided in the request. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - metric (:class:`google.cloud.logging_v2.types.LogMetric`): - Required. The new logs-based metric, - which must not have an identifier that - already exists. - - This corresponds to the ``metric`` 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.logging_v2.types.LogMetric: - Describes a logs-based metric. The - value of the metric is the number of log - entries that match a logs filter in a - given time interval. - Logs-based metrics can also be used to - extract values from logs and create a - distribution of the values. The - distribution records the statistics of - the extracted values along with an - optional histogram of the values as - specified by the bucket options. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, metric]) - 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 = logging_metrics.CreateLogMetricRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if metric is not None: - request.metric = metric - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_log_metric, - default_timeout=60.0, - 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, - ) - - # Done; return the response. - return response - - async def update_log_metric(self, - request: logging_metrics.UpdateLogMetricRequest = None, - *, - metric_name: str = None, - metric: logging_metrics.LogMetric = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_metrics.LogMetric: - r"""Creates or updates a logs-based metric. - - Args: - request (:class:`google.cloud.logging_v2.types.UpdateLogMetricRequest`): - The request object. The parameters to UpdateLogMetric. - metric_name (:class:`str`): - Required. The resource name of the metric to update: - - :: - - "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - - The updated metric must be provided in the request and - it's ``name`` field must be the same as ``[METRIC_ID]`` - If the metric does not exist in ``[PROJECT_ID]``, then a - new metric is created. - - This corresponds to the ``metric_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - metric (:class:`google.cloud.logging_v2.types.LogMetric`): - Required. The updated metric. - This corresponds to the ``metric`` 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.logging_v2.types.LogMetric: - Describes a logs-based metric. The - value of the metric is the number of log - entries that match a logs filter in a - given time interval. - Logs-based metrics can also be used to - extract values from logs and create a - distribution of the values. The - distribution records the statistics of - the extracted values along with an - optional histogram of the values as - specified by the bucket options. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([metric_name, metric]) - 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 = logging_metrics.UpdateLogMetricRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if metric_name is not None: - request.metric_name = metric_name - if metric is not None: - request.metric = metric - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_log_metric, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - 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(( - ("metric_name", request.metric_name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_log_metric(self, - request: logging_metrics.DeleteLogMetricRequest = None, - *, - metric_name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a logs-based metric. - - Args: - request (:class:`google.cloud.logging_v2.types.DeleteLogMetricRequest`): - The request object. The parameters to DeleteLogMetric. - metric_name (:class:`str`): - Required. The resource name of the metric to delete: - - :: - - "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - - This corresponds to the ``metric_name`` 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. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([metric_name]) - 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 = logging_metrics.DeleteLogMetricRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if metric_name is not None: - request.metric_name = metric_name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_log_metric, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - 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(( - ("metric_name", request.metric_name), - )), - ) - - # Send the request. - await 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-logging", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "MetricsServiceV2AsyncClient", -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/client.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/client.py deleted file mode 100644 index af554cf6..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ /dev/null @@ -1,799 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 distutils import util -import os -import re -from typing import Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api import distribution_pb2 # type: ignore -from google.api import metric_pb2 # type: ignore -from google.cloud.logging_v2.services.metrics_service_v2 import pagers -from google.cloud.logging_v2.types import logging_metrics -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO -from .transports.grpc import MetricsServiceV2GrpcTransport -from .transports.grpc_asyncio import MetricsServiceV2GrpcAsyncIOTransport - - -class MetricsServiceV2ClientMeta(type): - """Metaclass for the MetricsServiceV2 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[MetricsServiceV2Transport]] - _transport_registry["grpc"] = MetricsServiceV2GrpcTransport - _transport_registry["grpc_asyncio"] = MetricsServiceV2GrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[MetricsServiceV2Transport]: - """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 MetricsServiceV2Client(metaclass=MetricsServiceV2ClientMeta): - """Service for configuring logs-based metrics.""" - - @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 = "logging.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: - MetricsServiceV2Client: 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: - MetricsServiceV2Client: 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) -> MetricsServiceV2Transport: - """Returns the transport used by the client instance. - - Returns: - MetricsServiceV2Transport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def log_metric_path(project: str,metric: str,) -> str: - """Returns a fully-qualified log_metric string.""" - return "projects/{project}/metrics/{metric}".format(project=project, metric=metric, ) - - @staticmethod - def parse_log_metric_path(path: str) -> Dict[str,str]: - """Parses a log_metric path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/metrics/(?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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, MetricsServiceV2Transport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the metrics service v2 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, MetricsServiceV2Transport]): 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() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # 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, MetricsServiceV2Transport): - # transport is a MetricsServiceV2Transport instance. - if credentials or client_options.credentials_file: - 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: - 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=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), - ) - - def list_log_metrics(self, - request: Union[logging_metrics.ListLogMetricsRequest, dict] = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListLogMetricsPager: - r"""Lists logs-based metrics. - - Args: - request (Union[google.cloud.logging_v2.types.ListLogMetricsRequest, dict]): - The request object. The parameters to ListLogMetrics. - parent (str): - Required. The name of the project containing the - metrics: - - :: - - "projects/[PROJECT_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.logging_v2.services.metrics_service_v2.pagers.ListLogMetricsPager: - Result returned from ListLogMetrics. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 logging_metrics.ListLogMetricsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_metrics.ListLogMetricsRequest): - request = logging_metrics.ListLogMetricsRequest(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_log_metrics] - - # 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.ListLogMetricsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_log_metric(self, - request: Union[logging_metrics.GetLogMetricRequest, dict] = None, - *, - metric_name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_metrics.LogMetric: - r"""Gets a logs-based metric. - - Args: - request (Union[google.cloud.logging_v2.types.GetLogMetricRequest, dict]): - The request object. The parameters to GetLogMetric. - metric_name (str): - Required. The resource name of the desired metric: - - :: - - "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - - This corresponds to the ``metric_name`` 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.logging_v2.types.LogMetric: - Describes a logs-based metric. The - value of the metric is the number of log - entries that match a logs filter in a - given time interval. - Logs-based metrics can also be used to - extract values from logs and create a - distribution of the values. The - distribution records the statistics of - the extracted values along with an - optional histogram of the values as - specified by the bucket options. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([metric_name]) - 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 logging_metrics.GetLogMetricRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_metrics.GetLogMetricRequest): - request = logging_metrics.GetLogMetricRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if metric_name is not None: - request.metric_name = metric_name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_log_metric] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("metric_name", request.metric_name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_log_metric(self, - request: Union[logging_metrics.CreateLogMetricRequest, dict] = None, - *, - parent: str = None, - metric: logging_metrics.LogMetric = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_metrics.LogMetric: - r"""Creates a logs-based metric. - - Args: - request (Union[google.cloud.logging_v2.types.CreateLogMetricRequest, dict]): - The request object. The parameters to CreateLogMetric. - parent (str): - Required. The resource name of the project in which to - create the metric: - - :: - - "projects/[PROJECT_ID]" - - The new metric must be provided in the request. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - metric (google.cloud.logging_v2.types.LogMetric): - Required. The new logs-based metric, - which must not have an identifier that - already exists. - - This corresponds to the ``metric`` 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.logging_v2.types.LogMetric: - Describes a logs-based metric. The - value of the metric is the number of log - entries that match a logs filter in a - given time interval. - Logs-based metrics can also be used to - extract values from logs and create a - distribution of the values. The - distribution records the statistics of - the extracted values along with an - optional histogram of the values as - specified by the bucket options. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, metric]) - 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 logging_metrics.CreateLogMetricRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_metrics.CreateLogMetricRequest): - request = logging_metrics.CreateLogMetricRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if metric is not None: - request.metric = metric - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_log_metric] - - # 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, - ) - - # Done; return the response. - return response - - def update_log_metric(self, - request: Union[logging_metrics.UpdateLogMetricRequest, dict] = None, - *, - metric_name: str = None, - metric: logging_metrics.LogMetric = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> logging_metrics.LogMetric: - r"""Creates or updates a logs-based metric. - - Args: - request (Union[google.cloud.logging_v2.types.UpdateLogMetricRequest, dict]): - The request object. The parameters to UpdateLogMetric. - metric_name (str): - Required. The resource name of the metric to update: - - :: - - "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - - The updated metric must be provided in the request and - it's ``name`` field must be the same as ``[METRIC_ID]`` - If the metric does not exist in ``[PROJECT_ID]``, then a - new metric is created. - - This corresponds to the ``metric_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - metric (google.cloud.logging_v2.types.LogMetric): - Required. The updated metric. - This corresponds to the ``metric`` 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.logging_v2.types.LogMetric: - Describes a logs-based metric. The - value of the metric is the number of log - entries that match a logs filter in a - given time interval. - Logs-based metrics can also be used to - extract values from logs and create a - distribution of the values. The - distribution records the statistics of - the extracted values along with an - optional histogram of the values as - specified by the bucket options. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([metric_name, metric]) - 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 logging_metrics.UpdateLogMetricRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_metrics.UpdateLogMetricRequest): - request = logging_metrics.UpdateLogMetricRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if metric_name is not None: - request.metric_name = metric_name - if metric is not None: - request.metric = metric - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_log_metric] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("metric_name", request.metric_name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_log_metric(self, - request: Union[logging_metrics.DeleteLogMetricRequest, dict] = None, - *, - metric_name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a logs-based metric. - - Args: - request (Union[google.cloud.logging_v2.types.DeleteLogMetricRequest, dict]): - The request object. The parameters to DeleteLogMetric. - metric_name (str): - Required. The resource name of the metric to delete: - - :: - - "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - - This corresponds to the ``metric_name`` 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. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([metric_name]) - 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 logging_metrics.DeleteLogMetricRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, logging_metrics.DeleteLogMetricRequest): - request = logging_metrics.DeleteLogMetricRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if metric_name is not None: - request.metric_name = metric_name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_log_metric] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("metric_name", request.metric_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-logging", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "MetricsServiceV2Client", -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/pagers.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/pagers.py deleted file mode 100644 index a3faa77a..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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, Sequence, Tuple, Optional, Iterator - -from google.cloud.logging_v2.types import logging_metrics - - -class ListLogMetricsPager: - """A pager for iterating through ``list_log_metrics`` requests. - - This class thinly wraps an initial - :class:`google.cloud.logging_v2.types.ListLogMetricsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``metrics`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListLogMetrics`` requests and continue to iterate - through the ``metrics`` field on the - corresponding responses. - - All the usual :class:`google.cloud.logging_v2.types.ListLogMetricsResponse` - 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[..., logging_metrics.ListLogMetricsResponse], - request: logging_metrics.ListLogMetricsRequest, - response: logging_metrics.ListLogMetricsResponse, - *, - 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.logging_v2.types.ListLogMetricsRequest): - The initial request object. - response (google.cloud.logging_v2.types.ListLogMetricsResponse): - 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 = logging_metrics.ListLogMetricsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[logging_metrics.ListLogMetricsResponse]: - 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[logging_metrics.LogMetric]: - for page in self.pages: - yield from page.metrics - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListLogMetricsAsyncPager: - """A pager for iterating through ``list_log_metrics`` requests. - - This class thinly wraps an initial - :class:`google.cloud.logging_v2.types.ListLogMetricsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``metrics`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListLogMetrics`` requests and continue to iterate - through the ``metrics`` field on the - corresponding responses. - - All the usual :class:`google.cloud.logging_v2.types.ListLogMetricsResponse` - 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[logging_metrics.ListLogMetricsResponse]], - request: logging_metrics.ListLogMetricsRequest, - response: logging_metrics.ListLogMetricsResponse, - *, - 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.logging_v2.types.ListLogMetricsRequest): - The initial request object. - response (google.cloud.logging_v2.types.ListLogMetricsResponse): - 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 = logging_metrics.ListLogMetricsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[logging_metrics.ListLogMetricsResponse]: - 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[logging_metrics.LogMetric]: - async def async_generator(): - async for page in self.pages: - for response in page.metrics: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/transports/__init__.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/transports/__init__.py deleted file mode 100644 index 28e9b710..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 MetricsServiceV2Transport -from .grpc import MetricsServiceV2GrpcTransport -from .grpc_asyncio import MetricsServiceV2GrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[MetricsServiceV2Transport]] -_transport_registry['grpc'] = MetricsServiceV2GrpcTransport -_transport_registry['grpc_asyncio'] = MetricsServiceV2GrpcAsyncIOTransport - -__all__ = ( - 'MetricsServiceV2Transport', - 'MetricsServiceV2GrpcTransport', - 'MetricsServiceV2GrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py deleted file mode 100644 index b9170bf5..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py +++ /dev/null @@ -1,261 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.logging_v2.types import logging_metrics -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-logging', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class MetricsServiceV2Transport(abc.ABC): - """Abstract transport class for MetricsServiceV2.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', - ) - - DEFAULT_HOST: str = 'logging.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, - **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. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, 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) - - # 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 - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_log_metrics: gapic_v1.method.wrap_method( - self.list_log_metrics, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_log_metric: gapic_v1.method.wrap_method( - self.get_log_metric, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_log_metric: gapic_v1.method.wrap_method( - self.create_log_metric, - default_timeout=60.0, - client_info=client_info, - ), - self.update_log_metric: gapic_v1.method.wrap_method( - self.update_log_metric, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_log_metric: gapic_v1.method.wrap_method( - self.delete_log_metric, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.InternalServerError, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - } - - @property - def list_log_metrics(self) -> Callable[ - [logging_metrics.ListLogMetricsRequest], - Union[ - logging_metrics.ListLogMetricsResponse, - Awaitable[logging_metrics.ListLogMetricsResponse] - ]]: - raise NotImplementedError() - - @property - def get_log_metric(self) -> Callable[ - [logging_metrics.GetLogMetricRequest], - Union[ - logging_metrics.LogMetric, - Awaitable[logging_metrics.LogMetric] - ]]: - raise NotImplementedError() - - @property - def create_log_metric(self) -> Callable[ - [logging_metrics.CreateLogMetricRequest], - Union[ - logging_metrics.LogMetric, - Awaitable[logging_metrics.LogMetric] - ]]: - raise NotImplementedError() - - @property - def update_log_metric(self) -> Callable[ - [logging_metrics.UpdateLogMetricRequest], - Union[ - logging_metrics.LogMetric, - Awaitable[logging_metrics.LogMetric] - ]]: - raise NotImplementedError() - - @property - def delete_log_metric(self) -> Callable[ - [logging_metrics.DeleteLogMetricRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'MetricsServiceV2Transport', -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py deleted file mode 100644 index e300d9f5..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc.py +++ /dev/null @@ -1,357 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.logging_v2.types import logging_metrics -from google.protobuf import empty_pb2 # type: ignore -from .base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO - - -class MetricsServiceV2GrpcTransport(MetricsServiceV2Transport): - """gRPC backend transport for MetricsServiceV2. - - Service for configuring logs-based metrics. - - 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 = 'logging.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, - ) -> 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] = {} - - 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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 = 'logging.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 list_log_metrics(self) -> Callable[ - [logging_metrics.ListLogMetricsRequest], - logging_metrics.ListLogMetricsResponse]: - r"""Return a callable for the list log metrics method over gRPC. - - Lists logs-based metrics. - - Returns: - Callable[[~.ListLogMetricsRequest], - ~.ListLogMetricsResponse]: - 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_log_metrics' not in self._stubs: - self._stubs['list_log_metrics'] = self.grpc_channel.unary_unary( - '/google.logging.v2.MetricsServiceV2/ListLogMetrics', - request_serializer=logging_metrics.ListLogMetricsRequest.serialize, - response_deserializer=logging_metrics.ListLogMetricsResponse.deserialize, - ) - return self._stubs['list_log_metrics'] - - @property - def get_log_metric(self) -> Callable[ - [logging_metrics.GetLogMetricRequest], - logging_metrics.LogMetric]: - r"""Return a callable for the get log metric method over gRPC. - - Gets a logs-based metric. - - Returns: - Callable[[~.GetLogMetricRequest], - ~.LogMetric]: - 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 'get_log_metric' not in self._stubs: - self._stubs['get_log_metric'] = self.grpc_channel.unary_unary( - '/google.logging.v2.MetricsServiceV2/GetLogMetric', - request_serializer=logging_metrics.GetLogMetricRequest.serialize, - response_deserializer=logging_metrics.LogMetric.deserialize, - ) - return self._stubs['get_log_metric'] - - @property - def create_log_metric(self) -> Callable[ - [logging_metrics.CreateLogMetricRequest], - logging_metrics.LogMetric]: - r"""Return a callable for the create log metric method over gRPC. - - Creates a logs-based metric. - - Returns: - Callable[[~.CreateLogMetricRequest], - ~.LogMetric]: - 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 'create_log_metric' not in self._stubs: - self._stubs['create_log_metric'] = self.grpc_channel.unary_unary( - '/google.logging.v2.MetricsServiceV2/CreateLogMetric', - request_serializer=logging_metrics.CreateLogMetricRequest.serialize, - response_deserializer=logging_metrics.LogMetric.deserialize, - ) - return self._stubs['create_log_metric'] - - @property - def update_log_metric(self) -> Callable[ - [logging_metrics.UpdateLogMetricRequest], - logging_metrics.LogMetric]: - r"""Return a callable for the update log metric method over gRPC. - - Creates or updates a logs-based metric. - - Returns: - Callable[[~.UpdateLogMetricRequest], - ~.LogMetric]: - 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 'update_log_metric' not in self._stubs: - self._stubs['update_log_metric'] = self.grpc_channel.unary_unary( - '/google.logging.v2.MetricsServiceV2/UpdateLogMetric', - request_serializer=logging_metrics.UpdateLogMetricRequest.serialize, - response_deserializer=logging_metrics.LogMetric.deserialize, - ) - return self._stubs['update_log_metric'] - - @property - def delete_log_metric(self) -> Callable[ - [logging_metrics.DeleteLogMetricRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete log metric method over gRPC. - - Deletes a logs-based metric. - - Returns: - Callable[[~.DeleteLogMetricRequest], - ~.Empty]: - 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 'delete_log_metric' not in self._stubs: - self._stubs['delete_log_metric'] = self.grpc_channel.unary_unary( - '/google.logging.v2.MetricsServiceV2/DeleteLogMetric', - request_serializer=logging_metrics.DeleteLogMetricRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_log_metric'] - - -__all__ = ( - 'MetricsServiceV2GrpcTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc_asyncio.py b/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc_asyncio.py deleted file mode 100644 index 7da83282..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/services/metrics_service_v2/transports/grpc_asyncio.py +++ /dev/null @@ -1,361 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.logging_v2.types import logging_metrics -from google.protobuf import empty_pb2 # type: ignore -from .base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO -from .grpc import MetricsServiceV2GrpcTransport - - -class MetricsServiceV2GrpcAsyncIOTransport(MetricsServiceV2Transport): - """gRPC AsyncIO backend transport for MetricsServiceV2. - - Service for configuring logs-based metrics. - - 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 = 'logging.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 = 'logging.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, - ) -> 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] = {} - - 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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 list_log_metrics(self) -> Callable[ - [logging_metrics.ListLogMetricsRequest], - Awaitable[logging_metrics.ListLogMetricsResponse]]: - r"""Return a callable for the list log metrics method over gRPC. - - Lists logs-based metrics. - - Returns: - Callable[[~.ListLogMetricsRequest], - Awaitable[~.ListLogMetricsResponse]]: - 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_log_metrics' not in self._stubs: - self._stubs['list_log_metrics'] = self.grpc_channel.unary_unary( - '/google.logging.v2.MetricsServiceV2/ListLogMetrics', - request_serializer=logging_metrics.ListLogMetricsRequest.serialize, - response_deserializer=logging_metrics.ListLogMetricsResponse.deserialize, - ) - return self._stubs['list_log_metrics'] - - @property - def get_log_metric(self) -> Callable[ - [logging_metrics.GetLogMetricRequest], - Awaitable[logging_metrics.LogMetric]]: - r"""Return a callable for the get log metric method over gRPC. - - Gets a logs-based metric. - - Returns: - Callable[[~.GetLogMetricRequest], - Awaitable[~.LogMetric]]: - 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 'get_log_metric' not in self._stubs: - self._stubs['get_log_metric'] = self.grpc_channel.unary_unary( - '/google.logging.v2.MetricsServiceV2/GetLogMetric', - request_serializer=logging_metrics.GetLogMetricRequest.serialize, - response_deserializer=logging_metrics.LogMetric.deserialize, - ) - return self._stubs['get_log_metric'] - - @property - def create_log_metric(self) -> Callable[ - [logging_metrics.CreateLogMetricRequest], - Awaitable[logging_metrics.LogMetric]]: - r"""Return a callable for the create log metric method over gRPC. - - Creates a logs-based metric. - - Returns: - Callable[[~.CreateLogMetricRequest], - Awaitable[~.LogMetric]]: - 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 'create_log_metric' not in self._stubs: - self._stubs['create_log_metric'] = self.grpc_channel.unary_unary( - '/google.logging.v2.MetricsServiceV2/CreateLogMetric', - request_serializer=logging_metrics.CreateLogMetricRequest.serialize, - response_deserializer=logging_metrics.LogMetric.deserialize, - ) - return self._stubs['create_log_metric'] - - @property - def update_log_metric(self) -> Callable[ - [logging_metrics.UpdateLogMetricRequest], - Awaitable[logging_metrics.LogMetric]]: - r"""Return a callable for the update log metric method over gRPC. - - Creates or updates a logs-based metric. - - Returns: - Callable[[~.UpdateLogMetricRequest], - Awaitable[~.LogMetric]]: - 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 'update_log_metric' not in self._stubs: - self._stubs['update_log_metric'] = self.grpc_channel.unary_unary( - '/google.logging.v2.MetricsServiceV2/UpdateLogMetric', - request_serializer=logging_metrics.UpdateLogMetricRequest.serialize, - response_deserializer=logging_metrics.LogMetric.deserialize, - ) - return self._stubs['update_log_metric'] - - @property - def delete_log_metric(self) -> Callable[ - [logging_metrics.DeleteLogMetricRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete log metric method over gRPC. - - Deletes a logs-based metric. - - Returns: - Callable[[~.DeleteLogMetricRequest], - Awaitable[~.Empty]]: - 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 'delete_log_metric' not in self._stubs: - self._stubs['delete_log_metric'] = self.grpc_channel.unary_unary( - '/google.logging.v2.MetricsServiceV2/DeleteLogMetric', - request_serializer=logging_metrics.DeleteLogMetricRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_log_metric'] - - -__all__ = ( - 'MetricsServiceV2GrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/types/__init__.py b/owl-bot-staging/v2/google/cloud/logging_v2/types/__init__.py deleted file mode 100644 index 38c93c54..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/types/__init__.py +++ /dev/null @@ -1,138 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 .log_entry import ( - LogEntry, - LogEntryOperation, - LogEntrySourceLocation, -) -from .logging import ( - DeleteLogRequest, - ListLogEntriesRequest, - ListLogEntriesResponse, - ListLogsRequest, - ListLogsResponse, - ListMonitoredResourceDescriptorsRequest, - ListMonitoredResourceDescriptorsResponse, - TailLogEntriesRequest, - TailLogEntriesResponse, - WriteLogEntriesPartialErrors, - WriteLogEntriesRequest, - WriteLogEntriesResponse, -) -from .logging_config import ( - BigQueryOptions, - CmekSettings, - CreateBucketRequest, - CreateExclusionRequest, - CreateSinkRequest, - CreateViewRequest, - DeleteBucketRequest, - DeleteExclusionRequest, - DeleteSinkRequest, - DeleteViewRequest, - GetBucketRequest, - GetCmekSettingsRequest, - GetExclusionRequest, - GetSinkRequest, - GetViewRequest, - ListBucketsRequest, - ListBucketsResponse, - ListExclusionsRequest, - ListExclusionsResponse, - ListSinksRequest, - ListSinksResponse, - ListViewsRequest, - ListViewsResponse, - LogBucket, - LogExclusion, - LogSink, - LogView, - UndeleteBucketRequest, - UpdateBucketRequest, - UpdateCmekSettingsRequest, - UpdateExclusionRequest, - UpdateSinkRequest, - UpdateViewRequest, - LifecycleState, -) -from .logging_metrics import ( - CreateLogMetricRequest, - DeleteLogMetricRequest, - GetLogMetricRequest, - ListLogMetricsRequest, - ListLogMetricsResponse, - LogMetric, - UpdateLogMetricRequest, -) - -__all__ = ( - 'LogEntry', - 'LogEntryOperation', - 'LogEntrySourceLocation', - 'DeleteLogRequest', - 'ListLogEntriesRequest', - 'ListLogEntriesResponse', - 'ListLogsRequest', - 'ListLogsResponse', - 'ListMonitoredResourceDescriptorsRequest', - 'ListMonitoredResourceDescriptorsResponse', - 'TailLogEntriesRequest', - 'TailLogEntriesResponse', - 'WriteLogEntriesPartialErrors', - 'WriteLogEntriesRequest', - 'WriteLogEntriesResponse', - 'BigQueryOptions', - 'CmekSettings', - 'CreateBucketRequest', - 'CreateExclusionRequest', - 'CreateSinkRequest', - 'CreateViewRequest', - 'DeleteBucketRequest', - 'DeleteExclusionRequest', - 'DeleteSinkRequest', - 'DeleteViewRequest', - 'GetBucketRequest', - 'GetCmekSettingsRequest', - 'GetExclusionRequest', - 'GetSinkRequest', - 'GetViewRequest', - 'ListBucketsRequest', - 'ListBucketsResponse', - 'ListExclusionsRequest', - 'ListExclusionsResponse', - 'ListSinksRequest', - 'ListSinksResponse', - 'ListViewsRequest', - 'ListViewsResponse', - 'LogBucket', - 'LogExclusion', - 'LogSink', - 'LogView', - 'UndeleteBucketRequest', - 'UpdateBucketRequest', - 'UpdateCmekSettingsRequest', - 'UpdateExclusionRequest', - 'UpdateSinkRequest', - 'UpdateViewRequest', - 'LifecycleState', - 'CreateLogMetricRequest', - 'DeleteLogMetricRequest', - 'GetLogMetricRequest', - 'ListLogMetricsRequest', - 'ListLogMetricsResponse', - 'LogMetric', - 'UpdateLogMetricRequest', -) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/types/log_entry.py b/owl-bot-staging/v2/google/cloud/logging_v2/types/log_entry.py deleted file mode 100644 index 45b1c885..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/types/log_entry.py +++ /dev/null @@ -1,321 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 proto # type: ignore - -from google.api import monitored_resource_pb2 # type: ignore -from google.logging.type import http_request_pb2 # type: ignore -from google.logging.type import log_severity_pb2 # type: ignore -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.logging.v2', - manifest={ - 'LogEntry', - 'LogEntryOperation', - 'LogEntrySourceLocation', - }, -) - - -class LogEntry(proto.Message): - r"""An individual entry in a log. - Attributes: - log_name (str): - Required. The resource name of the log to which this log - entry belongs: - - :: - - "projects/[PROJECT_ID]/logs/[LOG_ID]" - "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" - "folders/[FOLDER_ID]/logs/[LOG_ID]" - - A project number may be used in place of PROJECT_ID. The - project number is translated to its corresponding PROJECT_ID - internally and the ``log_name`` field will contain - PROJECT_ID in queries and exports. - - ``[LOG_ID]`` must be URL-encoded within ``log_name``. - Example: - ``"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"``. - ``[LOG_ID]`` must be less than 512 characters long and can - only include the following characters: upper and lower case - alphanumeric characters, forward-slash, underscore, hyphen, - and period. - - For backward compatibility, if ``log_name`` begins with a - forward-slash, such as ``/projects/...``, then the log entry - is ingested as usual but the forward-slash is removed. - Listing the log entry will not show the leading slash and - filtering for a log name with a leading slash will never - return any results. - resource (google.api.monitored_resource_pb2.MonitoredResource): - Required. The monitored resource that - produced this log entry. - Example: a log entry that reports a database - error would be associated with the monitored - resource designating the particular database - that reported the error. - proto_payload (google.protobuf.any_pb2.Any): - The log entry payload, represented as a - protocol buffer. Some Google Cloud Platform - services use this field for their log entry - payloads. - The following protocol buffer types are - supported; user-defined types are not supported: - - "type.googleapis.com/google.cloud.audit.AuditLog" - "type.googleapis.com/google.appengine.logging.v1.RequestLog". - text_payload (str): - The log entry payload, represented as a - Unicode string (UTF-8). - json_payload (google.protobuf.struct_pb2.Struct): - The log entry payload, represented as a - structure that is expressed as a JSON object. - timestamp (google.protobuf.timestamp_pb2.Timestamp): - Optional. The time the event described by the log entry - occurred. This time is used to compute the log entry's age - and to enforce the logs retention period. If this field is - omitted in a new log entry, then Logging assigns it the - current time. Timestamps have nanosecond accuracy, but - trailing zeros in the fractional seconds might be omitted - when the timestamp is displayed. - - Incoming log entries must have timestamps that don't exceed - the `logs retention - period `__ - in the past, and that don't exceed 24 hours in the future. - Log entries outside those time boundaries aren't ingested by - Logging. - receive_timestamp (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the log entry was - received by Logging. - severity (google.logging.type.log_severity_pb2.LogSeverity): - Optional. The severity of the log entry. The default value - is ``LogSeverity.DEFAULT``. - insert_id (str): - Optional. A unique identifier for the log entry. If you - provide a value, then Logging considers other log entries in - the same project, with the same ``timestamp``, and with the - same ``insert_id`` to be duplicates which are removed in a - single query result. However, there are no guarantees of - de-duplication in the export of logs. - - If the ``insert_id`` is omitted when writing a log entry, - the Logging API assigns its own unique identifier in this - field. - - In queries, the ``insert_id`` is also used to order log - entries that have the same ``log_name`` and ``timestamp`` - values. - http_request (google.logging.type.http_request_pb2.HttpRequest): - Optional. Information about the HTTP request - associated with this log entry, if applicable. - labels (Sequence[google.cloud.logging_v2.types.LogEntry.LabelsEntry]): - Optional. A set of user-defined (key, value) - data that provides additional information about - the log entry. - operation (google.cloud.logging_v2.types.LogEntryOperation): - Optional. Information about an operation - associated with the log entry, if applicable. - trace (str): - Optional. Resource name of the trace associated with the log - entry, if any. If it contains a relative resource name, the - name is assumed to be relative to - ``//tracing.googleapis.com``. Example: - ``projects/my-projectid/traces/06796866738c859f2f19b7cfb3214824`` - span_id (str): - Optional. The span ID within the trace associated with the - log entry. - - For Trace spans, this is the same format that the Trace API - v2 uses: a 16-character hexadecimal encoding of an 8-byte - array, such as ``000000000000004a``. - trace_sampled (bool): - Optional. The sampling decision of the trace associated with - the log entry. - - True means that the trace resource name in the ``trace`` - field was sampled for storage in a trace backend. False - means that the trace was not sampled for storage when this - log entry was written, or the sampling decision was unknown - at the time. A non-sampled ``trace`` value is still useful - as a request correlation identifier. The default is False. - source_location (google.cloud.logging_v2.types.LogEntrySourceLocation): - Optional. Source code location information - associated with the log entry, if any. - """ - - log_name = proto.Field( - proto.STRING, - number=12, - ) - resource = proto.Field( - proto.MESSAGE, - number=8, - message=monitored_resource_pb2.MonitoredResource, - ) - proto_payload = proto.Field( - proto.MESSAGE, - number=2, - oneof='payload', - message=any_pb2.Any, - ) - text_payload = proto.Field( - proto.STRING, - number=3, - oneof='payload', - ) - json_payload = proto.Field( - proto.MESSAGE, - number=6, - oneof='payload', - message=struct_pb2.Struct, - ) - timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - receive_timestamp = proto.Field( - proto.MESSAGE, - number=24, - message=timestamp_pb2.Timestamp, - ) - severity = proto.Field( - proto.ENUM, - number=10, - enum=log_severity_pb2.LogSeverity, - ) - insert_id = proto.Field( - proto.STRING, - number=4, - ) - http_request = proto.Field( - proto.MESSAGE, - number=7, - message=http_request_pb2.HttpRequest, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=11, - ) - operation = proto.Field( - proto.MESSAGE, - number=15, - message='LogEntryOperation', - ) - trace = proto.Field( - proto.STRING, - number=22, - ) - span_id = proto.Field( - proto.STRING, - number=27, - ) - trace_sampled = proto.Field( - proto.BOOL, - number=30, - ) - source_location = proto.Field( - proto.MESSAGE, - number=23, - message='LogEntrySourceLocation', - ) - - -class LogEntryOperation(proto.Message): - r"""Additional information about a potentially long-running - operation with which a log entry is associated. - - Attributes: - id (str): - Optional. An arbitrary operation identifier. - Log entries with the same identifier are assumed - to be part of the same operation. - producer (str): - Optional. An arbitrary producer identifier. The combination - of ``id`` and ``producer`` must be globally unique. Examples - for ``producer``: ``"MyDivision.MyBigCompany.com"``, - ``"github.com/MyProject/MyApplication"``. - first (bool): - Optional. Set this to True if this is the - first log entry in the operation. - last (bool): - Optional. Set this to True if this is the - last log entry in the operation. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - producer = proto.Field( - proto.STRING, - number=2, - ) - first = proto.Field( - proto.BOOL, - number=3, - ) - last = proto.Field( - proto.BOOL, - number=4, - ) - - -class LogEntrySourceLocation(proto.Message): - r"""Additional information about the source code location that - produced the log entry. - - Attributes: - file (str): - Optional. Source file name. Depending on the - runtime environment, this might be a simple name - or a fully-qualified name. - line (int): - Optional. Line within the source file. - 1-based; 0 indicates no line number available. - function (str): - Optional. Human-readable name of the function or method - being invoked, with optional context such as the class or - package name. This information may be used in contexts such - as the logs viewer, where a file and line number are less - meaningful. The format can vary by language. For example: - ``qual.if.ied.Class.method`` (Java), ``dir/package.func`` - (Go), ``function`` (Python). - """ - - file = proto.Field( - proto.STRING, - number=1, - ) - line = proto.Field( - proto.INT64, - number=2, - ) - function = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/types/logging.py b/owl-bot-staging/v2/google/cloud/logging_v2/types/logging.py deleted file mode 100644 index cfae1781..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/types/logging.py +++ /dev/null @@ -1,573 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 proto # type: ignore - -from google.api import monitored_resource_pb2 # type: ignore -from google.cloud.logging_v2.types import log_entry -from google.protobuf import duration_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.logging.v2', - manifest={ - 'DeleteLogRequest', - 'WriteLogEntriesRequest', - 'WriteLogEntriesResponse', - 'WriteLogEntriesPartialErrors', - 'ListLogEntriesRequest', - 'ListLogEntriesResponse', - 'ListMonitoredResourceDescriptorsRequest', - 'ListMonitoredResourceDescriptorsResponse', - 'ListLogsRequest', - 'ListLogsResponse', - 'TailLogEntriesRequest', - 'TailLogEntriesResponse', - }, -) - - -class DeleteLogRequest(proto.Message): - r"""The parameters to DeleteLog. - Attributes: - log_name (str): - Required. The resource name of the log to delete: - - :: - - "projects/[PROJECT_ID]/logs/[LOG_ID]" - "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" - "folders/[FOLDER_ID]/logs/[LOG_ID]" - - ``[LOG_ID]`` must be URL-encoded. For example, - ``"projects/my-project-id/logs/syslog"``, - ``"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"``. - For more information about log names, see - [LogEntry][google.logging.v2.LogEntry]. - """ - - log_name = proto.Field( - proto.STRING, - number=1, - ) - - -class WriteLogEntriesRequest(proto.Message): - r"""The parameters to WriteLogEntries. - Attributes: - log_name (str): - Optional. A default log resource name that is assigned to - all log entries in ``entries`` that do not specify a value - for ``log_name``: - - :: - - "projects/[PROJECT_ID]/logs/[LOG_ID]" - "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" - "folders/[FOLDER_ID]/logs/[LOG_ID]" - - ``[LOG_ID]`` must be URL-encoded. For example: - - :: - - "projects/my-project-id/logs/syslog" - "organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity" - - The permission ``logging.logEntries.create`` is needed on - each project, organization, billing account, or folder that - is receiving new log entries, whether the resource is - specified in ``logName`` or in an individual log entry. - resource (google.api.monitored_resource_pb2.MonitoredResource): - Optional. A default monitored resource object that is - assigned to all log entries in ``entries`` that do not - specify a value for ``resource``. Example: - - :: - - { "type": "gce_instance", - "labels": { - "zone": "us-central1-a", "instance_id": "00000000000000000000" }} - - See [LogEntry][google.logging.v2.LogEntry]. - labels (Sequence[google.cloud.logging_v2.types.WriteLogEntriesRequest.LabelsEntry]): - Optional. Default labels that are added to the ``labels`` - field of all log entries in ``entries``. If a log entry - already has a label with the same key as a label in this - parameter, then the log entry's label is not changed. See - [LogEntry][google.logging.v2.LogEntry]. - entries (Sequence[google.cloud.logging_v2.types.LogEntry]): - Required. The log entries to send to Logging. The order of - log entries in this list does not matter. Values supplied in - this method's ``log_name``, ``resource``, and ``labels`` - fields are copied into those log entries in this list that - do not include values for their corresponding fields. For - more information, see the - [LogEntry][google.logging.v2.LogEntry] type. - - If the ``timestamp`` or ``insert_id`` fields are missing in - log entries, then this method supplies the current time or a - unique identifier, respectively. The supplied values are - chosen so that, among the log entries that did not supply - their own values, the entries earlier in the list will sort - before the entries later in the list. See the - ``entries.list`` method. - - Log entries with timestamps that are more than the `logs - retention - period `__ in - the past or more than 24 hours in the future will not be - available when calling ``entries.list``. However, those log - entries can still be `exported with - LogSinks `__. - - To improve throughput and to avoid exceeding the `quota - limit `__ for - calls to ``entries.write``, you should try to include - several log entries in this list, rather than calling this - method for each individual log entry. - partial_success (bool): - Optional. Whether valid entries should be written even if - some other entries fail due to INVALID_ARGUMENT or - PERMISSION_DENIED errors. If any entry is not written, then - the response status is the error associated with one of the - failed entries and the response includes error details keyed - by the entries' zero-based index in the ``entries.write`` - method. - dry_run (bool): - Optional. If true, the request should expect - normal response, but the entries won't be - persisted nor exported. Useful for checking - whether the logging API endpoints are working - properly before sending valuable data. - """ - - log_name = proto.Field( - proto.STRING, - number=1, - ) - resource = proto.Field( - proto.MESSAGE, - number=2, - message=monitored_resource_pb2.MonitoredResource, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=3, - ) - entries = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=log_entry.LogEntry, - ) - partial_success = proto.Field( - proto.BOOL, - number=5, - ) - dry_run = proto.Field( - proto.BOOL, - number=6, - ) - - -class WriteLogEntriesResponse(proto.Message): - r"""Result returned from WriteLogEntries. """ - - -class WriteLogEntriesPartialErrors(proto.Message): - r"""Error details for WriteLogEntries with partial success. - Attributes: - log_entry_errors (Sequence[google.cloud.logging_v2.types.WriteLogEntriesPartialErrors.LogEntryErrorsEntry]): - When ``WriteLogEntriesRequest.partial_success`` is true, - records the error status for entries that were not written - due to a permanent error, keyed by the entry's zero-based - index in ``WriteLogEntriesRequest.entries``. - - Failed requests for which no entries are written will not - include per-entry errors. - """ - - log_entry_errors = proto.MapField( - proto.INT32, - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - - -class ListLogEntriesRequest(proto.Message): - r"""The parameters to ``ListLogEntries``. - Attributes: - resource_names (Sequence[str]): - Required. Names of one or more parent resources from which - to retrieve log entries: - - :: - - "projects/[PROJECT_ID]" - "organizations/[ORGANIZATION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]" - "folders/[FOLDER_ID]" - - May alternatively be one or more views - projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID] - organization/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID] - billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID] - folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID] - - Projects listed in the ``project_ids`` field are added to - this list. - filter (str): - Optional. A filter that chooses which log entries to return. - See `Advanced Logs - Queries `__. - Only log entries that match the filter are returned. An - empty filter matches all log entries in the resources listed - in ``resource_names``. Referencing a parent resource that is - not listed in ``resource_names`` will cause the filter to - return no results. The maximum length of the filter is 20000 - characters. - order_by (str): - Optional. How the results should be sorted. Presently, the - only permitted values are ``"timestamp asc"`` (default) and - ``"timestamp desc"``. The first option returns entries in - order of increasing values of ``LogEntry.timestamp`` (oldest - first), and the second option returns entries in order of - decreasing timestamps (newest first). Entries with equal - timestamps are returned in order of their ``insert_id`` - values. - page_size (int): - Optional. The maximum number of results to return from this - request. Default is 50. If the value is negative or exceeds - 1000, the request is rejected. The presence of - ``next_page_token`` in the response indicates that more - results might be available. - page_token (str): - Optional. If present, then retrieve the next batch of - results from the preceding call to this method. - ``page_token`` must be the value of ``next_page_token`` from - the previous response. The values of other method parameters - should be identical to those in the previous call. - """ - - resource_names = proto.RepeatedField( - proto.STRING, - number=8, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - order_by = proto.Field( - proto.STRING, - number=3, - ) - page_size = proto.Field( - proto.INT32, - number=4, - ) - page_token = proto.Field( - proto.STRING, - number=5, - ) - - -class ListLogEntriesResponse(proto.Message): - r"""Result returned from ``ListLogEntries``. - Attributes: - entries (Sequence[google.cloud.logging_v2.types.LogEntry]): - A list of log entries. If ``entries`` is empty, - ``nextPageToken`` may still be returned, indicating that - more entries may exist. See ``nextPageToken`` for more - information. - next_page_token (str): - If there might be more results than those appearing in this - response, then ``nextPageToken`` is included. To get the - next set of results, call this method again using the value - of ``nextPageToken`` as ``pageToken``. - - If a value for ``next_page_token`` appears and the - ``entries`` field is empty, it means that the search found - no log entries so far but it did not have time to search all - the possible log entries. Retry the method with this value - for ``page_token`` to continue the search. Alternatively, - consider speeding up the search by changing your filter to - specify a single log name or resource type, or to narrow the - time range of the search. - """ - - @property - def raw_page(self): - return self - - entries = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=log_entry.LogEntry, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class ListMonitoredResourceDescriptorsRequest(proto.Message): - r"""The parameters to ListMonitoredResourceDescriptors - Attributes: - page_size (int): - Optional. The maximum number of results to return from this - request. Non-positive values are ignored. The presence of - ``nextPageToken`` in the response indicates that more - results might be available. - page_token (str): - Optional. If present, then retrieve the next batch of - results from the preceding call to this method. - ``pageToken`` must be the value of ``nextPageToken`` from - the previous response. The values of other method parameters - should be identical to those in the previous call. - """ - - page_size = proto.Field( - proto.INT32, - number=1, - ) - page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class ListMonitoredResourceDescriptorsResponse(proto.Message): - r"""Result returned from ListMonitoredResourceDescriptors. - Attributes: - resource_descriptors (Sequence[google.api.monitored_resource_pb2.MonitoredResourceDescriptor]): - A list of resource descriptors. - next_page_token (str): - If there might be more results than those appearing in this - response, then ``nextPageToken`` is included. To get the - next set of results, call this method again using the value - of ``nextPageToken`` as ``pageToken``. - """ - - @property - def raw_page(self): - return self - - resource_descriptors = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=monitored_resource_pb2.MonitoredResourceDescriptor, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class ListLogsRequest(proto.Message): - r"""The parameters to ListLogs. - Attributes: - parent (str): - Required. The resource name that owns the logs: - - :: - - "projects/[PROJECT_ID]" - "organizations/[ORGANIZATION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]" - "folders/[FOLDER_ID]". - page_size (int): - Optional. The maximum number of results to return from this - request. Non-positive values are ignored. The presence of - ``nextPageToken`` in the response indicates that more - results might be available. - page_token (str): - Optional. If present, then retrieve the next batch of - results from the preceding call to this method. - ``pageToken`` must be the value of ``nextPageToken`` from - the previous response. The values of other method parameters - should be identical to those in the previous call. - resource_names (Sequence[str]): - Optional. The resource name that owns the logs: - projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID] - organization/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID] - billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID] - folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID] - - To support legacy queries, it could also be: - "projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]". - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - resource_names = proto.RepeatedField( - proto.STRING, - number=8, - ) - - -class ListLogsResponse(proto.Message): - r"""Result returned from ListLogs. - Attributes: - log_names (Sequence[str]): - A list of log names. For example, - ``"projects/my-project/logs/syslog"`` or - ``"organizations/123/logs/cloudresourcemanager.googleapis.com%2Factivity"``. - next_page_token (str): - If there might be more results than those appearing in this - response, then ``nextPageToken`` is included. To get the - next set of results, call this method again using the value - of ``nextPageToken`` as ``pageToken``. - """ - - @property - def raw_page(self): - return self - - log_names = proto.RepeatedField( - proto.STRING, - number=3, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class TailLogEntriesRequest(proto.Message): - r"""The parameters to ``TailLogEntries``. - Attributes: - resource_names (Sequence[str]): - Required. Name of a parent resource from which to retrieve - log entries: - - :: - - "projects/[PROJECT_ID]" - "organizations/[ORGANIZATION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]" - "folders/[FOLDER_ID]" - - May alternatively be one or more views: - "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" - "organization/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" - "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]". - filter (str): - Optional. A filter that chooses which log entries to return. - See `Advanced Logs - Filters `__. - Only log entries that match the filter are returned. An - empty filter matches all log entries in the resources listed - in ``resource_names``. Referencing a parent resource that is - not in ``resource_names`` will cause the filter to return no - results. The maximum length of the filter is 20000 - characters. - buffer_window (google.protobuf.duration_pb2.Duration): - Optional. The amount of time to buffer log - entries at the server before being returned to - prevent out of order results due to late - arriving log entries. Valid values are between - 0-60000 milliseconds. Defaults to 2000 - milliseconds. - """ - - resource_names = proto.RepeatedField( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - buffer_window = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - - -class TailLogEntriesResponse(proto.Message): - r"""Result returned from ``TailLogEntries``. - Attributes: - entries (Sequence[google.cloud.logging_v2.types.LogEntry]): - A list of log entries. Each response in the stream will - order entries with increasing values of - ``LogEntry.timestamp``. Ordering is not guaranteed between - separate responses. - suppression_info (Sequence[google.cloud.logging_v2.types.TailLogEntriesResponse.SuppressionInfo]): - If entries that otherwise would have been - included in the session were not sent back to - the client, counts of relevant entries omitted - from the session with the reason that they were - not included. There will be at most one of each - reason per response. The counts represent the - number of suppressed entries since the last - streamed response. - """ - - class SuppressionInfo(proto.Message): - r"""Information about entries that were omitted from the session. - Attributes: - reason (google.cloud.logging_v2.types.TailLogEntriesResponse.SuppressionInfo.Reason): - The reason that entries were omitted from the - session. - suppressed_count (int): - A lower bound on the count of entries omitted due to - ``reason``. - """ - class Reason(proto.Enum): - r"""An indicator of why entries were omitted.""" - REASON_UNSPECIFIED = 0 - RATE_LIMIT = 1 - NOT_CONSUMED = 2 - - reason = proto.Field( - proto.ENUM, - number=1, - enum='TailLogEntriesResponse.SuppressionInfo.Reason', - ) - suppressed_count = proto.Field( - proto.INT32, - number=2, - ) - - entries = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=log_entry.LogEntry, - ) - suppression_info = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=SuppressionInfo, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/types/logging_config.py b/owl-bot-staging/v2/google/cloud/logging_v2/types/logging_config.py deleted file mode 100644 index a4b7b257..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/types/logging_config.py +++ /dev/null @@ -1,1457 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.logging.v2', - manifest={ - 'LifecycleState', - 'LogBucket', - 'LogView', - 'LogSink', - 'BigQueryOptions', - 'ListBucketsRequest', - 'ListBucketsResponse', - 'CreateBucketRequest', - 'UpdateBucketRequest', - 'GetBucketRequest', - 'DeleteBucketRequest', - 'UndeleteBucketRequest', - 'ListViewsRequest', - 'ListViewsResponse', - 'CreateViewRequest', - 'UpdateViewRequest', - 'GetViewRequest', - 'DeleteViewRequest', - 'ListSinksRequest', - 'ListSinksResponse', - 'GetSinkRequest', - 'CreateSinkRequest', - 'UpdateSinkRequest', - 'DeleteSinkRequest', - 'LogExclusion', - 'ListExclusionsRequest', - 'ListExclusionsResponse', - 'GetExclusionRequest', - 'CreateExclusionRequest', - 'UpdateExclusionRequest', - 'DeleteExclusionRequest', - 'GetCmekSettingsRequest', - 'UpdateCmekSettingsRequest', - 'CmekSettings', - }, -) - - -class LifecycleState(proto.Enum): - r"""LogBucket lifecycle states.""" - LIFECYCLE_STATE_UNSPECIFIED = 0 - ACTIVE = 1 - DELETE_REQUESTED = 2 - - -class LogBucket(proto.Message): - r"""Describes a repository of logs. - Attributes: - name (str): - The resource name of the bucket. For example: - "projects/my-project-id/locations/my-location/buckets/my-bucket-id - The supported locations are: "global" - - For the location of ``global`` it is unspecified where logs - are actually stored. Once a bucket has been created, the - location can not be changed. - description (str): - Describes this bucket. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The creation timestamp of the - bucket. This is not set for any of the default - buckets. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The last update timestamp of the - bucket. - retention_days (int): - Logs will be retained by default for this - amount of time, after which they will - automatically be deleted. The minimum retention - period is 1 day. If this value is set to zero at - bucket creation time, the default time of 30 - days will be used. - locked (bool): - Whether the bucket has been locked. - The retention period on a locked bucket may not - be changed. Locked buckets may only be deleted - if they are empty. - lifecycle_state (google.cloud.logging_v2.types.LifecycleState): - Output only. The bucket lifecycle state. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - create_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - retention_days = proto.Field( - proto.INT32, - number=11, - ) - locked = proto.Field( - proto.BOOL, - number=9, - ) - lifecycle_state = proto.Field( - proto.ENUM, - number=12, - enum='LifecycleState', - ) - - -class LogView(proto.Message): - r"""Describes a view over logs in a bucket. - Attributes: - name (str): - The resource name of the view. - For example - "projects/my-project-id/locations/my- - location/buckets/my-bucket-id/views/my-view - description (str): - Describes this view. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The creation timestamp of the - view. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The last update timestamp of the - view. - filter (str): - Filter that restricts which log entries in a bucket are - visible in this view. Filters are restricted to be a logical - AND of ==/!= of any of the following: originating - project/folder/organization/billing account. resource type - log id Example: SOURCE("projects/myproject") AND - resource.type = "gce_instance" AND LOG_ID("stdout") - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - create_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - filter = proto.Field( - proto.STRING, - number=7, - ) - - -class LogSink(proto.Message): - r"""Describes a sink used to export log entries to one of the - following destinations in any project: a Cloud Storage bucket, a - BigQuery dataset, or a Cloud Pub/Sub topic. A logs filter - controls which log entries are exported. The sink must be - created within a project, organization, billing account, or - folder. - - Attributes: - name (str): - Required. The client-assigned sink identifier, unique within - the project. Example: ``"my-syslog-errors-to-pubsub"``. Sink - identifiers are limited to 100 characters and can include - only the following characters: upper and lower-case - alphanumeric characters, underscores, hyphens, and periods. - First character has to be alphanumeric. - destination (str): - Required. The export destination: - - :: - - "storage.googleapis.com/[GCS_BUCKET]" - "bigquery.googleapis.com/projects/[PROJECT_ID]/datasets/[DATASET]" - "pubsub.googleapis.com/projects/[PROJECT_ID]/topics/[TOPIC_ID]" - - The sink's ``writer_identity``, set when the sink is - created, must have permission to write to the destination or - else the log entries are not exported. For more information, - see `Exporting Logs with - Sinks `__. - filter (str): - Optional. An `advanced logs - filter `__. - The only exported log entries are those that are in the - resource owning the sink and that match the filter. For - example: - - :: - - logName="projects/[PROJECT_ID]/logs/[LOG_ID]" AND severity>=ERROR - description (str): - Optional. A description of this sink. - The maximum length of the description is 8000 - characters. - disabled (bool): - Optional. If set to True, then this sink is - disabled and it does not export any log entries. - exclusions (Sequence[google.cloud.logging_v2.types.LogExclusion]): - Optional. Log entries that match any of the exclusion - filters will not be exported. If a log entry is matched by - both ``filter`` and one of ``exclusion_filters`` it will not - be exported. - output_version_format (google.cloud.logging_v2.types.LogSink.VersionFormat): - Deprecated. This field is unused. - writer_identity (str): - Output only. An IAM identity—a service account or - group—under which Logging writes the exported log entries to - the sink's destination. This field is set by - [sinks.create][google.logging.v2.ConfigServiceV2.CreateSink] - and - [sinks.update][google.logging.v2.ConfigServiceV2.UpdateSink] - based on the value of ``unique_writer_identity`` in those - methods. - - Until you grant this identity write-access to the - destination, log entry exports from this sink will fail. For - more information, see `Granting Access for a - Resource `__. - Consult the destination service's documentation to determine - the appropriate IAM roles to assign to the identity. - include_children (bool): - Optional. This field applies only to sinks owned by - organizations and folders. If the field is false, the - default, only the logs owned by the sink's parent resource - are available for export. If the field is true, then logs - from all the projects, folders, and billing accounts - contained in the sink's parent resource are also available - for export. Whether a particular log entry from the children - is exported depends on the sink's filter expression. For - example, if this field is true, then the filter - ``resource.type=gce_instance`` would export all Compute - Engine VM instance log entries from all projects in the - sink's parent. To only export entries from certain child - projects, filter on the project part of the log name: - - :: - - logName:("projects/test-project1/" OR "projects/test-project2/") AND - resource.type=gce_instance - bigquery_options (google.cloud.logging_v2.types.BigQueryOptions): - Optional. Options that affect sinks exporting - data to BigQuery. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The creation timestamp of the - sink. - This field may not be present for older sinks. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The last update timestamp of the - sink. - This field may not be present for older sinks. - """ - class VersionFormat(proto.Enum): - r"""Deprecated. This is unused.""" - VERSION_FORMAT_UNSPECIFIED = 0 - V2 = 1 - V1 = 2 - - name = proto.Field( - proto.STRING, - number=1, - ) - destination = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=5, - ) - description = proto.Field( - proto.STRING, - number=18, - ) - disabled = proto.Field( - proto.BOOL, - number=19, - ) - exclusions = proto.RepeatedField( - proto.MESSAGE, - number=16, - message='LogExclusion', - ) - output_version_format = proto.Field( - proto.ENUM, - number=6, - enum=VersionFormat, - ) - writer_identity = proto.Field( - proto.STRING, - number=8, - ) - include_children = proto.Field( - proto.BOOL, - number=9, - ) - bigquery_options = proto.Field( - proto.MESSAGE, - number=12, - oneof='options', - message='BigQueryOptions', - ) - create_time = proto.Field( - proto.MESSAGE, - number=13, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=14, - message=timestamp_pb2.Timestamp, - ) - - -class BigQueryOptions(proto.Message): - r"""Options that change functionality of a sink exporting data to - BigQuery. - - Attributes: - use_partitioned_tables (bool): - Optional. Whether to use `BigQuery's partition - tables `__. - By default, Logging creates dated tables based on the log - entries' timestamps, e.g. syslog_20170523. With partitioned - tables the date suffix is no longer present and `special - query - syntax `__ - has to be used instead. In both cases, tables are sharded - based on UTC timezone. - uses_timestamp_column_partitioning (bool): - Output only. True if new timestamp column based partitioning - is in use, false if legacy ingestion-time partitioning is in - use. All new sinks will have this field set true and will - use timestamp column based partitioning. If - use_partitioned_tables is false, this value has no meaning - and will be false. Legacy sinks using partitioned tables - will have this field set to false. - """ - - use_partitioned_tables = proto.Field( - proto.BOOL, - number=1, - ) - uses_timestamp_column_partitioning = proto.Field( - proto.BOOL, - number=3, - ) - - -class ListBucketsRequest(proto.Message): - r"""The parameters to ``ListBuckets``. - Attributes: - parent (str): - Required. The parent resource whose buckets are to be - listed: - - :: - - "projects/[PROJECT_ID]/locations/[LOCATION_ID]" - "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" - "folders/[FOLDER_ID]/locations/[LOCATION_ID]" - - Note: The locations portion of the resource must be - specified, but supplying the character ``-`` in place of - [LOCATION_ID] will return all buckets. - page_token (str): - Optional. If present, then retrieve the next batch of - results from the preceding call to this method. - ``pageToken`` must be the value of ``nextPageToken`` from - the previous response. The values of other method parameters - should be identical to those in the previous call. - page_size (int): - Optional. The maximum number of results to return from this - request. Non-positive values are ignored. The presence of - ``nextPageToken`` in the response indicates that more - results might be available. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_token = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - - -class ListBucketsResponse(proto.Message): - r"""The response from ListBuckets. - Attributes: - buckets (Sequence[google.cloud.logging_v2.types.LogBucket]): - A list of buckets. - next_page_token (str): - If there might be more results than appear in this response, - then ``nextPageToken`` is included. To get the next set of - results, call the same method again using the value of - ``nextPageToken`` as ``pageToken``. - """ - - @property - def raw_page(self): - return self - - buckets = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='LogBucket', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateBucketRequest(proto.Message): - r"""The parameters to ``CreateBucket``. - Attributes: - parent (str): - Required. The resource in which to create the bucket: - - :: - - "projects/[PROJECT_ID]/locations/[LOCATION_ID]" - - Example: ``"projects/my-logging-project/locations/global"`` - bucket_id (str): - Required. A client-assigned identifier such as - ``"my-bucket"``. Identifiers are limited to 100 characters - and can include only letters, digits, underscores, hyphens, - and periods. - bucket (google.cloud.logging_v2.types.LogBucket): - Required. The new bucket. The region - specified in the new bucket must be compliant - with any Location Restriction Org Policy. The - name field in the bucket is ignored. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - bucket_id = proto.Field( - proto.STRING, - number=2, - ) - bucket = proto.Field( - proto.MESSAGE, - number=3, - message='LogBucket', - ) - - -class UpdateBucketRequest(proto.Message): - r"""The parameters to ``UpdateBucket``. - Attributes: - name (str): - Required. The full resource name of the bucket to update. - - :: - - "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - - Example: - ``"projects/my-project-id/locations/my-location/buckets/my-bucket-id"``. - Also requires permission - "resourcemanager.projects.updateLiens" to set the locked - property - bucket (google.cloud.logging_v2.types.LogBucket): - Required. The updated bucket. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Field mask that specifies the fields in ``bucket`` - that need an update. A bucket field will be overwritten if, - and only if, it is in the update mask. ``name`` and output - only fields cannot be updated. - - For a detailed ``FieldMask`` definition, see - https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask - - Example: ``updateMask=retention_days``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - bucket = proto.Field( - proto.MESSAGE, - number=2, - message='LogBucket', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - - -class GetBucketRequest(proto.Message): - r"""The parameters to ``GetBucket``. - Attributes: - name (str): - Required. The resource name of the bucket: - - :: - - "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - - Example: - ``"projects/my-project-id/locations/my-location/buckets/my-bucket-id"``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteBucketRequest(proto.Message): - r"""The parameters to ``DeleteBucket``. - Attributes: - name (str): - Required. The full resource name of the bucket to delete. - - :: - - "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - - Example: - ``"projects/my-project-id/locations/my-location/buckets/my-bucket-id"``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UndeleteBucketRequest(proto.Message): - r"""The parameters to ``UndeleteBucket``. - Attributes: - name (str): - Required. The full resource name of the bucket to undelete. - - :: - - "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - - Example: - ``"projects/my-project-id/locations/my-location/buckets/my-bucket-id"``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListViewsRequest(proto.Message): - r"""The parameters to ``ListViews``. - Attributes: - parent (str): - Required. The bucket whose views are to be listed: - - :: - - "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]". - page_token (str): - Optional. If present, then retrieve the next batch of - results from the preceding call to this method. - ``pageToken`` must be the value of ``nextPageToken`` from - the previous response. The values of other method parameters - should be identical to those in the previous call. - page_size (int): - Optional. The maximum number of results to return from this - request. Non-positive values are ignored. The presence of - ``nextPageToken`` in the response indicates that more - results might be available. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_token = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - - -class ListViewsResponse(proto.Message): - r"""The response from ListViews. - Attributes: - views (Sequence[google.cloud.logging_v2.types.LogView]): - A list of views. - next_page_token (str): - If there might be more results than appear in this response, - then ``nextPageToken`` is included. To get the next set of - results, call the same method again using the value of - ``nextPageToken`` as ``pageToken``. - """ - - @property - def raw_page(self): - return self - - views = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='LogView', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateViewRequest(proto.Message): - r"""The parameters to ``CreateView``. - Attributes: - parent (str): - Required. The bucket in which to create the view - - :: - - "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - - Example: - ``"projects/my-logging-project/locations/my-location/buckets/my-bucket"`` - view_id (str): - Required. The id to use for this view. - view (google.cloud.logging_v2.types.LogView): - Required. The new view. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - view_id = proto.Field( - proto.STRING, - number=2, - ) - view = proto.Field( - proto.MESSAGE, - number=3, - message='LogView', - ) - - -class UpdateViewRequest(proto.Message): - r"""The parameters to ``UpdateView``. - Attributes: - name (str): - Required. The full resource name of the view to update - - :: - - "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" - - Example: - ``"projects/my-project-id/locations/my-location/buckets/my-bucket-id/views/my-view-id"``. - view (google.cloud.logging_v2.types.LogView): - Required. The updated view. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask that specifies the fields in ``view`` - that need an update. A field will be overwritten if, and - only if, it is in the update mask. ``name`` and output only - fields cannot be updated. - - For a detailed ``FieldMask`` definition, see - https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask - - Example: ``updateMask=filter``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - view = proto.Field( - proto.MESSAGE, - number=2, - message='LogView', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - - -class GetViewRequest(proto.Message): - r"""The parameters to ``GetView``. - Attributes: - name (str): - Required. The resource name of the policy: - - :: - - "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" - - Example: - ``"projects/my-project-id/locations/my-location/buckets/my-bucket-id/views/my-view-id"``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteViewRequest(proto.Message): - r"""The parameters to ``DeleteView``. - Attributes: - name (str): - Required. The full resource name of the view to delete: - - :: - - "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" - - Example: - ``"projects/my-project-id/locations/my-location/buckets/my-bucket-id/views/my-view-id"``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListSinksRequest(proto.Message): - r"""The parameters to ``ListSinks``. - Attributes: - parent (str): - Required. The parent resource whose sinks are to be listed: - - :: - - "projects/[PROJECT_ID]" - "organizations/[ORGANIZATION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]" - "folders/[FOLDER_ID]". - page_token (str): - Optional. If present, then retrieve the next batch of - results from the preceding call to this method. - ``pageToken`` must be the value of ``nextPageToken`` from - the previous response. The values of other method parameters - should be identical to those in the previous call. - page_size (int): - Optional. The maximum number of results to return from this - request. Non-positive values are ignored. The presence of - ``nextPageToken`` in the response indicates that more - results might be available. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_token = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - - -class ListSinksResponse(proto.Message): - r"""Result returned from ``ListSinks``. - Attributes: - sinks (Sequence[google.cloud.logging_v2.types.LogSink]): - A list of sinks. - next_page_token (str): - If there might be more results than appear in this response, - then ``nextPageToken`` is included. To get the next set of - results, call the same method again using the value of - ``nextPageToken`` as ``pageToken``. - """ - - @property - def raw_page(self): - return self - - sinks = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='LogSink', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetSinkRequest(proto.Message): - r"""The parameters to ``GetSink``. - Attributes: - sink_name (str): - Required. The resource name of the sink: - - :: - - "projects/[PROJECT_ID]/sinks/[SINK_ID]" - "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - "folders/[FOLDER_ID]/sinks/[SINK_ID]" - - Example: ``"projects/my-project-id/sinks/my-sink-id"``. - """ - - sink_name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateSinkRequest(proto.Message): - r"""The parameters to ``CreateSink``. - Attributes: - parent (str): - Required. The resource in which to create the sink: - - :: - - "projects/[PROJECT_ID]" - "organizations/[ORGANIZATION_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]" - "folders/[FOLDER_ID]" - - Examples: ``"projects/my-logging-project"``, - ``"organizations/123456789"``. - sink (google.cloud.logging_v2.types.LogSink): - Required. The new sink, whose ``name`` parameter is a sink - identifier that is not already in use. - unique_writer_identity (bool): - Optional. Determines the kind of IAM identity returned as - ``writer_identity`` in the new sink. If this value is - omitted or set to false, and if the sink's parent is a - project, then the value returned as ``writer_identity`` is - the same group or service account used by Logging before the - addition of writer identities to this API. The sink's - destination must be in the same project as the sink itself. - - If this field is set to true, or if the sink is owned by a - non-project resource such as an organization, then the value - of ``writer_identity`` will be a unique service account used - only for exports from the new sink. For more information, - see ``writer_identity`` in - [LogSink][google.logging.v2.LogSink]. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - sink = proto.Field( - proto.MESSAGE, - number=2, - message='LogSink', - ) - unique_writer_identity = proto.Field( - proto.BOOL, - number=3, - ) - - -class UpdateSinkRequest(proto.Message): - r"""The parameters to ``UpdateSink``. - Attributes: - sink_name (str): - Required. The full resource name of the sink to update, - including the parent resource and the sink identifier: - - :: - - "projects/[PROJECT_ID]/sinks/[SINK_ID]" - "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - "folders/[FOLDER_ID]/sinks/[SINK_ID]" - - Example: ``"projects/my-project-id/sinks/my-sink-id"``. - sink (google.cloud.logging_v2.types.LogSink): - Required. The updated sink, whose name is the same - identifier that appears as part of ``sink_name``. - unique_writer_identity (bool): - Optional. See - [sinks.create][google.logging.v2.ConfigServiceV2.CreateSink] - for a description of this field. When updating a sink, the - effect of this field on the value of ``writer_identity`` in - the updated sink depends on both the old and new values of - this field: - - - If the old and new values of this field are both false or - both true, then there is no change to the sink's - ``writer_identity``. - - If the old value is false and the new value is true, then - ``writer_identity`` is changed to a unique service - account. - - It is an error if the old value is true and the new value - is set to false or defaulted to false. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask that specifies the fields in ``sink`` - that need an update. A sink field will be overwritten if, - and only if, it is in the update mask. ``name`` and output - only fields cannot be updated. - - An empty updateMask is temporarily treated as using the - following mask for backwards compatibility purposes: - destination,filter,includeChildren At some point in the - future, behavior will be removed and specifying an empty - updateMask will be an error. - - For a detailed ``FieldMask`` definition, see - https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMask - - Example: ``updateMask=filter``. - """ - - sink_name = proto.Field( - proto.STRING, - number=1, - ) - sink = proto.Field( - proto.MESSAGE, - number=2, - message='LogSink', - ) - unique_writer_identity = proto.Field( - proto.BOOL, - number=3, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteSinkRequest(proto.Message): - r"""The parameters to ``DeleteSink``. - Attributes: - sink_name (str): - Required. The full resource name of the sink to delete, - including the parent resource and the sink identifier: - - :: - - "projects/[PROJECT_ID]/sinks/[SINK_ID]" - "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - "folders/[FOLDER_ID]/sinks/[SINK_ID]" - - Example: ``"projects/my-project-id/sinks/my-sink-id"``. - """ - - sink_name = proto.Field( - proto.STRING, - number=1, - ) - - -class LogExclusion(proto.Message): - r"""Specifies a set of log entries that are not to be stored in - Logging. If your GCP resource receives a large volume of logs, - you can use exclusions to reduce your chargeable logs. - Exclusions are processed after log sinks, so you can export log - entries before they are excluded. Note that organization-level - and folder-level exclusions don't apply to child resources, and - that you can't exclude audit log entries. - - Attributes: - name (str): - Required. A client-assigned identifier, such as - ``"load-balancer-exclusion"``. Identifiers are limited to - 100 characters and can include only letters, digits, - underscores, hyphens, and periods. First character has to be - alphanumeric. - description (str): - Optional. A description of this exclusion. - filter (str): - Required. An `advanced logs - filter `__ - that matches the log entries to be excluded. By using the - `sample - function `__, - you can exclude less than 100% of the matching log entries. - For example, the following query matches 99% of low-severity - log entries from Google Cloud Storage buckets: - - ``"resource.type=gcs_bucket severity`__ - for more information. - - Attributes: - name (str): - Required. The resource for which to retrieve CMEK settings. - - :: - - "projects/[PROJECT_ID]/cmekSettings" - "organizations/[ORGANIZATION_ID]/cmekSettings" - "billingAccounts/[BILLING_ACCOUNT_ID]/cmekSettings" - "folders/[FOLDER_ID]/cmekSettings" - - Example: ``"organizations/12345/cmekSettings"``. - - Note: CMEK for the Logs Router can currently only be - configured for GCP organizations. Once configured, it - applies to all projects and folders in the GCP organization. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateCmekSettingsRequest(proto.Message): - r"""The parameters to - [UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings]. - - See `Enabling CMEK for Logs - Router `__ - for more information. - - Attributes: - name (str): - Required. The resource name for the CMEK settings to update. - - :: - - "projects/[PROJECT_ID]/cmekSettings" - "organizations/[ORGANIZATION_ID]/cmekSettings" - "billingAccounts/[BILLING_ACCOUNT_ID]/cmekSettings" - "folders/[FOLDER_ID]/cmekSettings" - - Example: ``"organizations/12345/cmekSettings"``. - - Note: CMEK for the Logs Router can currently only be - configured for GCP organizations. Once configured, it - applies to all projects and folders in the GCP organization. - cmek_settings (google.cloud.logging_v2.types.CmekSettings): - Required. The CMEK settings to update. - - See `Enabling CMEK for Logs - Router `__ - for more information. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask identifying which fields from - ``cmek_settings`` should be updated. A field will be - overwritten if and only if it is in the update mask. Output - only fields cannot be updated. - - See [FieldMask][google.protobuf.FieldMask] for more - information. - - Example: ``"updateMask=kmsKeyName"`` - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - cmek_settings = proto.Field( - proto.MESSAGE, - number=2, - message='CmekSettings', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class CmekSettings(proto.Message): - r"""Describes the customer-managed encryption key (CMEK) settings - associated with a project, folder, organization, billing account, or - flexible resource. - - Note: CMEK for the Logs Router can currently only be configured for - GCP organizations. Once configured, it applies to all projects and - folders in the GCP organization. - - See `Enabling CMEK for Logs - Router `__ - for more information. - - Attributes: - name (str): - Output only. The resource name of the CMEK - settings. - kms_key_name (str): - The resource name for the configured Cloud KMS key. - - KMS key name format: - "projects/[PROJECT_ID]/locations/[LOCATION]/keyRings/[KEYRING]/cryptoKeys/[KEY]" - - For example: - ``"projects/my-project-id/locations/my-region/keyRings/key-ring-name/cryptoKeys/key-name"`` - - To enable CMEK for the Logs Router, set this field to a - valid ``kms_key_name`` for which the associated service - account has the required - ``roles/cloudkms.cryptoKeyEncrypterDecrypter`` role assigned - for the key. - - The Cloud KMS key used by the Log Router can be updated by - changing the ``kms_key_name`` to a new valid key name. - Encryption operations that are in progress will be completed - with the key that was in use when they started. Decryption - operations will be completed using the key that was used at - the time of encryption unless access to that key has been - revoked. - - To disable CMEK for the Logs Router, set this field to an - empty string. - - See `Enabling CMEK for Logs - Router `__ - for more information. - service_account_id (str): - Output only. The service account that will be used by the - Logs Router to access your Cloud KMS key. - - Before enabling CMEK for Logs Router, you must first assign - the role ``roles/cloudkms.cryptoKeyEncrypterDecrypter`` to - the service account that the Logs Router will use to access - your Cloud KMS key. Use - [GetCmekSettings][google.logging.v2.ConfigServiceV2.GetCmekSettings] - to obtain the service account ID. - - See `Enabling CMEK for Logs - Router `__ - for more information. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - kms_key_name = proto.Field( - proto.STRING, - number=2, - ) - service_account_id = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/google/cloud/logging_v2/types/logging_metrics.py b/owl-bot-staging/v2/google/cloud/logging_v2/types/logging_metrics.py deleted file mode 100644 index 252e4376..00000000 --- a/owl-bot-staging/v2/google/cloud/logging_v2/types/logging_metrics.py +++ /dev/null @@ -1,371 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 proto # type: ignore - -from google.api import distribution_pb2 # type: ignore -from google.api import metric_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.logging.v2', - manifest={ - 'LogMetric', - 'ListLogMetricsRequest', - 'ListLogMetricsResponse', - 'GetLogMetricRequest', - 'CreateLogMetricRequest', - 'UpdateLogMetricRequest', - 'DeleteLogMetricRequest', - }, -) - - -class LogMetric(proto.Message): - r"""Describes a logs-based metric. The value of the metric is the - number of log entries that match a logs filter in a given time - interval. - Logs-based metrics can also be used to extract values from logs - and create a distribution of the values. The distribution - records the statistics of the extracted values along with an - optional histogram of the values as specified by the bucket - options. - - Attributes: - name (str): - Required. The client-assigned metric identifier. Examples: - ``"error_count"``, ``"nginx/requests"``. - - Metric identifiers are limited to 100 characters and can - include only the following characters: ``A-Z``, ``a-z``, - ``0-9``, and the special characters ``_-.,+!*',()%/``. The - forward-slash character (``/``) denotes a hierarchy of name - pieces, and it cannot be the first character of the name. - - The metric identifier in this field must not be - `URL-encoded `__. - However, when the metric identifier appears as the - ``[METRIC_ID]`` part of a ``metric_name`` API parameter, - then the metric identifier must be URL-encoded. Example: - ``"projects/my-project/metrics/nginx%2Frequests"``. - description (str): - Optional. A description of this metric, which - is used in documentation. The maximum length of - the description is 8000 characters. - filter (str): - Required. An `advanced logs - filter `__ - which is used to match log entries. Example: - - :: - - "resource.type=gae_app AND severity>=ERROR" - - The maximum length of the filter is 20000 characters. - metric_descriptor (google.api.metric_pb2.MetricDescriptor): - Optional. The metric descriptor associated with the - logs-based metric. If unspecified, it uses a default metric - descriptor with a DELTA metric kind, INT64 value type, with - no labels and a unit of "1". Such a metric counts the number - of log entries matching the ``filter`` expression. - - The ``name``, ``type``, and ``description`` fields in the - ``metric_descriptor`` are output only, and is constructed - using the ``name`` and ``description`` field in the - LogMetric. - - To create a logs-based metric that records a distribution of - log values, a DELTA metric kind with a DISTRIBUTION value - type must be used along with a ``value_extractor`` - expression in the LogMetric. - - Each label in the metric descriptor must have a matching - label name as the key and an extractor expression as the - value in the ``label_extractors`` map. - - The ``metric_kind`` and ``value_type`` fields in the - ``metric_descriptor`` cannot be updated once initially - configured. New labels can be added in the - ``metric_descriptor``, but existing labels cannot be - modified except for their description. - value_extractor (str): - Optional. A ``value_extractor`` is required when using a - distribution logs-based metric to extract the values to - record from a log entry. Two functions are supported for - value extraction: ``EXTRACT(field)`` or - ``REGEXP_EXTRACT(field, regex)``. The argument are: - - 1. field: The name of the log entry field from which the - value is to be extracted. - 2. regex: A regular expression using the Google RE2 syntax - (https://github.com/google/re2/wiki/Syntax) with a single - capture group to extract data from the specified log - entry field. The value of the field is converted to a - string before applying the regex. It is an error to - specify a regex that does not include exactly one capture - group. - - The result of the extraction must be convertible to a double - type, as the distribution always records double values. If - either the extraction or the conversion to double fails, - then those values are not recorded in the distribution. - - Example: - ``REGEXP_EXTRACT(jsonPayload.request, ".*quantity=(\d+).*")`` - label_extractors (Sequence[google.cloud.logging_v2.types.LogMetric.LabelExtractorsEntry]): - Optional. A map from a label key string to an extractor - expression which is used to extract data from a log entry - field and assign as the label value. Each label key - specified in the LabelDescriptor must have an associated - extractor expression in this map. The syntax of the - extractor expression is the same as for the - ``value_extractor`` field. - - The extracted value is converted to the type defined in the - label descriptor. If the either the extraction or the type - conversion fails, the label will have a default value. The - default value for a string label is an empty string, for an - integer label its 0, and for a boolean label its ``false``. - - Note that there are upper bounds on the maximum number of - labels and the number of active time series that are allowed - in a project. - bucket_options (google.api.distribution_pb2.BucketOptions): - Optional. The ``bucket_options`` are required when the - logs-based metric is using a DISTRIBUTION value type and it - describes the bucket boundaries used to create a histogram - of the extracted values. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The creation timestamp of the - metric. - This field may not be present for older metrics. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The last update timestamp of the - metric. - This field may not be present for older metrics. - version (google.cloud.logging_v2.types.LogMetric.ApiVersion): - Deprecated. The API version that created or - updated this metric. The v2 format is used by - default and cannot be changed. - """ - class ApiVersion(proto.Enum): - r"""Logging API version.""" - V2 = 0 - V1 = 1 - - name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - filter = proto.Field( - proto.STRING, - number=3, - ) - metric_descriptor = proto.Field( - proto.MESSAGE, - number=5, - message=metric_pb2.MetricDescriptor, - ) - value_extractor = proto.Field( - proto.STRING, - number=6, - ) - label_extractors = proto.MapField( - proto.STRING, - proto.STRING, - number=7, - ) - bucket_options = proto.Field( - proto.MESSAGE, - number=8, - message=distribution_pb2.Distribution.BucketOptions, - ) - create_time = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - version = proto.Field( - proto.ENUM, - number=4, - enum=ApiVersion, - ) - - -class ListLogMetricsRequest(proto.Message): - r"""The parameters to ListLogMetrics. - Attributes: - parent (str): - Required. The name of the project containing the metrics: - - :: - - "projects/[PROJECT_ID]". - page_token (str): - Optional. If present, then retrieve the next batch of - results from the preceding call to this method. - ``pageToken`` must be the value of ``nextPageToken`` from - the previous response. The values of other method parameters - should be identical to those in the previous call. - page_size (int): - Optional. The maximum number of results to return from this - request. Non-positive values are ignored. The presence of - ``nextPageToken`` in the response indicates that more - results might be available. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_token = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - - -class ListLogMetricsResponse(proto.Message): - r"""Result returned from ListLogMetrics. - Attributes: - metrics (Sequence[google.cloud.logging_v2.types.LogMetric]): - A list of logs-based metrics. - next_page_token (str): - If there might be more results than appear in this response, - then ``nextPageToken`` is included. To get the next set of - results, call this method again using the value of - ``nextPageToken`` as ``pageToken``. - """ - - @property - def raw_page(self): - return self - - metrics = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='LogMetric', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetLogMetricRequest(proto.Message): - r"""The parameters to GetLogMetric. - Attributes: - metric_name (str): - Required. The resource name of the desired metric: - - :: - - "projects/[PROJECT_ID]/metrics/[METRIC_ID]". - """ - - metric_name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateLogMetricRequest(proto.Message): - r"""The parameters to CreateLogMetric. - Attributes: - parent (str): - Required. The resource name of the project in which to - create the metric: - - :: - - "projects/[PROJECT_ID]" - - The new metric must be provided in the request. - metric (google.cloud.logging_v2.types.LogMetric): - Required. The new logs-based metric, which - must not have an identifier that already exists. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - metric = proto.Field( - proto.MESSAGE, - number=2, - message='LogMetric', - ) - - -class UpdateLogMetricRequest(proto.Message): - r"""The parameters to UpdateLogMetric. - Attributes: - metric_name (str): - Required. The resource name of the metric to update: - - :: - - "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - - The updated metric must be provided in the request and it's - ``name`` field must be the same as ``[METRIC_ID]`` If the - metric does not exist in ``[PROJECT_ID]``, then a new metric - is created. - metric (google.cloud.logging_v2.types.LogMetric): - Required. The updated metric. - """ - - metric_name = proto.Field( - proto.STRING, - number=1, - ) - metric = proto.Field( - proto.MESSAGE, - number=2, - message='LogMetric', - ) - - -class DeleteLogMetricRequest(proto.Message): - r"""The parameters to DeleteLogMetric. - Attributes: - metric_name (str): - Required. The resource name of the metric to delete: - - :: - - "projects/[PROJECT_ID]/metrics/[METRIC_ID]". - """ - - metric_name = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v2/mypy.ini b/owl-bot-staging/v2/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v2/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v2/noxfile.py b/owl-bot-staging/v2/noxfile.py deleted file mode 100644 index 10ed0a99..00000000 --- a/owl-bot-staging/v2/noxfile.py +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/logging_v2/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) diff --git a/owl-bot-staging/v2/scripts/fixup_logging_v2_keywords.py b/owl-bot-staging/v2/scripts/fixup_logging_v2_keywords.py deleted file mode 100644 index 2a368fb9..00000000 --- a/owl-bot-staging/v2/scripts/fixup_logging_v2_keywords.py +++ /dev/null @@ -1,209 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2020 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 argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class loggingCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_bucket': ('parent', 'bucket_id', 'bucket', ), - 'create_exclusion': ('parent', 'exclusion', ), - 'create_log_metric': ('parent', 'metric', ), - 'create_sink': ('parent', 'sink', 'unique_writer_identity', ), - 'create_view': ('parent', 'view_id', 'view', ), - 'delete_bucket': ('name', ), - 'delete_exclusion': ('name', ), - 'delete_log': ('log_name', ), - 'delete_log_metric': ('metric_name', ), - 'delete_sink': ('sink_name', ), - 'delete_view': ('name', ), - 'get_bucket': ('name', ), - 'get_cmek_settings': ('name', ), - 'get_exclusion': ('name', ), - 'get_log_metric': ('metric_name', ), - 'get_sink': ('sink_name', ), - 'get_view': ('name', ), - 'list_buckets': ('parent', 'page_token', 'page_size', ), - 'list_exclusions': ('parent', 'page_token', 'page_size', ), - 'list_log_entries': ('resource_names', 'filter', 'order_by', 'page_size', 'page_token', ), - 'list_log_metrics': ('parent', 'page_token', 'page_size', ), - 'list_logs': ('parent', 'page_size', 'page_token', 'resource_names', ), - 'list_monitored_resource_descriptors': ('page_size', 'page_token', ), - 'list_sinks': ('parent', 'page_token', 'page_size', ), - 'list_views': ('parent', 'page_token', 'page_size', ), - 'tail_log_entries': ('resource_names', 'filter', 'buffer_window', ), - 'undelete_bucket': ('name', ), - 'update_bucket': ('name', 'bucket', 'update_mask', ), - 'update_cmek_settings': ('name', 'cmek_settings', 'update_mask', ), - 'update_exclusion': ('name', 'exclusion', 'update_mask', ), - 'update_log_metric': ('metric_name', 'metric', ), - 'update_sink': ('sink_name', 'sink', 'unique_writer_identity', 'update_mask', ), - 'update_view': ('name', 'view', 'update_mask', ), - 'write_log_entries': ('entries', 'log_name', 'resource', 'labels', 'partial_success', 'dry_run', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=loggingCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the logging client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v2/setup.py b/owl-bot-staging/v2/setup.py deleted file mode 100644 index 4b98728b..00000000 --- a/owl-bot-staging/v2/setup.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-cloud-logging', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v2/tests/__init__.py b/owl-bot-staging/v2/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v2/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 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. -# diff --git a/owl-bot-staging/v2/tests/unit/__init__.py b/owl-bot-staging/v2/tests/unit/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v2/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 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. -# diff --git a/owl-bot-staging/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 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. -# diff --git a/owl-bot-staging/v2/tests/unit/gapic/logging_v2/__init__.py b/owl-bot-staging/v2/tests/unit/gapic/logging_v2/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/logging_v2/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 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. -# diff --git a/owl-bot-staging/v2/tests/unit/gapic/logging_v2/test_config_service_v2.py b/owl-bot-staging/v2/tests/unit/gapic/logging_v2/test_config_service_v2.py deleted file mode 100644 index 979cbd36..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/logging_v2/test_config_service_v2.py +++ /dev/null @@ -1,6447 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.logging_v2.services.config_service_v2 import ConfigServiceV2AsyncClient -from google.cloud.logging_v2.services.config_service_v2 import ConfigServiceV2Client -from google.cloud.logging_v2.services.config_service_v2 import pagers -from google.cloud.logging_v2.services.config_service_v2 import transports -from google.cloud.logging_v2.services.config_service_v2.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.logging_v2.types import logging_config -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -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 ConfigServiceV2Client._get_default_mtls_endpoint(None) is None - assert ConfigServiceV2Client._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ConfigServiceV2Client._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ConfigServiceV2Client._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ConfigServiceV2Client._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ConfigServiceV2Client._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - ConfigServiceV2Client, - ConfigServiceV2AsyncClient, -]) -def test_config_service_v2_client_from_service_account_info(client_class): - 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) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'logging.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ConfigServiceV2GrpcTransport, "grpc"), - (transports.ConfigServiceV2GrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_config_service_v2_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", [ - ConfigServiceV2Client, - ConfigServiceV2AsyncClient, -]) -def test_config_service_v2_client_from_service_account_file(client_class): - 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") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'logging.googleapis.com:443' - - -def test_config_service_v2_client_get_transport_class(): - transport = ConfigServiceV2Client.get_transport_class() - available_transports = [ - transports.ConfigServiceV2GrpcTransport, - ] - assert transport in available_transports - - transport = ConfigServiceV2Client.get_transport_class("grpc") - assert transport == transports.ConfigServiceV2GrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConfigServiceV2Client, transports.ConfigServiceV2GrpcTransport, "grpc"), - (ConfigServiceV2AsyncClient, transports.ConfigServiceV2GrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ConfigServiceV2Client, "DEFAULT_ENDPOINT", modify_default_endpoint(ConfigServiceV2Client)) -@mock.patch.object(ConfigServiceV2AsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConfigServiceV2AsyncClient)) -def test_config_service_v2_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(ConfigServiceV2Client, '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(ConfigServiceV2Client, '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(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, - ) - - # 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() - 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, - ) - - # 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() - 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, - ) - - # 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() - - # 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() - - # 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) - 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, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ConfigServiceV2Client, transports.ConfigServiceV2GrpcTransport, "grpc", "true"), - (ConfigServiceV2AsyncClient, transports.ConfigServiceV2GrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ConfigServiceV2Client, transports.ConfigServiceV2GrpcTransport, "grpc", "false"), - (ConfigServiceV2AsyncClient, transports.ConfigServiceV2GrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ConfigServiceV2Client, "DEFAULT_ENDPOINT", modify_default_endpoint(ConfigServiceV2Client)) -@mock.patch.object(ConfigServiceV2AsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConfigServiceV2AsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_config_service_v2_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) - - 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, - ) - - # 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() - 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, - ) - - # 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() - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConfigServiceV2Client, transports.ConfigServiceV2GrpcTransport, "grpc"), - (ConfigServiceV2AsyncClient, transports.ConfigServiceV2GrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_config_service_v2_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) - 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, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConfigServiceV2Client, transports.ConfigServiceV2GrpcTransport, "grpc"), - (ConfigServiceV2AsyncClient, transports.ConfigServiceV2GrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_config_service_v2_client_client_options_credentials_file(client_class, transport_class, transport_name): - # 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) - 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, - ) - - -def test_config_service_v2_client_client_options_from_dict(): - with mock.patch('google.cloud.logging_v2.services.config_service_v2.transports.ConfigServiceV2GrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ConfigServiceV2Client( - 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, - ) - - -def test_list_buckets(transport: str = 'grpc', request_type=logging_config.ListBucketsRequest): - client = ConfigServiceV2Client( - 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_buckets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.ListBucketsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_buckets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.ListBucketsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBucketsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_buckets_from_dict(): - test_list_buckets(request_type=dict) - - -def test_list_buckets_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 = ConfigServiceV2Client( - 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_buckets), - '__call__') as call: - client.list_buckets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.ListBucketsRequest() - - -@pytest.mark.asyncio -async def test_list_buckets_async(transport: str = 'grpc_asyncio', request_type=logging_config.ListBucketsRequest): - client = ConfigServiceV2AsyncClient( - 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_buckets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_config.ListBucketsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_buckets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.ListBucketsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBucketsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_buckets_async_from_dict(): - await test_list_buckets_async(request_type=dict) - - -def test_list_buckets_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.ListBucketsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_buckets), - '__call__') as call: - call.return_value = logging_config.ListBucketsResponse() - client.list_buckets(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_buckets_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.ListBucketsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_buckets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.ListBucketsResponse()) - await client.list_buckets(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_buckets_flattened(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_buckets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.ListBucketsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_buckets( - 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] - assert args[0].parent == 'parent_value' - - -def test_list_buckets_flattened_error(): - client = ConfigServiceV2Client( - 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_buckets( - logging_config.ListBucketsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_buckets_flattened_async(): - client = ConfigServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_buckets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.ListBucketsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.ListBucketsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_buckets( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_buckets_flattened_error_async(): - client = ConfigServiceV2AsyncClient( - 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_buckets( - logging_config.ListBucketsRequest(), - parent='parent_value', - ) - - -def test_list_buckets_pager(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_buckets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - logging_config.ListBucketsResponse( - buckets=[ - logging_config.LogBucket(), - logging_config.LogBucket(), - logging_config.LogBucket(), - ], - next_page_token='abc', - ), - logging_config.ListBucketsResponse( - buckets=[], - next_page_token='def', - ), - logging_config.ListBucketsResponse( - buckets=[ - logging_config.LogBucket(), - ], - next_page_token='ghi', - ), - logging_config.ListBucketsResponse( - buckets=[ - logging_config.LogBucket(), - logging_config.LogBucket(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_buckets(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, logging_config.LogBucket) - for i in results) - -def test_list_buckets_pages(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_buckets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - logging_config.ListBucketsResponse( - buckets=[ - logging_config.LogBucket(), - logging_config.LogBucket(), - logging_config.LogBucket(), - ], - next_page_token='abc', - ), - logging_config.ListBucketsResponse( - buckets=[], - next_page_token='def', - ), - logging_config.ListBucketsResponse( - buckets=[ - logging_config.LogBucket(), - ], - next_page_token='ghi', - ), - logging_config.ListBucketsResponse( - buckets=[ - logging_config.LogBucket(), - logging_config.LogBucket(), - ], - ), - RuntimeError, - ) - pages = list(client.list_buckets(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_buckets_async_pager(): - client = ConfigServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_buckets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - logging_config.ListBucketsResponse( - buckets=[ - logging_config.LogBucket(), - logging_config.LogBucket(), - logging_config.LogBucket(), - ], - next_page_token='abc', - ), - logging_config.ListBucketsResponse( - buckets=[], - next_page_token='def', - ), - logging_config.ListBucketsResponse( - buckets=[ - logging_config.LogBucket(), - ], - next_page_token='ghi', - ), - logging_config.ListBucketsResponse( - buckets=[ - logging_config.LogBucket(), - logging_config.LogBucket(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_buckets(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, logging_config.LogBucket) - for i in responses) - -@pytest.mark.asyncio -async def test_list_buckets_async_pages(): - client = ConfigServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_buckets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - logging_config.ListBucketsResponse( - buckets=[ - logging_config.LogBucket(), - logging_config.LogBucket(), - logging_config.LogBucket(), - ], - next_page_token='abc', - ), - logging_config.ListBucketsResponse( - buckets=[], - next_page_token='def', - ), - logging_config.ListBucketsResponse( - buckets=[ - logging_config.LogBucket(), - ], - next_page_token='ghi', - ), - logging_config.ListBucketsResponse( - buckets=[ - logging_config.LogBucket(), - logging_config.LogBucket(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_buckets(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_bucket(transport: str = 'grpc', request_type=logging_config.GetBucketRequest): - client = ConfigServiceV2Client( - 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.get_bucket), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogBucket( - name='name_value', - description='description_value', - retention_days=1512, - locked=True, - lifecycle_state=logging_config.LifecycleState.ACTIVE, - ) - response = client.get_bucket(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.GetBucketRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogBucket) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.retention_days == 1512 - assert response.locked is True - assert response.lifecycle_state == logging_config.LifecycleState.ACTIVE - - -def test_get_bucket_from_dict(): - test_get_bucket(request_type=dict) - - -def test_get_bucket_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 = ConfigServiceV2Client( - 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.get_bucket), - '__call__') as call: - client.get_bucket() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.GetBucketRequest() - - -@pytest.mark.asyncio -async def test_get_bucket_async(transport: str = 'grpc_asyncio', request_type=logging_config.GetBucketRequest): - client = ConfigServiceV2AsyncClient( - 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.get_bucket), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogBucket( - name='name_value', - description='description_value', - retention_days=1512, - locked=True, - lifecycle_state=logging_config.LifecycleState.ACTIVE, - )) - response = await client.get_bucket(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.GetBucketRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogBucket) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.retention_days == 1512 - assert response.locked is True - assert response.lifecycle_state == logging_config.LifecycleState.ACTIVE - - -@pytest.mark.asyncio -async def test_get_bucket_async_from_dict(): - await test_get_bucket_async(request_type=dict) - - -def test_get_bucket_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.GetBucketRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_bucket), - '__call__') as call: - call.return_value = logging_config.LogBucket() - client.get_bucket(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_get_bucket_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.GetBucketRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_bucket), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogBucket()) - await client.get_bucket(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'] - - -def test_create_bucket(transport: str = 'grpc', request_type=logging_config.CreateBucketRequest): - client = ConfigServiceV2Client( - 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.create_bucket), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogBucket( - name='name_value', - description='description_value', - retention_days=1512, - locked=True, - lifecycle_state=logging_config.LifecycleState.ACTIVE, - ) - response = client.create_bucket(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.CreateBucketRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogBucket) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.retention_days == 1512 - assert response.locked is True - assert response.lifecycle_state == logging_config.LifecycleState.ACTIVE - - -def test_create_bucket_from_dict(): - test_create_bucket(request_type=dict) - - -def test_create_bucket_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 = ConfigServiceV2Client( - 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.create_bucket), - '__call__') as call: - client.create_bucket() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.CreateBucketRequest() - - -@pytest.mark.asyncio -async def test_create_bucket_async(transport: str = 'grpc_asyncio', request_type=logging_config.CreateBucketRequest): - client = ConfigServiceV2AsyncClient( - 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.create_bucket), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogBucket( - name='name_value', - description='description_value', - retention_days=1512, - locked=True, - lifecycle_state=logging_config.LifecycleState.ACTIVE, - )) - response = await client.create_bucket(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.CreateBucketRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogBucket) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.retention_days == 1512 - assert response.locked is True - assert response.lifecycle_state == logging_config.LifecycleState.ACTIVE - - -@pytest.mark.asyncio -async def test_create_bucket_async_from_dict(): - await test_create_bucket_async(request_type=dict) - - -def test_create_bucket_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.CreateBucketRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_bucket), - '__call__') as call: - call.return_value = logging_config.LogBucket() - client.create_bucket(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_create_bucket_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.CreateBucketRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_bucket), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogBucket()) - await client.create_bucket(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_update_bucket(transport: str = 'grpc', request_type=logging_config.UpdateBucketRequest): - client = ConfigServiceV2Client( - 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.update_bucket), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogBucket( - name='name_value', - description='description_value', - retention_days=1512, - locked=True, - lifecycle_state=logging_config.LifecycleState.ACTIVE, - ) - response = client.update_bucket(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.UpdateBucketRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogBucket) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.retention_days == 1512 - assert response.locked is True - assert response.lifecycle_state == logging_config.LifecycleState.ACTIVE - - -def test_update_bucket_from_dict(): - test_update_bucket(request_type=dict) - - -def test_update_bucket_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 = ConfigServiceV2Client( - 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.update_bucket), - '__call__') as call: - client.update_bucket() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.UpdateBucketRequest() - - -@pytest.mark.asyncio -async def test_update_bucket_async(transport: str = 'grpc_asyncio', request_type=logging_config.UpdateBucketRequest): - client = ConfigServiceV2AsyncClient( - 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.update_bucket), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogBucket( - name='name_value', - description='description_value', - retention_days=1512, - locked=True, - lifecycle_state=logging_config.LifecycleState.ACTIVE, - )) - response = await client.update_bucket(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.UpdateBucketRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogBucket) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.retention_days == 1512 - assert response.locked is True - assert response.lifecycle_state == logging_config.LifecycleState.ACTIVE - - -@pytest.mark.asyncio -async def test_update_bucket_async_from_dict(): - await test_update_bucket_async(request_type=dict) - - -def test_update_bucket_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.UpdateBucketRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_bucket), - '__call__') as call: - call.return_value = logging_config.LogBucket() - client.update_bucket(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_update_bucket_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.UpdateBucketRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_bucket), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogBucket()) - await client.update_bucket(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'] - - -def test_delete_bucket(transport: str = 'grpc', request_type=logging_config.DeleteBucketRequest): - client = ConfigServiceV2Client( - 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.delete_bucket), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_bucket(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.DeleteBucketRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_bucket_from_dict(): - test_delete_bucket(request_type=dict) - - -def test_delete_bucket_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 = ConfigServiceV2Client( - 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.delete_bucket), - '__call__') as call: - client.delete_bucket() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.DeleteBucketRequest() - - -@pytest.mark.asyncio -async def test_delete_bucket_async(transport: str = 'grpc_asyncio', request_type=logging_config.DeleteBucketRequest): - client = ConfigServiceV2AsyncClient( - 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.delete_bucket), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_bucket(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.DeleteBucketRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_bucket_async_from_dict(): - await test_delete_bucket_async(request_type=dict) - - -def test_delete_bucket_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.DeleteBucketRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_bucket), - '__call__') as call: - call.return_value = None - client.delete_bucket(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_delete_bucket_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.DeleteBucketRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_bucket), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_bucket(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'] - - -def test_undelete_bucket(transport: str = 'grpc', request_type=logging_config.UndeleteBucketRequest): - client = ConfigServiceV2Client( - 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.undelete_bucket), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.undelete_bucket(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.UndeleteBucketRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_undelete_bucket_from_dict(): - test_undelete_bucket(request_type=dict) - - -def test_undelete_bucket_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 = ConfigServiceV2Client( - 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.undelete_bucket), - '__call__') as call: - client.undelete_bucket() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.UndeleteBucketRequest() - - -@pytest.mark.asyncio -async def test_undelete_bucket_async(transport: str = 'grpc_asyncio', request_type=logging_config.UndeleteBucketRequest): - client = ConfigServiceV2AsyncClient( - 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.undelete_bucket), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.undelete_bucket(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.UndeleteBucketRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_undelete_bucket_async_from_dict(): - await test_undelete_bucket_async(request_type=dict) - - -def test_undelete_bucket_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.UndeleteBucketRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_bucket), - '__call__') as call: - call.return_value = None - client.undelete_bucket(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_undelete_bucket_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.UndeleteBucketRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_bucket), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.undelete_bucket(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'] - - -def test_list_views(transport: str = 'grpc', request_type=logging_config.ListViewsRequest): - client = ConfigServiceV2Client( - 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_views), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.ListViewsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_views(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.ListViewsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListViewsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_views_from_dict(): - test_list_views(request_type=dict) - - -def test_list_views_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 = ConfigServiceV2Client( - 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_views), - '__call__') as call: - client.list_views() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.ListViewsRequest() - - -@pytest.mark.asyncio -async def test_list_views_async(transport: str = 'grpc_asyncio', request_type=logging_config.ListViewsRequest): - client = ConfigServiceV2AsyncClient( - 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_views), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_config.ListViewsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_views(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.ListViewsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListViewsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_views_async_from_dict(): - await test_list_views_async(request_type=dict) - - -def test_list_views_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.ListViewsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_views), - '__call__') as call: - call.return_value = logging_config.ListViewsResponse() - client.list_views(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_views_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.ListViewsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_views), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.ListViewsResponse()) - await client.list_views(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_views_flattened(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_views), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.ListViewsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_views( - 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] - assert args[0].parent == 'parent_value' - - -def test_list_views_flattened_error(): - client = ConfigServiceV2Client( - 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_views( - logging_config.ListViewsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_views_flattened_async(): - client = ConfigServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_views), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.ListViewsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.ListViewsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_views( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_views_flattened_error_async(): - client = ConfigServiceV2AsyncClient( - 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_views( - logging_config.ListViewsRequest(), - parent='parent_value', - ) - - -def test_list_views_pager(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_views), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - logging_config.ListViewsResponse( - views=[ - logging_config.LogView(), - logging_config.LogView(), - logging_config.LogView(), - ], - next_page_token='abc', - ), - logging_config.ListViewsResponse( - views=[], - next_page_token='def', - ), - logging_config.ListViewsResponse( - views=[ - logging_config.LogView(), - ], - next_page_token='ghi', - ), - logging_config.ListViewsResponse( - views=[ - logging_config.LogView(), - logging_config.LogView(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_views(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, logging_config.LogView) - for i in results) - -def test_list_views_pages(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_views), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - logging_config.ListViewsResponse( - views=[ - logging_config.LogView(), - logging_config.LogView(), - logging_config.LogView(), - ], - next_page_token='abc', - ), - logging_config.ListViewsResponse( - views=[], - next_page_token='def', - ), - logging_config.ListViewsResponse( - views=[ - logging_config.LogView(), - ], - next_page_token='ghi', - ), - logging_config.ListViewsResponse( - views=[ - logging_config.LogView(), - logging_config.LogView(), - ], - ), - RuntimeError, - ) - pages = list(client.list_views(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_views_async_pager(): - client = ConfigServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_views), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - logging_config.ListViewsResponse( - views=[ - logging_config.LogView(), - logging_config.LogView(), - logging_config.LogView(), - ], - next_page_token='abc', - ), - logging_config.ListViewsResponse( - views=[], - next_page_token='def', - ), - logging_config.ListViewsResponse( - views=[ - logging_config.LogView(), - ], - next_page_token='ghi', - ), - logging_config.ListViewsResponse( - views=[ - logging_config.LogView(), - logging_config.LogView(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_views(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, logging_config.LogView) - for i in responses) - -@pytest.mark.asyncio -async def test_list_views_async_pages(): - client = ConfigServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_views), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - logging_config.ListViewsResponse( - views=[ - logging_config.LogView(), - logging_config.LogView(), - logging_config.LogView(), - ], - next_page_token='abc', - ), - logging_config.ListViewsResponse( - views=[], - next_page_token='def', - ), - logging_config.ListViewsResponse( - views=[ - logging_config.LogView(), - ], - next_page_token='ghi', - ), - logging_config.ListViewsResponse( - views=[ - logging_config.LogView(), - logging_config.LogView(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_views(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_view(transport: str = 'grpc', request_type=logging_config.GetViewRequest): - client = ConfigServiceV2Client( - 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.get_view), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogView( - name='name_value', - description='description_value', - filter='filter_value', - ) - response = client.get_view(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.GetViewRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogView) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - - -def test_get_view_from_dict(): - test_get_view(request_type=dict) - - -def test_get_view_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 = ConfigServiceV2Client( - 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.get_view), - '__call__') as call: - client.get_view() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.GetViewRequest() - - -@pytest.mark.asyncio -async def test_get_view_async(transport: str = 'grpc_asyncio', request_type=logging_config.GetViewRequest): - client = ConfigServiceV2AsyncClient( - 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.get_view), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogView( - name='name_value', - description='description_value', - filter='filter_value', - )) - response = await client.get_view(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.GetViewRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogView) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_get_view_async_from_dict(): - await test_get_view_async(request_type=dict) - - -def test_get_view_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.GetViewRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_view), - '__call__') as call: - call.return_value = logging_config.LogView() - client.get_view(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_get_view_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.GetViewRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_view), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogView()) - await client.get_view(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'] - - -def test_create_view(transport: str = 'grpc', request_type=logging_config.CreateViewRequest): - client = ConfigServiceV2Client( - 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.create_view), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogView( - name='name_value', - description='description_value', - filter='filter_value', - ) - response = client.create_view(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.CreateViewRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogView) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - - -def test_create_view_from_dict(): - test_create_view(request_type=dict) - - -def test_create_view_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 = ConfigServiceV2Client( - 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.create_view), - '__call__') as call: - client.create_view() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.CreateViewRequest() - - -@pytest.mark.asyncio -async def test_create_view_async(transport: str = 'grpc_asyncio', request_type=logging_config.CreateViewRequest): - client = ConfigServiceV2AsyncClient( - 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.create_view), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogView( - name='name_value', - description='description_value', - filter='filter_value', - )) - response = await client.create_view(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.CreateViewRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogView) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_create_view_async_from_dict(): - await test_create_view_async(request_type=dict) - - -def test_create_view_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.CreateViewRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_view), - '__call__') as call: - call.return_value = logging_config.LogView() - client.create_view(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_create_view_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.CreateViewRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_view), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogView()) - await client.create_view(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_update_view(transport: str = 'grpc', request_type=logging_config.UpdateViewRequest): - client = ConfigServiceV2Client( - 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.update_view), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogView( - name='name_value', - description='description_value', - filter='filter_value', - ) - response = client.update_view(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.UpdateViewRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogView) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - - -def test_update_view_from_dict(): - test_update_view(request_type=dict) - - -def test_update_view_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 = ConfigServiceV2Client( - 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.update_view), - '__call__') as call: - client.update_view() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.UpdateViewRequest() - - -@pytest.mark.asyncio -async def test_update_view_async(transport: str = 'grpc_asyncio', request_type=logging_config.UpdateViewRequest): - client = ConfigServiceV2AsyncClient( - 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.update_view), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogView( - name='name_value', - description='description_value', - filter='filter_value', - )) - response = await client.update_view(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.UpdateViewRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogView) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - - -@pytest.mark.asyncio -async def test_update_view_async_from_dict(): - await test_update_view_async(request_type=dict) - - -def test_update_view_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.UpdateViewRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_view), - '__call__') as call: - call.return_value = logging_config.LogView() - client.update_view(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_update_view_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.UpdateViewRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_view), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogView()) - await client.update_view(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'] - - -def test_delete_view(transport: str = 'grpc', request_type=logging_config.DeleteViewRequest): - client = ConfigServiceV2Client( - 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.delete_view), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_view(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.DeleteViewRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_view_from_dict(): - test_delete_view(request_type=dict) - - -def test_delete_view_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 = ConfigServiceV2Client( - 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.delete_view), - '__call__') as call: - client.delete_view() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.DeleteViewRequest() - - -@pytest.mark.asyncio -async def test_delete_view_async(transport: str = 'grpc_asyncio', request_type=logging_config.DeleteViewRequest): - client = ConfigServiceV2AsyncClient( - 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.delete_view), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_view(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.DeleteViewRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_view_async_from_dict(): - await test_delete_view_async(request_type=dict) - - -def test_delete_view_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.DeleteViewRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_view), - '__call__') as call: - call.return_value = None - client.delete_view(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_delete_view_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.DeleteViewRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_view), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_view(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'] - - -def test_list_sinks(transport: str = 'grpc', request_type=logging_config.ListSinksRequest): - client = ConfigServiceV2Client( - 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_sinks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.ListSinksResponse( - next_page_token='next_page_token_value', - ) - response = client.list_sinks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.ListSinksRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSinksPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_sinks_from_dict(): - test_list_sinks(request_type=dict) - - -def test_list_sinks_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 = ConfigServiceV2Client( - 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_sinks), - '__call__') as call: - client.list_sinks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.ListSinksRequest() - - -@pytest.mark.asyncio -async def test_list_sinks_async(transport: str = 'grpc_asyncio', request_type=logging_config.ListSinksRequest): - client = ConfigServiceV2AsyncClient( - 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_sinks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_config.ListSinksResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_sinks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.ListSinksRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSinksAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_sinks_async_from_dict(): - await test_list_sinks_async(request_type=dict) - - -def test_list_sinks_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.ListSinksRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sinks), - '__call__') as call: - call.return_value = logging_config.ListSinksResponse() - client.list_sinks(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_sinks_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.ListSinksRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sinks), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.ListSinksResponse()) - await client.list_sinks(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_sinks_flattened(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sinks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.ListSinksResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_sinks( - 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] - assert args[0].parent == 'parent_value' - - -def test_list_sinks_flattened_error(): - client = ConfigServiceV2Client( - 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_sinks( - logging_config.ListSinksRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_sinks_flattened_async(): - client = ConfigServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sinks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.ListSinksResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.ListSinksResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_sinks( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_sinks_flattened_error_async(): - client = ConfigServiceV2AsyncClient( - 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_sinks( - logging_config.ListSinksRequest(), - parent='parent_value', - ) - - -def test_list_sinks_pager(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sinks), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - logging_config.ListSinksResponse( - sinks=[ - logging_config.LogSink(), - logging_config.LogSink(), - logging_config.LogSink(), - ], - next_page_token='abc', - ), - logging_config.ListSinksResponse( - sinks=[], - next_page_token='def', - ), - logging_config.ListSinksResponse( - sinks=[ - logging_config.LogSink(), - ], - next_page_token='ghi', - ), - logging_config.ListSinksResponse( - sinks=[ - logging_config.LogSink(), - logging_config.LogSink(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_sinks(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, logging_config.LogSink) - for i in results) - -def test_list_sinks_pages(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sinks), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - logging_config.ListSinksResponse( - sinks=[ - logging_config.LogSink(), - logging_config.LogSink(), - logging_config.LogSink(), - ], - next_page_token='abc', - ), - logging_config.ListSinksResponse( - sinks=[], - next_page_token='def', - ), - logging_config.ListSinksResponse( - sinks=[ - logging_config.LogSink(), - ], - next_page_token='ghi', - ), - logging_config.ListSinksResponse( - sinks=[ - logging_config.LogSink(), - logging_config.LogSink(), - ], - ), - RuntimeError, - ) - pages = list(client.list_sinks(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_sinks_async_pager(): - client = ConfigServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sinks), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - logging_config.ListSinksResponse( - sinks=[ - logging_config.LogSink(), - logging_config.LogSink(), - logging_config.LogSink(), - ], - next_page_token='abc', - ), - logging_config.ListSinksResponse( - sinks=[], - next_page_token='def', - ), - logging_config.ListSinksResponse( - sinks=[ - logging_config.LogSink(), - ], - next_page_token='ghi', - ), - logging_config.ListSinksResponse( - sinks=[ - logging_config.LogSink(), - logging_config.LogSink(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_sinks(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, logging_config.LogSink) - for i in responses) - -@pytest.mark.asyncio -async def test_list_sinks_async_pages(): - client = ConfigServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sinks), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - logging_config.ListSinksResponse( - sinks=[ - logging_config.LogSink(), - logging_config.LogSink(), - logging_config.LogSink(), - ], - next_page_token='abc', - ), - logging_config.ListSinksResponse( - sinks=[], - next_page_token='def', - ), - logging_config.ListSinksResponse( - sinks=[ - logging_config.LogSink(), - ], - next_page_token='ghi', - ), - logging_config.ListSinksResponse( - sinks=[ - logging_config.LogSink(), - logging_config.LogSink(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_sinks(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_sink(transport: str = 'grpc', request_type=logging_config.GetSinkRequest): - client = ConfigServiceV2Client( - 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.get_sink), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogSink( - name='name_value', - destination='destination_value', - filter='filter_value', - description='description_value', - disabled=True, - output_version_format=logging_config.LogSink.VersionFormat.V2, - writer_identity='writer_identity_value', - include_children=True, - bigquery_options=logging_config.BigQueryOptions(use_partitioned_tables=True), - ) - response = client.get_sink(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.GetSinkRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogSink) - assert response.name == 'name_value' - assert response.destination == 'destination_value' - assert response.filter == 'filter_value' - assert response.description == 'description_value' - assert response.disabled is True - assert response.output_version_format == logging_config.LogSink.VersionFormat.V2 - assert response.writer_identity == 'writer_identity_value' - assert response.include_children is True - - -def test_get_sink_from_dict(): - test_get_sink(request_type=dict) - - -def test_get_sink_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 = ConfigServiceV2Client( - 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.get_sink), - '__call__') as call: - client.get_sink() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.GetSinkRequest() - - -@pytest.mark.asyncio -async def test_get_sink_async(transport: str = 'grpc_asyncio', request_type=logging_config.GetSinkRequest): - client = ConfigServiceV2AsyncClient( - 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.get_sink), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogSink( - name='name_value', - destination='destination_value', - filter='filter_value', - description='description_value', - disabled=True, - output_version_format=logging_config.LogSink.VersionFormat.V2, - writer_identity='writer_identity_value', - include_children=True, - )) - response = await client.get_sink(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.GetSinkRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogSink) - assert response.name == 'name_value' - assert response.destination == 'destination_value' - assert response.filter == 'filter_value' - assert response.description == 'description_value' - assert response.disabled is True - assert response.output_version_format == logging_config.LogSink.VersionFormat.V2 - assert response.writer_identity == 'writer_identity_value' - assert response.include_children is True - - -@pytest.mark.asyncio -async def test_get_sink_async_from_dict(): - await test_get_sink_async(request_type=dict) - - -def test_get_sink_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.GetSinkRequest() - - request.sink_name = 'sink_name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_sink), - '__call__') as call: - call.return_value = logging_config.LogSink() - client.get_sink(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', - 'sink_name=sink_name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_sink_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.GetSinkRequest() - - request.sink_name = 'sink_name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_sink), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogSink()) - await client.get_sink(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', - 'sink_name=sink_name/value', - ) in kw['metadata'] - - -def test_get_sink_flattened(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_sink), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogSink() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_sink( - sink_name='sink_name_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] - assert args[0].sink_name == 'sink_name_value' - - -def test_get_sink_flattened_error(): - client = ConfigServiceV2Client( - 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.get_sink( - logging_config.GetSinkRequest(), - sink_name='sink_name_value', - ) - - -@pytest.mark.asyncio -async def test_get_sink_flattened_async(): - client = ConfigServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_sink), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogSink() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogSink()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_sink( - sink_name='sink_name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].sink_name == 'sink_name_value' - - -@pytest.mark.asyncio -async def test_get_sink_flattened_error_async(): - client = ConfigServiceV2AsyncClient( - 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.get_sink( - logging_config.GetSinkRequest(), - sink_name='sink_name_value', - ) - - -def test_create_sink(transport: str = 'grpc', request_type=logging_config.CreateSinkRequest): - client = ConfigServiceV2Client( - 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.create_sink), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogSink( - name='name_value', - destination='destination_value', - filter='filter_value', - description='description_value', - disabled=True, - output_version_format=logging_config.LogSink.VersionFormat.V2, - writer_identity='writer_identity_value', - include_children=True, - bigquery_options=logging_config.BigQueryOptions(use_partitioned_tables=True), - ) - response = client.create_sink(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.CreateSinkRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogSink) - assert response.name == 'name_value' - assert response.destination == 'destination_value' - assert response.filter == 'filter_value' - assert response.description == 'description_value' - assert response.disabled is True - assert response.output_version_format == logging_config.LogSink.VersionFormat.V2 - assert response.writer_identity == 'writer_identity_value' - assert response.include_children is True - - -def test_create_sink_from_dict(): - test_create_sink(request_type=dict) - - -def test_create_sink_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 = ConfigServiceV2Client( - 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.create_sink), - '__call__') as call: - client.create_sink() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.CreateSinkRequest() - - -@pytest.mark.asyncio -async def test_create_sink_async(transport: str = 'grpc_asyncio', request_type=logging_config.CreateSinkRequest): - client = ConfigServiceV2AsyncClient( - 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.create_sink), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogSink( - name='name_value', - destination='destination_value', - filter='filter_value', - description='description_value', - disabled=True, - output_version_format=logging_config.LogSink.VersionFormat.V2, - writer_identity='writer_identity_value', - include_children=True, - )) - response = await client.create_sink(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.CreateSinkRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogSink) - assert response.name == 'name_value' - assert response.destination == 'destination_value' - assert response.filter == 'filter_value' - assert response.description == 'description_value' - assert response.disabled is True - assert response.output_version_format == logging_config.LogSink.VersionFormat.V2 - assert response.writer_identity == 'writer_identity_value' - assert response.include_children is True - - -@pytest.mark.asyncio -async def test_create_sink_async_from_dict(): - await test_create_sink_async(request_type=dict) - - -def test_create_sink_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.CreateSinkRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_sink), - '__call__') as call: - call.return_value = logging_config.LogSink() - client.create_sink(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_create_sink_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.CreateSinkRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_sink), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogSink()) - await client.create_sink(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_create_sink_flattened(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_sink), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogSink() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_sink( - parent='parent_value', - sink=logging_config.LogSink(name='name_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] - assert args[0].parent == 'parent_value' - assert args[0].sink == logging_config.LogSink(name='name_value') - - -def test_create_sink_flattened_error(): - client = ConfigServiceV2Client( - 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.create_sink( - logging_config.CreateSinkRequest(), - parent='parent_value', - sink=logging_config.LogSink(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_sink_flattened_async(): - client = ConfigServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_sink), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogSink() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogSink()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_sink( - parent='parent_value', - sink=logging_config.LogSink(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].sink == logging_config.LogSink(name='name_value') - - -@pytest.mark.asyncio -async def test_create_sink_flattened_error_async(): - client = ConfigServiceV2AsyncClient( - 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.create_sink( - logging_config.CreateSinkRequest(), - parent='parent_value', - sink=logging_config.LogSink(name='name_value'), - ) - - -def test_update_sink(transport: str = 'grpc', request_type=logging_config.UpdateSinkRequest): - client = ConfigServiceV2Client( - 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.update_sink), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogSink( - name='name_value', - destination='destination_value', - filter='filter_value', - description='description_value', - disabled=True, - output_version_format=logging_config.LogSink.VersionFormat.V2, - writer_identity='writer_identity_value', - include_children=True, - bigquery_options=logging_config.BigQueryOptions(use_partitioned_tables=True), - ) - response = client.update_sink(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.UpdateSinkRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogSink) - assert response.name == 'name_value' - assert response.destination == 'destination_value' - assert response.filter == 'filter_value' - assert response.description == 'description_value' - assert response.disabled is True - assert response.output_version_format == logging_config.LogSink.VersionFormat.V2 - assert response.writer_identity == 'writer_identity_value' - assert response.include_children is True - - -def test_update_sink_from_dict(): - test_update_sink(request_type=dict) - - -def test_update_sink_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 = ConfigServiceV2Client( - 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.update_sink), - '__call__') as call: - client.update_sink() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.UpdateSinkRequest() - - -@pytest.mark.asyncio -async def test_update_sink_async(transport: str = 'grpc_asyncio', request_type=logging_config.UpdateSinkRequest): - client = ConfigServiceV2AsyncClient( - 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.update_sink), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogSink( - name='name_value', - destination='destination_value', - filter='filter_value', - description='description_value', - disabled=True, - output_version_format=logging_config.LogSink.VersionFormat.V2, - writer_identity='writer_identity_value', - include_children=True, - )) - response = await client.update_sink(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.UpdateSinkRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogSink) - assert response.name == 'name_value' - assert response.destination == 'destination_value' - assert response.filter == 'filter_value' - assert response.description == 'description_value' - assert response.disabled is True - assert response.output_version_format == logging_config.LogSink.VersionFormat.V2 - assert response.writer_identity == 'writer_identity_value' - assert response.include_children is True - - -@pytest.mark.asyncio -async def test_update_sink_async_from_dict(): - await test_update_sink_async(request_type=dict) - - -def test_update_sink_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.UpdateSinkRequest() - - request.sink_name = 'sink_name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_sink), - '__call__') as call: - call.return_value = logging_config.LogSink() - client.update_sink(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', - 'sink_name=sink_name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_sink_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.UpdateSinkRequest() - - request.sink_name = 'sink_name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_sink), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogSink()) - await client.update_sink(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', - 'sink_name=sink_name/value', - ) in kw['metadata'] - - -def test_update_sink_flattened(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_sink), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogSink() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_sink( - sink_name='sink_name_value', - sink=logging_config.LogSink(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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] - assert args[0].sink_name == 'sink_name_value' - assert args[0].sink == logging_config.LogSink(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_sink_flattened_error(): - client = ConfigServiceV2Client( - 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.update_sink( - logging_config.UpdateSinkRequest(), - sink_name='sink_name_value', - sink=logging_config.LogSink(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_sink_flattened_async(): - client = ConfigServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_sink), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogSink() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogSink()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_sink( - sink_name='sink_name_value', - sink=logging_config.LogSink(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].sink_name == 'sink_name_value' - assert args[0].sink == logging_config.LogSink(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_sink_flattened_error_async(): - client = ConfigServiceV2AsyncClient( - 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.update_sink( - logging_config.UpdateSinkRequest(), - sink_name='sink_name_value', - sink=logging_config.LogSink(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_sink(transport: str = 'grpc', request_type=logging_config.DeleteSinkRequest): - client = ConfigServiceV2Client( - 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.delete_sink), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_sink(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.DeleteSinkRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_sink_from_dict(): - test_delete_sink(request_type=dict) - - -def test_delete_sink_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 = ConfigServiceV2Client( - 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.delete_sink), - '__call__') as call: - client.delete_sink() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.DeleteSinkRequest() - - -@pytest.mark.asyncio -async def test_delete_sink_async(transport: str = 'grpc_asyncio', request_type=logging_config.DeleteSinkRequest): - client = ConfigServiceV2AsyncClient( - 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.delete_sink), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_sink(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.DeleteSinkRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_sink_async_from_dict(): - await test_delete_sink_async(request_type=dict) - - -def test_delete_sink_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.DeleteSinkRequest() - - request.sink_name = 'sink_name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_sink), - '__call__') as call: - call.return_value = None - client.delete_sink(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', - 'sink_name=sink_name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_sink_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.DeleteSinkRequest() - - request.sink_name = 'sink_name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_sink), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_sink(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', - 'sink_name=sink_name/value', - ) in kw['metadata'] - - -def test_delete_sink_flattened(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_sink), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_sink( - sink_name='sink_name_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] - assert args[0].sink_name == 'sink_name_value' - - -def test_delete_sink_flattened_error(): - client = ConfigServiceV2Client( - 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.delete_sink( - logging_config.DeleteSinkRequest(), - sink_name='sink_name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_sink_flattened_async(): - client = ConfigServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_sink), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_sink( - sink_name='sink_name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].sink_name == 'sink_name_value' - - -@pytest.mark.asyncio -async def test_delete_sink_flattened_error_async(): - client = ConfigServiceV2AsyncClient( - 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.delete_sink( - logging_config.DeleteSinkRequest(), - sink_name='sink_name_value', - ) - - -def test_list_exclusions(transport: str = 'grpc', request_type=logging_config.ListExclusionsRequest): - client = ConfigServiceV2Client( - 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_exclusions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.ListExclusionsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_exclusions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.ListExclusionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListExclusionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_exclusions_from_dict(): - test_list_exclusions(request_type=dict) - - -def test_list_exclusions_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 = ConfigServiceV2Client( - 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_exclusions), - '__call__') as call: - client.list_exclusions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.ListExclusionsRequest() - - -@pytest.mark.asyncio -async def test_list_exclusions_async(transport: str = 'grpc_asyncio', request_type=logging_config.ListExclusionsRequest): - client = ConfigServiceV2AsyncClient( - 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_exclusions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_config.ListExclusionsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_exclusions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.ListExclusionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListExclusionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_exclusions_async_from_dict(): - await test_list_exclusions_async(request_type=dict) - - -def test_list_exclusions_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.ListExclusionsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_exclusions), - '__call__') as call: - call.return_value = logging_config.ListExclusionsResponse() - client.list_exclusions(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_exclusions_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.ListExclusionsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_exclusions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.ListExclusionsResponse()) - await client.list_exclusions(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_exclusions_flattened(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_exclusions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.ListExclusionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_exclusions( - 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] - assert args[0].parent == 'parent_value' - - -def test_list_exclusions_flattened_error(): - client = ConfigServiceV2Client( - 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_exclusions( - logging_config.ListExclusionsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_exclusions_flattened_async(): - client = ConfigServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_exclusions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.ListExclusionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.ListExclusionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_exclusions( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_exclusions_flattened_error_async(): - client = ConfigServiceV2AsyncClient( - 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_exclusions( - logging_config.ListExclusionsRequest(), - parent='parent_value', - ) - - -def test_list_exclusions_pager(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_exclusions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - logging_config.ListExclusionsResponse( - exclusions=[ - logging_config.LogExclusion(), - logging_config.LogExclusion(), - logging_config.LogExclusion(), - ], - next_page_token='abc', - ), - logging_config.ListExclusionsResponse( - exclusions=[], - next_page_token='def', - ), - logging_config.ListExclusionsResponse( - exclusions=[ - logging_config.LogExclusion(), - ], - next_page_token='ghi', - ), - logging_config.ListExclusionsResponse( - exclusions=[ - logging_config.LogExclusion(), - logging_config.LogExclusion(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_exclusions(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, logging_config.LogExclusion) - for i in results) - -def test_list_exclusions_pages(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_exclusions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - logging_config.ListExclusionsResponse( - exclusions=[ - logging_config.LogExclusion(), - logging_config.LogExclusion(), - logging_config.LogExclusion(), - ], - next_page_token='abc', - ), - logging_config.ListExclusionsResponse( - exclusions=[], - next_page_token='def', - ), - logging_config.ListExclusionsResponse( - exclusions=[ - logging_config.LogExclusion(), - ], - next_page_token='ghi', - ), - logging_config.ListExclusionsResponse( - exclusions=[ - logging_config.LogExclusion(), - logging_config.LogExclusion(), - ], - ), - RuntimeError, - ) - pages = list(client.list_exclusions(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_exclusions_async_pager(): - client = ConfigServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_exclusions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - logging_config.ListExclusionsResponse( - exclusions=[ - logging_config.LogExclusion(), - logging_config.LogExclusion(), - logging_config.LogExclusion(), - ], - next_page_token='abc', - ), - logging_config.ListExclusionsResponse( - exclusions=[], - next_page_token='def', - ), - logging_config.ListExclusionsResponse( - exclusions=[ - logging_config.LogExclusion(), - ], - next_page_token='ghi', - ), - logging_config.ListExclusionsResponse( - exclusions=[ - logging_config.LogExclusion(), - logging_config.LogExclusion(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_exclusions(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, logging_config.LogExclusion) - for i in responses) - -@pytest.mark.asyncio -async def test_list_exclusions_async_pages(): - client = ConfigServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_exclusions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - logging_config.ListExclusionsResponse( - exclusions=[ - logging_config.LogExclusion(), - logging_config.LogExclusion(), - logging_config.LogExclusion(), - ], - next_page_token='abc', - ), - logging_config.ListExclusionsResponse( - exclusions=[], - next_page_token='def', - ), - logging_config.ListExclusionsResponse( - exclusions=[ - logging_config.LogExclusion(), - ], - next_page_token='ghi', - ), - logging_config.ListExclusionsResponse( - exclusions=[ - logging_config.LogExclusion(), - logging_config.LogExclusion(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_exclusions(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_exclusion(transport: str = 'grpc', request_type=logging_config.GetExclusionRequest): - client = ConfigServiceV2Client( - 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.get_exclusion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogExclusion( - name='name_value', - description='description_value', - filter='filter_value', - disabled=True, - ) - response = client.get_exclusion(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.GetExclusionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogExclusion) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.disabled is True - - -def test_get_exclusion_from_dict(): - test_get_exclusion(request_type=dict) - - -def test_get_exclusion_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 = ConfigServiceV2Client( - 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.get_exclusion), - '__call__') as call: - client.get_exclusion() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.GetExclusionRequest() - - -@pytest.mark.asyncio -async def test_get_exclusion_async(transport: str = 'grpc_asyncio', request_type=logging_config.GetExclusionRequest): - client = ConfigServiceV2AsyncClient( - 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.get_exclusion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogExclusion( - name='name_value', - description='description_value', - filter='filter_value', - disabled=True, - )) - response = await client.get_exclusion(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.GetExclusionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogExclusion) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.disabled is True - - -@pytest.mark.asyncio -async def test_get_exclusion_async_from_dict(): - await test_get_exclusion_async(request_type=dict) - - -def test_get_exclusion_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.GetExclusionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_exclusion), - '__call__') as call: - call.return_value = logging_config.LogExclusion() - client.get_exclusion(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_get_exclusion_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.GetExclusionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_exclusion), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogExclusion()) - await client.get_exclusion(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'] - - -def test_get_exclusion_flattened(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_exclusion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogExclusion() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_exclusion( - name='name_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] - assert args[0].name == 'name_value' - - -def test_get_exclusion_flattened_error(): - client = ConfigServiceV2Client( - 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.get_exclusion( - logging_config.GetExclusionRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_exclusion_flattened_async(): - client = ConfigServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_exclusion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogExclusion() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogExclusion()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_exclusion( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_exclusion_flattened_error_async(): - client = ConfigServiceV2AsyncClient( - 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.get_exclusion( - logging_config.GetExclusionRequest(), - name='name_value', - ) - - -def test_create_exclusion(transport: str = 'grpc', request_type=logging_config.CreateExclusionRequest): - client = ConfigServiceV2Client( - 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.create_exclusion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogExclusion( - name='name_value', - description='description_value', - filter='filter_value', - disabled=True, - ) - response = client.create_exclusion(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.CreateExclusionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogExclusion) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.disabled is True - - -def test_create_exclusion_from_dict(): - test_create_exclusion(request_type=dict) - - -def test_create_exclusion_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 = ConfigServiceV2Client( - 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.create_exclusion), - '__call__') as call: - client.create_exclusion() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.CreateExclusionRequest() - - -@pytest.mark.asyncio -async def test_create_exclusion_async(transport: str = 'grpc_asyncio', request_type=logging_config.CreateExclusionRequest): - client = ConfigServiceV2AsyncClient( - 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.create_exclusion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogExclusion( - name='name_value', - description='description_value', - filter='filter_value', - disabled=True, - )) - response = await client.create_exclusion(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.CreateExclusionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogExclusion) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.disabled is True - - -@pytest.mark.asyncio -async def test_create_exclusion_async_from_dict(): - await test_create_exclusion_async(request_type=dict) - - -def test_create_exclusion_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.CreateExclusionRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_exclusion), - '__call__') as call: - call.return_value = logging_config.LogExclusion() - client.create_exclusion(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_create_exclusion_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.CreateExclusionRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_exclusion), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogExclusion()) - await client.create_exclusion(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_create_exclusion_flattened(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_exclusion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogExclusion() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_exclusion( - parent='parent_value', - exclusion=logging_config.LogExclusion(name='name_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] - assert args[0].parent == 'parent_value' - assert args[0].exclusion == logging_config.LogExclusion(name='name_value') - - -def test_create_exclusion_flattened_error(): - client = ConfigServiceV2Client( - 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.create_exclusion( - logging_config.CreateExclusionRequest(), - parent='parent_value', - exclusion=logging_config.LogExclusion(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_exclusion_flattened_async(): - client = ConfigServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_exclusion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogExclusion() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogExclusion()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_exclusion( - parent='parent_value', - exclusion=logging_config.LogExclusion(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].exclusion == logging_config.LogExclusion(name='name_value') - - -@pytest.mark.asyncio -async def test_create_exclusion_flattened_error_async(): - client = ConfigServiceV2AsyncClient( - 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.create_exclusion( - logging_config.CreateExclusionRequest(), - parent='parent_value', - exclusion=logging_config.LogExclusion(name='name_value'), - ) - - -def test_update_exclusion(transport: str = 'grpc', request_type=logging_config.UpdateExclusionRequest): - client = ConfigServiceV2Client( - 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.update_exclusion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogExclusion( - name='name_value', - description='description_value', - filter='filter_value', - disabled=True, - ) - response = client.update_exclusion(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.UpdateExclusionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogExclusion) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.disabled is True - - -def test_update_exclusion_from_dict(): - test_update_exclusion(request_type=dict) - - -def test_update_exclusion_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 = ConfigServiceV2Client( - 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.update_exclusion), - '__call__') as call: - client.update_exclusion() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.UpdateExclusionRequest() - - -@pytest.mark.asyncio -async def test_update_exclusion_async(transport: str = 'grpc_asyncio', request_type=logging_config.UpdateExclusionRequest): - client = ConfigServiceV2AsyncClient( - 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.update_exclusion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogExclusion( - name='name_value', - description='description_value', - filter='filter_value', - disabled=True, - )) - response = await client.update_exclusion(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.UpdateExclusionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.LogExclusion) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.disabled is True - - -@pytest.mark.asyncio -async def test_update_exclusion_async_from_dict(): - await test_update_exclusion_async(request_type=dict) - - -def test_update_exclusion_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.UpdateExclusionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_exclusion), - '__call__') as call: - call.return_value = logging_config.LogExclusion() - client.update_exclusion(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_update_exclusion_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.UpdateExclusionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_exclusion), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogExclusion()) - await client.update_exclusion(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'] - - -def test_update_exclusion_flattened(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_exclusion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogExclusion() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_exclusion( - name='name_value', - exclusion=logging_config.LogExclusion(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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] - assert args[0].name == 'name_value' - assert args[0].exclusion == logging_config.LogExclusion(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_exclusion_flattened_error(): - client = ConfigServiceV2Client( - 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.update_exclusion( - logging_config.UpdateExclusionRequest(), - name='name_value', - exclusion=logging_config.LogExclusion(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_exclusion_flattened_async(): - client = ConfigServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_exclusion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.LogExclusion() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.LogExclusion()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_exclusion( - name='name_value', - exclusion=logging_config.LogExclusion(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - assert args[0].exclusion == logging_config.LogExclusion(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_exclusion_flattened_error_async(): - client = ConfigServiceV2AsyncClient( - 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.update_exclusion( - logging_config.UpdateExclusionRequest(), - name='name_value', - exclusion=logging_config.LogExclusion(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_exclusion(transport: str = 'grpc', request_type=logging_config.DeleteExclusionRequest): - client = ConfigServiceV2Client( - 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.delete_exclusion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_exclusion(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.DeleteExclusionRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_exclusion_from_dict(): - test_delete_exclusion(request_type=dict) - - -def test_delete_exclusion_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 = ConfigServiceV2Client( - 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.delete_exclusion), - '__call__') as call: - client.delete_exclusion() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.DeleteExclusionRequest() - - -@pytest.mark.asyncio -async def test_delete_exclusion_async(transport: str = 'grpc_asyncio', request_type=logging_config.DeleteExclusionRequest): - client = ConfigServiceV2AsyncClient( - 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.delete_exclusion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_exclusion(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.DeleteExclusionRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_exclusion_async_from_dict(): - await test_delete_exclusion_async(request_type=dict) - - -def test_delete_exclusion_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.DeleteExclusionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_exclusion), - '__call__') as call: - call.return_value = None - client.delete_exclusion(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_delete_exclusion_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.DeleteExclusionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_exclusion), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_exclusion(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'] - - -def test_delete_exclusion_flattened(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_exclusion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_exclusion( - name='name_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] - assert args[0].name == 'name_value' - - -def test_delete_exclusion_flattened_error(): - client = ConfigServiceV2Client( - 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.delete_exclusion( - logging_config.DeleteExclusionRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_exclusion_flattened_async(): - client = ConfigServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_exclusion), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_exclusion( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_delete_exclusion_flattened_error_async(): - client = ConfigServiceV2AsyncClient( - 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.delete_exclusion( - logging_config.DeleteExclusionRequest(), - name='name_value', - ) - - -def test_get_cmek_settings(transport: str = 'grpc', request_type=logging_config.GetCmekSettingsRequest): - client = ConfigServiceV2Client( - 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.get_cmek_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.CmekSettings( - name='name_value', - kms_key_name='kms_key_name_value', - service_account_id='service_account_id_value', - ) - response = client.get_cmek_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.GetCmekSettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.CmekSettings) - assert response.name == 'name_value' - assert response.kms_key_name == 'kms_key_name_value' - assert response.service_account_id == 'service_account_id_value' - - -def test_get_cmek_settings_from_dict(): - test_get_cmek_settings(request_type=dict) - - -def test_get_cmek_settings_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 = ConfigServiceV2Client( - 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.get_cmek_settings), - '__call__') as call: - client.get_cmek_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.GetCmekSettingsRequest() - - -@pytest.mark.asyncio -async def test_get_cmek_settings_async(transport: str = 'grpc_asyncio', request_type=logging_config.GetCmekSettingsRequest): - client = ConfigServiceV2AsyncClient( - 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.get_cmek_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_config.CmekSettings( - name='name_value', - kms_key_name='kms_key_name_value', - service_account_id='service_account_id_value', - )) - response = await client.get_cmek_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.GetCmekSettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.CmekSettings) - assert response.name == 'name_value' - assert response.kms_key_name == 'kms_key_name_value' - assert response.service_account_id == 'service_account_id_value' - - -@pytest.mark.asyncio -async def test_get_cmek_settings_async_from_dict(): - await test_get_cmek_settings_async(request_type=dict) - - -def test_get_cmek_settings_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.GetCmekSettingsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_cmek_settings), - '__call__') as call: - call.return_value = logging_config.CmekSettings() - client.get_cmek_settings(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_get_cmek_settings_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.GetCmekSettingsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_cmek_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.CmekSettings()) - await client.get_cmek_settings(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'] - - -def test_update_cmek_settings(transport: str = 'grpc', request_type=logging_config.UpdateCmekSettingsRequest): - client = ConfigServiceV2Client( - 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.update_cmek_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_config.CmekSettings( - name='name_value', - kms_key_name='kms_key_name_value', - service_account_id='service_account_id_value', - ) - response = client.update_cmek_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.UpdateCmekSettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.CmekSettings) - assert response.name == 'name_value' - assert response.kms_key_name == 'kms_key_name_value' - assert response.service_account_id == 'service_account_id_value' - - -def test_update_cmek_settings_from_dict(): - test_update_cmek_settings(request_type=dict) - - -def test_update_cmek_settings_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 = ConfigServiceV2Client( - 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.update_cmek_settings), - '__call__') as call: - client.update_cmek_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.UpdateCmekSettingsRequest() - - -@pytest.mark.asyncio -async def test_update_cmek_settings_async(transport: str = 'grpc_asyncio', request_type=logging_config.UpdateCmekSettingsRequest): - client = ConfigServiceV2AsyncClient( - 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.update_cmek_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_config.CmekSettings( - name='name_value', - kms_key_name='kms_key_name_value', - service_account_id='service_account_id_value', - )) - response = await client.update_cmek_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_config.UpdateCmekSettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_config.CmekSettings) - assert response.name == 'name_value' - assert response.kms_key_name == 'kms_key_name_value' - assert response.service_account_id == 'service_account_id_value' - - -@pytest.mark.asyncio -async def test_update_cmek_settings_async_from_dict(): - await test_update_cmek_settings_async(request_type=dict) - - -def test_update_cmek_settings_field_headers(): - client = ConfigServiceV2Client( - 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 = logging_config.UpdateCmekSettingsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_cmek_settings), - '__call__') as call: - call.return_value = logging_config.CmekSettings() - client.update_cmek_settings(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_update_cmek_settings_field_headers_async(): - client = ConfigServiceV2AsyncClient( - 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 = logging_config.UpdateCmekSettingsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_cmek_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.CmekSettings()) - await client.update_cmek_settings(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'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ConfigServiceV2GrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ConfigServiceV2GrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConfigServiceV2Client( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ConfigServiceV2GrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConfigServiceV2Client( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConfigServiceV2GrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ConfigServiceV2Client(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConfigServiceV2GrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ConfigServiceV2GrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ConfigServiceV2GrpcTransport, - transports.ConfigServiceV2GrpcAsyncIOTransport, -]) -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() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ConfigServiceV2GrpcTransport, - ) - -def test_config_service_v2_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ConfigServiceV2Transport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_config_service_v2_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.logging_v2.services.config_service_v2.transports.ConfigServiceV2Transport.__init__') as Transport: - Transport.return_value = None - transport = transports.ConfigServiceV2Transport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_buckets', - 'get_bucket', - 'create_bucket', - 'update_bucket', - 'delete_bucket', - 'undelete_bucket', - 'list_views', - 'get_view', - 'create_view', - 'update_view', - 'delete_view', - 'list_sinks', - 'get_sink', - 'create_sink', - 'update_sink', - 'delete_sink', - 'list_exclusions', - 'get_exclusion', - 'create_exclusion', - 'update_exclusion', - 'delete_exclusion', - 'get_cmek_settings', - 'update_cmek_settings', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_config_service_v2_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.logging_v2.services.config_service_v2.transports.ConfigServiceV2Transport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConfigServiceV2Transport( - 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/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_config_service_v2_base_transport_with_credentials_file_old_google_auth(): - # 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.logging_v2.services.config_service_v2.transports.ConfigServiceV2Transport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConfigServiceV2Transport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - ), - quota_project_id="octopus", - ) - - -def test_config_service_v2_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.logging_v2.services.config_service_v2.transports.ConfigServiceV2Transport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConfigServiceV2Transport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_config_service_v2_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) - ConfigServiceV2Client() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_config_service_v2_auth_adc_old_google_auth(): - # 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) - ConfigServiceV2Client() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only', 'https://www.googleapis.com/auth/logging.admin', 'https://www.googleapis.com/auth/logging.read',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ConfigServiceV2GrpcTransport, - transports.ConfigServiceV2GrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_config_service_v2_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/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only', 'https://www.googleapis.com/auth/logging.admin', 'https://www.googleapis.com/auth/logging.read',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ConfigServiceV2GrpcTransport, - transports.ConfigServiceV2GrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_config_service_v2_transport_auth_adc_old_google_auth(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") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ConfigServiceV2GrpcTransport, grpc_helpers), - (transports.ConfigServiceV2GrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_config_service_v2_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( - "logging.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', -), - scopes=["1", "2"], - default_host="logging.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ConfigServiceV2GrpcTransport, transports.ConfigServiceV2GrpcAsyncIOTransport]) -def test_config_service_v2_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 - ) - - -def test_config_service_v2_host_no_port(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='logging.googleapis.com'), - ) - assert client.transport._host == 'logging.googleapis.com:443' - - -def test_config_service_v2_host_with_port(): - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='logging.googleapis.com:8000'), - ) - assert client.transport._host == 'logging.googleapis.com:8000' - -def test_config_service_v2_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConfigServiceV2GrpcTransport( - 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_config_service_v2_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConfigServiceV2GrpcAsyncIOTransport( - 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.ConfigServiceV2GrpcTransport, transports.ConfigServiceV2GrpcAsyncIOTransport]) -def test_config_service_v2_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.ConfigServiceV2GrpcTransport, transports.ConfigServiceV2GrpcAsyncIOTransport]) -def test_config_service_v2_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_cmek_settings_path(): - project = "squid" - expected = "projects/{project}/cmekSettings".format(project=project, ) - actual = ConfigServiceV2Client.cmek_settings_path(project) - assert expected == actual - - -def test_parse_cmek_settings_path(): - expected = { - "project": "clam", - } - path = ConfigServiceV2Client.cmek_settings_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigServiceV2Client.parse_cmek_settings_path(path) - assert expected == actual - -def test_log_bucket_path(): - project = "whelk" - location = "octopus" - bucket = "oyster" - expected = "projects/{project}/locations/{location}/buckets/{bucket}".format(project=project, location=location, bucket=bucket, ) - actual = ConfigServiceV2Client.log_bucket_path(project, location, bucket) - assert expected == actual - - -def test_parse_log_bucket_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "bucket": "mussel", - } - path = ConfigServiceV2Client.log_bucket_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigServiceV2Client.parse_log_bucket_path(path) - assert expected == actual - -def test_log_exclusion_path(): - project = "winkle" - exclusion = "nautilus" - expected = "projects/{project}/exclusions/{exclusion}".format(project=project, exclusion=exclusion, ) - actual = ConfigServiceV2Client.log_exclusion_path(project, exclusion) - assert expected == actual - - -def test_parse_log_exclusion_path(): - expected = { - "project": "scallop", - "exclusion": "abalone", - } - path = ConfigServiceV2Client.log_exclusion_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigServiceV2Client.parse_log_exclusion_path(path) - assert expected == actual - -def test_log_sink_path(): - project = "squid" - sink = "clam" - expected = "projects/{project}/sinks/{sink}".format(project=project, sink=sink, ) - actual = ConfigServiceV2Client.log_sink_path(project, sink) - assert expected == actual - - -def test_parse_log_sink_path(): - expected = { - "project": "whelk", - "sink": "octopus", - } - path = ConfigServiceV2Client.log_sink_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigServiceV2Client.parse_log_sink_path(path) - assert expected == actual - -def test_log_view_path(): - project = "oyster" - location = "nudibranch" - bucket = "cuttlefish" - view = "mussel" - expected = "projects/{project}/locations/{location}/buckets/{bucket}/views/{view}".format(project=project, location=location, bucket=bucket, view=view, ) - actual = ConfigServiceV2Client.log_view_path(project, location, bucket, view) - assert expected == actual - - -def test_parse_log_view_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "bucket": "scallop", - "view": "abalone", - } - path = ConfigServiceV2Client.log_view_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigServiceV2Client.parse_log_view_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ConfigServiceV2Client.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = ConfigServiceV2Client.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigServiceV2Client.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = ConfigServiceV2Client.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = ConfigServiceV2Client.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigServiceV2Client.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ConfigServiceV2Client.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = ConfigServiceV2Client.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigServiceV2Client.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = ConfigServiceV2Client.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = ConfigServiceV2Client.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigServiceV2Client.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ConfigServiceV2Client.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = ConfigServiceV2Client.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigServiceV2Client.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.ConfigServiceV2Transport, '_prep_wrapped_messages') as prep: - client = ConfigServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ConfigServiceV2Transport, '_prep_wrapped_messages') as prep: - transport_class = ConfigServiceV2Client.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v2/tests/unit/gapic/logging_v2/test_logging_service_v2.py b/owl-bot-staging/v2/tests/unit/gapic/logging_v2/test_logging_service_v2.py deleted file mode 100644 index b9528146..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/logging_v2/test_logging_service_v2.py +++ /dev/null @@ -1,2494 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api import monitored_resource_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.logging_v2.services.logging_service_v2 import LoggingServiceV2AsyncClient -from google.cloud.logging_v2.services.logging_service_v2 import LoggingServiceV2Client -from google.cloud.logging_v2.services.logging_service_v2 import pagers -from google.cloud.logging_v2.services.logging_service_v2 import transports -from google.cloud.logging_v2.services.logging_service_v2.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.logging_v2.types import log_entry -from google.cloud.logging_v2.types import logging -from google.logging.type import http_request_pb2 # type: ignore -from google.logging.type import log_severity_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -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 LoggingServiceV2Client._get_default_mtls_endpoint(None) is None - assert LoggingServiceV2Client._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert LoggingServiceV2Client._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert LoggingServiceV2Client._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert LoggingServiceV2Client._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert LoggingServiceV2Client._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - LoggingServiceV2Client, - LoggingServiceV2AsyncClient, -]) -def test_logging_service_v2_client_from_service_account_info(client_class): - 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) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'logging.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.LoggingServiceV2GrpcTransport, "grpc"), - (transports.LoggingServiceV2GrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_logging_service_v2_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", [ - LoggingServiceV2Client, - LoggingServiceV2AsyncClient, -]) -def test_logging_service_v2_client_from_service_account_file(client_class): - 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") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'logging.googleapis.com:443' - - -def test_logging_service_v2_client_get_transport_class(): - transport = LoggingServiceV2Client.get_transport_class() - available_transports = [ - transports.LoggingServiceV2GrpcTransport, - ] - assert transport in available_transports - - transport = LoggingServiceV2Client.get_transport_class("grpc") - assert transport == transports.LoggingServiceV2GrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (LoggingServiceV2Client, transports.LoggingServiceV2GrpcTransport, "grpc"), - (LoggingServiceV2AsyncClient, transports.LoggingServiceV2GrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(LoggingServiceV2Client, "DEFAULT_ENDPOINT", modify_default_endpoint(LoggingServiceV2Client)) -@mock.patch.object(LoggingServiceV2AsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LoggingServiceV2AsyncClient)) -def test_logging_service_v2_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(LoggingServiceV2Client, '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(LoggingServiceV2Client, '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(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, - ) - - # 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() - 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, - ) - - # 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() - 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, - ) - - # 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() - - # 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() - - # 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) - 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, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (LoggingServiceV2Client, transports.LoggingServiceV2GrpcTransport, "grpc", "true"), - (LoggingServiceV2AsyncClient, transports.LoggingServiceV2GrpcAsyncIOTransport, "grpc_asyncio", "true"), - (LoggingServiceV2Client, transports.LoggingServiceV2GrpcTransport, "grpc", "false"), - (LoggingServiceV2AsyncClient, transports.LoggingServiceV2GrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(LoggingServiceV2Client, "DEFAULT_ENDPOINT", modify_default_endpoint(LoggingServiceV2Client)) -@mock.patch.object(LoggingServiceV2AsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LoggingServiceV2AsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_logging_service_v2_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) - - 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, - ) - - # 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() - 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, - ) - - # 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() - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (LoggingServiceV2Client, transports.LoggingServiceV2GrpcTransport, "grpc"), - (LoggingServiceV2AsyncClient, transports.LoggingServiceV2GrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_logging_service_v2_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) - 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, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (LoggingServiceV2Client, transports.LoggingServiceV2GrpcTransport, "grpc"), - (LoggingServiceV2AsyncClient, transports.LoggingServiceV2GrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_logging_service_v2_client_client_options_credentials_file(client_class, transport_class, transport_name): - # 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) - 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, - ) - - -def test_logging_service_v2_client_client_options_from_dict(): - with mock.patch('google.cloud.logging_v2.services.logging_service_v2.transports.LoggingServiceV2GrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = LoggingServiceV2Client( - 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, - ) - - -def test_delete_log(transport: str = 'grpc', request_type=logging.DeleteLogRequest): - client = LoggingServiceV2Client( - 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.delete_log), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_log(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging.DeleteLogRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_log_from_dict(): - test_delete_log(request_type=dict) - - -def test_delete_log_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 = LoggingServiceV2Client( - 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.delete_log), - '__call__') as call: - client.delete_log() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging.DeleteLogRequest() - - -@pytest.mark.asyncio -async def test_delete_log_async(transport: str = 'grpc_asyncio', request_type=logging.DeleteLogRequest): - client = LoggingServiceV2AsyncClient( - 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.delete_log), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_log(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging.DeleteLogRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_log_async_from_dict(): - await test_delete_log_async(request_type=dict) - - -def test_delete_log_field_headers(): - client = LoggingServiceV2Client( - 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 = logging.DeleteLogRequest() - - request.log_name = 'log_name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_log), - '__call__') as call: - call.return_value = None - client.delete_log(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', - 'log_name=log_name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_log_field_headers_async(): - client = LoggingServiceV2AsyncClient( - 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 = logging.DeleteLogRequest() - - request.log_name = 'log_name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_log), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_log(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', - 'log_name=log_name/value', - ) in kw['metadata'] - - -def test_delete_log_flattened(): - client = LoggingServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_log), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_log( - log_name='log_name_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] - assert args[0].log_name == 'log_name_value' - - -def test_delete_log_flattened_error(): - client = LoggingServiceV2Client( - 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.delete_log( - logging.DeleteLogRequest(), - log_name='log_name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_log_flattened_async(): - client = LoggingServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_log), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_log( - log_name='log_name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].log_name == 'log_name_value' - - -@pytest.mark.asyncio -async def test_delete_log_flattened_error_async(): - client = LoggingServiceV2AsyncClient( - 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.delete_log( - logging.DeleteLogRequest(), - log_name='log_name_value', - ) - - -def test_write_log_entries(transport: str = 'grpc', request_type=logging.WriteLogEntriesRequest): - client = LoggingServiceV2Client( - 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.write_log_entries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging.WriteLogEntriesResponse( - ) - response = client.write_log_entries(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging.WriteLogEntriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging.WriteLogEntriesResponse) - - -def test_write_log_entries_from_dict(): - test_write_log_entries(request_type=dict) - - -def test_write_log_entries_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 = LoggingServiceV2Client( - 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.write_log_entries), - '__call__') as call: - client.write_log_entries() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging.WriteLogEntriesRequest() - - -@pytest.mark.asyncio -async def test_write_log_entries_async(transport: str = 'grpc_asyncio', request_type=logging.WriteLogEntriesRequest): - client = LoggingServiceV2AsyncClient( - 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.write_log_entries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging.WriteLogEntriesResponse( - )) - response = await client.write_log_entries(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging.WriteLogEntriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging.WriteLogEntriesResponse) - - -@pytest.mark.asyncio -async def test_write_log_entries_async_from_dict(): - await test_write_log_entries_async(request_type=dict) - - -def test_write_log_entries_flattened(): - client = LoggingServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_log_entries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging.WriteLogEntriesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.write_log_entries( - log_name='log_name_value', - resource=monitored_resource_pb2.MonitoredResource(type_='type__value'), - labels={'key_value': 'value_value'}, - entries=[log_entry.LogEntry(log_name='log_name_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] - assert args[0].log_name == 'log_name_value' - assert args[0].resource == monitored_resource_pb2.MonitoredResource(type_='type__value') - assert args[0].labels == {'key_value': 'value_value'} - assert args[0].entries == [log_entry.LogEntry(log_name='log_name_value')] - - -def test_write_log_entries_flattened_error(): - client = LoggingServiceV2Client( - 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.write_log_entries( - logging.WriteLogEntriesRequest(), - log_name='log_name_value', - resource=monitored_resource_pb2.MonitoredResource(type_='type__value'), - labels={'key_value': 'value_value'}, - entries=[log_entry.LogEntry(log_name='log_name_value')], - ) - - -@pytest.mark.asyncio -async def test_write_log_entries_flattened_async(): - client = LoggingServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_log_entries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging.WriteLogEntriesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging.WriteLogEntriesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.write_log_entries( - log_name='log_name_value', - resource=monitored_resource_pb2.MonitoredResource(type_='type__value'), - labels={'key_value': 'value_value'}, - entries=[log_entry.LogEntry(log_name='log_name_value')], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].log_name == 'log_name_value' - assert args[0].resource == monitored_resource_pb2.MonitoredResource(type_='type__value') - assert args[0].labels == {'key_value': 'value_value'} - assert args[0].entries == [log_entry.LogEntry(log_name='log_name_value')] - - -@pytest.mark.asyncio -async def test_write_log_entries_flattened_error_async(): - client = LoggingServiceV2AsyncClient( - 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.write_log_entries( - logging.WriteLogEntriesRequest(), - log_name='log_name_value', - resource=monitored_resource_pb2.MonitoredResource(type_='type__value'), - labels={'key_value': 'value_value'}, - entries=[log_entry.LogEntry(log_name='log_name_value')], - ) - - -def test_list_log_entries(transport: str = 'grpc', request_type=logging.ListLogEntriesRequest): - client = LoggingServiceV2Client( - 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_log_entries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging.ListLogEntriesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_log_entries(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging.ListLogEntriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLogEntriesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_log_entries_from_dict(): - test_list_log_entries(request_type=dict) - - -def test_list_log_entries_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 = LoggingServiceV2Client( - 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_log_entries), - '__call__') as call: - client.list_log_entries() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging.ListLogEntriesRequest() - - -@pytest.mark.asyncio -async def test_list_log_entries_async(transport: str = 'grpc_asyncio', request_type=logging.ListLogEntriesRequest): - client = LoggingServiceV2AsyncClient( - 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_log_entries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging.ListLogEntriesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_log_entries(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging.ListLogEntriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLogEntriesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_log_entries_async_from_dict(): - await test_list_log_entries_async(request_type=dict) - - -def test_list_log_entries_flattened(): - client = LoggingServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_log_entries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging.ListLogEntriesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_log_entries( - resource_names=['resource_names_value'], - filter='filter_value', - order_by='order_by_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] - assert args[0].resource_names == ['resource_names_value'] - assert args[0].filter == 'filter_value' - assert args[0].order_by == 'order_by_value' - - -def test_list_log_entries_flattened_error(): - client = LoggingServiceV2Client( - 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_log_entries( - logging.ListLogEntriesRequest(), - resource_names=['resource_names_value'], - filter='filter_value', - order_by='order_by_value', - ) - - -@pytest.mark.asyncio -async def test_list_log_entries_flattened_async(): - client = LoggingServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_log_entries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging.ListLogEntriesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging.ListLogEntriesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_log_entries( - resource_names=['resource_names_value'], - filter='filter_value', - order_by='order_by_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].resource_names == ['resource_names_value'] - assert args[0].filter == 'filter_value' - assert args[0].order_by == 'order_by_value' - - -@pytest.mark.asyncio -async def test_list_log_entries_flattened_error_async(): - client = LoggingServiceV2AsyncClient( - 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_log_entries( - logging.ListLogEntriesRequest(), - resource_names=['resource_names_value'], - filter='filter_value', - order_by='order_by_value', - ) - - -def test_list_log_entries_pager(): - client = LoggingServiceV2Client( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_log_entries), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - logging.ListLogEntriesResponse( - entries=[ - log_entry.LogEntry(), - log_entry.LogEntry(), - log_entry.LogEntry(), - ], - next_page_token='abc', - ), - logging.ListLogEntriesResponse( - entries=[], - next_page_token='def', - ), - logging.ListLogEntriesResponse( - entries=[ - log_entry.LogEntry(), - ], - next_page_token='ghi', - ), - logging.ListLogEntriesResponse( - entries=[ - log_entry.LogEntry(), - log_entry.LogEntry(), - ], - ), - RuntimeError, - ) - - metadata = () - pager = client.list_log_entries(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, log_entry.LogEntry) - for i in results) - -def test_list_log_entries_pages(): - client = LoggingServiceV2Client( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_log_entries), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - logging.ListLogEntriesResponse( - entries=[ - log_entry.LogEntry(), - log_entry.LogEntry(), - log_entry.LogEntry(), - ], - next_page_token='abc', - ), - logging.ListLogEntriesResponse( - entries=[], - next_page_token='def', - ), - logging.ListLogEntriesResponse( - entries=[ - log_entry.LogEntry(), - ], - next_page_token='ghi', - ), - logging.ListLogEntriesResponse( - entries=[ - log_entry.LogEntry(), - log_entry.LogEntry(), - ], - ), - RuntimeError, - ) - pages = list(client.list_log_entries(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_log_entries_async_pager(): - client = LoggingServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_log_entries), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - logging.ListLogEntriesResponse( - entries=[ - log_entry.LogEntry(), - log_entry.LogEntry(), - log_entry.LogEntry(), - ], - next_page_token='abc', - ), - logging.ListLogEntriesResponse( - entries=[], - next_page_token='def', - ), - logging.ListLogEntriesResponse( - entries=[ - log_entry.LogEntry(), - ], - next_page_token='ghi', - ), - logging.ListLogEntriesResponse( - entries=[ - log_entry.LogEntry(), - log_entry.LogEntry(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_log_entries(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, log_entry.LogEntry) - for i in responses) - -@pytest.mark.asyncio -async def test_list_log_entries_async_pages(): - client = LoggingServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_log_entries), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - logging.ListLogEntriesResponse( - entries=[ - log_entry.LogEntry(), - log_entry.LogEntry(), - log_entry.LogEntry(), - ], - next_page_token='abc', - ), - logging.ListLogEntriesResponse( - entries=[], - next_page_token='def', - ), - logging.ListLogEntriesResponse( - entries=[ - log_entry.LogEntry(), - ], - next_page_token='ghi', - ), - logging.ListLogEntriesResponse( - entries=[ - log_entry.LogEntry(), - log_entry.LogEntry(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_log_entries(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_list_monitored_resource_descriptors(transport: str = 'grpc', request_type=logging.ListMonitoredResourceDescriptorsRequest): - client = LoggingServiceV2Client( - 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_monitored_resource_descriptors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging.ListMonitoredResourceDescriptorsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_monitored_resource_descriptors(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging.ListMonitoredResourceDescriptorsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMonitoredResourceDescriptorsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_monitored_resource_descriptors_from_dict(): - test_list_monitored_resource_descriptors(request_type=dict) - - -def test_list_monitored_resource_descriptors_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 = LoggingServiceV2Client( - 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_monitored_resource_descriptors), - '__call__') as call: - client.list_monitored_resource_descriptors() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging.ListMonitoredResourceDescriptorsRequest() - - -@pytest.mark.asyncio -async def test_list_monitored_resource_descriptors_async(transport: str = 'grpc_asyncio', request_type=logging.ListMonitoredResourceDescriptorsRequest): - client = LoggingServiceV2AsyncClient( - 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_monitored_resource_descriptors), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging.ListMonitoredResourceDescriptorsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_monitored_resource_descriptors(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging.ListMonitoredResourceDescriptorsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMonitoredResourceDescriptorsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_monitored_resource_descriptors_async_from_dict(): - await test_list_monitored_resource_descriptors_async(request_type=dict) - - -def test_list_monitored_resource_descriptors_pager(): - client = LoggingServiceV2Client( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_monitored_resource_descriptors), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - logging.ListMonitoredResourceDescriptorsResponse( - resource_descriptors=[ - monitored_resource_pb2.MonitoredResourceDescriptor(), - monitored_resource_pb2.MonitoredResourceDescriptor(), - monitored_resource_pb2.MonitoredResourceDescriptor(), - ], - next_page_token='abc', - ), - logging.ListMonitoredResourceDescriptorsResponse( - resource_descriptors=[], - next_page_token='def', - ), - logging.ListMonitoredResourceDescriptorsResponse( - resource_descriptors=[ - monitored_resource_pb2.MonitoredResourceDescriptor(), - ], - next_page_token='ghi', - ), - logging.ListMonitoredResourceDescriptorsResponse( - resource_descriptors=[ - monitored_resource_pb2.MonitoredResourceDescriptor(), - monitored_resource_pb2.MonitoredResourceDescriptor(), - ], - ), - RuntimeError, - ) - - metadata = () - pager = client.list_monitored_resource_descriptors(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, monitored_resource_pb2.MonitoredResourceDescriptor) - for i in results) - -def test_list_monitored_resource_descriptors_pages(): - client = LoggingServiceV2Client( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_monitored_resource_descriptors), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - logging.ListMonitoredResourceDescriptorsResponse( - resource_descriptors=[ - monitored_resource_pb2.MonitoredResourceDescriptor(), - monitored_resource_pb2.MonitoredResourceDescriptor(), - monitored_resource_pb2.MonitoredResourceDescriptor(), - ], - next_page_token='abc', - ), - logging.ListMonitoredResourceDescriptorsResponse( - resource_descriptors=[], - next_page_token='def', - ), - logging.ListMonitoredResourceDescriptorsResponse( - resource_descriptors=[ - monitored_resource_pb2.MonitoredResourceDescriptor(), - ], - next_page_token='ghi', - ), - logging.ListMonitoredResourceDescriptorsResponse( - resource_descriptors=[ - monitored_resource_pb2.MonitoredResourceDescriptor(), - monitored_resource_pb2.MonitoredResourceDescriptor(), - ], - ), - RuntimeError, - ) - pages = list(client.list_monitored_resource_descriptors(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_monitored_resource_descriptors_async_pager(): - client = LoggingServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_monitored_resource_descriptors), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - logging.ListMonitoredResourceDescriptorsResponse( - resource_descriptors=[ - monitored_resource_pb2.MonitoredResourceDescriptor(), - monitored_resource_pb2.MonitoredResourceDescriptor(), - monitored_resource_pb2.MonitoredResourceDescriptor(), - ], - next_page_token='abc', - ), - logging.ListMonitoredResourceDescriptorsResponse( - resource_descriptors=[], - next_page_token='def', - ), - logging.ListMonitoredResourceDescriptorsResponse( - resource_descriptors=[ - monitored_resource_pb2.MonitoredResourceDescriptor(), - ], - next_page_token='ghi', - ), - logging.ListMonitoredResourceDescriptorsResponse( - resource_descriptors=[ - monitored_resource_pb2.MonitoredResourceDescriptor(), - monitored_resource_pb2.MonitoredResourceDescriptor(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_monitored_resource_descriptors(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, monitored_resource_pb2.MonitoredResourceDescriptor) - for i in responses) - -@pytest.mark.asyncio -async def test_list_monitored_resource_descriptors_async_pages(): - client = LoggingServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_monitored_resource_descriptors), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - logging.ListMonitoredResourceDescriptorsResponse( - resource_descriptors=[ - monitored_resource_pb2.MonitoredResourceDescriptor(), - monitored_resource_pb2.MonitoredResourceDescriptor(), - monitored_resource_pb2.MonitoredResourceDescriptor(), - ], - next_page_token='abc', - ), - logging.ListMonitoredResourceDescriptorsResponse( - resource_descriptors=[], - next_page_token='def', - ), - logging.ListMonitoredResourceDescriptorsResponse( - resource_descriptors=[ - monitored_resource_pb2.MonitoredResourceDescriptor(), - ], - next_page_token='ghi', - ), - logging.ListMonitoredResourceDescriptorsResponse( - resource_descriptors=[ - monitored_resource_pb2.MonitoredResourceDescriptor(), - monitored_resource_pb2.MonitoredResourceDescriptor(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_monitored_resource_descriptors(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_list_logs(transport: str = 'grpc', request_type=logging.ListLogsRequest): - client = LoggingServiceV2Client( - 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_logs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging.ListLogsResponse( - log_names=['log_names_value'], - next_page_token='next_page_token_value', - ) - response = client.list_logs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging.ListLogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLogsPager) - assert response.log_names == ['log_names_value'] - assert response.next_page_token == 'next_page_token_value' - - -def test_list_logs_from_dict(): - test_list_logs(request_type=dict) - - -def test_list_logs_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 = LoggingServiceV2Client( - 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_logs), - '__call__') as call: - client.list_logs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging.ListLogsRequest() - - -@pytest.mark.asyncio -async def test_list_logs_async(transport: str = 'grpc_asyncio', request_type=logging.ListLogsRequest): - client = LoggingServiceV2AsyncClient( - 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_logs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging.ListLogsResponse( - log_names=['log_names_value'], - next_page_token='next_page_token_value', - )) - response = await client.list_logs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging.ListLogsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLogsAsyncPager) - assert response.log_names == ['log_names_value'] - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_logs_async_from_dict(): - await test_list_logs_async(request_type=dict) - - -def test_list_logs_field_headers(): - client = LoggingServiceV2Client( - 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 = logging.ListLogsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_logs), - '__call__') as call: - call.return_value = logging.ListLogsResponse() - client.list_logs(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_logs_field_headers_async(): - client = LoggingServiceV2AsyncClient( - 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 = logging.ListLogsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_logs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging.ListLogsResponse()) - await client.list_logs(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_logs_flattened(): - client = LoggingServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_logs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging.ListLogsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_logs( - 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] - assert args[0].parent == 'parent_value' - - -def test_list_logs_flattened_error(): - client = LoggingServiceV2Client( - 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_logs( - logging.ListLogsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_logs_flattened_async(): - client = LoggingServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_logs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging.ListLogsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging.ListLogsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_logs( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_logs_flattened_error_async(): - client = LoggingServiceV2AsyncClient( - 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_logs( - logging.ListLogsRequest(), - parent='parent_value', - ) - - -def test_list_logs_pager(): - client = LoggingServiceV2Client( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_logs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - logging.ListLogsResponse( - log_names=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - logging.ListLogsResponse( - log_names=[], - next_page_token='def', - ), - logging.ListLogsResponse( - log_names=[ - str(), - ], - next_page_token='ghi', - ), - logging.ListLogsResponse( - log_names=[ - str(), - str(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_logs(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, str) - for i in results) - -def test_list_logs_pages(): - client = LoggingServiceV2Client( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_logs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - logging.ListLogsResponse( - log_names=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - logging.ListLogsResponse( - log_names=[], - next_page_token='def', - ), - logging.ListLogsResponse( - log_names=[ - str(), - ], - next_page_token='ghi', - ), - logging.ListLogsResponse( - log_names=[ - str(), - str(), - ], - ), - RuntimeError, - ) - pages = list(client.list_logs(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_logs_async_pager(): - client = LoggingServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_logs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - logging.ListLogsResponse( - log_names=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - logging.ListLogsResponse( - log_names=[], - next_page_token='def', - ), - logging.ListLogsResponse( - log_names=[ - str(), - ], - next_page_token='ghi', - ), - logging.ListLogsResponse( - log_names=[ - str(), - str(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_logs(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, str) - for i in responses) - -@pytest.mark.asyncio -async def test_list_logs_async_pages(): - client = LoggingServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_logs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - logging.ListLogsResponse( - log_names=[ - str(), - str(), - str(), - ], - next_page_token='abc', - ), - logging.ListLogsResponse( - log_names=[], - next_page_token='def', - ), - logging.ListLogsResponse( - log_names=[ - str(), - ], - next_page_token='ghi', - ), - logging.ListLogsResponse( - log_names=[ - str(), - str(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_logs(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_tail_log_entries(transport: str = 'grpc', request_type=logging.TailLogEntriesRequest): - client = LoggingServiceV2Client( - 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() - requests = [request] - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.tail_log_entries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iter([logging.TailLogEntriesResponse()]) - response = client.tail_log_entries(iter(requests)) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert next(args[0]) == request - - # Establish that the response is the type that we expect. - for message in response: - assert isinstance(message, logging.TailLogEntriesResponse) - - -def test_tail_log_entries_from_dict(): - test_tail_log_entries(request_type=dict) - - -@pytest.mark.asyncio -async def test_tail_log_entries_async(transport: str = 'grpc_asyncio', request_type=logging.TailLogEntriesRequest): - client = LoggingServiceV2AsyncClient( - 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() - requests = [request] - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.tail_log_entries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock(side_effect=[logging.TailLogEntriesResponse()]) - response = await client.tail_log_entries(iter(requests)) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert next(args[0]) == request - - # Establish that the response is the type that we expect. - message = await response.read() - assert isinstance(message, logging.TailLogEntriesResponse) - - -@pytest.mark.asyncio -async def test_tail_log_entries_async_from_dict(): - await test_tail_log_entries_async(request_type=dict) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.LoggingServiceV2GrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LoggingServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.LoggingServiceV2GrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LoggingServiceV2Client( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.LoggingServiceV2GrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LoggingServiceV2Client( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.LoggingServiceV2GrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = LoggingServiceV2Client(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.LoggingServiceV2GrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.LoggingServiceV2GrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.LoggingServiceV2GrpcTransport, - transports.LoggingServiceV2GrpcAsyncIOTransport, -]) -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() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = LoggingServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.LoggingServiceV2GrpcTransport, - ) - -def test_logging_service_v2_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.LoggingServiceV2Transport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_logging_service_v2_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.logging_v2.services.logging_service_v2.transports.LoggingServiceV2Transport.__init__') as Transport: - Transport.return_value = None - transport = transports.LoggingServiceV2Transport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'delete_log', - 'write_log_entries', - 'list_log_entries', - 'list_monitored_resource_descriptors', - 'list_logs', - 'tail_log_entries', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_logging_service_v2_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.logging_v2.services.logging_service_v2.transports.LoggingServiceV2Transport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LoggingServiceV2Transport( - 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/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_logging_service_v2_base_transport_with_credentials_file_old_google_auth(): - # 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.logging_v2.services.logging_service_v2.transports.LoggingServiceV2Transport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LoggingServiceV2Transport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', - ), - quota_project_id="octopus", - ) - - -def test_logging_service_v2_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.logging_v2.services.logging_service_v2.transports.LoggingServiceV2Transport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LoggingServiceV2Transport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_logging_service_v2_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) - LoggingServiceV2Client() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_logging_service_v2_auth_adc_old_google_auth(): - # 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) - LoggingServiceV2Client() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only', 'https://www.googleapis.com/auth/logging.admin', 'https://www.googleapis.com/auth/logging.read', 'https://www.googleapis.com/auth/logging.write',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.LoggingServiceV2GrpcTransport, - transports.LoggingServiceV2GrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_logging_service_v2_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/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only', 'https://www.googleapis.com/auth/logging.admin', 'https://www.googleapis.com/auth/logging.read', 'https://www.googleapis.com/auth/logging.write',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.LoggingServiceV2GrpcTransport, - transports.LoggingServiceV2GrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_logging_service_v2_transport_auth_adc_old_google_auth(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") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.LoggingServiceV2GrpcTransport, grpc_helpers), - (transports.LoggingServiceV2GrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_logging_service_v2_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( - "logging.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', -), - scopes=["1", "2"], - default_host="logging.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.LoggingServiceV2GrpcTransport, transports.LoggingServiceV2GrpcAsyncIOTransport]) -def test_logging_service_v2_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 - ) - - -def test_logging_service_v2_host_no_port(): - client = LoggingServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='logging.googleapis.com'), - ) - assert client.transport._host == 'logging.googleapis.com:443' - - -def test_logging_service_v2_host_with_port(): - client = LoggingServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='logging.googleapis.com:8000'), - ) - assert client.transport._host == 'logging.googleapis.com:8000' - -def test_logging_service_v2_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LoggingServiceV2GrpcTransport( - 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_logging_service_v2_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LoggingServiceV2GrpcAsyncIOTransport( - 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.LoggingServiceV2GrpcTransport, transports.LoggingServiceV2GrpcAsyncIOTransport]) -def test_logging_service_v2_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.LoggingServiceV2GrpcTransport, transports.LoggingServiceV2GrpcAsyncIOTransport]) -def test_logging_service_v2_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_log_path(): - project = "squid" - log = "clam" - expected = "projects/{project}/logs/{log}".format(project=project, log=log, ) - actual = LoggingServiceV2Client.log_path(project, log) - assert expected == actual - - -def test_parse_log_path(): - expected = { - "project": "whelk", - "log": "octopus", - } - path = LoggingServiceV2Client.log_path(**expected) - - # Check that the path construction is reversible. - actual = LoggingServiceV2Client.parse_log_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = LoggingServiceV2Client.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = LoggingServiceV2Client.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = LoggingServiceV2Client.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = LoggingServiceV2Client.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = LoggingServiceV2Client.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = LoggingServiceV2Client.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = LoggingServiceV2Client.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = LoggingServiceV2Client.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = LoggingServiceV2Client.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = LoggingServiceV2Client.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = LoggingServiceV2Client.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = LoggingServiceV2Client.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = LoggingServiceV2Client.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = LoggingServiceV2Client.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = LoggingServiceV2Client.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.LoggingServiceV2Transport, '_prep_wrapped_messages') as prep: - client = LoggingServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.LoggingServiceV2Transport, '_prep_wrapped_messages') as prep: - transport_class = LoggingServiceV2Client.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v2/tests/unit/gapic/logging_v2/test_metrics_service_v2.py b/owl-bot-staging/v2/tests/unit/gapic/logging_v2/test_metrics_service_v2.py deleted file mode 100644 index 5ce85b42..00000000 --- a/owl-bot-staging/v2/tests/unit/gapic/logging_v2/test_metrics_service_v2.py +++ /dev/null @@ -1,2359 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 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 -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api import distribution_pb2 # type: ignore -from google.api import label_pb2 # type: ignore -from google.api import launch_stage_pb2 # type: ignore -from google.api import metric_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.logging_v2.services.metrics_service_v2 import MetricsServiceV2AsyncClient -from google.cloud.logging_v2.services.metrics_service_v2 import MetricsServiceV2Client -from google.cloud.logging_v2.services.metrics_service_v2 import pagers -from google.cloud.logging_v2.services.metrics_service_v2 import transports -from google.cloud.logging_v2.services.metrics_service_v2.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.logging_v2.types import logging_metrics -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -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 MetricsServiceV2Client._get_default_mtls_endpoint(None) is None - assert MetricsServiceV2Client._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert MetricsServiceV2Client._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert MetricsServiceV2Client._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert MetricsServiceV2Client._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert MetricsServiceV2Client._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - MetricsServiceV2Client, - MetricsServiceV2AsyncClient, -]) -def test_metrics_service_v2_client_from_service_account_info(client_class): - 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) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'logging.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.MetricsServiceV2GrpcTransport, "grpc"), - (transports.MetricsServiceV2GrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_metrics_service_v2_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", [ - MetricsServiceV2Client, - MetricsServiceV2AsyncClient, -]) -def test_metrics_service_v2_client_from_service_account_file(client_class): - 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") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'logging.googleapis.com:443' - - -def test_metrics_service_v2_client_get_transport_class(): - transport = MetricsServiceV2Client.get_transport_class() - available_transports = [ - transports.MetricsServiceV2GrpcTransport, - ] - assert transport in available_transports - - transport = MetricsServiceV2Client.get_transport_class("grpc") - assert transport == transports.MetricsServiceV2GrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (MetricsServiceV2Client, transports.MetricsServiceV2GrpcTransport, "grpc"), - (MetricsServiceV2AsyncClient, transports.MetricsServiceV2GrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(MetricsServiceV2Client, "DEFAULT_ENDPOINT", modify_default_endpoint(MetricsServiceV2Client)) -@mock.patch.object(MetricsServiceV2AsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(MetricsServiceV2AsyncClient)) -def test_metrics_service_v2_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(MetricsServiceV2Client, '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(MetricsServiceV2Client, '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(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, - ) - - # 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() - 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, - ) - - # 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() - 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, - ) - - # 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() - - # 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() - - # 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) - 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, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (MetricsServiceV2Client, transports.MetricsServiceV2GrpcTransport, "grpc", "true"), - (MetricsServiceV2AsyncClient, transports.MetricsServiceV2GrpcAsyncIOTransport, "grpc_asyncio", "true"), - (MetricsServiceV2Client, transports.MetricsServiceV2GrpcTransport, "grpc", "false"), - (MetricsServiceV2AsyncClient, transports.MetricsServiceV2GrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(MetricsServiceV2Client, "DEFAULT_ENDPOINT", modify_default_endpoint(MetricsServiceV2Client)) -@mock.patch.object(MetricsServiceV2AsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(MetricsServiceV2AsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_metrics_service_v2_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) - - 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, - ) - - # 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() - 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, - ) - - # 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() - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (MetricsServiceV2Client, transports.MetricsServiceV2GrpcTransport, "grpc"), - (MetricsServiceV2AsyncClient, transports.MetricsServiceV2GrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_metrics_service_v2_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) - 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, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (MetricsServiceV2Client, transports.MetricsServiceV2GrpcTransport, "grpc"), - (MetricsServiceV2AsyncClient, transports.MetricsServiceV2GrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_metrics_service_v2_client_client_options_credentials_file(client_class, transport_class, transport_name): - # 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) - 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, - ) - - -def test_metrics_service_v2_client_client_options_from_dict(): - with mock.patch('google.cloud.logging_v2.services.metrics_service_v2.transports.MetricsServiceV2GrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = MetricsServiceV2Client( - 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, - ) - - -def test_list_log_metrics(transport: str = 'grpc', request_type=logging_metrics.ListLogMetricsRequest): - client = MetricsServiceV2Client( - 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_log_metrics), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_metrics.ListLogMetricsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_log_metrics(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_metrics.ListLogMetricsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLogMetricsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_log_metrics_from_dict(): - test_list_log_metrics(request_type=dict) - - -def test_list_log_metrics_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 = MetricsServiceV2Client( - 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_log_metrics), - '__call__') as call: - client.list_log_metrics() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_metrics.ListLogMetricsRequest() - - -@pytest.mark.asyncio -async def test_list_log_metrics_async(transport: str = 'grpc_asyncio', request_type=logging_metrics.ListLogMetricsRequest): - client = MetricsServiceV2AsyncClient( - 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_log_metrics), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_metrics.ListLogMetricsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_log_metrics(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_metrics.ListLogMetricsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListLogMetricsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_log_metrics_async_from_dict(): - await test_list_log_metrics_async(request_type=dict) - - -def test_list_log_metrics_field_headers(): - client = MetricsServiceV2Client( - 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 = logging_metrics.ListLogMetricsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_log_metrics), - '__call__') as call: - call.return_value = logging_metrics.ListLogMetricsResponse() - client.list_log_metrics(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_log_metrics_field_headers_async(): - client = MetricsServiceV2AsyncClient( - 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 = logging_metrics.ListLogMetricsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_log_metrics), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_metrics.ListLogMetricsResponse()) - await client.list_log_metrics(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_log_metrics_flattened(): - client = MetricsServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_log_metrics), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_metrics.ListLogMetricsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_log_metrics( - 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] - assert args[0].parent == 'parent_value' - - -def test_list_log_metrics_flattened_error(): - client = MetricsServiceV2Client( - 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_log_metrics( - logging_metrics.ListLogMetricsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_log_metrics_flattened_async(): - client = MetricsServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_log_metrics), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_metrics.ListLogMetricsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_metrics.ListLogMetricsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_log_metrics( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_log_metrics_flattened_error_async(): - client = MetricsServiceV2AsyncClient( - 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_log_metrics( - logging_metrics.ListLogMetricsRequest(), - parent='parent_value', - ) - - -def test_list_log_metrics_pager(): - client = MetricsServiceV2Client( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_log_metrics), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - logging_metrics.ListLogMetricsResponse( - metrics=[ - logging_metrics.LogMetric(), - logging_metrics.LogMetric(), - logging_metrics.LogMetric(), - ], - next_page_token='abc', - ), - logging_metrics.ListLogMetricsResponse( - metrics=[], - next_page_token='def', - ), - logging_metrics.ListLogMetricsResponse( - metrics=[ - logging_metrics.LogMetric(), - ], - next_page_token='ghi', - ), - logging_metrics.ListLogMetricsResponse( - metrics=[ - logging_metrics.LogMetric(), - logging_metrics.LogMetric(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_log_metrics(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, logging_metrics.LogMetric) - for i in results) - -def test_list_log_metrics_pages(): - client = MetricsServiceV2Client( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_log_metrics), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - logging_metrics.ListLogMetricsResponse( - metrics=[ - logging_metrics.LogMetric(), - logging_metrics.LogMetric(), - logging_metrics.LogMetric(), - ], - next_page_token='abc', - ), - logging_metrics.ListLogMetricsResponse( - metrics=[], - next_page_token='def', - ), - logging_metrics.ListLogMetricsResponse( - metrics=[ - logging_metrics.LogMetric(), - ], - next_page_token='ghi', - ), - logging_metrics.ListLogMetricsResponse( - metrics=[ - logging_metrics.LogMetric(), - logging_metrics.LogMetric(), - ], - ), - RuntimeError, - ) - pages = list(client.list_log_metrics(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_log_metrics_async_pager(): - client = MetricsServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_log_metrics), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - logging_metrics.ListLogMetricsResponse( - metrics=[ - logging_metrics.LogMetric(), - logging_metrics.LogMetric(), - logging_metrics.LogMetric(), - ], - next_page_token='abc', - ), - logging_metrics.ListLogMetricsResponse( - metrics=[], - next_page_token='def', - ), - logging_metrics.ListLogMetricsResponse( - metrics=[ - logging_metrics.LogMetric(), - ], - next_page_token='ghi', - ), - logging_metrics.ListLogMetricsResponse( - metrics=[ - logging_metrics.LogMetric(), - logging_metrics.LogMetric(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_log_metrics(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, logging_metrics.LogMetric) - for i in responses) - -@pytest.mark.asyncio -async def test_list_log_metrics_async_pages(): - client = MetricsServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_log_metrics), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - logging_metrics.ListLogMetricsResponse( - metrics=[ - logging_metrics.LogMetric(), - logging_metrics.LogMetric(), - logging_metrics.LogMetric(), - ], - next_page_token='abc', - ), - logging_metrics.ListLogMetricsResponse( - metrics=[], - next_page_token='def', - ), - logging_metrics.ListLogMetricsResponse( - metrics=[ - logging_metrics.LogMetric(), - ], - next_page_token='ghi', - ), - logging_metrics.ListLogMetricsResponse( - metrics=[ - logging_metrics.LogMetric(), - logging_metrics.LogMetric(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_log_metrics(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_log_metric(transport: str = 'grpc', request_type=logging_metrics.GetLogMetricRequest): - client = MetricsServiceV2Client( - 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.get_log_metric), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_metrics.LogMetric( - name='name_value', - description='description_value', - filter='filter_value', - value_extractor='value_extractor_value', - version=logging_metrics.LogMetric.ApiVersion.V1, - ) - response = client.get_log_metric(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_metrics.GetLogMetricRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_metrics.LogMetric) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.value_extractor == 'value_extractor_value' - assert response.version == logging_metrics.LogMetric.ApiVersion.V1 - - -def test_get_log_metric_from_dict(): - test_get_log_metric(request_type=dict) - - -def test_get_log_metric_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 = MetricsServiceV2Client( - 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.get_log_metric), - '__call__') as call: - client.get_log_metric() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_metrics.GetLogMetricRequest() - - -@pytest.mark.asyncio -async def test_get_log_metric_async(transport: str = 'grpc_asyncio', request_type=logging_metrics.GetLogMetricRequest): - client = MetricsServiceV2AsyncClient( - 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.get_log_metric), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_metrics.LogMetric( - name='name_value', - description='description_value', - filter='filter_value', - value_extractor='value_extractor_value', - version=logging_metrics.LogMetric.ApiVersion.V1, - )) - response = await client.get_log_metric(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_metrics.GetLogMetricRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_metrics.LogMetric) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.value_extractor == 'value_extractor_value' - assert response.version == logging_metrics.LogMetric.ApiVersion.V1 - - -@pytest.mark.asyncio -async def test_get_log_metric_async_from_dict(): - await test_get_log_metric_async(request_type=dict) - - -def test_get_log_metric_field_headers(): - client = MetricsServiceV2Client( - 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 = logging_metrics.GetLogMetricRequest() - - request.metric_name = 'metric_name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_log_metric), - '__call__') as call: - call.return_value = logging_metrics.LogMetric() - client.get_log_metric(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', - 'metric_name=metric_name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_log_metric_field_headers_async(): - client = MetricsServiceV2AsyncClient( - 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 = logging_metrics.GetLogMetricRequest() - - request.metric_name = 'metric_name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_log_metric), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_metrics.LogMetric()) - await client.get_log_metric(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', - 'metric_name=metric_name/value', - ) in kw['metadata'] - - -def test_get_log_metric_flattened(): - client = MetricsServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_log_metric), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_metrics.LogMetric() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_log_metric( - metric_name='metric_name_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] - assert args[0].metric_name == 'metric_name_value' - - -def test_get_log_metric_flattened_error(): - client = MetricsServiceV2Client( - 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.get_log_metric( - logging_metrics.GetLogMetricRequest(), - metric_name='metric_name_value', - ) - - -@pytest.mark.asyncio -async def test_get_log_metric_flattened_async(): - client = MetricsServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_log_metric), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_metrics.LogMetric() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_metrics.LogMetric()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_log_metric( - metric_name='metric_name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].metric_name == 'metric_name_value' - - -@pytest.mark.asyncio -async def test_get_log_metric_flattened_error_async(): - client = MetricsServiceV2AsyncClient( - 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.get_log_metric( - logging_metrics.GetLogMetricRequest(), - metric_name='metric_name_value', - ) - - -def test_create_log_metric(transport: str = 'grpc', request_type=logging_metrics.CreateLogMetricRequest): - client = MetricsServiceV2Client( - 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.create_log_metric), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_metrics.LogMetric( - name='name_value', - description='description_value', - filter='filter_value', - value_extractor='value_extractor_value', - version=logging_metrics.LogMetric.ApiVersion.V1, - ) - response = client.create_log_metric(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_metrics.CreateLogMetricRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_metrics.LogMetric) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.value_extractor == 'value_extractor_value' - assert response.version == logging_metrics.LogMetric.ApiVersion.V1 - - -def test_create_log_metric_from_dict(): - test_create_log_metric(request_type=dict) - - -def test_create_log_metric_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 = MetricsServiceV2Client( - 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.create_log_metric), - '__call__') as call: - client.create_log_metric() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_metrics.CreateLogMetricRequest() - - -@pytest.mark.asyncio -async def test_create_log_metric_async(transport: str = 'grpc_asyncio', request_type=logging_metrics.CreateLogMetricRequest): - client = MetricsServiceV2AsyncClient( - 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.create_log_metric), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_metrics.LogMetric( - name='name_value', - description='description_value', - filter='filter_value', - value_extractor='value_extractor_value', - version=logging_metrics.LogMetric.ApiVersion.V1, - )) - response = await client.create_log_metric(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_metrics.CreateLogMetricRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_metrics.LogMetric) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.value_extractor == 'value_extractor_value' - assert response.version == logging_metrics.LogMetric.ApiVersion.V1 - - -@pytest.mark.asyncio -async def test_create_log_metric_async_from_dict(): - await test_create_log_metric_async(request_type=dict) - - -def test_create_log_metric_field_headers(): - client = MetricsServiceV2Client( - 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 = logging_metrics.CreateLogMetricRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_log_metric), - '__call__') as call: - call.return_value = logging_metrics.LogMetric() - client.create_log_metric(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_create_log_metric_field_headers_async(): - client = MetricsServiceV2AsyncClient( - 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 = logging_metrics.CreateLogMetricRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_log_metric), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_metrics.LogMetric()) - await client.create_log_metric(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_create_log_metric_flattened(): - client = MetricsServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_log_metric), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_metrics.LogMetric() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_log_metric( - parent='parent_value', - metric=logging_metrics.LogMetric(name='name_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] - assert args[0].parent == 'parent_value' - assert args[0].metric == logging_metrics.LogMetric(name='name_value') - - -def test_create_log_metric_flattened_error(): - client = MetricsServiceV2Client( - 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.create_log_metric( - logging_metrics.CreateLogMetricRequest(), - parent='parent_value', - metric=logging_metrics.LogMetric(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_log_metric_flattened_async(): - client = MetricsServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_log_metric), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_metrics.LogMetric() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_metrics.LogMetric()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_log_metric( - parent='parent_value', - metric=logging_metrics.LogMetric(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].metric == logging_metrics.LogMetric(name='name_value') - - -@pytest.mark.asyncio -async def test_create_log_metric_flattened_error_async(): - client = MetricsServiceV2AsyncClient( - 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.create_log_metric( - logging_metrics.CreateLogMetricRequest(), - parent='parent_value', - metric=logging_metrics.LogMetric(name='name_value'), - ) - - -def test_update_log_metric(transport: str = 'grpc', request_type=logging_metrics.UpdateLogMetricRequest): - client = MetricsServiceV2Client( - 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.update_log_metric), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_metrics.LogMetric( - name='name_value', - description='description_value', - filter='filter_value', - value_extractor='value_extractor_value', - version=logging_metrics.LogMetric.ApiVersion.V1, - ) - response = client.update_log_metric(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_metrics.UpdateLogMetricRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_metrics.LogMetric) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.value_extractor == 'value_extractor_value' - assert response.version == logging_metrics.LogMetric.ApiVersion.V1 - - -def test_update_log_metric_from_dict(): - test_update_log_metric(request_type=dict) - - -def test_update_log_metric_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 = MetricsServiceV2Client( - 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.update_log_metric), - '__call__') as call: - client.update_log_metric() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_metrics.UpdateLogMetricRequest() - - -@pytest.mark.asyncio -async def test_update_log_metric_async(transport: str = 'grpc_asyncio', request_type=logging_metrics.UpdateLogMetricRequest): - client = MetricsServiceV2AsyncClient( - 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.update_log_metric), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(logging_metrics.LogMetric( - name='name_value', - description='description_value', - filter='filter_value', - value_extractor='value_extractor_value', - version=logging_metrics.LogMetric.ApiVersion.V1, - )) - response = await client.update_log_metric(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_metrics.UpdateLogMetricRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, logging_metrics.LogMetric) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.filter == 'filter_value' - assert response.value_extractor == 'value_extractor_value' - assert response.version == logging_metrics.LogMetric.ApiVersion.V1 - - -@pytest.mark.asyncio -async def test_update_log_metric_async_from_dict(): - await test_update_log_metric_async(request_type=dict) - - -def test_update_log_metric_field_headers(): - client = MetricsServiceV2Client( - 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 = logging_metrics.UpdateLogMetricRequest() - - request.metric_name = 'metric_name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_log_metric), - '__call__') as call: - call.return_value = logging_metrics.LogMetric() - client.update_log_metric(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', - 'metric_name=metric_name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_log_metric_field_headers_async(): - client = MetricsServiceV2AsyncClient( - 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 = logging_metrics.UpdateLogMetricRequest() - - request.metric_name = 'metric_name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_log_metric), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_metrics.LogMetric()) - await client.update_log_metric(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', - 'metric_name=metric_name/value', - ) in kw['metadata'] - - -def test_update_log_metric_flattened(): - client = MetricsServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_log_metric), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_metrics.LogMetric() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_log_metric( - metric_name='metric_name_value', - metric=logging_metrics.LogMetric(name='name_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] - assert args[0].metric_name == 'metric_name_value' - assert args[0].metric == logging_metrics.LogMetric(name='name_value') - - -def test_update_log_metric_flattened_error(): - client = MetricsServiceV2Client( - 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.update_log_metric( - logging_metrics.UpdateLogMetricRequest(), - metric_name='metric_name_value', - metric=logging_metrics.LogMetric(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_update_log_metric_flattened_async(): - client = MetricsServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_log_metric), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = logging_metrics.LogMetric() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_metrics.LogMetric()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_log_metric( - metric_name='metric_name_value', - metric=logging_metrics.LogMetric(name='name_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].metric_name == 'metric_name_value' - assert args[0].metric == logging_metrics.LogMetric(name='name_value') - - -@pytest.mark.asyncio -async def test_update_log_metric_flattened_error_async(): - client = MetricsServiceV2AsyncClient( - 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.update_log_metric( - logging_metrics.UpdateLogMetricRequest(), - metric_name='metric_name_value', - metric=logging_metrics.LogMetric(name='name_value'), - ) - - -def test_delete_log_metric(transport: str = 'grpc', request_type=logging_metrics.DeleteLogMetricRequest): - client = MetricsServiceV2Client( - 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.delete_log_metric), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_log_metric(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == logging_metrics.DeleteLogMetricRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_log_metric_from_dict(): - test_delete_log_metric(request_type=dict) - - -def test_delete_log_metric_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 = MetricsServiceV2Client( - 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.delete_log_metric), - '__call__') as call: - client.delete_log_metric() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == logging_metrics.DeleteLogMetricRequest() - - -@pytest.mark.asyncio -async def test_delete_log_metric_async(transport: str = 'grpc_asyncio', request_type=logging_metrics.DeleteLogMetricRequest): - client = MetricsServiceV2AsyncClient( - 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.delete_log_metric), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_log_metric(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == logging_metrics.DeleteLogMetricRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_log_metric_async_from_dict(): - await test_delete_log_metric_async(request_type=dict) - - -def test_delete_log_metric_field_headers(): - client = MetricsServiceV2Client( - 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 = logging_metrics.DeleteLogMetricRequest() - - request.metric_name = 'metric_name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_log_metric), - '__call__') as call: - call.return_value = None - client.delete_log_metric(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', - 'metric_name=metric_name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_log_metric_field_headers_async(): - client = MetricsServiceV2AsyncClient( - 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 = logging_metrics.DeleteLogMetricRequest() - - request.metric_name = 'metric_name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_log_metric), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_log_metric(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', - 'metric_name=metric_name/value', - ) in kw['metadata'] - - -def test_delete_log_metric_flattened(): - client = MetricsServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_log_metric), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_log_metric( - metric_name='metric_name_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] - assert args[0].metric_name == 'metric_name_value' - - -def test_delete_log_metric_flattened_error(): - client = MetricsServiceV2Client( - 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.delete_log_metric( - logging_metrics.DeleteLogMetricRequest(), - metric_name='metric_name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_log_metric_flattened_async(): - client = MetricsServiceV2AsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_log_metric), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_log_metric( - metric_name='metric_name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].metric_name == 'metric_name_value' - - -@pytest.mark.asyncio -async def test_delete_log_metric_flattened_error_async(): - client = MetricsServiceV2AsyncClient( - 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.delete_log_metric( - logging_metrics.DeleteLogMetricRequest(), - metric_name='metric_name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.MetricsServiceV2GrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = MetricsServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.MetricsServiceV2GrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = MetricsServiceV2Client( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.MetricsServiceV2GrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = MetricsServiceV2Client( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.MetricsServiceV2GrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = MetricsServiceV2Client(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.MetricsServiceV2GrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.MetricsServiceV2GrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.MetricsServiceV2GrpcTransport, - transports.MetricsServiceV2GrpcAsyncIOTransport, -]) -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() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = MetricsServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.MetricsServiceV2GrpcTransport, - ) - -def test_metrics_service_v2_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.MetricsServiceV2Transport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_metrics_service_v2_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.logging_v2.services.metrics_service_v2.transports.MetricsServiceV2Transport.__init__') as Transport: - Transport.return_value = None - transport = transports.MetricsServiceV2Transport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_log_metrics', - 'get_log_metric', - 'create_log_metric', - 'update_log_metric', - 'delete_log_metric', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_metrics_service_v2_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.logging_v2.services.metrics_service_v2.transports.MetricsServiceV2Transport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.MetricsServiceV2Transport( - 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/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_metrics_service_v2_base_transport_with_credentials_file_old_google_auth(): - # 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.logging_v2.services.metrics_service_v2.transports.MetricsServiceV2Transport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.MetricsServiceV2Transport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', - ), - quota_project_id="octopus", - ) - - -def test_metrics_service_v2_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.logging_v2.services.metrics_service_v2.transports.MetricsServiceV2Transport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.MetricsServiceV2Transport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_metrics_service_v2_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) - MetricsServiceV2Client() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_metrics_service_v2_auth_adc_old_google_auth(): - # 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) - MetricsServiceV2Client() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only', 'https://www.googleapis.com/auth/logging.admin', 'https://www.googleapis.com/auth/logging.read', 'https://www.googleapis.com/auth/logging.write',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.MetricsServiceV2GrpcTransport, - transports.MetricsServiceV2GrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_metrics_service_v2_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/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only', 'https://www.googleapis.com/auth/logging.admin', 'https://www.googleapis.com/auth/logging.read', 'https://www.googleapis.com/auth/logging.write',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.MetricsServiceV2GrpcTransport, - transports.MetricsServiceV2GrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_metrics_service_v2_transport_auth_adc_old_google_auth(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") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.MetricsServiceV2GrpcTransport, grpc_helpers), - (transports.MetricsServiceV2GrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_metrics_service_v2_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( - "logging.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', -), - scopes=["1", "2"], - default_host="logging.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.MetricsServiceV2GrpcTransport, transports.MetricsServiceV2GrpcAsyncIOTransport]) -def test_metrics_service_v2_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 - ) - - -def test_metrics_service_v2_host_no_port(): - client = MetricsServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='logging.googleapis.com'), - ) - assert client.transport._host == 'logging.googleapis.com:443' - - -def test_metrics_service_v2_host_with_port(): - client = MetricsServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='logging.googleapis.com:8000'), - ) - assert client.transport._host == 'logging.googleapis.com:8000' - -def test_metrics_service_v2_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.MetricsServiceV2GrpcTransport( - 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_metrics_service_v2_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.MetricsServiceV2GrpcAsyncIOTransport( - 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.MetricsServiceV2GrpcTransport, transports.MetricsServiceV2GrpcAsyncIOTransport]) -def test_metrics_service_v2_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.MetricsServiceV2GrpcTransport, transports.MetricsServiceV2GrpcAsyncIOTransport]) -def test_metrics_service_v2_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_log_metric_path(): - project = "squid" - metric = "clam" - expected = "projects/{project}/metrics/{metric}".format(project=project, metric=metric, ) - actual = MetricsServiceV2Client.log_metric_path(project, metric) - assert expected == actual - - -def test_parse_log_metric_path(): - expected = { - "project": "whelk", - "metric": "octopus", - } - path = MetricsServiceV2Client.log_metric_path(**expected) - - # Check that the path construction is reversible. - actual = MetricsServiceV2Client.parse_log_metric_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = MetricsServiceV2Client.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = MetricsServiceV2Client.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = MetricsServiceV2Client.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = MetricsServiceV2Client.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = MetricsServiceV2Client.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = MetricsServiceV2Client.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = MetricsServiceV2Client.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = MetricsServiceV2Client.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = MetricsServiceV2Client.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = MetricsServiceV2Client.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = MetricsServiceV2Client.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = MetricsServiceV2Client.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = MetricsServiceV2Client.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = MetricsServiceV2Client.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = MetricsServiceV2Client.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.MetricsServiceV2Transport, '_prep_wrapped_messages') as prep: - client = MetricsServiceV2Client( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.MetricsServiceV2Transport, '_prep_wrapped_messages') as prep: - transport_class = MetricsServiceV2Client.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/renovate.json b/renovate.json index 9d2f2512..bcd0e005 100644 --- a/renovate.json +++ b/renovate.json @@ -1,6 +1,9 @@ { "extends": [ - "config:base", ":preserveSemverRanges" + "config:base", + "group:all", + ":preserveSemverRanges", + ":disableDependencyDashboard" ], "ignorePaths": [".pre-commit-config.yaml"], "pip_requirements": { diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py index 125bb619..93a9122c 100644 --- a/samples/snippets/noxfile.py +++ b/samples/snippets/noxfile.py @@ -39,17 +39,15 @@ TEST_CONFIG = { # You can opt out from the test for specific Python versions. - 'ignored_versions': ["2.7"], - + "ignored_versions": [], # Old samples are opted out of enforcing Python type hints # All new samples should feature them - 'enforce_type_hints': False, - + "enforce_type_hints": False, # An envvar key for determining the project id to use. Change it # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a # build specific Cloud project. You can also use your own string # to use your own Cloud project. - 'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT', + "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', # If you need to use a specific version of pip, # change pip_version_override to the string representation @@ -57,13 +55,13 @@ "pip_version_override": None, # A dictionary you want to inject into your test. Don't put any # secrets here. These values will override predefined values. - 'envs': {}, + "envs": {}, } try: # Ensure we can import noxfile_config in the project's directory. - sys.path.append('.') + sys.path.append(".") from noxfile_config import TEST_CONFIG_OVERRIDE except ImportError as e: print("No user noxfile_config found: detail: {}".format(e)) @@ -78,25 +76,32 @@ def get_pytest_env_vars() -> Dict[str, str]: ret = {} # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG['gcloud_project_env'] + env_key = TEST_CONFIG["gcloud_project_env"] # This should error out if not set. - ret['GOOGLE_CLOUD_PROJECT'] = os.environ[env_key] + ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] # Apply user supplied envs. - ret.update(TEST_CONFIG['envs']) + ret.update(TEST_CONFIG["envs"]) return ret # DO NOT EDIT - automatically generated. -# All versions used to tested samples. -ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8", "3.9"] +# All versions used to test samples. +ALL_VERSIONS = ["3.6", "3.7", "3.8", "3.9", "3.10"] # Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG['ignored_versions'] +IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) -INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ("True", "true") +INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( + "True", + "true", +) + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + # # Style Checks # @@ -141,7 +146,7 @@ def _determine_local_import_names(start_dir: str) -> List[str]: @nox.session def lint(session: nox.sessions.Session) -> None: - if not TEST_CONFIG['enforce_type_hints']: + if not TEST_CONFIG["enforce_type_hints"]: session.install("flake8", "flake8-import-order") else: session.install("flake8", "flake8-import-order", "flake8-annotations") @@ -150,9 +155,11 @@ def lint(session: nox.sessions.Session) -> None: args = FLAKE8_COMMON_ARGS + [ "--application-import-names", ",".join(local_names), - "." + ".", ] session.run("flake8", *args) + + # # Black # @@ -165,6 +172,7 @@ def blacken(session: nox.sessions.Session) -> None: session.run("black", *python_files) + # # Sample Tests # @@ -173,7 +181,9 @@ def blacken(session: nox.sessions.Session) -> None: PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] -def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> None: +def _session_tests( + session: nox.sessions.Session, post_install: Callable = None +) -> None: if TEST_CONFIG["pip_version_override"]: pip_version = TEST_CONFIG["pip_version_override"] session.install(f"pip=={pip_version}") @@ -203,7 +213,7 @@ def _session_tests(session: nox.sessions.Session, post_install: Callable = None) # on travis where slow and flaky tests are excluded. # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html success_codes=[0, 5], - env=get_pytest_env_vars() + env=get_pytest_env_vars(), ) @@ -213,9 +223,9 @@ def py(session: nox.sessions.Session) -> None: if session.python in TESTED_VERSIONS: _session_tests(session) else: - session.skip("SKIPPED: {} tests are disabled for this sample.".format( - session.python - )) + session.skip( + "SKIPPED: {} tests are disabled for this sample.".format(session.python) + ) # diff --git a/scripts/readme-gen/templates/install_deps.tmpl.rst b/scripts/readme-gen/templates/install_deps.tmpl.rst index a0406dba..275d6498 100644 --- a/scripts/readme-gen/templates/install_deps.tmpl.rst +++ b/scripts/readme-gen/templates/install_deps.tmpl.rst @@ -12,7 +12,7 @@ Install Dependencies .. _Python Development Environment Setup Guide: https://cloud.google.com/python/setup -#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+. +#. Create a virtualenv. Samples are compatible with Python 3.6+. .. code-block:: bash diff --git a/setup.py b/setup.py index 5b882211..a54a0f87 100644 --- a/setup.py +++ b/setup.py @@ -40,7 +40,7 @@ # https://github.com/googleapis/google-cloud-python/issues/10566 "google-cloud-core >= 1.4.1, <3.0.0dev", "grpc-google-iam-v1 >= 0.12.3, < 0.13dev", - "proto-plus >= 1.11.0", + "proto-plus >= 1.15.0", "packaging >= 14.3", ] extras = {} diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index 7e089b8b..8d3ae390 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -7,5 +7,5 @@ # Then this file should have foo==1.14.0 google-api-core==1.26.0 google-cloud-core==1.4.1 -proto-plus==1.11.0 +proto-plus==1.15.0 packaging==14.3