`__
for more information.
+ kms_key_version_name (str):
+ The CryptoKeyVersion resource name for the configured Cloud
+ KMS key.
+
+ KMS key name format:
+
+ ::
+
+ "projects/[PROJECT_ID]/locations/[LOCATION]/keyRings/[KEYRING]/cryptoKeys/[KEY]/cryptoKeyVersions/[VERSION]"
+
+ For example:
+
+ ``"projects/my-project/locations/us-central1/keyRings/my-ring/cryptoKeys/my-key/cryptoKeyVersions/1"``
+
+ This is a read-only field used to convey the specific
+ configured CryptoKeyVersion of ``kms_key`` that has been
+ configured. It will be populated in cases where the CMEK
+ settings are bound to a single key version.
+
+ If this field is populated, the ``kms_key`` is tied to a
+ specific CryptoKeyVersion.
service_account_id (str):
Output only. The service account that will be used by the
Log Router to access your Cloud KMS key.
@@ -1635,6 +1982,10 @@ class CmekSettings(proto.Message):
proto.STRING,
number=2,
)
+ kms_key_version_name: str = proto.Field(
+ proto.STRING,
+ number=4,
+ )
service_account_id: str = proto.Field(
proto.STRING,
number=3,
@@ -1937,4 +2288,131 @@ class CopyLogEntriesResponse(proto.Message):
)
+class BucketMetadata(proto.Message):
+ r"""Metadata for LongRunningUpdateBucket Operations.
+
+ This message has `oneof`_ fields (mutually exclusive fields).
+ For each oneof, at most one member field can be set at the same time.
+ Setting any member of the oneof automatically clears all other
+ members.
+
+ .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields
+
+ Attributes:
+ start_time (google.protobuf.timestamp_pb2.Timestamp):
+ The create time of an operation.
+ end_time (google.protobuf.timestamp_pb2.Timestamp):
+ The end time of an operation.
+ state (google.cloud.logging_v2.types.OperationState):
+ State of an operation.
+ create_bucket_request (google.cloud.logging_v2.types.CreateBucketRequest):
+ LongRunningCreateBucket RPC request.
+
+ This field is a member of `oneof`_ ``request``.
+ update_bucket_request (google.cloud.logging_v2.types.UpdateBucketRequest):
+ LongRunningUpdateBucket RPC request.
+
+ This field is a member of `oneof`_ ``request``.
+ """
+
+ start_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ message=timestamp_pb2.Timestamp,
+ )
+ end_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message=timestamp_pb2.Timestamp,
+ )
+ state: "OperationState" = proto.Field(
+ proto.ENUM,
+ number=3,
+ enum="OperationState",
+ )
+ create_bucket_request: "CreateBucketRequest" = proto.Field(
+ proto.MESSAGE,
+ number=4,
+ oneof="request",
+ message="CreateBucketRequest",
+ )
+ update_bucket_request: "UpdateBucketRequest" = proto.Field(
+ proto.MESSAGE,
+ number=5,
+ oneof="request",
+ message="UpdateBucketRequest",
+ )
+
+
+class LinkMetadata(proto.Message):
+ r"""Metadata for long running Link operations.
+
+ This message has `oneof`_ fields (mutually exclusive fields).
+ For each oneof, at most one member field can be set at the same time.
+ Setting any member of the oneof automatically clears all other
+ members.
+
+ .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields
+
+ Attributes:
+ start_time (google.protobuf.timestamp_pb2.Timestamp):
+ The start time of an operation.
+ end_time (google.protobuf.timestamp_pb2.Timestamp):
+ The end time of an operation.
+ state (google.cloud.logging_v2.types.OperationState):
+ State of an operation.
+ create_link_request (google.cloud.logging_v2.types.CreateLinkRequest):
+ CreateLink RPC request.
+
+ This field is a member of `oneof`_ ``request``.
+ delete_link_request (google.cloud.logging_v2.types.DeleteLinkRequest):
+ DeleteLink RPC request.
+
+ This field is a member of `oneof`_ ``request``.
+ """
+
+ start_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ message=timestamp_pb2.Timestamp,
+ )
+ end_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message=timestamp_pb2.Timestamp,
+ )
+ state: "OperationState" = proto.Field(
+ proto.ENUM,
+ number=3,
+ enum="OperationState",
+ )
+ create_link_request: "CreateLinkRequest" = proto.Field(
+ proto.MESSAGE,
+ number=4,
+ oneof="request",
+ message="CreateLinkRequest",
+ )
+ delete_link_request: "DeleteLinkRequest" = proto.Field(
+ proto.MESSAGE,
+ number=5,
+ oneof="request",
+ message="DeleteLinkRequest",
+ )
+
+
+class LocationMetadata(proto.Message):
+ r"""Cloud Logging specific location metadata.
+
+ Attributes:
+ log_analytics_enabled (bool):
+ Indicates whether or not Log Analytics
+ features are supported in the given location.
+ """
+
+ log_analytics_enabled: bool = proto.Field(
+ proto.BOOL,
+ number=1,
+ )
+
+
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/logging_v2/types/logging_metrics.py b/google/cloud/logging_v2/types/logging_metrics.py
index 0d31860a0..dd90dd3cb 100644
--- a/google/cloud/logging_v2/types/logging_metrics.py
+++ b/google/cloud/logging_v2/types/logging_metrics.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -42,6 +42,7 @@ 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
@@ -79,6 +80,17 @@ class LogMetric(proto.Message):
"resource.type=gae_app AND severity>=ERROR"
The maximum length of the filter is 20000 characters.
+ bucket_name (str):
+ Optional. The resource name of the Log Bucket that owns the
+ Log Metric. Only Log Buckets in projects are supported. The
+ bucket has to be in the same project as the metric.
+
+ For example:
+
+ ``projects/my-project/locations/global/buckets/my-bucket``
+
+ If empty, then the Log Metric is considered a non-Bucket Log
+ Metric.
disabled (bool):
Optional. If set to True, then this metric is
disabled and it does not generate any points.
@@ -113,7 +125,7 @@ class LogMetric(proto.Message):
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:
+ ``REGEXP_EXTRACT(field, regex)``. The arguments are:
1. field: The name of the log entry field from which the
value is to be extracted.
@@ -142,7 +154,7 @@ class LogMetric(proto.Message):
``value_extractor`` field.
The extracted value is converted to the type defined in the
- label descriptor. If the either the extraction or the type
+ label descriptor. If 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``.
@@ -193,6 +205,10 @@ class ApiVersion(proto.Enum):
proto.STRING,
number=3,
)
+ bucket_name: str = proto.Field(
+ proto.STRING,
+ number=13,
+ )
disabled: bool = proto.Field(
proto.BOOL,
number=12,
diff --git a/noxfile.py b/noxfile.py
index 7ebe500a3..b75e78ac3 100644
--- a/noxfile.py
+++ b/noxfile.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -17,22 +17,32 @@
# Generated by synthtool. DO NOT EDIT!
from __future__ import absolute_import
+
import os
import pathlib
import re
import shutil
+from typing import Dict, List
import warnings
import nox
FLAKE8_VERSION = "flake8==6.1.0"
-BLACK_VERSION = "black==22.3.0"
-ISORT_VERSION = "isort==5.10.1"
+BLACK_VERSION = "black[jupyter]==23.7.0"
+ISORT_VERSION = "isort==5.11.0"
LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"]
DEFAULT_PYTHON_VERSION = "3.8"
-UNIT_TEST_PYTHON_VERSIONS = ["3.7", "3.8", "3.9", "3.10", "3.11"]
+UNIT_TEST_PYTHON_VERSIONS: List[str] = [
+ "3.7",
+ "3.8",
+ "3.9",
+ "3.10",
+ "3.11",
+ "3.12",
+ "3.13",
+]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
@@ -40,36 +50,36 @@
"pytest-cov",
"pytest-asyncio",
]
-UNIT_TEST_EXTERNAL_DEPENDENCIES = [
+UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [
"flask",
"webob",
"django",
]
-UNIT_TEST_LOCAL_DEPENDENCIES = []
-UNIT_TEST_DEPENDENCIES = []
-UNIT_TEST_EXTRAS = []
-UNIT_TEST_EXTRAS_BY_PYTHON = {}
+UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = []
+UNIT_TEST_DEPENDENCIES: List[str] = []
+UNIT_TEST_EXTRAS: List[str] = []
+UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
-SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"]
-SYSTEM_TEST_STANDARD_DEPENDENCIES = [
+SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.12"]
+SYSTEM_TEST_STANDARD_DEPENDENCIES: List[str] = [
"mock",
"pytest",
"google-cloud-testutils",
]
-SYSTEM_TEST_EXTERNAL_DEPENDENCIES = [
+SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [
"google-cloud-bigquery",
"google-cloud-pubsub",
"google-cloud-storage",
"google-cloud-testutils",
+ "opentelemetry-sdk",
]
-SYSTEM_TEST_LOCAL_DEPENDENCIES = []
-SYSTEM_TEST_DEPENDENCIES = []
-SYSTEM_TEST_EXTRAS = []
-SYSTEM_TEST_EXTRAS_BY_PYTHON = {}
+SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = []
+SYSTEM_TEST_DEPENDENCIES: List[str] = []
+SYSTEM_TEST_EXTRAS: List[str] = []
+SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute()
-# 'docfx' is excluded since it only needs to run in 'docs-presubmit'
nox.options.sessions = [
"unit",
"system",
@@ -78,6 +88,8 @@
"lint_setup_py",
"blacken",
"docs",
+ "docfx",
+ "format",
]
# Error if a python version is missing
@@ -165,14 +177,28 @@ def install_unittest_dependencies(session, *constraints):
session.install("-e", ".", *constraints)
-def default(session):
+@nox.session(python=UNIT_TEST_PYTHON_VERSIONS)
+@nox.parametrize(
+ "protobuf_implementation",
+ ["python", "upb", "cpp"],
+)
+def unit(session, protobuf_implementation):
# Install all test dependencies, then install this package in-place.
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
+ session.skip("cpp implementation is not supported in python 3.11+")
+
constraints_path = str(
CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt"
)
install_unittest_dependencies(session, "-c", constraints_path)
+ # TODO(https://github.com/googleapis/synthtool/issues/1976):
+ # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped.
+ # The 'cpp' implementation requires Protobuf<4.
+ if protobuf_implementation == "cpp":
+ session.install("protobuf<4")
+
# Run py.test against the unit tests.
session.run(
"py.test",
@@ -186,17 +212,13 @@ def default(session):
"--cov-fail-under=0",
os.path.join("tests", "unit"),
*session.posargs,
+ env={
+ "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation,
+ },
)
-@nox.session(python=UNIT_TEST_PYTHON_VERSIONS)
-def unit(session):
- """Run the unit test suite."""
- default(session)
-
-
def install_systemtest_dependencies(session, *constraints):
-
# Use pre-release gRPC for system tests.
# Exclude version 1.52.0rc1 which has a known issue.
# See https://github.com/grpc/grpc/issues/32163
@@ -282,13 +304,22 @@ def cover(session):
session.run("coverage", "erase")
-@nox.session(python="3.9")
+@nox.session(python="3.10")
def docs(session):
"""Build the docs for this library."""
session.install("-e", ".")
session.install(
- "sphinx==4.0.1",
+ # We need to pin to specific versions of the `sphinxcontrib-*` packages
+ # which still support sphinx 4.x.
+ # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344
+ # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345.
+ "sphinxcontrib-applehelp==1.0.4",
+ "sphinxcontrib-devhelp==1.0.2",
+ "sphinxcontrib-htmlhelp==2.0.1",
+ "sphinxcontrib-qthelp==1.0.3",
+ "sphinxcontrib-serializinghtml==1.1.5",
+ "sphinx==4.5.0",
"alabaster",
"recommonmark",
)
@@ -308,12 +339,21 @@ def docs(session):
)
-@nox.session(python="3.9")
+@nox.session(python="3.10")
def docfx(session):
"""Build the docfx yaml files for this library."""
session.install("-e", ".")
session.install(
+ # We need to pin to specific versions of the `sphinxcontrib-*` packages
+ # which still support sphinx 4.x.
+ # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344
+ # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345.
+ "sphinxcontrib-applehelp==1.0.4",
+ "sphinxcontrib-devhelp==1.0.2",
+ "sphinxcontrib-htmlhelp==2.0.1",
+ "sphinxcontrib-qthelp==1.0.3",
+ "sphinxcontrib-serializinghtml==1.1.5",
"gcp-sphinx-docfx-yaml",
"alabaster",
"recommonmark",
@@ -345,10 +385,17 @@ def docfx(session):
)
-@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS)
-def prerelease_deps(session):
+@nox.session(python="3.13")
+@nox.parametrize(
+ "protobuf_implementation",
+ ["python", "upb", "cpp"],
+)
+def prerelease_deps(session, protobuf_implementation):
"""Run all tests with prerelease versions of dependencies installed."""
+ if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"):
+ session.skip("cpp implementation is not supported in python 3.11+")
+
# Install all dependencies
session.install("-e", ".[all, tests, tracing]")
unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES
@@ -380,12 +427,13 @@ def prerelease_deps(session):
session.install(*constraints_deps)
prerel_deps = [
+ "google-cloud-audit-log",
"protobuf",
# dependency of grpc
"six",
+ "grpc-google-iam-v1",
"googleapis-common-protos",
- # Exclude version 1.52.0rc1 which has a known issue. See https://github.com/grpc/grpc/issues/32163
- "grpcio!=1.52.0rc1",
+ "grpcio",
"grpcio-status",
"google-api-core",
"google-auth",
@@ -411,7 +459,13 @@ def prerelease_deps(session):
session.run("python", "-c", "import grpc; print(grpc.__version__)")
session.run("python", "-c", "import google.auth; print(google.auth.__version__)")
- session.run("py.test", "tests/unit")
+ session.run(
+ "py.test",
+ "tests/unit",
+ env={
+ "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation,
+ },
+ )
system_test_path = os.path.join("tests", "system.py")
system_test_folder_path = os.path.join("tests", "system")
@@ -424,6 +478,9 @@ def prerelease_deps(session):
f"--junitxml=system_{session.python}_sponge_log.xml",
system_test_path,
*session.posargs,
+ env={
+ "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation,
+ },
)
if os.path.exists(system_test_folder_path):
session.run(
@@ -432,4 +489,7 @@ def prerelease_deps(session):
f"--junitxml=system_{session.python}_sponge_log.xml",
system_test_folder_path,
*session.posargs,
+ env={
+ "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation,
+ },
)
diff --git a/owlbot.py b/owlbot.py
index 3e932c854..2be8464c2 100644
--- a/owlbot.py
+++ b/owlbot.py
@@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+import glob
import json
import os
import shutil
@@ -66,12 +67,13 @@ def place_before(path, text, *before_text, escape=None):
s.move([library], excludes=[
"**/gapic_version.py",
"setup.py",
- "testing/constraints-3.7.txt",
+ "testing/constraints*.txt",
"README.rst",
"google/cloud/logging/__init__.py", # generated types are hidden from users
"google/cloud/logging_v2/__init__.py",
"docs/index.rst",
"docs/logging_v2", # Don't include gapic library docs. Users should use the hand-written layer instead
+ "docs/multiprocessing.rst",
"scripts/fixup_logging_v2_keywords.py", # don't include script since it only works for generated layer
],
)
@@ -91,7 +93,9 @@ def place_before(path, text, *before_text, escape=None):
"google-cloud-pubsub",
"google-cloud-storage",
"google-cloud-testutils",
+ "opentelemetry-sdk"
],
+ system_test_python_versions=["3.12"],
unit_test_external_dependencies=["flask", "webob", "django"],
samples=True,
)
@@ -107,6 +111,13 @@ def place_before(path, text, *before_text, escape=None):
"README.rst", # This repo has a customized README
],
)
+s.replace("noxfile.py",
+"""prerel_deps = \[
+ "protobuf",""",
+"""prerel_deps = [
+ "google-cloud-audit-log",
+ "protobuf",""",
+)
# adjust .trampolinerc for environment tests
s.replace(".trampolinerc", "required_envvars[^\)]*\)", "required_envvars+=()")
@@ -116,13 +127,6 @@ def place_before(path, text, *before_text, escape=None):
'pass_down_envvars+=(\n "ENVIRONMENT"\n "RUNTIME"',
)
-# don't lint environment tests
-s.replace(
- ".flake8",
- "exclude =",
- "exclude =\n # Exclude environment test code.\n tests/environment/**\n",
-)
-
# use conventional commits for renovate bot
s.replace(
"renovate.json",
@@ -139,6 +143,110 @@ def place_before(path, text, *before_text, escape=None):
python.py_samples()
+# For autogenerated sample code, resolve object paths by finding the specific subpackage
+# the object belongs to. This is because we leave out all autogenerated packages from the
+# __init__.py of logging_v2. For now, this is manually copy-pasted from the __all__s of each
+# subpackage's __init__.py.
+gapic_objects = {
+ "logging_v2.services.config_service_v2": [
+ "ConfigServiceV2Client",
+ "ConfigServiceV2AsyncClient"
+ ],
+ "logging_v2.services.logging_service_v2": [
+ "LoggingServiceV2Client",
+ "LoggingServiceV2AsyncClient"
+ ],
+ "logging_v2.services.metrics_service_v2": [
+ "MetricsServiceV2Client",
+ "MetricsServiceV2AsyncClient"
+ ],
+ "logging_v2.types": [
+ "LogEntry",
+ "LogEntryOperation",
+ "LogEntrySourceLocation",
+ "LogSplit",
+ "DeleteLogRequest",
+ "ListLogEntriesRequest",
+ "ListLogEntriesResponse",
+ "ListLogsRequest",
+ "ListLogsResponse",
+ "ListMonitoredResourceDescriptorsRequest",
+ "ListMonitoredResourceDescriptorsResponse",
+ "TailLogEntriesRequest",
+ "TailLogEntriesResponse",
+ "WriteLogEntriesPartialErrors",
+ "WriteLogEntriesRequest",
+ "WriteLogEntriesResponse",
+ "BigQueryDataset",
+ "BigQueryOptions",
+ "BucketMetadata",
+ "CmekSettings",
+ "CopyLogEntriesMetadata",
+ "CopyLogEntriesRequest",
+ "CopyLogEntriesResponse",
+ "CreateBucketRequest",
+ "CreateExclusionRequest",
+ "CreateLinkRequest",
+ "CreateSinkRequest",
+ "CreateViewRequest",
+ "DeleteBucketRequest",
+ "DeleteExclusionRequest",
+ "DeleteLinkRequest",
+ "DeleteSinkRequest",
+ "DeleteViewRequest",
+ "GetBucketRequest",
+ "GetCmekSettingsRequest",
+ "GetExclusionRequest",
+ "GetLinkRequest",
+ "GetSettingsRequest",
+ "GetSinkRequest",
+ "GetViewRequest",
+ "IndexConfig",
+ "Link",
+ "LinkMetadata",
+ "ListBucketsRequest",
+ "ListBucketsResponse",
+ "ListExclusionsRequest",
+ "ListExclusionsResponse",
+ "ListLinksRequest",
+ "ListLinksResponse",
+ "ListSinksRequest",
+ "ListSinksResponse",
+ "ListViewsRequest",
+ "ListViewsResponse",
+ "LocationMetadata",
+ "LogBucket",
+ "LogExclusion",
+ "LogSink",
+ "LogView",
+ "Settings",
+ "UndeleteBucketRequest",
+ "UpdateBucketRequest",
+ "UpdateCmekSettingsRequest",
+ "UpdateExclusionRequest",
+ "UpdateSettingsRequest",
+ "UpdateSinkRequest",
+ "UpdateViewRequest",
+ "IndexType",
+ "LifecycleState",
+ "OperationState",
+ "CreateLogMetricRequest",
+ "DeleteLogMetricRequest",
+ "GetLogMetricRequest",
+ "ListLogMetricsRequest",
+ "ListLogMetricsResponse",
+ "LogMetric",
+ "UpdateLogMetricRequest"
+ ]
+}
+
+sample_files = glob.glob("samples/generated_samples/logging_v2_*.py")
+for subpackage_name in gapic_objects:
+ for object_name in gapic_objects[subpackage_name]:
+ text = "logging_v2." + object_name
+ replacement = subpackage_name + "." + object_name
+ s.replace(sample_files, text, replacement)
+
s.shell.run(["nox", "-s", "blacken"], hide_output=False)
s.shell.run(["nox", "-s", "blacken"], cwd="samples/snippets", hide_output=False)
@@ -147,7 +255,7 @@ def place_before(path, text, *before_text, escape=None):
# --------------------------------------------------------------------------
# add shared environment variables to test configs
-tracked_subdirs = ["continuous", "presubmit", "release", "samples", "docs"]
+tracked_subdirs = ["continuous", "presubmit", "samples"]
for subdir in tracked_subdirs:
for path, subdirs, files in os.walk(f".kokoro/{subdir}"):
for name in files:
diff --git a/pytest.ini b/pytest.ini
new file mode 100644
index 000000000..2d8ce14b8
--- /dev/null
+++ b/pytest.ini
@@ -0,0 +1,29 @@
+[pytest]
+filterwarnings =
+ # treat all warnings as errors
+ error
+ # Remove once https://github.com/protocolbuffers/protobuf/issues/12186 is fixed
+ ignore:.*custom tp_new.*in Python 3.14:DeprecationWarning
+ # Remove once Release PR https://github.com/googleapis/python-api-common-protos/pull/191 is merged
+ ignore:.*pkg_resources.declare_namespace:DeprecationWarning
+ ignore:.*pkg_resources is deprecated as an API:DeprecationWarning
+ # Remove warning once https://github.com/grpc/grpc/issues/35974 is fixed
+ ignore:unclosed:ResourceWarning
+ # Remove after support for Python 3.7 is dropped
+ ignore:After January 1, 2024, new releases of this library will drop support for Python 3.7:DeprecationWarning
+ # Remove warning once https://github.com/googleapis/gapic-generator-python/issues/1939 is fixed
+ ignore:get_mtls_endpoint_and_cert_source is deprecated.:DeprecationWarning
+ # DeprecationWarnings triggered by Flask 1.0 testing by Flask dependencies in test code
+ # 3.7 deprecation warnings
+ ignore:Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3,and in 3.9 it will stop working:DeprecationWarning
+ # 3.8 - 3.9 deprecation warnings
+ ignore:Importing 'itsdangerous.json' is deprecated and will be removed in ItsDangerous 2.1. Use Python's 'json' module instead.:DeprecationWarning
+ ignore:Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.10 it will stop working:DeprecationWarning
+ # 3.12 deprecation warnings
+ ignore:Attribute s is deprecated and will be removed in Python 3.14; use value instead:DeprecationWarning
+ ignore:ast.Str is deprecated and will be removed in Python 3.14; use ast.Constant instead:DeprecationWarning
+ ignore:'pkgutil.get_loader' is deprecated and slated for removal in Python 3.14; use importlib.util.find_spec\(\) instead:DeprecationWarning
+ # Remove warning once https://github.com/protocolbuffers/protobuf/issues/17345 is fixed
+ ignore:.*Please use message_factory.GetMessageClass\(\) instead. SymbolDatabase.GetPrototype\(\) will be removed soon.:UserWarning
+ # Remove warning once https://github.com/googleapis/gapic-generator-python/issues/2046 is fixed
+ ignore:coroutine 'AsyncMockMixin._execute_mock_call' was never awaited:RuntimeWarning
diff --git a/renovate.json b/renovate.json
index dde963098..ff5e5c4c6 100644
--- a/renovate.json
+++ b/renovate.json
@@ -5,7 +5,7 @@
":preserveSemverRanges",
":disableDependencyDashboard"
],
- "ignorePaths": [".pre-commit-config.yaml", ".kokoro/requirements.txt", "setup.py"],
+ "ignorePaths": [".pre-commit-config.yaml", ".kokoro/requirements.txt", "setup.py", ".github/workflows/unittest.yml"],
"pip_requirements": {
"fileMatch": ["requirements-test.txt", "samples/[\\S/]*constraints.txt", "samples/[\\S/]*constraints-test.txt"]
},
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_copy_log_entries_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_copy_log_entries_async.py
index dead26544..f4a59244d 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_copy_log_entries_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_copy_log_entries_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_copy_log_entries():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.CopyLogEntriesRequest(
+ request = logging_v2.types.CopyLogEntriesRequest(
name="name_value",
destination="destination_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_copy_log_entries_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_copy_log_entries_sync.py
index 949dde286..896bfe77d 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_copy_log_entries_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_copy_log_entries_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_copy_log_entries():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.CopyLogEntriesRequest(
+ request = logging_v2.types.CopyLogEntriesRequest(
name="name_value",
destination="destination_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_create_bucket_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_create_bucket_async.py
index f399b226f..25292de97 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_create_bucket_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_create_bucket_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_create_bucket():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.CreateBucketRequest(
+ request = logging_v2.types.CreateBucketRequest(
parent="parent_value",
bucket_id="bucket_id_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_create_bucket_async_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_create_bucket_async_async.py
new file mode 100644
index 000000000..95c692aac
--- /dev/null
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_create_bucket_async_async.py
@@ -0,0 +1,57 @@
+# -*- coding: utf-8 -*-
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generated code. DO NOT EDIT!
+#
+# Snippet for CreateBucketAsync
+# NOTE: This snippet has been automatically generated for illustrative purposes only.
+# It may require modifications to work in your environment.
+
+# To install the latest published package dependency, execute the following:
+# python3 -m pip install google-cloud-logging
+
+
+# [START logging_v2_generated_ConfigServiceV2_CreateBucketAsync_async]
+# This snippet has been automatically generated and should be regarded as a
+# code template only.
+# It will require modifications to work:
+# - It may require correct/in-range values for request initialization.
+# - It may require specifying regional endpoints when creating the service
+# client as shown in:
+# https://googleapis.dev/python/google-api-core/latest/client_options.html
+from google.cloud import logging_v2
+
+
+async def sample_create_bucket_async():
+ # Create a client
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
+
+ # Initialize request argument(s)
+ request = logging_v2.types.CreateBucketRequest(
+ parent="parent_value",
+ bucket_id="bucket_id_value",
+ )
+
+ # Make the request
+ operation = client.create_bucket_async(request=request)
+
+ print("Waiting for operation to complete...")
+
+ response = (await operation).result()
+
+ # Handle the response
+ print(response)
+
+# [END logging_v2_generated_ConfigServiceV2_CreateBucketAsync_async]
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_create_bucket_async_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_create_bucket_async_sync.py
new file mode 100644
index 000000000..d1da5bbe7
--- /dev/null
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_create_bucket_async_sync.py
@@ -0,0 +1,57 @@
+# -*- coding: utf-8 -*-
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generated code. DO NOT EDIT!
+#
+# Snippet for CreateBucketAsync
+# NOTE: This snippet has been automatically generated for illustrative purposes only.
+# It may require modifications to work in your environment.
+
+# To install the latest published package dependency, execute the following:
+# python3 -m pip install google-cloud-logging
+
+
+# [START logging_v2_generated_ConfigServiceV2_CreateBucketAsync_sync]
+# This snippet has been automatically generated and should be regarded as a
+# code template only.
+# It will require modifications to work:
+# - It may require correct/in-range values for request initialization.
+# - It may require specifying regional endpoints when creating the service
+# client as shown in:
+# https://googleapis.dev/python/google-api-core/latest/client_options.html
+from google.cloud import logging_v2
+
+
+def sample_create_bucket_async():
+ # Create a client
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
+
+ # Initialize request argument(s)
+ request = logging_v2.types.CreateBucketRequest(
+ parent="parent_value",
+ bucket_id="bucket_id_value",
+ )
+
+ # Make the request
+ operation = client.create_bucket_async(request=request)
+
+ print("Waiting for operation to complete...")
+
+ response = operation.result()
+
+ # Handle the response
+ print(response)
+
+# [END logging_v2_generated_ConfigServiceV2_CreateBucketAsync_sync]
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_create_bucket_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_create_bucket_sync.py
index 374173f52..395188ef8 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_create_bucket_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_create_bucket_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_create_bucket():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.CreateBucketRequest(
+ request = logging_v2.types.CreateBucketRequest(
parent="parent_value",
bucket_id="bucket_id_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_create_exclusion_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_create_exclusion_async.py
index 8f14d777f..10cb193be 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_create_exclusion_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_create_exclusion_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,14 +36,14 @@
async def sample_create_exclusion():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- exclusion = logging_v2.LogExclusion()
+ exclusion = logging_v2.types.LogExclusion()
exclusion.name = "name_value"
exclusion.filter = "filter_value"
- request = logging_v2.CreateExclusionRequest(
+ request = logging_v2.types.CreateExclusionRequest(
parent="parent_value",
exclusion=exclusion,
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_create_exclusion_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_create_exclusion_sync.py
index 11bd92ad5..a52541ea4 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_create_exclusion_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_create_exclusion_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,14 +36,14 @@
def sample_create_exclusion():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- exclusion = logging_v2.LogExclusion()
+ exclusion = logging_v2.types.LogExclusion()
exclusion.name = "name_value"
exclusion.filter = "filter_value"
- request = logging_v2.CreateExclusionRequest(
+ request = logging_v2.types.CreateExclusionRequest(
parent="parent_value",
exclusion=exclusion,
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_create_link_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_create_link_async.py
new file mode 100644
index 000000000..8e4558480
--- /dev/null
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_create_link_async.py
@@ -0,0 +1,57 @@
+# -*- coding: utf-8 -*-
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generated code. DO NOT EDIT!
+#
+# Snippet for CreateLink
+# NOTE: This snippet has been automatically generated for illustrative purposes only.
+# It may require modifications to work in your environment.
+
+# To install the latest published package dependency, execute the following:
+# python3 -m pip install google-cloud-logging
+
+
+# [START logging_v2_generated_ConfigServiceV2_CreateLink_async]
+# This snippet has been automatically generated and should be regarded as a
+# code template only.
+# It will require modifications to work:
+# - It may require correct/in-range values for request initialization.
+# - It may require specifying regional endpoints when creating the service
+# client as shown in:
+# https://googleapis.dev/python/google-api-core/latest/client_options.html
+from google.cloud import logging_v2
+
+
+async def sample_create_link():
+ # Create a client
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
+
+ # Initialize request argument(s)
+ request = logging_v2.types.CreateLinkRequest(
+ parent="parent_value",
+ link_id="link_id_value",
+ )
+
+ # Make the request
+ operation = client.create_link(request=request)
+
+ print("Waiting for operation to complete...")
+
+ response = (await operation).result()
+
+ # Handle the response
+ print(response)
+
+# [END logging_v2_generated_ConfigServiceV2_CreateLink_async]
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_create_link_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_create_link_sync.py
new file mode 100644
index 000000000..e1f948394
--- /dev/null
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_create_link_sync.py
@@ -0,0 +1,57 @@
+# -*- coding: utf-8 -*-
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generated code. DO NOT EDIT!
+#
+# Snippet for CreateLink
+# NOTE: This snippet has been automatically generated for illustrative purposes only.
+# It may require modifications to work in your environment.
+
+# To install the latest published package dependency, execute the following:
+# python3 -m pip install google-cloud-logging
+
+
+# [START logging_v2_generated_ConfigServiceV2_CreateLink_sync]
+# This snippet has been automatically generated and should be regarded as a
+# code template only.
+# It will require modifications to work:
+# - It may require correct/in-range values for request initialization.
+# - It may require specifying regional endpoints when creating the service
+# client as shown in:
+# https://googleapis.dev/python/google-api-core/latest/client_options.html
+from google.cloud import logging_v2
+
+
+def sample_create_link():
+ # Create a client
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
+
+ # Initialize request argument(s)
+ request = logging_v2.types.CreateLinkRequest(
+ parent="parent_value",
+ link_id="link_id_value",
+ )
+
+ # Make the request
+ operation = client.create_link(request=request)
+
+ print("Waiting for operation to complete...")
+
+ response = operation.result()
+
+ # Handle the response
+ print(response)
+
+# [END logging_v2_generated_ConfigServiceV2_CreateLink_sync]
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_create_sink_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_create_sink_async.py
index 0fc007986..e83d648a1 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_create_sink_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_create_sink_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,14 +36,14 @@
async def sample_create_sink():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- sink = logging_v2.LogSink()
+ sink = logging_v2.types.LogSink()
sink.name = "name_value"
sink.destination = "destination_value"
- request = logging_v2.CreateSinkRequest(
+ request = logging_v2.types.CreateSinkRequest(
parent="parent_value",
sink=sink,
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_create_sink_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_create_sink_sync.py
index d6d2a0d7d..aa694125d 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_create_sink_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_create_sink_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,14 +36,14 @@
def sample_create_sink():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- sink = logging_v2.LogSink()
+ sink = logging_v2.types.LogSink()
sink.name = "name_value"
sink.destination = "destination_value"
- request = logging_v2.CreateSinkRequest(
+ request = logging_v2.types.CreateSinkRequest(
parent="parent_value",
sink=sink,
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_create_view_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_create_view_async.py
index 016f3e70b..f40f1f6d5 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_create_view_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_create_view_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_create_view():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.CreateViewRequest(
+ request = logging_v2.types.CreateViewRequest(
parent="parent_value",
view_id="view_id_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_create_view_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_create_view_sync.py
index 3ee9567f1..d4f174cf5 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_create_view_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_create_view_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_create_view():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.CreateViewRequest(
+ request = logging_v2.types.CreateViewRequest(
parent="parent_value",
view_id="view_id_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_delete_bucket_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_delete_bucket_async.py
index 6633aa3c4..d56884bf3 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_delete_bucket_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_delete_bucket_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_delete_bucket():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.DeleteBucketRequest(
+ request = logging_v2.types.DeleteBucketRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_delete_bucket_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_delete_bucket_sync.py
index ec39ca1a0..0b4b38bf4 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_delete_bucket_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_delete_bucket_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_delete_bucket():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.DeleteBucketRequest(
+ request = logging_v2.types.DeleteBucketRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_delete_exclusion_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_delete_exclusion_async.py
index 9d6146c57..1004cf6e8 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_delete_exclusion_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_delete_exclusion_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_delete_exclusion():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.DeleteExclusionRequest(
+ request = logging_v2.types.DeleteExclusionRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_delete_exclusion_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_delete_exclusion_sync.py
index bc051e4e0..e3c3f0be0 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_delete_exclusion_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_delete_exclusion_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_delete_exclusion():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.DeleteExclusionRequest(
+ request = logging_v2.types.DeleteExclusionRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_delete_link_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_delete_link_async.py
new file mode 100644
index 000000000..30407d37e
--- /dev/null
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_delete_link_async.py
@@ -0,0 +1,56 @@
+# -*- coding: utf-8 -*-
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generated code. DO NOT EDIT!
+#
+# Snippet for DeleteLink
+# NOTE: This snippet has been automatically generated for illustrative purposes only.
+# It may require modifications to work in your environment.
+
+# To install the latest published package dependency, execute the following:
+# python3 -m pip install google-cloud-logging
+
+
+# [START logging_v2_generated_ConfigServiceV2_DeleteLink_async]
+# This snippet has been automatically generated and should be regarded as a
+# code template only.
+# It will require modifications to work:
+# - It may require correct/in-range values for request initialization.
+# - It may require specifying regional endpoints when creating the service
+# client as shown in:
+# https://googleapis.dev/python/google-api-core/latest/client_options.html
+from google.cloud import logging_v2
+
+
+async def sample_delete_link():
+ # Create a client
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
+
+ # Initialize request argument(s)
+ request = logging_v2.types.DeleteLinkRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ operation = client.delete_link(request=request)
+
+ print("Waiting for operation to complete...")
+
+ response = (await operation).result()
+
+ # Handle the response
+ print(response)
+
+# [END logging_v2_generated_ConfigServiceV2_DeleteLink_async]
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_delete_link_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_delete_link_sync.py
new file mode 100644
index 000000000..8ddbbcaf3
--- /dev/null
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_delete_link_sync.py
@@ -0,0 +1,56 @@
+# -*- coding: utf-8 -*-
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generated code. DO NOT EDIT!
+#
+# Snippet for DeleteLink
+# NOTE: This snippet has been automatically generated for illustrative purposes only.
+# It may require modifications to work in your environment.
+
+# To install the latest published package dependency, execute the following:
+# python3 -m pip install google-cloud-logging
+
+
+# [START logging_v2_generated_ConfigServiceV2_DeleteLink_sync]
+# This snippet has been automatically generated and should be regarded as a
+# code template only.
+# It will require modifications to work:
+# - It may require correct/in-range values for request initialization.
+# - It may require specifying regional endpoints when creating the service
+# client as shown in:
+# https://googleapis.dev/python/google-api-core/latest/client_options.html
+from google.cloud import logging_v2
+
+
+def sample_delete_link():
+ # Create a client
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
+
+ # Initialize request argument(s)
+ request = logging_v2.types.DeleteLinkRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ operation = client.delete_link(request=request)
+
+ print("Waiting for operation to complete...")
+
+ response = operation.result()
+
+ # Handle the response
+ print(response)
+
+# [END logging_v2_generated_ConfigServiceV2_DeleteLink_sync]
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_delete_sink_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_delete_sink_async.py
index 62a27ea1d..17ed0b302 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_delete_sink_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_delete_sink_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_delete_sink():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.DeleteSinkRequest(
+ request = logging_v2.types.DeleteSinkRequest(
sink_name="sink_name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_delete_sink_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_delete_sink_sync.py
index fa7d6f6e7..bc82c3aa0 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_delete_sink_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_delete_sink_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_delete_sink():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.DeleteSinkRequest(
+ request = logging_v2.types.DeleteSinkRequest(
sink_name="sink_name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_delete_view_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_delete_view_async.py
index 2fed68bbc..ca77b619c 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_delete_view_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_delete_view_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_delete_view():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.DeleteViewRequest(
+ request = logging_v2.types.DeleteViewRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_delete_view_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_delete_view_sync.py
index 53bda04c9..f6cd1237a 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_delete_view_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_delete_view_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_delete_view():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.DeleteViewRequest(
+ request = logging_v2.types.DeleteViewRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_get_bucket_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_get_bucket_async.py
index 1a91ecdd6..fd2b2a966 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_get_bucket_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_get_bucket_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_get_bucket():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.GetBucketRequest(
+ request = logging_v2.types.GetBucketRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_get_bucket_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_get_bucket_sync.py
index 337050c45..728615d94 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_get_bucket_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_get_bucket_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_get_bucket():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.GetBucketRequest(
+ request = logging_v2.types.GetBucketRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_get_cmek_settings_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_get_cmek_settings_async.py
index 6998c4b4a..eb661ea33 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_get_cmek_settings_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_get_cmek_settings_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_get_cmek_settings():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.GetCmekSettingsRequest(
+ request = logging_v2.types.GetCmekSettingsRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_get_cmek_settings_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_get_cmek_settings_sync.py
index a91ec6042..cc0b8e49a 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_get_cmek_settings_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_get_cmek_settings_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_get_cmek_settings():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.GetCmekSettingsRequest(
+ request = logging_v2.types.GetCmekSettingsRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_get_exclusion_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_get_exclusion_async.py
index 83a5bcda4..c3a10df02 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_get_exclusion_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_get_exclusion_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_get_exclusion():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.GetExclusionRequest(
+ request = logging_v2.types.GetExclusionRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_get_exclusion_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_get_exclusion_sync.py
index 913ec9968..0009b048b 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_get_exclusion_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_get_exclusion_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_get_exclusion():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.GetExclusionRequest(
+ request = logging_v2.types.GetExclusionRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_get_link_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_get_link_async.py
new file mode 100644
index 000000000..2f1e4647f
--- /dev/null
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_get_link_async.py
@@ -0,0 +1,52 @@
+# -*- coding: utf-8 -*-
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generated code. DO NOT EDIT!
+#
+# Snippet for GetLink
+# NOTE: This snippet has been automatically generated for illustrative purposes only.
+# It may require modifications to work in your environment.
+
+# To install the latest published package dependency, execute the following:
+# python3 -m pip install google-cloud-logging
+
+
+# [START logging_v2_generated_ConfigServiceV2_GetLink_async]
+# This snippet has been automatically generated and should be regarded as a
+# code template only.
+# It will require modifications to work:
+# - It may require correct/in-range values for request initialization.
+# - It may require specifying regional endpoints when creating the service
+# client as shown in:
+# https://googleapis.dev/python/google-api-core/latest/client_options.html
+from google.cloud import logging_v2
+
+
+async def sample_get_link():
+ # Create a client
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
+
+ # Initialize request argument(s)
+ request = logging_v2.types.GetLinkRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = await client.get_link(request=request)
+
+ # Handle the response
+ print(response)
+
+# [END logging_v2_generated_ConfigServiceV2_GetLink_async]
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_get_link_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_get_link_sync.py
new file mode 100644
index 000000000..8c8d9ddc1
--- /dev/null
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_get_link_sync.py
@@ -0,0 +1,52 @@
+# -*- coding: utf-8 -*-
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generated code. DO NOT EDIT!
+#
+# Snippet for GetLink
+# NOTE: This snippet has been automatically generated for illustrative purposes only.
+# It may require modifications to work in your environment.
+
+# To install the latest published package dependency, execute the following:
+# python3 -m pip install google-cloud-logging
+
+
+# [START logging_v2_generated_ConfigServiceV2_GetLink_sync]
+# This snippet has been automatically generated and should be regarded as a
+# code template only.
+# It will require modifications to work:
+# - It may require correct/in-range values for request initialization.
+# - It may require specifying regional endpoints when creating the service
+# client as shown in:
+# https://googleapis.dev/python/google-api-core/latest/client_options.html
+from google.cloud import logging_v2
+
+
+def sample_get_link():
+ # Create a client
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
+
+ # Initialize request argument(s)
+ request = logging_v2.types.GetLinkRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = client.get_link(request=request)
+
+ # Handle the response
+ print(response)
+
+# [END logging_v2_generated_ConfigServiceV2_GetLink_sync]
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_get_settings_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_get_settings_async.py
index c095649bc..41abc13ac 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_get_settings_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_get_settings_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_get_settings():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.GetSettingsRequest(
+ request = logging_v2.types.GetSettingsRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_get_settings_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_get_settings_sync.py
index 2b5350a5a..93bb910a5 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_get_settings_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_get_settings_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_get_settings():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.GetSettingsRequest(
+ request = logging_v2.types.GetSettingsRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_get_sink_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_get_sink_async.py
index 0739e175b..bdc293b5b 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_get_sink_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_get_sink_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_get_sink():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.GetSinkRequest(
+ request = logging_v2.types.GetSinkRequest(
sink_name="sink_name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_get_sink_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_get_sink_sync.py
index ff34156f3..a4b12474d 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_get_sink_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_get_sink_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_get_sink():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.GetSinkRequest(
+ request = logging_v2.types.GetSinkRequest(
sink_name="sink_name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_get_view_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_get_view_async.py
index 5de975ecc..4474f6c28 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_get_view_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_get_view_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_get_view():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.GetViewRequest(
+ request = logging_v2.types.GetViewRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_get_view_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_get_view_sync.py
index a9818b572..ce5680889 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_get_view_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_get_view_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_get_view():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.GetViewRequest(
+ request = logging_v2.types.GetViewRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_list_buckets_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_list_buckets_async.py
index 614e9ec66..d4aebfa95 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_list_buckets_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_list_buckets_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_list_buckets():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.ListBucketsRequest(
+ request = logging_v2.types.ListBucketsRequest(
parent="parent_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_list_buckets_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_list_buckets_sync.py
index 0c7912f7f..7fd1e53de 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_list_buckets_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_list_buckets_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_list_buckets():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.ListBucketsRequest(
+ request = logging_v2.types.ListBucketsRequest(
parent="parent_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_list_exclusions_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_list_exclusions_async.py
index a1aa5ed6f..199b152b9 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_list_exclusions_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_list_exclusions_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_list_exclusions():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.ListExclusionsRequest(
+ request = logging_v2.types.ListExclusionsRequest(
parent="parent_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_list_exclusions_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_list_exclusions_sync.py
index 8cdac9d12..7eafeb00e 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_list_exclusions_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_list_exclusions_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_list_exclusions():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.ListExclusionsRequest(
+ request = logging_v2.types.ListExclusionsRequest(
parent="parent_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_list_links_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_list_links_async.py
new file mode 100644
index 000000000..a8eee844c
--- /dev/null
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_list_links_async.py
@@ -0,0 +1,53 @@
+# -*- coding: utf-8 -*-
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generated code. DO NOT EDIT!
+#
+# Snippet for ListLinks
+# NOTE: This snippet has been automatically generated for illustrative purposes only.
+# It may require modifications to work in your environment.
+
+# To install the latest published package dependency, execute the following:
+# python3 -m pip install google-cloud-logging
+
+
+# [START logging_v2_generated_ConfigServiceV2_ListLinks_async]
+# This snippet has been automatically generated and should be regarded as a
+# code template only.
+# It will require modifications to work:
+# - It may require correct/in-range values for request initialization.
+# - It may require specifying regional endpoints when creating the service
+# client as shown in:
+# https://googleapis.dev/python/google-api-core/latest/client_options.html
+from google.cloud import logging_v2
+
+
+async def sample_list_links():
+ # Create a client
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
+
+ # Initialize request argument(s)
+ request = logging_v2.types.ListLinksRequest(
+ parent="parent_value",
+ )
+
+ # Make the request
+ page_result = client.list_links(request=request)
+
+ # Handle the response
+ async for response in page_result:
+ print(response)
+
+# [END logging_v2_generated_ConfigServiceV2_ListLinks_async]
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_list_links_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_list_links_sync.py
new file mode 100644
index 000000000..d6fde0bb7
--- /dev/null
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_list_links_sync.py
@@ -0,0 +1,53 @@
+# -*- coding: utf-8 -*-
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generated code. DO NOT EDIT!
+#
+# Snippet for ListLinks
+# NOTE: This snippet has been automatically generated for illustrative purposes only.
+# It may require modifications to work in your environment.
+
+# To install the latest published package dependency, execute the following:
+# python3 -m pip install google-cloud-logging
+
+
+# [START logging_v2_generated_ConfigServiceV2_ListLinks_sync]
+# This snippet has been automatically generated and should be regarded as a
+# code template only.
+# It will require modifications to work:
+# - It may require correct/in-range values for request initialization.
+# - It may require specifying regional endpoints when creating the service
+# client as shown in:
+# https://googleapis.dev/python/google-api-core/latest/client_options.html
+from google.cloud import logging_v2
+
+
+def sample_list_links():
+ # Create a client
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
+
+ # Initialize request argument(s)
+ request = logging_v2.types.ListLinksRequest(
+ parent="parent_value",
+ )
+
+ # Make the request
+ page_result = client.list_links(request=request)
+
+ # Handle the response
+ for response in page_result:
+ print(response)
+
+# [END logging_v2_generated_ConfigServiceV2_ListLinks_sync]
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_list_sinks_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_list_sinks_async.py
index ea81f5c8b..33e10deb2 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_list_sinks_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_list_sinks_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_list_sinks():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.ListSinksRequest(
+ request = logging_v2.types.ListSinksRequest(
parent="parent_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_list_sinks_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_list_sinks_sync.py
index 05a35323d..162119bc1 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_list_sinks_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_list_sinks_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_list_sinks():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.ListSinksRequest(
+ request = logging_v2.types.ListSinksRequest(
parent="parent_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_list_views_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_list_views_async.py
index c39fb2d9e..43e835259 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_list_views_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_list_views_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_list_views():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.ListViewsRequest(
+ request = logging_v2.types.ListViewsRequest(
parent="parent_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_list_views_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_list_views_sync.py
index 270e5c145..dbddce32c 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_list_views_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_list_views_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_list_views():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.ListViewsRequest(
+ request = logging_v2.types.ListViewsRequest(
parent="parent_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_undelete_bucket_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_undelete_bucket_async.py
index eeca015d1..7650a542f 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_undelete_bucket_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_undelete_bucket_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_undelete_bucket():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.UndeleteBucketRequest(
+ request = logging_v2.types.UndeleteBucketRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_undelete_bucket_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_undelete_bucket_sync.py
index 6355e2a62..c320d118e 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_undelete_bucket_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_undelete_bucket_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_undelete_bucket():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.UndeleteBucketRequest(
+ request = logging_v2.types.UndeleteBucketRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_update_bucket_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_update_bucket_async.py
index 450f5662a..4566ea26a 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_update_bucket_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_update_bucket_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_update_bucket():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.UpdateBucketRequest(
+ request = logging_v2.types.UpdateBucketRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_update_bucket_async_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_update_bucket_async_async.py
new file mode 100644
index 000000000..f127c9904
--- /dev/null
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_update_bucket_async_async.py
@@ -0,0 +1,56 @@
+# -*- coding: utf-8 -*-
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generated code. DO NOT EDIT!
+#
+# Snippet for UpdateBucketAsync
+# NOTE: This snippet has been automatically generated for illustrative purposes only.
+# It may require modifications to work in your environment.
+
+# To install the latest published package dependency, execute the following:
+# python3 -m pip install google-cloud-logging
+
+
+# [START logging_v2_generated_ConfigServiceV2_UpdateBucketAsync_async]
+# This snippet has been automatically generated and should be regarded as a
+# code template only.
+# It will require modifications to work:
+# - It may require correct/in-range values for request initialization.
+# - It may require specifying regional endpoints when creating the service
+# client as shown in:
+# https://googleapis.dev/python/google-api-core/latest/client_options.html
+from google.cloud import logging_v2
+
+
+async def sample_update_bucket_async():
+ # Create a client
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
+
+ # Initialize request argument(s)
+ request = logging_v2.types.UpdateBucketRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ operation = client.update_bucket_async(request=request)
+
+ print("Waiting for operation to complete...")
+
+ response = (await operation).result()
+
+ # Handle the response
+ print(response)
+
+# [END logging_v2_generated_ConfigServiceV2_UpdateBucketAsync_async]
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_update_bucket_async_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_update_bucket_async_sync.py
new file mode 100644
index 000000000..550aed7fb
--- /dev/null
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_update_bucket_async_sync.py
@@ -0,0 +1,56 @@
+# -*- coding: utf-8 -*-
+# Copyright 2025 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generated code. DO NOT EDIT!
+#
+# Snippet for UpdateBucketAsync
+# NOTE: This snippet has been automatically generated for illustrative purposes only.
+# It may require modifications to work in your environment.
+
+# To install the latest published package dependency, execute the following:
+# python3 -m pip install google-cloud-logging
+
+
+# [START logging_v2_generated_ConfigServiceV2_UpdateBucketAsync_sync]
+# This snippet has been automatically generated and should be regarded as a
+# code template only.
+# It will require modifications to work:
+# - It may require correct/in-range values for request initialization.
+# - It may require specifying regional endpoints when creating the service
+# client as shown in:
+# https://googleapis.dev/python/google-api-core/latest/client_options.html
+from google.cloud import logging_v2
+
+
+def sample_update_bucket_async():
+ # Create a client
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
+
+ # Initialize request argument(s)
+ request = logging_v2.types.UpdateBucketRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ operation = client.update_bucket_async(request=request)
+
+ print("Waiting for operation to complete...")
+
+ response = operation.result()
+
+ # Handle the response
+ print(response)
+
+# [END logging_v2_generated_ConfigServiceV2_UpdateBucketAsync_sync]
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_update_bucket_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_update_bucket_sync.py
index 81aa0fb92..bfa58357d 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_update_bucket_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_update_bucket_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_update_bucket():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.UpdateBucketRequest(
+ request = logging_v2.types.UpdateBucketRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_update_cmek_settings_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_update_cmek_settings_async.py
index e1a2421fe..22e799e9d 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_update_cmek_settings_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_update_cmek_settings_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_update_cmek_settings():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.UpdateCmekSettingsRequest(
+ request = logging_v2.types.UpdateCmekSettingsRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_update_cmek_settings_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_update_cmek_settings_sync.py
index 1828ce84c..766376e0e 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_update_cmek_settings_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_update_cmek_settings_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_update_cmek_settings():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.UpdateCmekSettingsRequest(
+ request = logging_v2.types.UpdateCmekSettingsRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_update_exclusion_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_update_exclusion_async.py
index 873fecb73..a19fbea8c 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_update_exclusion_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_update_exclusion_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,14 +36,14 @@
async def sample_update_exclusion():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- exclusion = logging_v2.LogExclusion()
+ exclusion = logging_v2.types.LogExclusion()
exclusion.name = "name_value"
exclusion.filter = "filter_value"
- request = logging_v2.UpdateExclusionRequest(
+ request = logging_v2.types.UpdateExclusionRequest(
name="name_value",
exclusion=exclusion,
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_update_exclusion_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_update_exclusion_sync.py
index 958572b93..3ba3a8f24 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_update_exclusion_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_update_exclusion_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,14 +36,14 @@
def sample_update_exclusion():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- exclusion = logging_v2.LogExclusion()
+ exclusion = logging_v2.types.LogExclusion()
exclusion.name = "name_value"
exclusion.filter = "filter_value"
- request = logging_v2.UpdateExclusionRequest(
+ request = logging_v2.types.UpdateExclusionRequest(
name="name_value",
exclusion=exclusion,
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_update_settings_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_update_settings_async.py
index 531b431f1..84a3dd245 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_update_settings_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_update_settings_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_update_settings():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.UpdateSettingsRequest(
+ request = logging_v2.types.UpdateSettingsRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_update_settings_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_update_settings_sync.py
index 3381a4aad..3754cd2e7 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_update_settings_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_update_settings_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_update_settings():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.UpdateSettingsRequest(
+ request = logging_v2.types.UpdateSettingsRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_update_sink_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_update_sink_async.py
index 400d57897..f2c54208b 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_update_sink_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_update_sink_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,14 +36,14 @@
async def sample_update_sink():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- sink = logging_v2.LogSink()
+ sink = logging_v2.types.LogSink()
sink.name = "name_value"
sink.destination = "destination_value"
- request = logging_v2.UpdateSinkRequest(
+ request = logging_v2.types.UpdateSinkRequest(
sink_name="sink_name_value",
sink=sink,
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_update_sink_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_update_sink_sync.py
index cc3a1be43..6238f9a10 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_update_sink_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_update_sink_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,14 +36,14 @@
def sample_update_sink():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- sink = logging_v2.LogSink()
+ sink = logging_v2.types.LogSink()
sink.name = "name_value"
sink.destination = "destination_value"
- request = logging_v2.UpdateSinkRequest(
+ request = logging_v2.types.UpdateSinkRequest(
sink_name="sink_name_value",
sink=sink,
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_update_view_async.py b/samples/generated_samples/logging_v2_generated_config_service_v2_update_view_async.py
index 8ccc9f3c3..9ba5fc19f 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_update_view_async.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_update_view_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_update_view():
# Create a client
- client = logging_v2.ConfigServiceV2AsyncClient()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.UpdateViewRequest(
+ request = logging_v2.types.UpdateViewRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_config_service_v2_update_view_sync.py b/samples/generated_samples/logging_v2_generated_config_service_v2_update_view_sync.py
index 33014bf23..97a2ebe4d 100644
--- a/samples/generated_samples/logging_v2_generated_config_service_v2_update_view_sync.py
+++ b/samples/generated_samples/logging_v2_generated_config_service_v2_update_view_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_update_view():
# Create a client
- client = logging_v2.ConfigServiceV2Client()
+ client = logging_v2.services.config_service_v2.ConfigServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.UpdateViewRequest(
+ request = logging_v2.types.UpdateViewRequest(
name="name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_logging_service_v2_delete_log_async.py b/samples/generated_samples/logging_v2_generated_logging_service_v2_delete_log_async.py
index 209dd510d..89495ff0b 100644
--- a/samples/generated_samples/logging_v2_generated_logging_service_v2_delete_log_async.py
+++ b/samples/generated_samples/logging_v2_generated_logging_service_v2_delete_log_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_delete_log():
# Create a client
- client = logging_v2.LoggingServiceV2AsyncClient()
+ client = logging_v2.services.logging_service_v2.LoggingServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.DeleteLogRequest(
+ request = logging_v2.types.DeleteLogRequest(
log_name="log_name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_logging_service_v2_delete_log_sync.py b/samples/generated_samples/logging_v2_generated_logging_service_v2_delete_log_sync.py
index 86f6c9ccb..24e4cd924 100644
--- a/samples/generated_samples/logging_v2_generated_logging_service_v2_delete_log_sync.py
+++ b/samples/generated_samples/logging_v2_generated_logging_service_v2_delete_log_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_delete_log():
# Create a client
- client = logging_v2.LoggingServiceV2Client()
+ client = logging_v2.services.logging_service_v2.LoggingServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.DeleteLogRequest(
+ request = logging_v2.types.DeleteLogRequest(
log_name="log_name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_logging_service_v2_list_log_entries_async.py b/samples/generated_samples/logging_v2_generated_logging_service_v2_list_log_entries_async.py
index d968835f7..e5226e985 100644
--- a/samples/generated_samples/logging_v2_generated_logging_service_v2_list_log_entries_async.py
+++ b/samples/generated_samples/logging_v2_generated_logging_service_v2_list_log_entries_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_list_log_entries():
# Create a client
- client = logging_v2.LoggingServiceV2AsyncClient()
+ client = logging_v2.services.logging_service_v2.LoggingServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.ListLogEntriesRequest(
+ request = logging_v2.types.ListLogEntriesRequest(
resource_names=['resource_names_value1', 'resource_names_value2'],
)
diff --git a/samples/generated_samples/logging_v2_generated_logging_service_v2_list_log_entries_sync.py b/samples/generated_samples/logging_v2_generated_logging_service_v2_list_log_entries_sync.py
index d200793fa..3fb660f90 100644
--- a/samples/generated_samples/logging_v2_generated_logging_service_v2_list_log_entries_sync.py
+++ b/samples/generated_samples/logging_v2_generated_logging_service_v2_list_log_entries_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_list_log_entries():
# Create a client
- client = logging_v2.LoggingServiceV2Client()
+ client = logging_v2.services.logging_service_v2.LoggingServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.ListLogEntriesRequest(
+ request = logging_v2.types.ListLogEntriesRequest(
resource_names=['resource_names_value1', 'resource_names_value2'],
)
diff --git a/samples/generated_samples/logging_v2_generated_logging_service_v2_list_logs_async.py b/samples/generated_samples/logging_v2_generated_logging_service_v2_list_logs_async.py
index eebad0bfd..4e3153fd6 100644
--- a/samples/generated_samples/logging_v2_generated_logging_service_v2_list_logs_async.py
+++ b/samples/generated_samples/logging_v2_generated_logging_service_v2_list_logs_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_list_logs():
# Create a client
- client = logging_v2.LoggingServiceV2AsyncClient()
+ client = logging_v2.services.logging_service_v2.LoggingServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.ListLogsRequest(
+ request = logging_v2.types.ListLogsRequest(
parent="parent_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_logging_service_v2_list_logs_sync.py b/samples/generated_samples/logging_v2_generated_logging_service_v2_list_logs_sync.py
index 8d132377e..fa44c8cc7 100644
--- a/samples/generated_samples/logging_v2_generated_logging_service_v2_list_logs_sync.py
+++ b/samples/generated_samples/logging_v2_generated_logging_service_v2_list_logs_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_list_logs():
# Create a client
- client = logging_v2.LoggingServiceV2Client()
+ client = logging_v2.services.logging_service_v2.LoggingServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.ListLogsRequest(
+ request = logging_v2.types.ListLogsRequest(
parent="parent_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_logging_service_v2_list_monitored_resource_descriptors_async.py b/samples/generated_samples/logging_v2_generated_logging_service_v2_list_monitored_resource_descriptors_async.py
index 4b99bc6f0..054520607 100644
--- a/samples/generated_samples/logging_v2_generated_logging_service_v2_list_monitored_resource_descriptors_async.py
+++ b/samples/generated_samples/logging_v2_generated_logging_service_v2_list_monitored_resource_descriptors_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_list_monitored_resource_descriptors():
# Create a client
- client = logging_v2.LoggingServiceV2AsyncClient()
+ client = logging_v2.services.logging_service_v2.LoggingServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.ListMonitoredResourceDescriptorsRequest(
+ request = logging_v2.types.ListMonitoredResourceDescriptorsRequest(
)
# Make the request
diff --git a/samples/generated_samples/logging_v2_generated_logging_service_v2_list_monitored_resource_descriptors_sync.py b/samples/generated_samples/logging_v2_generated_logging_service_v2_list_monitored_resource_descriptors_sync.py
index c54a2201f..cd404c1e1 100644
--- a/samples/generated_samples/logging_v2_generated_logging_service_v2_list_monitored_resource_descriptors_sync.py
+++ b/samples/generated_samples/logging_v2_generated_logging_service_v2_list_monitored_resource_descriptors_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_list_monitored_resource_descriptors():
# Create a client
- client = logging_v2.LoggingServiceV2Client()
+ client = logging_v2.services.logging_service_v2.LoggingServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.ListMonitoredResourceDescriptorsRequest(
+ request = logging_v2.types.ListMonitoredResourceDescriptorsRequest(
)
# Make the request
diff --git a/samples/generated_samples/logging_v2_generated_logging_service_v2_tail_log_entries_async.py b/samples/generated_samples/logging_v2_generated_logging_service_v2_tail_log_entries_async.py
index f1afa6fae..81eb975b9 100644
--- a/samples/generated_samples/logging_v2_generated_logging_service_v2_tail_log_entries_async.py
+++ b/samples/generated_samples/logging_v2_generated_logging_service_v2_tail_log_entries_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,15 +36,15 @@
async def sample_tail_log_entries():
# Create a client
- client = logging_v2.LoggingServiceV2AsyncClient()
+ client = logging_v2.services.logging_service_v2.LoggingServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.TailLogEntriesRequest(
+ request = logging_v2.types.TailLogEntriesRequest(
resource_names=['resource_names_value1', 'resource_names_value2'],
)
# This method expects an iterator which contains
- # 'logging_v2.TailLogEntriesRequest' objects
+ # 'logging_v2.types.TailLogEntriesRequest' objects
# Here we create a generator that yields a single `request` for
# demonstrative purposes.
requests = [request]
diff --git a/samples/generated_samples/logging_v2_generated_logging_service_v2_tail_log_entries_sync.py b/samples/generated_samples/logging_v2_generated_logging_service_v2_tail_log_entries_sync.py
index 29461c6f8..5d91ceb7e 100644
--- a/samples/generated_samples/logging_v2_generated_logging_service_v2_tail_log_entries_sync.py
+++ b/samples/generated_samples/logging_v2_generated_logging_service_v2_tail_log_entries_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,15 +36,15 @@
def sample_tail_log_entries():
# Create a client
- client = logging_v2.LoggingServiceV2Client()
+ client = logging_v2.services.logging_service_v2.LoggingServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.TailLogEntriesRequest(
+ request = logging_v2.types.TailLogEntriesRequest(
resource_names=['resource_names_value1', 'resource_names_value2'],
)
# This method expects an iterator which contains
- # 'logging_v2.TailLogEntriesRequest' objects
+ # 'logging_v2.types.TailLogEntriesRequest' objects
# Here we create a generator that yields a single `request` for
# demonstrative purposes.
requests = [request]
diff --git a/samples/generated_samples/logging_v2_generated_logging_service_v2_write_log_entries_async.py b/samples/generated_samples/logging_v2_generated_logging_service_v2_write_log_entries_async.py
index bd7954828..300dd7819 100644
--- a/samples/generated_samples/logging_v2_generated_logging_service_v2_write_log_entries_async.py
+++ b/samples/generated_samples/logging_v2_generated_logging_service_v2_write_log_entries_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,13 +36,13 @@
async def sample_write_log_entries():
# Create a client
- client = logging_v2.LoggingServiceV2AsyncClient()
+ client = logging_v2.services.logging_service_v2.LoggingServiceV2AsyncClient()
# Initialize request argument(s)
- entries = logging_v2.LogEntry()
+ entries = logging_v2.types.LogEntry()
entries.log_name = "log_name_value"
- request = logging_v2.WriteLogEntriesRequest(
+ request = logging_v2.types.WriteLogEntriesRequest(
entries=entries,
)
diff --git a/samples/generated_samples/logging_v2_generated_logging_service_v2_write_log_entries_sync.py b/samples/generated_samples/logging_v2_generated_logging_service_v2_write_log_entries_sync.py
index d28fbe7a0..7b16177ce 100644
--- a/samples/generated_samples/logging_v2_generated_logging_service_v2_write_log_entries_sync.py
+++ b/samples/generated_samples/logging_v2_generated_logging_service_v2_write_log_entries_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,13 +36,13 @@
def sample_write_log_entries():
# Create a client
- client = logging_v2.LoggingServiceV2Client()
+ client = logging_v2.services.logging_service_v2.LoggingServiceV2Client()
# Initialize request argument(s)
- entries = logging_v2.LogEntry()
+ entries = logging_v2.types.LogEntry()
entries.log_name = "log_name_value"
- request = logging_v2.WriteLogEntriesRequest(
+ request = logging_v2.types.WriteLogEntriesRequest(
entries=entries,
)
diff --git a/samples/generated_samples/logging_v2_generated_metrics_service_v2_create_log_metric_async.py b/samples/generated_samples/logging_v2_generated_metrics_service_v2_create_log_metric_async.py
index d351980e9..8ea8a849b 100644
--- a/samples/generated_samples/logging_v2_generated_metrics_service_v2_create_log_metric_async.py
+++ b/samples/generated_samples/logging_v2_generated_metrics_service_v2_create_log_metric_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,14 +36,14 @@
async def sample_create_log_metric():
# Create a client
- client = logging_v2.MetricsServiceV2AsyncClient()
+ client = logging_v2.services.metrics_service_v2.MetricsServiceV2AsyncClient()
# Initialize request argument(s)
- metric = logging_v2.LogMetric()
+ metric = logging_v2.types.LogMetric()
metric.name = "name_value"
metric.filter = "filter_value"
- request = logging_v2.CreateLogMetricRequest(
+ request = logging_v2.types.CreateLogMetricRequest(
parent="parent_value",
metric=metric,
)
diff --git a/samples/generated_samples/logging_v2_generated_metrics_service_v2_create_log_metric_sync.py b/samples/generated_samples/logging_v2_generated_metrics_service_v2_create_log_metric_sync.py
index bb9a56579..f67758eae 100644
--- a/samples/generated_samples/logging_v2_generated_metrics_service_v2_create_log_metric_sync.py
+++ b/samples/generated_samples/logging_v2_generated_metrics_service_v2_create_log_metric_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,14 +36,14 @@
def sample_create_log_metric():
# Create a client
- client = logging_v2.MetricsServiceV2Client()
+ client = logging_v2.services.metrics_service_v2.MetricsServiceV2Client()
# Initialize request argument(s)
- metric = logging_v2.LogMetric()
+ metric = logging_v2.types.LogMetric()
metric.name = "name_value"
metric.filter = "filter_value"
- request = logging_v2.CreateLogMetricRequest(
+ request = logging_v2.types.CreateLogMetricRequest(
parent="parent_value",
metric=metric,
)
diff --git a/samples/generated_samples/logging_v2_generated_metrics_service_v2_delete_log_metric_async.py b/samples/generated_samples/logging_v2_generated_metrics_service_v2_delete_log_metric_async.py
index 54a73b141..68a5e6c8d 100644
--- a/samples/generated_samples/logging_v2_generated_metrics_service_v2_delete_log_metric_async.py
+++ b/samples/generated_samples/logging_v2_generated_metrics_service_v2_delete_log_metric_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_delete_log_metric():
# Create a client
- client = logging_v2.MetricsServiceV2AsyncClient()
+ client = logging_v2.services.metrics_service_v2.MetricsServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.DeleteLogMetricRequest(
+ request = logging_v2.types.DeleteLogMetricRequest(
metric_name="metric_name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_metrics_service_v2_delete_log_metric_sync.py b/samples/generated_samples/logging_v2_generated_metrics_service_v2_delete_log_metric_sync.py
index 73276ef18..462f8bc32 100644
--- a/samples/generated_samples/logging_v2_generated_metrics_service_v2_delete_log_metric_sync.py
+++ b/samples/generated_samples/logging_v2_generated_metrics_service_v2_delete_log_metric_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_delete_log_metric():
# Create a client
- client = logging_v2.MetricsServiceV2Client()
+ client = logging_v2.services.metrics_service_v2.MetricsServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.DeleteLogMetricRequest(
+ request = logging_v2.types.DeleteLogMetricRequest(
metric_name="metric_name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_metrics_service_v2_get_log_metric_async.py b/samples/generated_samples/logging_v2_generated_metrics_service_v2_get_log_metric_async.py
index d6ef03c48..9eeea97fc 100644
--- a/samples/generated_samples/logging_v2_generated_metrics_service_v2_get_log_metric_async.py
+++ b/samples/generated_samples/logging_v2_generated_metrics_service_v2_get_log_metric_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_get_log_metric():
# Create a client
- client = logging_v2.MetricsServiceV2AsyncClient()
+ client = logging_v2.services.metrics_service_v2.MetricsServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.GetLogMetricRequest(
+ request = logging_v2.types.GetLogMetricRequest(
metric_name="metric_name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_metrics_service_v2_get_log_metric_sync.py b/samples/generated_samples/logging_v2_generated_metrics_service_v2_get_log_metric_sync.py
index 6ab2bb57f..cf60c346d 100644
--- a/samples/generated_samples/logging_v2_generated_metrics_service_v2_get_log_metric_sync.py
+++ b/samples/generated_samples/logging_v2_generated_metrics_service_v2_get_log_metric_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_get_log_metric():
# Create a client
- client = logging_v2.MetricsServiceV2Client()
+ client = logging_v2.services.metrics_service_v2.MetricsServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.GetLogMetricRequest(
+ request = logging_v2.types.GetLogMetricRequest(
metric_name="metric_name_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_metrics_service_v2_list_log_metrics_async.py b/samples/generated_samples/logging_v2_generated_metrics_service_v2_list_log_metrics_async.py
index 92c92395a..f7bc654c8 100644
--- a/samples/generated_samples/logging_v2_generated_metrics_service_v2_list_log_metrics_async.py
+++ b/samples/generated_samples/logging_v2_generated_metrics_service_v2_list_log_metrics_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
async def sample_list_log_metrics():
# Create a client
- client = logging_v2.MetricsServiceV2AsyncClient()
+ client = logging_v2.services.metrics_service_v2.MetricsServiceV2AsyncClient()
# Initialize request argument(s)
- request = logging_v2.ListLogMetricsRequest(
+ request = logging_v2.types.ListLogMetricsRequest(
parent="parent_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_metrics_service_v2_list_log_metrics_sync.py b/samples/generated_samples/logging_v2_generated_metrics_service_v2_list_log_metrics_sync.py
index 5a3e64692..4ae9a795e 100644
--- a/samples/generated_samples/logging_v2_generated_metrics_service_v2_list_log_metrics_sync.py
+++ b/samples/generated_samples/logging_v2_generated_metrics_service_v2_list_log_metrics_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,10 +36,10 @@
def sample_list_log_metrics():
# Create a client
- client = logging_v2.MetricsServiceV2Client()
+ client = logging_v2.services.metrics_service_v2.MetricsServiceV2Client()
# Initialize request argument(s)
- request = logging_v2.ListLogMetricsRequest(
+ request = logging_v2.types.ListLogMetricsRequest(
parent="parent_value",
)
diff --git a/samples/generated_samples/logging_v2_generated_metrics_service_v2_update_log_metric_async.py b/samples/generated_samples/logging_v2_generated_metrics_service_v2_update_log_metric_async.py
index 9a794a4cc..2c3669bca 100644
--- a/samples/generated_samples/logging_v2_generated_metrics_service_v2_update_log_metric_async.py
+++ b/samples/generated_samples/logging_v2_generated_metrics_service_v2_update_log_metric_async.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,14 +36,14 @@
async def sample_update_log_metric():
# Create a client
- client = logging_v2.MetricsServiceV2AsyncClient()
+ client = logging_v2.services.metrics_service_v2.MetricsServiceV2AsyncClient()
# Initialize request argument(s)
- metric = logging_v2.LogMetric()
+ metric = logging_v2.types.LogMetric()
metric.name = "name_value"
metric.filter = "filter_value"
- request = logging_v2.UpdateLogMetricRequest(
+ request = logging_v2.types.UpdateLogMetricRequest(
metric_name="metric_name_value",
metric=metric,
)
diff --git a/samples/generated_samples/logging_v2_generated_metrics_service_v2_update_log_metric_sync.py b/samples/generated_samples/logging_v2_generated_metrics_service_v2_update_log_metric_sync.py
index 39a6e72e3..2fed9c39e 100644
--- a/samples/generated_samples/logging_v2_generated_metrics_service_v2_update_log_metric_sync.py
+++ b/samples/generated_samples/logging_v2_generated_metrics_service_v2_update_log_metric_sync.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -36,14 +36,14 @@
def sample_update_log_metric():
# Create a client
- client = logging_v2.MetricsServiceV2Client()
+ client = logging_v2.services.metrics_service_v2.MetricsServiceV2Client()
# Initialize request argument(s)
- metric = logging_v2.LogMetric()
+ metric = logging_v2.types.LogMetric()
metric.name = "name_value"
metric.filter = "filter_value"
- request = logging_v2.UpdateLogMetricRequest(
+ request = logging_v2.types.UpdateLogMetricRequest(
metric_name="metric_name_value",
metric=metric,
)
diff --git a/samples/generated_samples/snippet_metadata_google.logging.v2.json b/samples/generated_samples/snippet_metadata_google.logging.v2.json
index 0cf8959de..7d77545ab 100644
--- a/samples/generated_samples/snippet_metadata_google.logging.v2.json
+++ b/samples/generated_samples/snippet_metadata_google.logging.v2.json
@@ -8,7 +8,7 @@
],
"language": "PYTHON",
"name": "google-cloud-logging",
- "version": "3.6.0"
+ "version": "3.12.1"
},
"snippets": [
{
@@ -43,7 +43,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.api_core.operation_async.AsyncOperation",
@@ -119,7 +119,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.api_core.operation.Operation",
@@ -164,6 +164,159 @@
],
"title": "logging_v2_generated_config_service_v2_copy_log_entries_sync.py"
},
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient",
+ "shortName": "ConfigServiceV2AsyncClient"
+ },
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.create_bucket_async",
+ "method": {
+ "fullName": "google.logging.v2.ConfigServiceV2.CreateBucketAsync",
+ "service": {
+ "fullName": "google.logging.v2.ConfigServiceV2",
+ "shortName": "ConfigServiceV2"
+ },
+ "shortName": "CreateBucketAsync"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.logging_v2.types.CreateBucketRequest"
+ },
+ {
+ "name": "retry",
+ "type": "google.api_core.retry.Retry"
+ },
+ {
+ "name": "timeout",
+ "type": "float"
+ },
+ {
+ "name": "metadata",
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
+ }
+ ],
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "create_bucket_async"
+ },
+ "description": "Sample for CreateBucketAsync",
+ "file": "logging_v2_generated_config_service_v2_create_bucket_async_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_CreateBucketAsync_async",
+ "segments": [
+ {
+ "end": 56,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 56,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 46,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 53,
+ "start": 47,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 57,
+ "start": 54,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "logging_v2_generated_config_service_v2_create_bucket_async_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client",
+ "shortName": "ConfigServiceV2Client"
+ },
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.create_bucket_async",
+ "method": {
+ "fullName": "google.logging.v2.ConfigServiceV2.CreateBucketAsync",
+ "service": {
+ "fullName": "google.logging.v2.ConfigServiceV2",
+ "shortName": "ConfigServiceV2"
+ },
+ "shortName": "CreateBucketAsync"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.logging_v2.types.CreateBucketRequest"
+ },
+ {
+ "name": "retry",
+ "type": "google.api_core.retry.Retry"
+ },
+ {
+ "name": "timeout",
+ "type": "float"
+ },
+ {
+ "name": "metadata",
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
+ }
+ ],
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "create_bucket_async"
+ },
+ "description": "Sample for CreateBucketAsync",
+ "file": "logging_v2_generated_config_service_v2_create_bucket_async_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_CreateBucketAsync_sync",
+ "segments": [
+ {
+ "end": 56,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 56,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 46,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 53,
+ "start": 47,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 57,
+ "start": 54,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "logging_v2_generated_config_service_v2_create_bucket_async_sync.py"
+ },
{
"canonical": true,
"clientMethod": {
@@ -196,7 +349,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.LogBucket",
@@ -272,7 +425,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.LogBucket",
@@ -357,7 +510,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.LogExclusion",
@@ -441,7 +594,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.LogExclusion",
@@ -494,27 +647,31 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient",
"shortName": "ConfigServiceV2AsyncClient"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.create_sink",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.create_link",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.CreateSink",
+ "fullName": "google.logging.v2.ConfigServiceV2.CreateLink",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "CreateSink"
+ "shortName": "CreateLink"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.CreateSinkRequest"
+ "type": "google.cloud.logging_v2.types.CreateLinkRequest"
},
{
"name": "parent",
"type": "str"
},
{
- "name": "sink",
- "type": "google.cloud.logging_v2.types.LogSink"
+ "name": "link",
+ "type": "google.cloud.logging_v2.types.Link"
+ },
+ {
+ "name": "link_id",
+ "type": "str"
},
{
"name": "retry",
@@ -526,17 +683,105 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.logging_v2.types.LogSink",
- "shortName": "create_sink"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "create_link"
},
- "description": "Sample for CreateSink",
- "file": "logging_v2_generated_config_service_v2_create_sink_async.py",
+ "description": "Sample for CreateLink",
+ "file": "logging_v2_generated_config_service_v2_create_link_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_CreateSink_async",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_CreateLink_async",
+ "segments": [
+ {
+ "end": 56,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 56,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 46,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 53,
+ "start": 47,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 57,
+ "start": 54,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "logging_v2_generated_config_service_v2_create_link_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client",
+ "shortName": "ConfigServiceV2Client"
+ },
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.create_link",
+ "method": {
+ "fullName": "google.logging.v2.ConfigServiceV2.CreateLink",
+ "service": {
+ "fullName": "google.logging.v2.ConfigServiceV2",
+ "shortName": "ConfigServiceV2"
+ },
+ "shortName": "CreateLink"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.logging_v2.types.CreateLinkRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
+ },
+ {
+ "name": "link",
+ "type": "google.cloud.logging_v2.types.Link"
+ },
+ {
+ "name": "link_id",
+ "type": "str"
+ },
+ {
+ "name": "retry",
+ "type": "google.api_core.retry.Retry"
+ },
+ {
+ "name": "timeout",
+ "type": "float"
+ },
+ {
+ "name": "metadata",
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
+ }
+ ],
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "create_link"
+ },
+ "description": "Sample for CreateLink",
+ "file": "logging_v2_generated_config_service_v2_create_link_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_CreateLink_sync",
"segments": [
{
"end": 56,
@@ -554,22 +799,569 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 50,
+ "end": 46,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 53,
+ "start": 47,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 57,
+ "start": 54,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "logging_v2_generated_config_service_v2_create_link_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient",
+ "shortName": "ConfigServiceV2AsyncClient"
+ },
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.create_sink",
+ "method": {
+ "fullName": "google.logging.v2.ConfigServiceV2.CreateSink",
+ "service": {
+ "fullName": "google.logging.v2.ConfigServiceV2",
+ "shortName": "ConfigServiceV2"
+ },
+ "shortName": "CreateSink"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.logging_v2.types.CreateSinkRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
+ },
+ {
+ "name": "sink",
+ "type": "google.cloud.logging_v2.types.LogSink"
+ },
+ {
+ "name": "retry",
+ "type": "google.api_core.retry.Retry"
+ },
+ {
+ "name": "timeout",
+ "type": "float"
+ },
+ {
+ "name": "metadata",
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
+ }
+ ],
+ "resultType": "google.cloud.logging_v2.types.LogSink",
+ "shortName": "create_sink"
+ },
+ "description": "Sample for CreateSink",
+ "file": "logging_v2_generated_config_service_v2_create_sink_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_CreateSink_async",
+ "segments": [
+ {
+ "end": 56,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 56,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 50,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 53,
+ "start": 51,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 57,
+ "start": 54,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "logging_v2_generated_config_service_v2_create_sink_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client",
+ "shortName": "ConfigServiceV2Client"
+ },
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.create_sink",
+ "method": {
+ "fullName": "google.logging.v2.ConfigServiceV2.CreateSink",
+ "service": {
+ "fullName": "google.logging.v2.ConfigServiceV2",
+ "shortName": "ConfigServiceV2"
+ },
+ "shortName": "CreateSink"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.logging_v2.types.CreateSinkRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
+ },
+ {
+ "name": "sink",
+ "type": "google.cloud.logging_v2.types.LogSink"
+ },
+ {
+ "name": "retry",
+ "type": "google.api_core.retry.Retry"
+ },
+ {
+ "name": "timeout",
+ "type": "float"
+ },
+ {
+ "name": "metadata",
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
+ }
+ ],
+ "resultType": "google.cloud.logging_v2.types.LogSink",
+ "shortName": "create_sink"
+ },
+ "description": "Sample for CreateSink",
+ "file": "logging_v2_generated_config_service_v2_create_sink_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_CreateSink_sync",
+ "segments": [
+ {
+ "end": 56,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 56,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 50,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 53,
+ "start": 51,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 57,
+ "start": 54,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "logging_v2_generated_config_service_v2_create_sink_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient",
+ "shortName": "ConfigServiceV2AsyncClient"
+ },
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.create_view",
+ "method": {
+ "fullName": "google.logging.v2.ConfigServiceV2.CreateView",
+ "service": {
+ "fullName": "google.logging.v2.ConfigServiceV2",
+ "shortName": "ConfigServiceV2"
+ },
+ "shortName": "CreateView"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.logging_v2.types.CreateViewRequest"
+ },
+ {
+ "name": "retry",
+ "type": "google.api_core.retry.Retry"
+ },
+ {
+ "name": "timeout",
+ "type": "float"
+ },
+ {
+ "name": "metadata",
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
+ }
+ ],
+ "resultType": "google.cloud.logging_v2.types.LogView",
+ "shortName": "create_view"
+ },
+ "description": "Sample for CreateView",
+ "file": "logging_v2_generated_config_service_v2_create_view_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_CreateView_async",
+ "segments": [
+ {
+ "end": 52,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 52,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 46,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 49,
+ "start": 47,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 53,
+ "start": 50,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "logging_v2_generated_config_service_v2_create_view_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client",
+ "shortName": "ConfigServiceV2Client"
+ },
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.create_view",
+ "method": {
+ "fullName": "google.logging.v2.ConfigServiceV2.CreateView",
+ "service": {
+ "fullName": "google.logging.v2.ConfigServiceV2",
+ "shortName": "ConfigServiceV2"
+ },
+ "shortName": "CreateView"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.logging_v2.types.CreateViewRequest"
+ },
+ {
+ "name": "retry",
+ "type": "google.api_core.retry.Retry"
+ },
+ {
+ "name": "timeout",
+ "type": "float"
+ },
+ {
+ "name": "metadata",
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
+ }
+ ],
+ "resultType": "google.cloud.logging_v2.types.LogView",
+ "shortName": "create_view"
+ },
+ "description": "Sample for CreateView",
+ "file": "logging_v2_generated_config_service_v2_create_view_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_CreateView_sync",
+ "segments": [
+ {
+ "end": 52,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 52,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 46,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 49,
+ "start": 47,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 53,
+ "start": 50,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "logging_v2_generated_config_service_v2_create_view_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient",
+ "shortName": "ConfigServiceV2AsyncClient"
+ },
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.delete_bucket",
+ "method": {
+ "fullName": "google.logging.v2.ConfigServiceV2.DeleteBucket",
+ "service": {
+ "fullName": "google.logging.v2.ConfigServiceV2",
+ "shortName": "ConfigServiceV2"
+ },
+ "shortName": "DeleteBucket"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.logging_v2.types.DeleteBucketRequest"
+ },
+ {
+ "name": "retry",
+ "type": "google.api_core.retry.Retry"
+ },
+ {
+ "name": "timeout",
+ "type": "float"
+ },
+ {
+ "name": "metadata",
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
+ }
+ ],
+ "shortName": "delete_bucket"
+ },
+ "description": "Sample for DeleteBucket",
+ "file": "logging_v2_generated_config_service_v2_delete_bucket_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteBucket_async",
+ "segments": [
+ {
+ "end": 49,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 49,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 45,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "start": 46,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 50,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "logging_v2_generated_config_service_v2_delete_bucket_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client",
+ "shortName": "ConfigServiceV2Client"
+ },
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.delete_bucket",
+ "method": {
+ "fullName": "google.logging.v2.ConfigServiceV2.DeleteBucket",
+ "service": {
+ "fullName": "google.logging.v2.ConfigServiceV2",
+ "shortName": "ConfigServiceV2"
+ },
+ "shortName": "DeleteBucket"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.logging_v2.types.DeleteBucketRequest"
+ },
+ {
+ "name": "retry",
+ "type": "google.api_core.retry.Retry"
+ },
+ {
+ "name": "timeout",
+ "type": "float"
+ },
+ {
+ "name": "metadata",
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
+ }
+ ],
+ "shortName": "delete_bucket"
+ },
+ "description": "Sample for DeleteBucket",
+ "file": "logging_v2_generated_config_service_v2_delete_bucket_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteBucket_sync",
+ "segments": [
+ {
+ "end": 49,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 49,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 45,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "start": 46,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 50,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "logging_v2_generated_config_service_v2_delete_bucket_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient",
+ "shortName": "ConfigServiceV2AsyncClient"
+ },
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.delete_exclusion",
+ "method": {
+ "fullName": "google.logging.v2.ConfigServiceV2.DeleteExclusion",
+ "service": {
+ "fullName": "google.logging.v2.ConfigServiceV2",
+ "shortName": "ConfigServiceV2"
+ },
+ "shortName": "DeleteExclusion"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.logging_v2.types.DeleteExclusionRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
+ },
+ {
+ "name": "retry",
+ "type": "google.api_core.retry.Retry"
+ },
+ {
+ "name": "timeout",
+ "type": "float"
+ },
+ {
+ "name": "metadata",
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
+ }
+ ],
+ "shortName": "delete_exclusion"
+ },
+ "description": "Sample for DeleteExclusion",
+ "file": "logging_v2_generated_config_service_v2_delete_exclusion_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteExclusion_async",
+ "segments": [
+ {
+ "end": 49,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 49,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 53,
- "start": 51,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 57,
- "start": 54,
+ "end": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_create_sink_async.py"
+ "title": "logging_v2_generated_config_service_v2_delete_exclusion_async.py"
},
{
"canonical": true,
@@ -578,28 +1370,24 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2Client",
"shortName": "ConfigServiceV2Client"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.create_sink",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.delete_exclusion",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.CreateSink",
+ "fullName": "google.logging.v2.ConfigServiceV2.DeleteExclusion",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "CreateSink"
+ "shortName": "DeleteExclusion"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.CreateSinkRequest"
+ "type": "google.cloud.logging_v2.types.DeleteExclusionRequest"
},
{
- "name": "parent",
+ "name": "name",
"type": "str"
},
- {
- "name": "sink",
- "type": "google.cloud.logging_v2.types.LogSink"
- },
{
"name": "retry",
"type": "google.api_core.retry.Retry"
@@ -610,25 +1398,24 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.logging_v2.types.LogSink",
- "shortName": "create_sink"
+ "shortName": "delete_exclusion"
},
- "description": "Sample for CreateSink",
- "file": "logging_v2_generated_config_service_v2_create_sink_sync.py",
+ "description": "Sample for DeleteExclusion",
+ "file": "logging_v2_generated_config_service_v2_delete_exclusion_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_CreateSink_sync",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteExclusion_sync",
"segments": [
{
- "end": 56,
+ "end": 49,
"start": 27,
"type": "FULL"
},
{
- "end": 56,
+ "end": 49,
"start": 27,
"type": "SHORT"
},
@@ -638,22 +1425,20 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 50,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 53,
- "start": 51,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 57,
- "start": 54,
+ "end": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_create_sink_sync.py"
+ "title": "logging_v2_generated_config_service_v2_delete_exclusion_sync.py"
},
{
"canonical": true,
@@ -663,19 +1448,23 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient",
"shortName": "ConfigServiceV2AsyncClient"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.create_view",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.delete_link",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.CreateView",
+ "fullName": "google.logging.v2.ConfigServiceV2.DeleteLink",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "CreateView"
+ "shortName": "DeleteLink"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.CreateViewRequest"
+ "type": "google.cloud.logging_v2.types.DeleteLinkRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -687,25 +1476,25 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.logging_v2.types.LogView",
- "shortName": "create_view"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "delete_link"
},
- "description": "Sample for CreateView",
- "file": "logging_v2_generated_config_service_v2_create_view_async.py",
+ "description": "Sample for DeleteLink",
+ "file": "logging_v2_generated_config_service_v2_delete_link_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_CreateView_async",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteLink_async",
"segments": [
{
- "end": 52,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -715,22 +1504,22 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 46,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 49,
- "start": 47,
+ "end": 52,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 53,
- "start": 50,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_create_view_async.py"
+ "title": "logging_v2_generated_config_service_v2_delete_link_async.py"
},
{
"canonical": true,
@@ -739,19 +1528,23 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2Client",
"shortName": "ConfigServiceV2Client"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.create_view",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.delete_link",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.CreateView",
+ "fullName": "google.logging.v2.ConfigServiceV2.DeleteLink",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "CreateView"
+ "shortName": "DeleteLink"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.CreateViewRequest"
+ "type": "google.cloud.logging_v2.types.DeleteLinkRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -763,25 +1556,25 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.logging_v2.types.LogView",
- "shortName": "create_view"
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "delete_link"
},
- "description": "Sample for CreateView",
- "file": "logging_v2_generated_config_service_v2_create_view_sync.py",
+ "description": "Sample for DeleteLink",
+ "file": "logging_v2_generated_config_service_v2_delete_link_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_CreateView_sync",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteLink_sync",
"segments": [
{
- "end": 52,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -791,22 +1584,22 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 46,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 49,
- "start": 47,
+ "end": 52,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 53,
- "start": 50,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_create_view_sync.py"
+ "title": "logging_v2_generated_config_service_v2_delete_link_sync.py"
},
{
"canonical": true,
@@ -816,19 +1609,23 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient",
"shortName": "ConfigServiceV2AsyncClient"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.delete_bucket",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.delete_sink",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.DeleteBucket",
+ "fullName": "google.logging.v2.ConfigServiceV2.DeleteSink",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "DeleteBucket"
+ "shortName": "DeleteSink"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.DeleteBucketRequest"
+ "type": "google.cloud.logging_v2.types.DeleteSinkRequest"
+ },
+ {
+ "name": "sink_name",
+ "type": "str"
},
{
"name": "retry",
@@ -840,16 +1637,16 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "shortName": "delete_bucket"
+ "shortName": "delete_sink"
},
- "description": "Sample for DeleteBucket",
- "file": "logging_v2_generated_config_service_v2_delete_bucket_async.py",
+ "description": "Sample for DeleteSink",
+ "file": "logging_v2_generated_config_service_v2_delete_sink_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteBucket_async",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteSink_async",
"segments": [
{
"end": 49,
@@ -880,7 +1677,7 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_delete_bucket_async.py"
+ "title": "logging_v2_generated_config_service_v2_delete_sink_async.py"
},
{
"canonical": true,
@@ -889,19 +1686,23 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2Client",
"shortName": "ConfigServiceV2Client"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.delete_bucket",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.delete_sink",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.DeleteBucket",
+ "fullName": "google.logging.v2.ConfigServiceV2.DeleteSink",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "DeleteBucket"
+ "shortName": "DeleteSink"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.DeleteBucketRequest"
+ "type": "google.cloud.logging_v2.types.DeleteSinkRequest"
+ },
+ {
+ "name": "sink_name",
+ "type": "str"
},
{
"name": "retry",
@@ -913,16 +1714,16 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "shortName": "delete_bucket"
+ "shortName": "delete_sink"
},
- "description": "Sample for DeleteBucket",
- "file": "logging_v2_generated_config_service_v2_delete_bucket_sync.py",
+ "description": "Sample for DeleteSink",
+ "file": "logging_v2_generated_config_service_v2_delete_sink_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteBucket_sync",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteSink_sync",
"segments": [
{
"end": 49,
@@ -953,7 +1754,7 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_delete_bucket_sync.py"
+ "title": "logging_v2_generated_config_service_v2_delete_sink_sync.py"
},
{
"canonical": true,
@@ -963,23 +1764,19 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient",
"shortName": "ConfigServiceV2AsyncClient"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.delete_exclusion",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.delete_view",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.DeleteExclusion",
+ "fullName": "google.logging.v2.ConfigServiceV2.DeleteView",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "DeleteExclusion"
+ "shortName": "DeleteView"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.DeleteExclusionRequest"
- },
- {
- "name": "name",
- "type": "str"
+ "type": "google.cloud.logging_v2.types.DeleteViewRequest"
},
{
"name": "retry",
@@ -991,16 +1788,16 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "shortName": "delete_exclusion"
+ "shortName": "delete_view"
},
- "description": "Sample for DeleteExclusion",
- "file": "logging_v2_generated_config_service_v2_delete_exclusion_async.py",
+ "description": "Sample for DeleteView",
+ "file": "logging_v2_generated_config_service_v2_delete_view_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteExclusion_async",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteView_async",
"segments": [
{
"end": 49,
@@ -1031,7 +1828,7 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_delete_exclusion_async.py"
+ "title": "logging_v2_generated_config_service_v2_delete_view_async.py"
},
{
"canonical": true,
@@ -1040,23 +1837,19 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2Client",
"shortName": "ConfigServiceV2Client"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.delete_exclusion",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.delete_view",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.DeleteExclusion",
+ "fullName": "google.logging.v2.ConfigServiceV2.DeleteView",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "DeleteExclusion"
+ "shortName": "DeleteView"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.DeleteExclusionRequest"
- },
- {
- "name": "name",
- "type": "str"
+ "type": "google.cloud.logging_v2.types.DeleteViewRequest"
},
{
"name": "retry",
@@ -1068,16 +1861,16 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "shortName": "delete_exclusion"
+ "shortName": "delete_view"
},
- "description": "Sample for DeleteExclusion",
- "file": "logging_v2_generated_config_service_v2_delete_exclusion_sync.py",
+ "description": "Sample for DeleteView",
+ "file": "logging_v2_generated_config_service_v2_delete_view_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteExclusion_sync",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteView_sync",
"segments": [
{
"end": 49,
@@ -1108,7 +1901,7 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_delete_exclusion_sync.py"
+ "title": "logging_v2_generated_config_service_v2_delete_view_sync.py"
},
{
"canonical": true,
@@ -1118,23 +1911,19 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient",
"shortName": "ConfigServiceV2AsyncClient"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.delete_sink",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.get_bucket",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.DeleteSink",
+ "fullName": "google.logging.v2.ConfigServiceV2.GetBucket",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "DeleteSink"
+ "shortName": "GetBucket"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.DeleteSinkRequest"
- },
- {
- "name": "sink_name",
- "type": "str"
+ "type": "google.cloud.logging_v2.types.GetBucketRequest"
},
{
"name": "retry",
@@ -1146,24 +1935,25 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "shortName": "delete_sink"
+ "resultType": "google.cloud.logging_v2.types.LogBucket",
+ "shortName": "get_bucket"
},
- "description": "Sample for DeleteSink",
- "file": "logging_v2_generated_config_service_v2_delete_sink_async.py",
+ "description": "Sample for GetBucket",
+ "file": "logging_v2_generated_config_service_v2_get_bucket_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteSink_async",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_GetBucket_async",
"segments": [
{
- "end": 49,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 49,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -1178,15 +1968,17 @@
"type": "REQUEST_INITIALIZATION"
},
{
+ "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 50,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_delete_sink_async.py"
+ "title": "logging_v2_generated_config_service_v2_get_bucket_async.py"
},
{
"canonical": true,
@@ -1195,23 +1987,19 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2Client",
"shortName": "ConfigServiceV2Client"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.delete_sink",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.get_bucket",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.DeleteSink",
+ "fullName": "google.logging.v2.ConfigServiceV2.GetBucket",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "DeleteSink"
+ "shortName": "GetBucket"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.DeleteSinkRequest"
- },
- {
- "name": "sink_name",
- "type": "str"
+ "type": "google.cloud.logging_v2.types.GetBucketRequest"
},
{
"name": "retry",
@@ -1223,24 +2011,25 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "shortName": "delete_sink"
+ "resultType": "google.cloud.logging_v2.types.LogBucket",
+ "shortName": "get_bucket"
},
- "description": "Sample for DeleteSink",
- "file": "logging_v2_generated_config_service_v2_delete_sink_sync.py",
+ "description": "Sample for GetBucket",
+ "file": "logging_v2_generated_config_service_v2_get_bucket_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteSink_sync",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_GetBucket_sync",
"segments": [
{
- "end": 49,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 49,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -1255,15 +2044,17 @@
"type": "REQUEST_INITIALIZATION"
},
{
+ "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 50,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_delete_sink_sync.py"
+ "title": "logging_v2_generated_config_service_v2_get_bucket_sync.py"
},
{
"canonical": true,
@@ -1273,19 +2064,19 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient",
"shortName": "ConfigServiceV2AsyncClient"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.delete_view",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.get_cmek_settings",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.DeleteView",
+ "fullName": "google.logging.v2.ConfigServiceV2.GetCmekSettings",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "DeleteView"
+ "shortName": "GetCmekSettings"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.DeleteViewRequest"
+ "type": "google.cloud.logging_v2.types.GetCmekSettingsRequest"
},
{
"name": "retry",
@@ -1297,24 +2088,25 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "shortName": "delete_view"
+ "resultType": "google.cloud.logging_v2.types.CmekSettings",
+ "shortName": "get_cmek_settings"
},
- "description": "Sample for DeleteView",
- "file": "logging_v2_generated_config_service_v2_delete_view_async.py",
+ "description": "Sample for GetCmekSettings",
+ "file": "logging_v2_generated_config_service_v2_get_cmek_settings_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteView_async",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_GetCmekSettings_async",
"segments": [
{
- "end": 49,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 49,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -1329,15 +2121,17 @@
"type": "REQUEST_INITIALIZATION"
},
{
+ "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 50,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_delete_view_async.py"
+ "title": "logging_v2_generated_config_service_v2_get_cmek_settings_async.py"
},
{
"canonical": true,
@@ -1346,19 +2140,19 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2Client",
"shortName": "ConfigServiceV2Client"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.delete_view",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.get_cmek_settings",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.DeleteView",
+ "fullName": "google.logging.v2.ConfigServiceV2.GetCmekSettings",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "DeleteView"
+ "shortName": "GetCmekSettings"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.DeleteViewRequest"
+ "type": "google.cloud.logging_v2.types.GetCmekSettingsRequest"
},
{
"name": "retry",
@@ -1370,24 +2164,25 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "shortName": "delete_view"
+ "resultType": "google.cloud.logging_v2.types.CmekSettings",
+ "shortName": "get_cmek_settings"
},
- "description": "Sample for DeleteView",
- "file": "logging_v2_generated_config_service_v2_delete_view_sync.py",
+ "description": "Sample for GetCmekSettings",
+ "file": "logging_v2_generated_config_service_v2_get_cmek_settings_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteView_sync",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_GetCmekSettings_sync",
"segments": [
{
- "end": 49,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 49,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -1402,15 +2197,17 @@
"type": "REQUEST_INITIALIZATION"
},
{
+ "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 50,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_delete_view_sync.py"
+ "title": "logging_v2_generated_config_service_v2_get_cmek_settings_sync.py"
},
{
"canonical": true,
@@ -1420,19 +2217,23 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient",
"shortName": "ConfigServiceV2AsyncClient"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.get_bucket",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.get_exclusion",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.GetBucket",
+ "fullName": "google.logging.v2.ConfigServiceV2.GetExclusion",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "GetBucket"
+ "shortName": "GetExclusion"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.GetBucketRequest"
+ "type": "google.cloud.logging_v2.types.GetExclusionRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -1444,17 +2245,17 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.logging_v2.types.LogBucket",
- "shortName": "get_bucket"
+ "resultType": "google.cloud.logging_v2.types.LogExclusion",
+ "shortName": "get_exclusion"
},
- "description": "Sample for GetBucket",
- "file": "logging_v2_generated_config_service_v2_get_bucket_async.py",
+ "description": "Sample for GetExclusion",
+ "file": "logging_v2_generated_config_service_v2_get_exclusion_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_GetBucket_async",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_GetExclusion_async",
"segments": [
{
"end": 51,
@@ -1487,7 +2288,7 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_get_bucket_async.py"
+ "title": "logging_v2_generated_config_service_v2_get_exclusion_async.py"
},
{
"canonical": true,
@@ -1496,19 +2297,23 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2Client",
"shortName": "ConfigServiceV2Client"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.get_bucket",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.get_exclusion",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.GetBucket",
+ "fullName": "google.logging.v2.ConfigServiceV2.GetExclusion",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "GetBucket"
+ "shortName": "GetExclusion"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.GetBucketRequest"
+ "type": "google.cloud.logging_v2.types.GetExclusionRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -1520,17 +2325,17 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.logging_v2.types.LogBucket",
- "shortName": "get_bucket"
+ "resultType": "google.cloud.logging_v2.types.LogExclusion",
+ "shortName": "get_exclusion"
},
- "description": "Sample for GetBucket",
- "file": "logging_v2_generated_config_service_v2_get_bucket_sync.py",
+ "description": "Sample for GetExclusion",
+ "file": "logging_v2_generated_config_service_v2_get_exclusion_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_GetBucket_sync",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_GetExclusion_sync",
"segments": [
{
"end": 51,
@@ -1563,7 +2368,7 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_get_bucket_sync.py"
+ "title": "logging_v2_generated_config_service_v2_get_exclusion_sync.py"
},
{
"canonical": true,
@@ -1573,19 +2378,23 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient",
"shortName": "ConfigServiceV2AsyncClient"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.get_cmek_settings",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.get_link",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.GetCmekSettings",
+ "fullName": "google.logging.v2.ConfigServiceV2.GetLink",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "GetCmekSettings"
+ "shortName": "GetLink"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.GetCmekSettingsRequest"
+ "type": "google.cloud.logging_v2.types.GetLinkRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -1597,17 +2406,17 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.logging_v2.types.CmekSettings",
- "shortName": "get_cmek_settings"
+ "resultType": "google.cloud.logging_v2.types.Link",
+ "shortName": "get_link"
},
- "description": "Sample for GetCmekSettings",
- "file": "logging_v2_generated_config_service_v2_get_cmek_settings_async.py",
+ "description": "Sample for GetLink",
+ "file": "logging_v2_generated_config_service_v2_get_link_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_GetCmekSettings_async",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_GetLink_async",
"segments": [
{
"end": 51,
@@ -1640,7 +2449,7 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_get_cmek_settings_async.py"
+ "title": "logging_v2_generated_config_service_v2_get_link_async.py"
},
{
"canonical": true,
@@ -1649,19 +2458,23 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2Client",
"shortName": "ConfigServiceV2Client"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.get_cmek_settings",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.get_link",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.GetCmekSettings",
+ "fullName": "google.logging.v2.ConfigServiceV2.GetLink",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "GetCmekSettings"
+ "shortName": "GetLink"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.GetCmekSettingsRequest"
+ "type": "google.cloud.logging_v2.types.GetLinkRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -1673,17 +2486,17 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.logging_v2.types.CmekSettings",
- "shortName": "get_cmek_settings"
+ "resultType": "google.cloud.logging_v2.types.Link",
+ "shortName": "get_link"
},
- "description": "Sample for GetCmekSettings",
- "file": "logging_v2_generated_config_service_v2_get_cmek_settings_sync.py",
+ "description": "Sample for GetLink",
+ "file": "logging_v2_generated_config_service_v2_get_link_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_GetCmekSettings_sync",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_GetLink_sync",
"segments": [
{
"end": 51,
@@ -1716,7 +2529,7 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_get_cmek_settings_sync.py"
+ "title": "logging_v2_generated_config_service_v2_get_link_sync.py"
},
{
"canonical": true,
@@ -1726,19 +2539,19 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient",
"shortName": "ConfigServiceV2AsyncClient"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.get_exclusion",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.get_settings",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.GetExclusion",
+ "fullName": "google.logging.v2.ConfigServiceV2.GetSettings",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "GetExclusion"
+ "shortName": "GetSettings"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.GetExclusionRequest"
+ "type": "google.cloud.logging_v2.types.GetSettingsRequest"
},
{
"name": "name",
@@ -1754,17 +2567,17 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.logging_v2.types.LogExclusion",
- "shortName": "get_exclusion"
+ "resultType": "google.cloud.logging_v2.types.Settings",
+ "shortName": "get_settings"
},
- "description": "Sample for GetExclusion",
- "file": "logging_v2_generated_config_service_v2_get_exclusion_async.py",
+ "description": "Sample for GetSettings",
+ "file": "logging_v2_generated_config_service_v2_get_settings_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_GetExclusion_async",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_GetSettings_async",
"segments": [
{
"end": 51,
@@ -1797,7 +2610,7 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_get_exclusion_async.py"
+ "title": "logging_v2_generated_config_service_v2_get_settings_async.py"
},
{
"canonical": true,
@@ -1806,19 +2619,19 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2Client",
"shortName": "ConfigServiceV2Client"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.get_exclusion",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.get_settings",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.GetExclusion",
+ "fullName": "google.logging.v2.ConfigServiceV2.GetSettings",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "GetExclusion"
+ "shortName": "GetSettings"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.GetExclusionRequest"
+ "type": "google.cloud.logging_v2.types.GetSettingsRequest"
},
{
"name": "name",
@@ -1834,17 +2647,17 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.logging_v2.types.LogExclusion",
- "shortName": "get_exclusion"
+ "resultType": "google.cloud.logging_v2.types.Settings",
+ "shortName": "get_settings"
},
- "description": "Sample for GetExclusion",
- "file": "logging_v2_generated_config_service_v2_get_exclusion_sync.py",
+ "description": "Sample for GetSettings",
+ "file": "logging_v2_generated_config_service_v2_get_settings_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_GetExclusion_sync",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_GetSettings_sync",
"segments": [
{
"end": 51,
@@ -1877,7 +2690,7 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_get_exclusion_sync.py"
+ "title": "logging_v2_generated_config_service_v2_get_settings_sync.py"
},
{
"canonical": true,
@@ -1887,22 +2700,22 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient",
"shortName": "ConfigServiceV2AsyncClient"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.get_settings",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.get_sink",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.GetSettings",
+ "fullName": "google.logging.v2.ConfigServiceV2.GetSink",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "GetSettings"
+ "shortName": "GetSink"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.GetSettingsRequest"
+ "type": "google.cloud.logging_v2.types.GetSinkRequest"
},
{
- "name": "name",
+ "name": "sink_name",
"type": "str"
},
{
@@ -1915,17 +2728,17 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.logging_v2.types.Settings",
- "shortName": "get_settings"
+ "resultType": "google.cloud.logging_v2.types.LogSink",
+ "shortName": "get_sink"
},
- "description": "Sample for GetSettings",
- "file": "logging_v2_generated_config_service_v2_get_settings_async.py",
+ "description": "Sample for GetSink",
+ "file": "logging_v2_generated_config_service_v2_get_sink_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_GetSettings_async",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_GetSink_async",
"segments": [
{
"end": 51,
@@ -1958,7 +2771,7 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_get_settings_async.py"
+ "title": "logging_v2_generated_config_service_v2_get_sink_async.py"
},
{
"canonical": true,
@@ -1967,22 +2780,22 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2Client",
"shortName": "ConfigServiceV2Client"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.get_settings",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.get_sink",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.GetSettings",
+ "fullName": "google.logging.v2.ConfigServiceV2.GetSink",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "GetSettings"
+ "shortName": "GetSink"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.GetSettingsRequest"
+ "type": "google.cloud.logging_v2.types.GetSinkRequest"
},
{
- "name": "name",
+ "name": "sink_name",
"type": "str"
},
{
@@ -1995,17 +2808,17 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.logging_v2.types.Settings",
- "shortName": "get_settings"
+ "resultType": "google.cloud.logging_v2.types.LogSink",
+ "shortName": "get_sink"
},
- "description": "Sample for GetSettings",
- "file": "logging_v2_generated_config_service_v2_get_settings_sync.py",
+ "description": "Sample for GetSink",
+ "file": "logging_v2_generated_config_service_v2_get_sink_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_GetSettings_sync",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_GetSink_sync",
"segments": [
{
"end": 51,
@@ -2038,7 +2851,7 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_get_settings_sync.py"
+ "title": "logging_v2_generated_config_service_v2_get_sink_sync.py"
},
{
"canonical": true,
@@ -2048,23 +2861,19 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient",
"shortName": "ConfigServiceV2AsyncClient"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.get_sink",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.get_view",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.GetSink",
+ "fullName": "google.logging.v2.ConfigServiceV2.GetView",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "GetSink"
+ "shortName": "GetView"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.GetSinkRequest"
- },
- {
- "name": "sink_name",
- "type": "str"
+ "type": "google.cloud.logging_v2.types.GetViewRequest"
},
{
"name": "retry",
@@ -2076,17 +2885,17 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.logging_v2.types.LogSink",
- "shortName": "get_sink"
+ "resultType": "google.cloud.logging_v2.types.LogView",
+ "shortName": "get_view"
},
- "description": "Sample for GetSink",
- "file": "logging_v2_generated_config_service_v2_get_sink_async.py",
+ "description": "Sample for GetView",
+ "file": "logging_v2_generated_config_service_v2_get_view_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_GetSink_async",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_GetView_async",
"segments": [
{
"end": 51,
@@ -2119,7 +2928,7 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_get_sink_async.py"
+ "title": "logging_v2_generated_config_service_v2_get_view_async.py"
},
{
"canonical": true,
@@ -2128,23 +2937,19 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2Client",
"shortName": "ConfigServiceV2Client"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.get_sink",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.get_view",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.GetSink",
+ "fullName": "google.logging.v2.ConfigServiceV2.GetView",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "GetSink"
+ "shortName": "GetView"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.GetSinkRequest"
- },
- {
- "name": "sink_name",
- "type": "str"
+ "type": "google.cloud.logging_v2.types.GetViewRequest"
},
{
"name": "retry",
@@ -2156,17 +2961,17 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.logging_v2.types.LogSink",
- "shortName": "get_sink"
+ "resultType": "google.cloud.logging_v2.types.LogView",
+ "shortName": "get_view"
},
- "description": "Sample for GetSink",
- "file": "logging_v2_generated_config_service_v2_get_sink_sync.py",
+ "description": "Sample for GetView",
+ "file": "logging_v2_generated_config_service_v2_get_view_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_GetSink_sync",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_GetView_sync",
"segments": [
{
"end": 51,
@@ -2199,7 +3004,7 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_get_sink_sync.py"
+ "title": "logging_v2_generated_config_service_v2_get_view_sync.py"
},
{
"canonical": true,
@@ -2209,19 +3014,23 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient",
"shortName": "ConfigServiceV2AsyncClient"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.get_view",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.list_buckets",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.GetView",
+ "fullName": "google.logging.v2.ConfigServiceV2.ListBuckets",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "GetView"
+ "shortName": "ListBuckets"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.GetViewRequest"
+ "type": "google.cloud.logging_v2.types.ListBucketsRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
},
{
"name": "retry",
@@ -2233,25 +3042,25 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.logging_v2.types.LogView",
- "shortName": "get_view"
+ "resultType": "google.cloud.logging_v2.services.config_service_v2.pagers.ListBucketsAsyncPager",
+ "shortName": "list_buckets"
},
- "description": "Sample for GetView",
- "file": "logging_v2_generated_config_service_v2_get_view_async.py",
+ "description": "Sample for ListBuckets",
+ "file": "logging_v2_generated_config_service_v2_list_buckets_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_GetView_async",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_ListBuckets_async",
"segments": [
{
- "end": 51,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -2271,12 +3080,12 @@
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
+ "end": 53,
"start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_get_view_async.py"
+ "title": "logging_v2_generated_config_service_v2_list_buckets_async.py"
},
{
"canonical": true,
@@ -2285,19 +3094,23 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2Client",
"shortName": "ConfigServiceV2Client"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.get_view",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.list_buckets",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.GetView",
+ "fullName": "google.logging.v2.ConfigServiceV2.ListBuckets",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "GetView"
+ "shortName": "ListBuckets"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.GetViewRequest"
+ "type": "google.cloud.logging_v2.types.ListBucketsRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
},
{
"name": "retry",
@@ -2309,25 +3122,25 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.logging_v2.types.LogView",
- "shortName": "get_view"
+ "resultType": "google.cloud.logging_v2.services.config_service_v2.pagers.ListBucketsPager",
+ "shortName": "list_buckets"
},
- "description": "Sample for GetView",
- "file": "logging_v2_generated_config_service_v2_get_view_sync.py",
+ "description": "Sample for ListBuckets",
+ "file": "logging_v2_generated_config_service_v2_list_buckets_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_GetView_sync",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_ListBuckets_sync",
"segments": [
{
- "end": 51,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -2347,12 +3160,12 @@
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
+ "end": 53,
"start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_get_view_sync.py"
+ "title": "logging_v2_generated_config_service_v2_list_buckets_sync.py"
},
{
"canonical": true,
@@ -2362,19 +3175,19 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient",
"shortName": "ConfigServiceV2AsyncClient"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.list_buckets",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.list_exclusions",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.ListBuckets",
+ "fullName": "google.logging.v2.ConfigServiceV2.ListExclusions",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "ListBuckets"
+ "shortName": "ListExclusions"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.ListBucketsRequest"
+ "type": "google.cloud.logging_v2.types.ListExclusionsRequest"
},
{
"name": "parent",
@@ -2390,17 +3203,17 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.logging_v2.services.config_service_v2.pagers.ListBucketsAsyncPager",
- "shortName": "list_buckets"
+ "resultType": "google.cloud.logging_v2.services.config_service_v2.pagers.ListExclusionsAsyncPager",
+ "shortName": "list_exclusions"
},
- "description": "Sample for ListBuckets",
- "file": "logging_v2_generated_config_service_v2_list_buckets_async.py",
+ "description": "Sample for ListExclusions",
+ "file": "logging_v2_generated_config_service_v2_list_exclusions_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_ListBuckets_async",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_ListExclusions_async",
"segments": [
{
"end": 52,
@@ -2433,7 +3246,7 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_list_buckets_async.py"
+ "title": "logging_v2_generated_config_service_v2_list_exclusions_async.py"
},
{
"canonical": true,
@@ -2442,19 +3255,19 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2Client",
"shortName": "ConfigServiceV2Client"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.list_buckets",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.list_exclusions",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.ListBuckets",
+ "fullName": "google.logging.v2.ConfigServiceV2.ListExclusions",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "ListBuckets"
+ "shortName": "ListExclusions"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.ListBucketsRequest"
+ "type": "google.cloud.logging_v2.types.ListExclusionsRequest"
},
{
"name": "parent",
@@ -2470,17 +3283,17 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.logging_v2.services.config_service_v2.pagers.ListBucketsPager",
- "shortName": "list_buckets"
+ "resultType": "google.cloud.logging_v2.services.config_service_v2.pagers.ListExclusionsPager",
+ "shortName": "list_exclusions"
},
- "description": "Sample for ListBuckets",
- "file": "logging_v2_generated_config_service_v2_list_buckets_sync.py",
+ "description": "Sample for ListExclusions",
+ "file": "logging_v2_generated_config_service_v2_list_exclusions_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_ListBuckets_sync",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_ListExclusions_sync",
"segments": [
{
"end": 52,
@@ -2513,7 +3326,7 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_list_buckets_sync.py"
+ "title": "logging_v2_generated_config_service_v2_list_exclusions_sync.py"
},
{
"canonical": true,
@@ -2523,19 +3336,19 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient",
"shortName": "ConfigServiceV2AsyncClient"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.list_exclusions",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.list_links",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.ListExclusions",
+ "fullName": "google.logging.v2.ConfigServiceV2.ListLinks",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "ListExclusions"
+ "shortName": "ListLinks"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.ListExclusionsRequest"
+ "type": "google.cloud.logging_v2.types.ListLinksRequest"
},
{
"name": "parent",
@@ -2551,17 +3364,17 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.logging_v2.services.config_service_v2.pagers.ListExclusionsAsyncPager",
- "shortName": "list_exclusions"
+ "resultType": "google.cloud.logging_v2.services.config_service_v2.pagers.ListLinksAsyncPager",
+ "shortName": "list_links"
},
- "description": "Sample for ListExclusions",
- "file": "logging_v2_generated_config_service_v2_list_exclusions_async.py",
+ "description": "Sample for ListLinks",
+ "file": "logging_v2_generated_config_service_v2_list_links_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_ListExclusions_async",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_ListLinks_async",
"segments": [
{
"end": 52,
@@ -2594,7 +3407,7 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_list_exclusions_async.py"
+ "title": "logging_v2_generated_config_service_v2_list_links_async.py"
},
{
"canonical": true,
@@ -2603,19 +3416,19 @@
"fullName": "google.cloud.logging_v2.ConfigServiceV2Client",
"shortName": "ConfigServiceV2Client"
},
- "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.list_exclusions",
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.list_links",
"method": {
- "fullName": "google.logging.v2.ConfigServiceV2.ListExclusions",
+ "fullName": "google.logging.v2.ConfigServiceV2.ListLinks",
"service": {
"fullName": "google.logging.v2.ConfigServiceV2",
"shortName": "ConfigServiceV2"
},
- "shortName": "ListExclusions"
+ "shortName": "ListLinks"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.logging_v2.types.ListExclusionsRequest"
+ "type": "google.cloud.logging_v2.types.ListLinksRequest"
},
{
"name": "parent",
@@ -2631,17 +3444,17 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.logging_v2.services.config_service_v2.pagers.ListExclusionsPager",
- "shortName": "list_exclusions"
+ "resultType": "google.cloud.logging_v2.services.config_service_v2.pagers.ListLinksPager",
+ "shortName": "list_links"
},
- "description": "Sample for ListExclusions",
- "file": "logging_v2_generated_config_service_v2_list_exclusions_sync.py",
+ "description": "Sample for ListLinks",
+ "file": "logging_v2_generated_config_service_v2_list_links_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "logging_v2_generated_ConfigServiceV2_ListExclusions_sync",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_ListLinks_sync",
"segments": [
{
"end": 52,
@@ -2674,7 +3487,7 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "logging_v2_generated_config_service_v2_list_exclusions_sync.py"
+ "title": "logging_v2_generated_config_service_v2_list_links_sync.py"
},
{
"canonical": true,
@@ -2712,7 +3525,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.services.config_service_v2.pagers.ListSinksAsyncPager",
@@ -2792,7 +3605,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.services.config_service_v2.pagers.ListSinksPager",
@@ -2873,7 +3686,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.services.config_service_v2.pagers.ListViewsAsyncPager",
@@ -2953,7 +3766,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.services.config_service_v2.pagers.ListViewsPager",
@@ -3030,7 +3843,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"shortName": "undelete_bucket"
@@ -3103,7 +3916,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"shortName": "undelete_bucket"
@@ -3145,6 +3958,159 @@
],
"title": "logging_v2_generated_config_service_v2_undelete_bucket_sync.py"
},
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient",
+ "shortName": "ConfigServiceV2AsyncClient"
+ },
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2AsyncClient.update_bucket_async",
+ "method": {
+ "fullName": "google.logging.v2.ConfigServiceV2.UpdateBucketAsync",
+ "service": {
+ "fullName": "google.logging.v2.ConfigServiceV2",
+ "shortName": "ConfigServiceV2"
+ },
+ "shortName": "UpdateBucketAsync"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.logging_v2.types.UpdateBucketRequest"
+ },
+ {
+ "name": "retry",
+ "type": "google.api_core.retry.Retry"
+ },
+ {
+ "name": "timeout",
+ "type": "float"
+ },
+ {
+ "name": "metadata",
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
+ }
+ ],
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "update_bucket_async"
+ },
+ "description": "Sample for UpdateBucketAsync",
+ "file": "logging_v2_generated_config_service_v2_update_bucket_async_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_UpdateBucketAsync_async",
+ "segments": [
+ {
+ "end": 55,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 55,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 45,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 52,
+ "start": 46,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 56,
+ "start": 53,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "logging_v2_generated_config_service_v2_update_bucket_async_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client",
+ "shortName": "ConfigServiceV2Client"
+ },
+ "fullName": "google.cloud.logging_v2.ConfigServiceV2Client.update_bucket_async",
+ "method": {
+ "fullName": "google.logging.v2.ConfigServiceV2.UpdateBucketAsync",
+ "service": {
+ "fullName": "google.logging.v2.ConfigServiceV2",
+ "shortName": "ConfigServiceV2"
+ },
+ "shortName": "UpdateBucketAsync"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.logging_v2.types.UpdateBucketRequest"
+ },
+ {
+ "name": "retry",
+ "type": "google.api_core.retry.Retry"
+ },
+ {
+ "name": "timeout",
+ "type": "float"
+ },
+ {
+ "name": "metadata",
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
+ }
+ ],
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "update_bucket_async"
+ },
+ "description": "Sample for UpdateBucketAsync",
+ "file": "logging_v2_generated_config_service_v2_update_bucket_async_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "logging_v2_generated_ConfigServiceV2_UpdateBucketAsync_sync",
+ "segments": [
+ {
+ "end": 55,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 55,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 45,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 52,
+ "start": 46,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 56,
+ "start": 53,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "logging_v2_generated_config_service_v2_update_bucket_async_sync.py"
+ },
{
"canonical": true,
"clientMethod": {
@@ -3177,7 +4143,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.LogBucket",
@@ -3253,7 +4219,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.LogBucket",
@@ -3330,7 +4296,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.CmekSettings",
@@ -3406,7 +4372,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.CmekSettings",
@@ -3495,7 +4461,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.LogExclusion",
@@ -3583,7 +4549,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.LogExclusion",
@@ -3668,7 +4634,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.Settings",
@@ -3752,7 +4718,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.Settings",
@@ -3841,7 +4807,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.LogSink",
@@ -3929,7 +4895,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.LogSink",
@@ -4006,7 +4972,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.LogView",
@@ -4082,7 +5048,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.LogView",
@@ -4163,7 +5129,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"shortName": "delete_log"
@@ -4240,7 +5206,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"shortName": "delete_log"
@@ -4326,7 +5292,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.services.logging_service_v2.pagers.ListLogEntriesAsyncPager",
@@ -4414,7 +5380,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.services.logging_service_v2.pagers.ListLogEntriesPager",
@@ -4495,7 +5461,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.services.logging_service_v2.pagers.ListLogsAsyncPager",
@@ -4575,7 +5541,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.services.logging_service_v2.pagers.ListLogsPager",
@@ -4652,7 +5618,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.services.logging_service_v2.pagers.ListMonitoredResourceDescriptorsAsyncPager",
@@ -4728,7 +5694,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.services.logging_service_v2.pagers.ListMonitoredResourceDescriptorsPager",
@@ -4805,7 +5771,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "Iterable[google.cloud.logging_v2.types.TailLogEntriesResponse]",
@@ -4881,7 +5847,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "Iterable[google.cloud.logging_v2.types.TailLogEntriesResponse]",
@@ -4974,7 +5940,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.WriteLogEntriesResponse",
@@ -5066,7 +6032,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.WriteLogEntriesResponse",
@@ -5151,7 +6117,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.LogMetric",
@@ -5235,7 +6201,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.LogMetric",
@@ -5316,7 +6282,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"shortName": "delete_log_metric"
@@ -5393,7 +6359,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"shortName": "delete_log_metric"
@@ -5471,7 +6437,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.LogMetric",
@@ -5551,7 +6517,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.LogMetric",
@@ -5632,7 +6598,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.services.metrics_service_v2.pagers.ListLogMetricsAsyncPager",
@@ -5712,7 +6678,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.services.metrics_service_v2.pagers.ListLogMetricsPager",
@@ -5797,7 +6763,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.LogMetric",
@@ -5881,7 +6847,7 @@
},
{
"name": "metadata",
- "type": "Sequence[Tuple[str, str]"
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
"resultType": "google.cloud.logging_v2.types.LogMetric",
diff --git a/samples/snippets/export_test.py b/samples/snippets/export_test.py
index b1ecf4923..845359e09 100644
--- a/samples/snippets/export_test.py
+++ b/samples/snippets/export_test.py
@@ -13,19 +13,30 @@
# limitations under the License.
import os
+import re
import random
import string
+import time
import backoff
-from google.cloud import logging
+from google.cloud import logging, storage
import pytest
import export
BUCKET = os.environ["CLOUD_STORAGE_BUCKET"]
-TEST_SINK_NAME_TMPL = "example_sink_{}"
+TEST_SINK_NAME_TMPL = "example_sink_{}_{}"
TEST_SINK_FILTER = "severity>=CRITICAL"
+TIMESTAMP = int(time.time())
+
+# Threshold beyond which the cleanup_old_sinks fixture will delete
+# old sink, in seconds
+CLEANUP_THRESHOLD = 7200 # 2 hours
+
+# Max buckets to delete at a time, to mitigate operation timeout
+# issues. To turn off in the future, set to None.
+MAX_BUCKETS = 1500
def _random_id():
@@ -34,12 +45,49 @@ def _random_id():
)
-@pytest.yield_fixture
-def example_sink():
+def _create_sink_name():
+ return TEST_SINK_NAME_TMPL.format(TIMESTAMP, _random_id())
+
+
+@backoff.on_exception(backoff.expo, Exception, max_time=60, raise_on_giveup=False)
+def _delete_object(obj):
+ obj.delete()
+
+
+# Runs once for entire test suite
+@pytest.fixture(scope="module")
+def cleanup_old_sinks():
+ client = logging.Client()
+ test_sink_name_regex = (
+ r"^" + TEST_SINK_NAME_TMPL.format(r"(\d+)", r"[A-Z0-9]{6}") + r"$"
+ )
+ for sink in client.list_sinks():
+ match = re.match(test_sink_name_regex, sink.name)
+ if match:
+ sink_timestamp = int(match.group(1))
+ if TIMESTAMP - sink_timestamp > CLEANUP_THRESHOLD:
+ _delete_object(sink)
+
+ storage_client = storage.Client()
+
+ # See _sink_storage_setup in usage_guide.py for details about how
+ # sinks are named.
+ test_bucket_name_regex = r"^sink\-storage\-(\d+)$"
+ for bucket in storage_client.list_buckets(max_results=MAX_BUCKETS):
+ match = re.match(test_bucket_name_regex, bucket.name)
+ if match:
+ # Bucket timestamp is int(time.time() * 1000)
+ bucket_timestamp = int(match.group(1))
+ if TIMESTAMP - bucket_timestamp // 1000 > CLEANUP_THRESHOLD:
+ _delete_object(bucket)
+
+
+@pytest.fixture
+def example_sink(cleanup_old_sinks):
client = logging.Client()
sink = client.sink(
- TEST_SINK_NAME_TMPL.format(_random_id()),
+ _create_sink_name(),
filter_=TEST_SINK_FILTER,
destination="storage.googleapis.com/{bucket}".format(bucket=BUCKET),
)
@@ -48,10 +96,7 @@ def example_sink():
yield sink
- try:
- sink.delete()
- except Exception:
- pass
+ _delete_object(sink)
def test_list(example_sink, capsys):
@@ -65,16 +110,13 @@ def eventually_consistent_test():
def test_create(capsys):
- sink_name = TEST_SINK_NAME_TMPL.format(_random_id())
+ sink_name = _create_sink_name()
try:
export.create_sink(sink_name, BUCKET, TEST_SINK_FILTER)
# Clean-up the temporary sink.
finally:
- try:
- logging.Client().sink(sink_name).delete()
- except Exception:
- pass
+ _delete_object(logging.Client().sink(sink_name))
out, _ = capsys.readouterr()
assert sink_name in out
diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py
index 1224cbe21..c9a3d1ecb 100644
--- a/samples/snippets/noxfile.py
+++ b/samples/snippets/noxfile.py
@@ -89,7 +89,7 @@ def get_pytest_env_vars() -> Dict[str, str]:
# DO NOT EDIT - automatically generated.
# All versions used to test samples.
-ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10", "3.11"]
+ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
# Any default versions that should be ignored.
IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"]
diff --git a/samples/snippets/requirements-test.txt b/samples/snippets/requirements-test.txt
index cbd0a47de..37eb1f9aa 100644
--- a/samples/snippets/requirements-test.txt
+++ b/samples/snippets/requirements-test.txt
@@ -1,2 +1,3 @@
backoff==2.2.1
-pytest==7.4.0
+pytest===7.4.4; python_version == '3.7'
+pytest==8.2.2; python_version >= '3.8'
diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt
index d4cc2c363..8a52ee5c6 100644
--- a/samples/snippets/requirements.txt
+++ b/samples/snippets/requirements.txt
@@ -1,4 +1,4 @@
-google-cloud-logging==3.6.0
-google-cloud-bigquery==3.11.4
-google-cloud-storage==2.10.0
-google-cloud-pubsub==2.18.2
+google-cloud-logging==3.10.0
+google-cloud-bigquery==3.25.0
+google-cloud-storage==2.17.0
+google-cloud-pubsub==2.22.0
diff --git a/samples/snippets/snippets.py b/samples/snippets/snippets.py
index 39399dcf7..736311e0f 100644
--- a/samples/snippets/snippets.py
+++ b/samples/snippets/snippets.py
@@ -38,7 +38,7 @@ def write_entry(logger_name):
logger.log_text("Hello, world!")
# Simple text log with severity.
- logger.log_text("Goodbye, world!", severity="ERROR")
+ logger.log_text("Goodbye, world!", severity="WARNING")
# Struct log. The struct can be any JSON-serializable dictionary.
logger.log_struct(
@@ -46,7 +46,8 @@ def write_entry(logger_name):
"name": "King Arthur",
"quest": "Find the Holy Grail",
"favorite_color": "Blue",
- }
+ },
+ severity="INFO",
)
print("Wrote logs to {}.".format(logger.name))
diff --git a/samples/snippets/usage_guide.py b/samples/snippets/usage_guide.py
index 5c9e86990..6dee33798 100644
--- a/samples/snippets/usage_guide.py
+++ b/samples/snippets/usage_guide.py
@@ -475,13 +475,47 @@ def using_extras(client):
def setup_logging(client):
import logging
- # [START setup_logging]
+ # [START logging_setup_logging]
client.setup_logging(log_level=logging.INFO)
- # [END setup_logging]
+ # [END logging_setup_logging]
- # [START setup_logging_excludes]
+ # [START logging_setup_logging_excludes]
client.setup_logging(log_level=logging.INFO, excluded_loggers=("werkzeug",))
- # [END setup_logging_excludes]
+ # [END logging_setup_logging_excludes]
+
+
+@snippet
+def logging_dict_config(client):
+ # [START logging_dict_config]
+ import logging.config
+
+ import google.cloud.logging
+
+ client = google.cloud.logging.Client()
+
+ LOGGING = {
+ "version": 1,
+ "handlers": {
+ "cloud_logging_handler": {
+ "class": "google.cloud.logging.handlers.CloudLoggingHandler",
+ "client": client,
+ },
+ "structured_log_handler": {
+ "class": "google.cloud.logging.handlers.StructuredLogHandler"
+ },
+ },
+ "root": {"handlers": [], "level": "WARNING"},
+ "loggers": {
+ "cloud_logger": {"handlers": ["cloud_logging_handler"], "level": "INFO"},
+ "structured_logger": {
+ "handlers": ["structured_log_handler"],
+ "level": "INFO",
+ },
+ },
+ }
+
+ logging.config.dictConfig(LOGGING)
+ # [END logging_dict_config]
def _line_no(func):
diff --git a/samples/snippets/usage_guide_test.py b/samples/snippets/usage_guide_test.py
index f02d82fbd..3f606dd65 100644
--- a/samples/snippets/usage_guide_test.py
+++ b/samples/snippets/usage_guide_test.py
@@ -88,3 +88,9 @@ def test_client_list_entries():
for item in to_delete:
usage_guide._backoff_not_found(item.delete)
+
+
+def test_dict_config():
+ client = Client()
+
+ usage_guide.logging_dict_config(client)
diff --git a/scripts/decrypt-secrets.sh b/scripts/decrypt-secrets.sh
index 0018b421d..120b0ddc4 100755
--- a/scripts/decrypt-secrets.sh
+++ b/scripts/decrypt-secrets.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# Copyright 2023 Google LLC All rights reserved.
+# Copyright 2024 Google LLC All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/scripts/readme-gen/readme_gen.py b/scripts/readme-gen/readme_gen.py
index 1acc11983..8f5e248a0 100644
--- a/scripts/readme-gen/readme_gen.py
+++ b/scripts/readme-gen/readme_gen.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python
-# Copyright 2023 Google LLC
+# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/setup.cfg b/setup.cfg
deleted file mode 100644
index 052350089..000000000
--- a/setup.cfg
+++ /dev/null
@@ -1,19 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright 2023 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
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# Generated by synthtool. DO NOT EDIT!
-[bdist_wheel]
-universal = 1
diff --git a/setup.py b/setup.py
index f43fd0bf9..c80db0467 100644
--- a/setup.py
+++ b/setup.py
@@ -36,14 +36,19 @@
release_status = "Development Status :: 5 - Production/Stable"
dependencies = [
- "google-api-core[grpc] >= 1.33.2, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*",
- "google-cloud-appengine-logging>=0.1.0, <2.0.0dev",
- "google-cloud-audit-log >= 0.1.0, < 1.0.0dev",
- "google-cloud-core >= 2.0.0, <3.0.0dev",
- "grpc-google-iam-v1 >=0.12.4, <1.0.0dev",
- "proto-plus >= 1.22.0, <2.0.0dev",
- "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'",
- "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
+ "google-api-core[grpc] >= 1.34.1, <3.0.0,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*",
+ # Exclude incompatible versions of `google-auth`
+ # See https://github.com/googleapis/google-cloud-python/issues/12364
+ "google-auth >= 2.14.1, <3.0.0,!=2.24.0,!=2.25.0",
+ "google-cloud-appengine-logging>=0.1.3, <2.0.0",
+ "google-cloud-audit-log >= 0.3.1, < 1.0.0",
+ "google-cloud-core >= 2.0.0, <3.0.0",
+ "grpc-google-iam-v1 >=0.12.4, <1.0.0",
+ "opentelemetry-api >= 1.9.0",
+ "proto-plus >= 1.22.0, <2.0.0",
+ "proto-plus >= 1.22.2, <2.0.0; python_version>='3.11'",
+ "proto-plus >= 1.25.0, <2.0.0; python_version>='3.13'",
+ "protobuf>=3.20.2,<7.0.0,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
]
url = "https://github.com/googleapis/python-logging"
@@ -55,14 +60,10 @@
packages = [
package
- for package in setuptools.PEP420PackageFinder.find()
+ for package in setuptools.find_namespace_packages()
if package.startswith("google")
]
-namespaces = ["google"]
-if "google.cloud" in packages:
- namespaces.append("google.cloud")
-
setuptools.setup(
name=name,
version=version,
@@ -83,13 +84,13 @@
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
+ "Programming Language :: Python :: 3.12",
"Operating System :: OS Independent",
"Topic :: Internet",
],
platforms="Posix; MacOS X; Windows",
packages=packages,
python_requires=">=3.7",
- namespace_packages=namespaces,
install_requires=dependencies,
include_package_data=True,
zip_safe=False,
diff --git a/testing/constraints-3.10.txt b/testing/constraints-3.10.txt
index ed7f9aed2..981d37ac6 100644
--- a/testing/constraints-3.10.txt
+++ b/testing/constraints-3.10.txt
@@ -2,5 +2,15 @@
# This constraints file is required for unit tests.
# List all library dependencies and extras in this file.
google-api-core
+google-auth
proto-plus
protobuf
+google-cloud-core
+google-cloud-appengine-logging
+google-cloud-audit-log
+grpc-google-iam-v1
+opentelemetry-api
+
+# optional dependencies
+django
+flask
diff --git a/testing/constraints-3.11.txt b/testing/constraints-3.11.txt
index ed7f9aed2..981d37ac6 100644
--- a/testing/constraints-3.11.txt
+++ b/testing/constraints-3.11.txt
@@ -2,5 +2,15 @@
# This constraints file is required for unit tests.
# List all library dependencies and extras in this file.
google-api-core
+google-auth
proto-plus
protobuf
+google-cloud-core
+google-cloud-appengine-logging
+google-cloud-audit-log
+grpc-google-iam-v1
+opentelemetry-api
+
+# optional dependencies
+django
+flask
diff --git a/testing/constraints-3.12.txt b/testing/constraints-3.12.txt
index ed7f9aed2..981d37ac6 100644
--- a/testing/constraints-3.12.txt
+++ b/testing/constraints-3.12.txt
@@ -2,5 +2,15 @@
# This constraints file is required for unit tests.
# List all library dependencies and extras in this file.
google-api-core
+google-auth
proto-plus
protobuf
+google-cloud-core
+google-cloud-appengine-logging
+google-cloud-audit-log
+grpc-google-iam-v1
+opentelemetry-api
+
+# optional dependencies
+django
+flask
diff --git a/testing/constraints-3.13.txt b/testing/constraints-3.13.txt
new file mode 100644
index 000000000..981d37ac6
--- /dev/null
+++ b/testing/constraints-3.13.txt
@@ -0,0 +1,16 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+google-auth
+proto-plus
+protobuf
+google-cloud-core
+google-cloud-appengine-logging
+google-cloud-audit-log
+grpc-google-iam-v1
+opentelemetry-api
+
+# optional dependencies
+django
+flask
diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt
index 587626c54..113004889 100644
--- a/testing/constraints-3.7.txt
+++ b/testing/constraints-3.7.txt
@@ -4,7 +4,22 @@
# Pin the version to the lower bound.
# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev",
# Then this file should have google-cloud-foo==1.14.0
-google-api-core==1.33.2
+google-api-core==1.34.1
+google-auth==2.14.1
proto-plus==1.22.0
-protobuf==3.19.5
+protobuf==3.20.2
google-cloud-core==2.0.0
+google-cloud-appengine-logging==0.1.3
+google-cloud-audit-log==0.3.1
+grpc-google-iam-v1==0.12.4
+opentelemetry-api==1.9.0
+
+# Lower bound testing for optional dependencies
+django==3.2
+
+# Need specific versions of Flask dependencies for Flask 1.0 to work
+flask==1.0.0
+jinja2==2.10.1
+markupsafe==2.0.1
+itsdangerous==2.0.1
+werkzeug==1.0.1
\ No newline at end of file
diff --git a/testing/constraints-3.8.txt b/testing/constraints-3.8.txt
index ed7f9aed2..76b620077 100644
--- a/testing/constraints-3.8.txt
+++ b/testing/constraints-3.8.txt
@@ -1,6 +1,22 @@
# -*- coding: utf-8 -*-
# This constraints file is required for unit tests.
# List all library dependencies and extras in this file.
-google-api-core
-proto-plus
-protobuf
+google-api-core==2.14.0
+google-auth==2.14.1
+proto-plus==1.22.0
+protobuf==4.21.6
+google-cloud-core==2.0.0
+google-cloud-appengine-logging==0.1.3
+google-cloud-audit-log==0.3.1
+grpc-google-iam-v1==0.12.4
+opentelemetry-api==1.9.0
+
+# Lower bound testing for optional dependencies
+django==3.2
+
+# Need specific versions of Flask dependencies for Flask 1.0 to work
+flask==1.0.0
+jinja2==2.10.1
+markupsafe==2.0.1
+itsdangerous==2.0.1
+werkzeug==1.0.1
diff --git a/testing/constraints-3.9.txt b/testing/constraints-3.9.txt
index ed7f9aed2..10c5cba87 100644
--- a/testing/constraints-3.9.txt
+++ b/testing/constraints-3.9.txt
@@ -2,5 +2,21 @@
# This constraints file is required for unit tests.
# List all library dependencies and extras in this file.
google-api-core
+google-auth
proto-plus
protobuf
+google-cloud-core
+google-cloud-appengine-logging
+google-cloud-audit-log
+grpc-google-iam-v1
+opentelemetry-api==1.9.0
+
+# Lower bound testing for optional dependencies
+django==3.2
+
+# Need specific versions of Flask dependencies for Flask 1.0 to work
+flask==1.0.0
+jinja2==2.10.1
+markupsafe==2.0.1
+itsdangerous==2.0.1
+werkzeug==1.0.1
diff --git a/tests/__init__.py b/tests/__init__.py
index e8e1c3845..cbf94b283 100644
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/tests/system/test_system.py b/tests/system/test_system.py
index 8d39408d3..487ecde62 100644
--- a/tests/system/test_system.py
+++ b/tests/system/test_system.py
@@ -19,6 +19,7 @@
import numbers
import os
import pytest
+import sys
import unittest
import uuid
@@ -33,6 +34,7 @@
import google.cloud.logging
from google.cloud._helpers import UTC
from google.cloud.logging_v2.handlers import CloudLoggingHandler
+from google.cloud.logging_v2.handlers.transports import BackgroundThreadTransport
from google.cloud.logging_v2.handlers.transports import SyncTransport
from google.cloud.logging_v2 import client
from google.cloud.logging_v2.resource import Resource
@@ -117,8 +119,26 @@ def setUpModule():
)
-class TestLogging(unittest.TestCase):
+def _cleanup_otel_sdk_modules(f):
+ """
+ Decorator to delete all references to opentelemetry SDK modules after a
+ testcase is run. Test case should import opentelemetry SDK modules inside
+ the function. This is to test situations where the opentelemetry SDK
+ is not imported at all.
+ """
+
+ def wrapped(*args, **kwargs):
+ f(*args, **kwargs)
+
+ # Deleting from sys.modules should be good enough in this use case
+ for module_name in list(sys.modules.keys()):
+ if module_name.startswith("opentelemetry.sdk"):
+ sys.modules.pop(module_name)
+
+ return wrapped
+
+class TestLogging(unittest.TestCase):
JSON_PAYLOAD = {
"message": "System test: test_log_struct",
"weather": {
@@ -193,6 +213,7 @@ def test_list_entry_with_auditlog(self):
"methodName": "test",
"resourceName": "test",
"serviceName": "test",
+ "requestMetadata": {"callerIp": "127.0.0.1"},
}
audit_struct = self._dict_to_struct(audit_dict)
@@ -224,6 +245,12 @@ def test_list_entry_with_auditlog(self):
protobuf_entry.to_api_repr()["protoPayload"]["methodName"],
audit_dict["methodName"],
)
+ self.assertEqual(
+ protobuf_entry.to_api_repr()["protoPayload"]["requestMetadata"][
+ "callerIp"
+ ],
+ audit_dict["requestMetadata"]["callerIp"],
+ )
def test_list_entry_with_requestlog(self):
"""
@@ -330,7 +357,7 @@ def test_log_text_with_timestamp(self):
text_payload = "System test: test_log_text_with_timestamp"
gapic_logger = Config.CLIENT.logger(self._logger_name("log_text_ts"))
http_logger = Config.HTTP_CLIENT.logger(self._logger_name("log_text_ts_http"))
- now = datetime.utcnow()
+ now = datetime.now(timezone.utc)
loggers = (
[gapic_logger]
if Config.use_mtls == "always"
@@ -350,7 +377,7 @@ def test_log_text_with_resource(self):
gapic_logger = Config.CLIENT.logger(self._logger_name("log_text_res"))
http_logger = Config.HTTP_CLIENT.logger(self._logger_name("log_text_res_http"))
- now = datetime.utcnow()
+ now = datetime.now(timezone.utc)
loggers = (
[gapic_logger]
if Config.use_mtls == "always"
@@ -596,10 +623,10 @@ def test_handlers_w_extras(self):
"trace_sampled": True,
"http_request": expected_request,
"source_location": expected_source,
- "resource": Resource(type="cloudiot_device", labels={}),
+ "resource": Resource(type="global", labels={}),
"labels": {"test-label": "manual"},
}
- cloud_logger.warn(LOG_MESSAGE, extra=extra)
+ cloud_logger.warning(LOG_MESSAGE, extra=extra)
entries = _list_entries(logger)
self.assertEqual(len(entries), 1)
@@ -628,7 +655,7 @@ def test_handlers_w_json_fields(self):
cloud_logger = logging.getLogger(LOGGER_NAME)
cloud_logger.addHandler(handler)
extra = {"json_fields": {"hello": "world", "two": 2}}
- cloud_logger.warn(LOG_MESSAGE, extra=extra)
+ cloud_logger.warning(LOG_MESSAGE, extra=extra)
entries = _list_entries(logger)
self.assertEqual(len(entries), 1)
@@ -656,6 +683,109 @@ def test_log_root_handler(self):
self.assertEqual(len(entries), 1)
self.assertEqual(entries[0].payload, expected_payload)
+ @_cleanup_otel_sdk_modules
+ def test_log_handler_otel_integration(self):
+ # Doing OTel imports here to not taint the other tests with OTel SDK imports
+ from opentelemetry import trace
+ from opentelemetry.sdk.trace import TracerProvider
+
+ LOG_MESSAGE = "This is a test of OpenTelemetry"
+ LOGGER_NAME = "otel-integration"
+ handler_name = self._logger_name(LOGGER_NAME)
+
+ handler = CloudLoggingHandler(
+ Config.CLIENT, name=handler_name, transport=SyncTransport
+ )
+ # only create the logger to delete, hidden otherwise
+ logger = Config.CLIENT.logger(handler.name)
+ self.to_delete.append(logger)
+
+ # Set up OTel SDK
+ provider = TracerProvider()
+
+ tracer = provider.get_tracer("test_system")
+ with tracer.start_as_current_span("test-span") as span:
+ context = span.get_span_context()
+ expected_trace_id = f"projects/{Config.CLIENT.project}/traces/{trace.format_trace_id(context.trace_id)}"
+ expected_span_id = trace.format_span_id(context.span_id)
+ expected_tracesampled = context.trace_flags.sampled
+
+ cloud_logger = logging.getLogger(LOGGER_NAME)
+ cloud_logger.addHandler(handler)
+ cloud_logger.warning(LOG_MESSAGE)
+
+ entries = _list_entries(logger)
+ self.assertEqual(len(entries), 1)
+ self.assertEqual(entries[0].trace, expected_trace_id)
+ self.assertEqual(entries[0].span_id, expected_span_id)
+ self.assertTrue(entries[0].trace_sampled, expected_tracesampled)
+
+ def test_log_handler_close(self):
+ from multiprocessing import Process
+
+ LOG_MESSAGE = "This is a test of handler.close before exiting."
+ LOGGER_NAME = "close-test"
+ handler_name = self._logger_name(LOGGER_NAME)
+
+ # only create the logger to delete, hidden otherwise
+ logger = Config.CLIENT.logger(handler_name)
+ self.to_delete.append(logger)
+
+ # Run a simulation of logging an entry then immediately shutting down.
+ # The .close() function before the process exits should prevent the
+ # thread shutdown error and let us log the message.
+ def subprocess_main():
+ # logger.delete and logger.list_entries work by filtering on log name, so we
+ # can create new objects with the same name and have the queries on the parent
+ # process still work.
+ handler = CloudLoggingHandler(
+ Config.CLIENT, name=handler_name, transport=BackgroundThreadTransport
+ )
+ cloud_logger = logging.getLogger(LOGGER_NAME)
+ cloud_logger.addHandler(handler)
+ cloud_logger.warning(LOG_MESSAGE)
+ handler.close()
+
+ proc = Process(target=subprocess_main)
+ proc.start()
+ proc.join()
+ entries = _list_entries(logger)
+ self.assertEqual(len(entries), 1)
+ self.assertEqual(entries[0].payload, LOG_MESSAGE)
+
+ def test_log_client_flush_handlers(self):
+ from multiprocessing import Process
+
+ LOG_MESSAGE = "This is a test of client.flush_handlers before exiting."
+ LOGGER_NAME = "close-test"
+ handler_name = self._logger_name(LOGGER_NAME)
+
+ # only create the logger to delete, hidden otherwise
+ logger = Config.CLIENT.logger(handler_name)
+ self.to_delete.append(logger)
+
+ # Run a simulation of logging an entry then immediately shutting down.
+ # The .close() function before the process exits should prevent the
+ # thread shutdown error and let us log the message.
+ def subprocess_main():
+ # logger.delete and logger.list_entries work by filtering on log name, so we
+ # can create new objects with the same name and have the queries on the parent
+ # process still work.
+ handler = CloudLoggingHandler(
+ Config.CLIENT, name=handler_name, transport=BackgroundThreadTransport
+ )
+ cloud_logger = logging.getLogger(LOGGER_NAME)
+ cloud_logger.addHandler(handler)
+ cloud_logger.warning(LOG_MESSAGE)
+ Config.CLIENT.flush_handlers()
+
+ proc = Process(target=subprocess_main)
+ proc.start()
+ proc.join()
+ entries = _list_entries(logger)
+ self.assertEqual(len(entries), 1)
+ self.assertEqual(entries[0].payload, LOG_MESSAGE)
+
def test_create_metric(self):
METRIC_NAME = "test-create-metric%s" % (_RESOURCE_ID,)
metric = Config.CLIENT.metric(
@@ -807,7 +937,7 @@ def _init_bigquery_dataset(self):
# Stackdriver Logging to write into it.
retry = RetryErrors((TooManyRequests, BadGateway, ServiceUnavailable))
bigquery_client = bigquery.Client()
- dataset_ref = bigquery_client.dataset(dataset_name)
+ dataset_ref = bigquery.DatasetReference(Config.CLIENT.project, dataset_name)
dataset = retry(bigquery_client.create_dataset)(bigquery.Dataset(dataset_ref))
self.to_delete.append((bigquery_client, dataset))
bigquery_client.get_dataset(dataset)
diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py
index e8e1c3845..cbf94b283 100644
--- a/tests/unit/__init__.py
+++ b/tests/unit/__init__.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/tests/unit/gapic/__init__.py b/tests/unit/gapic/__init__.py
index e8e1c3845..cbf94b283 100644
--- a/tests/unit/gapic/__init__.py
+++ b/tests/unit/gapic/__init__.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/tests/unit/gapic/logging_v2/__init__.py b/tests/unit/gapic/logging_v2/__init__.py
index e8e1c3845..cbf94b283 100644
--- a/tests/unit/gapic/logging_v2/__init__.py
+++ b/tests/unit/gapic/logging_v2/__init__.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
diff --git a/tests/unit/gapic/logging_v2/test_config_service_v2.py b/tests/unit/gapic/logging_v2/test_config_service_v2.py
index be77714c0..73a8f5d32 100644
--- a/tests/unit/gapic/logging_v2/test_config_service_v2.py
+++ b/tests/unit/gapic/logging_v2/test_config_service_v2.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -24,11 +24,20 @@
import grpc
from grpc.experimental import aio
+import json
import math
import pytest
+from google.api_core import api_core_version
from proto.marshal.rules.dates import DurationRule, TimestampRule
from proto.marshal.rules import wrappers
+try:
+ from google.auth.aio import credentials as ga_credentials_async
+
+ HAS_GOOGLE_AUTH_AIO = True
+except ImportError: # pragma: NO COVER
+ HAS_GOOGLE_AUTH_AIO = False
+
from google.api_core import client_options
from google.api_core import exceptions as core_exceptions
from google.api_core import future
@@ -39,6 +48,7 @@
from google.api_core import operation_async # type: ignore
from google.api_core import operations_v1
from google.api_core import path_template
+from google.api_core import retry as retries
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.logging_v2.services.config_service_v2 import (
@@ -48,17 +58,40 @@
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.types import logging_config
-from google.longrunning import operations_pb2
+from google.longrunning import operations_pb2 # type: ignore
from google.oauth2 import service_account
+from google.protobuf import empty_pb2 # type: ignore
from google.protobuf import field_mask_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
import google.auth
+CRED_INFO_JSON = {
+ "credential_source": "/path/to/file",
+ "credential_type": "service account credentials",
+ "principal": "service-account@example.com",
+}
+CRED_INFO_STRING = json.dumps(CRED_INFO_JSON)
+
+
+async def mock_async_gen(data, chunk_size=1):
+ for i in range(0, len(data)): # pragma: NO COVER
+ chunk = data[i : i + chunk_size]
+ yield chunk.encode("utf-8")
+
+
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
+# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
+# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
+def async_anonymous_credentials():
+ if HAS_GOOGLE_AUTH_AIO:
+ return ga_credentials_async.AnonymousCredentials()
+ return ga_credentials.AnonymousCredentials()
+
+
# 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.
@@ -70,6 +103,17 @@ def modify_default_endpoint(client):
)
+# If default endpoint template is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint template so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint_template(client):
+ return (
+ "test.{UNIVERSE_DOMAIN}"
+ if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE)
+ else client._DEFAULT_ENDPOINT_TEMPLATE
+ )
+
+
def test__get_default_mtls_endpoint():
api_endpoint = "example.googleapis.com"
api_mtls_endpoint = "example.mtls.googleapis.com"
@@ -99,6 +143,237 @@ def test__get_default_mtls_endpoint():
)
+def test__read_environment_variables():
+ assert ConfigServiceV2Client._read_environment_variables() == (False, "auto", None)
+
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ assert ConfigServiceV2Client._read_environment_variables() == (
+ True,
+ "auto",
+ None,
+ )
+
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}):
+ assert ConfigServiceV2Client._read_environment_variables() == (
+ False,
+ "auto",
+ None,
+ )
+
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}
+ ):
+ with pytest.raises(ValueError) as excinfo:
+ ConfigServiceV2Client._read_environment_variables()
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
+ )
+
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ assert ConfigServiceV2Client._read_environment_variables() == (
+ False,
+ "never",
+ None,
+ )
+
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ assert ConfigServiceV2Client._read_environment_variables() == (
+ False,
+ "always",
+ None,
+ )
+
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}):
+ assert ConfigServiceV2Client._read_environment_variables() == (
+ False,
+ "auto",
+ None,
+ )
+
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
+ with pytest.raises(MutualTLSChannelError) as excinfo:
+ ConfigServiceV2Client._read_environment_variables()
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
+ )
+
+ with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}):
+ assert ConfigServiceV2Client._read_environment_variables() == (
+ False,
+ "auto",
+ "foo.com",
+ )
+
+
+def test__get_client_cert_source():
+ mock_provided_cert_source = mock.Mock()
+ mock_default_cert_source = mock.Mock()
+
+ assert ConfigServiceV2Client._get_client_cert_source(None, False) is None
+ assert (
+ ConfigServiceV2Client._get_client_cert_source(mock_provided_cert_source, False)
+ is None
+ )
+ assert (
+ ConfigServiceV2Client._get_client_cert_source(mock_provided_cert_source, True)
+ == mock_provided_cert_source
+ )
+
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source", return_value=True
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=mock_default_cert_source,
+ ):
+ assert (
+ ConfigServiceV2Client._get_client_cert_source(None, True)
+ is mock_default_cert_source
+ )
+ assert (
+ ConfigServiceV2Client._get_client_cert_source(
+ mock_provided_cert_source, "true"
+ )
+ is mock_provided_cert_source
+ )
+
+
+@mock.patch.object(
+ ConfigServiceV2Client,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(ConfigServiceV2Client),
+)
+@mock.patch.object(
+ ConfigServiceV2AsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(ConfigServiceV2AsyncClient),
+)
+def test__get_api_endpoint():
+ api_override = "foo.com"
+ mock_client_cert_source = mock.Mock()
+ default_universe = ConfigServiceV2Client._DEFAULT_UNIVERSE
+ default_endpoint = ConfigServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=default_universe
+ )
+ mock_universe = "bar.com"
+ mock_endpoint = ConfigServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=mock_universe
+ )
+
+ assert (
+ ConfigServiceV2Client._get_api_endpoint(
+ api_override, mock_client_cert_source, default_universe, "always"
+ )
+ == api_override
+ )
+ assert (
+ ConfigServiceV2Client._get_api_endpoint(
+ None, mock_client_cert_source, default_universe, "auto"
+ )
+ == ConfigServiceV2Client.DEFAULT_MTLS_ENDPOINT
+ )
+ assert (
+ ConfigServiceV2Client._get_api_endpoint(None, None, default_universe, "auto")
+ == default_endpoint
+ )
+ assert (
+ ConfigServiceV2Client._get_api_endpoint(None, None, default_universe, "always")
+ == ConfigServiceV2Client.DEFAULT_MTLS_ENDPOINT
+ )
+ assert (
+ ConfigServiceV2Client._get_api_endpoint(
+ None, mock_client_cert_source, default_universe, "always"
+ )
+ == ConfigServiceV2Client.DEFAULT_MTLS_ENDPOINT
+ )
+ assert (
+ ConfigServiceV2Client._get_api_endpoint(None, None, mock_universe, "never")
+ == mock_endpoint
+ )
+ assert (
+ ConfigServiceV2Client._get_api_endpoint(None, None, default_universe, "never")
+ == default_endpoint
+ )
+
+ with pytest.raises(MutualTLSChannelError) as excinfo:
+ ConfigServiceV2Client._get_api_endpoint(
+ None, mock_client_cert_source, mock_universe, "auto"
+ )
+ assert (
+ str(excinfo.value)
+ == "mTLS is not supported in any universe other than googleapis.com."
+ )
+
+
+def test__get_universe_domain():
+ client_universe_domain = "foo.com"
+ universe_domain_env = "bar.com"
+
+ assert (
+ ConfigServiceV2Client._get_universe_domain(
+ client_universe_domain, universe_domain_env
+ )
+ == client_universe_domain
+ )
+ assert (
+ ConfigServiceV2Client._get_universe_domain(None, universe_domain_env)
+ == universe_domain_env
+ )
+ assert (
+ ConfigServiceV2Client._get_universe_domain(None, None)
+ == ConfigServiceV2Client._DEFAULT_UNIVERSE
+ )
+
+ with pytest.raises(ValueError) as excinfo:
+ ConfigServiceV2Client._get_universe_domain("", None)
+ assert str(excinfo.value) == "Universe Domain cannot be an empty string."
+
+
+@pytest.mark.parametrize(
+ "error_code,cred_info_json,show_cred_info",
+ [
+ (401, CRED_INFO_JSON, True),
+ (403, CRED_INFO_JSON, True),
+ (404, CRED_INFO_JSON, True),
+ (500, CRED_INFO_JSON, False),
+ (401, None, False),
+ (403, None, False),
+ (404, None, False),
+ (500, None, False),
+ ],
+)
+def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info):
+ cred = mock.Mock(["get_cred_info"])
+ cred.get_cred_info = mock.Mock(return_value=cred_info_json)
+ client = ConfigServiceV2Client(credentials=cred)
+ client._transport._credentials = cred
+
+ error = core_exceptions.GoogleAPICallError("message", details=["foo"])
+ error.code = error_code
+
+ client._add_cred_info_for_auth_errors(error)
+ if show_cred_info:
+ assert error.details == ["foo", CRED_INFO_STRING]
+ else:
+ assert error.details == ["foo"]
+
+
+@pytest.mark.parametrize("error_code", [401, 403, 404, 500])
+def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code):
+ cred = mock.Mock([])
+ assert not hasattr(cred, "get_cred_info")
+ client = ConfigServiceV2Client(credentials=cred)
+ client._transport._credentials = cred
+
+ error = core_exceptions.GoogleAPICallError("message", details=[])
+ error.code = error_code
+
+ client._add_cred_info_for_auth_errors(error)
+ assert error.details == []
+
+
@pytest.mark.parametrize(
"client_class,transport_name",
[
@@ -201,13 +476,13 @@ def test_config_service_v2_client_get_transport_class():
)
@mock.patch.object(
ConfigServiceV2Client,
- "DEFAULT_ENDPOINT",
- modify_default_endpoint(ConfigServiceV2Client),
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(ConfigServiceV2Client),
)
@mock.patch.object(
ConfigServiceV2AsyncClient,
- "DEFAULT_ENDPOINT",
- modify_default_endpoint(ConfigServiceV2AsyncClient),
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(ConfigServiceV2AsyncClient),
)
def test_config_service_v2_client_client_options(
client_class, transport_class, transport_name
@@ -249,7 +524,9 @@ def test_config_service_v2_client_client_options(
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
@@ -279,15 +556,23 @@ def test_config_service_v2_client_client_options(
# 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):
+ with pytest.raises(MutualTLSChannelError) as excinfo:
client = client_class(transport=transport_name)
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
+ )
# 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):
+ with pytest.raises(ValueError) as excinfo:
client = client_class(transport=transport_name)
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
+ )
# Check the case quota_project_id is provided
options = client_options.ClientOptions(quota_project_id="octopus")
@@ -297,7 +582,9 @@ def test_config_service_v2_client_client_options(
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id="octopus",
@@ -315,7 +602,9 @@ def test_config_service_v2_client_client_options(
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
@@ -356,13 +645,13 @@ def test_config_service_v2_client_client_options(
)
@mock.patch.object(
ConfigServiceV2Client,
- "DEFAULT_ENDPOINT",
- modify_default_endpoint(ConfigServiceV2Client),
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(ConfigServiceV2Client),
)
@mock.patch.object(
ConfigServiceV2AsyncClient,
- "DEFAULT_ENDPOINT",
- modify_default_endpoint(ConfigServiceV2AsyncClient),
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(ConfigServiceV2AsyncClient),
)
@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
def test_config_service_v2_client_mtls_env_auto(
@@ -385,7 +674,9 @@ def test_config_service_v2_client_mtls_env_auto(
if use_client_cert_env == "false":
expected_client_cert_source = None
- expected_host = client.DEFAULT_ENDPOINT
+ expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ )
else:
expected_client_cert_source = client_cert_source_callback
expected_host = client.DEFAULT_MTLS_ENDPOINT
@@ -417,7 +708,9 @@ def test_config_service_v2_client_mtls_env_auto(
return_value=client_cert_source_callback,
):
if use_client_cert_env == "false":
- expected_host = client.DEFAULT_ENDPOINT
+ expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ )
expected_client_cert_source = None
else:
expected_host = client.DEFAULT_MTLS_ENDPOINT
@@ -451,7 +744,9 @@ def test_config_service_v2_client_mtls_env_auto(
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
@@ -541,6 +836,115 @@ def test_config_service_v2_client_get_mtls_endpoint_and_cert_source(client_class
assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
assert cert_source == mock_client_cert_source
+ # 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) as excinfo:
+ client_class.get_mtls_endpoint_and_cert_source()
+
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
+ )
+
+ # 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) as excinfo:
+ client_class.get_mtls_endpoint_and_cert_source()
+
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class", [ConfigServiceV2Client, ConfigServiceV2AsyncClient]
+)
+@mock.patch.object(
+ ConfigServiceV2Client,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(ConfigServiceV2Client),
+)
+@mock.patch.object(
+ ConfigServiceV2AsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(ConfigServiceV2AsyncClient),
+)
+def test_config_service_v2_client_client_api_endpoint(client_class):
+ mock_client_cert_source = client_cert_source_callback
+ api_override = "foo.com"
+ default_universe = ConfigServiceV2Client._DEFAULT_UNIVERSE
+ default_endpoint = ConfigServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=default_universe
+ )
+ mock_universe = "bar.com"
+ mock_endpoint = ConfigServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=mock_universe
+ )
+
+ # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true",
+ # use ClientOptions.api_endpoint as the api endpoint regardless.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ with mock.patch(
+ "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source, api_endpoint=api_override
+ )
+ client = client_class(
+ client_options=options,
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert client.api_endpoint == api_override
+
+ # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ client = client_class(credentials=ga_credentials.AnonymousCredentials())
+ assert client.api_endpoint == default_endpoint
+
+ # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always",
+ # use the DEFAULT_MTLS_ENDPOINT as the api endpoint.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ client = client_class(credentials=ga_credentials.AnonymousCredentials())
+ assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
+
+ # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default),
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist,
+ # and ClientOptions.universe_domain="bar.com",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint.
+ options = client_options.ClientOptions()
+ universe_exists = hasattr(options, "universe_domain")
+ if universe_exists:
+ options = client_options.ClientOptions(universe_domain=mock_universe)
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ else:
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert client.api_endpoint == (
+ mock_endpoint if universe_exists else default_endpoint
+ )
+ assert client.universe_domain == (
+ mock_universe if universe_exists else default_universe
+ )
+
+ # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint.
+ options = client_options.ClientOptions()
+ if hasattr(options, "universe_domain"):
+ delattr(options, "universe_domain")
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert client.api_endpoint == default_endpoint
+
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
@@ -566,7 +970,9 @@ def test_config_service_v2_client_client_options_scopes(
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=["1", "2"],
client_cert_source_for_mtls=None,
quota_project_id=None,
@@ -605,7 +1011,9 @@ def test_config_service_v2_client_client_options_credentials_file(
patched.assert_called_once_with(
credentials=None,
credentials_file="credentials.json",
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
@@ -665,7 +1073,9 @@ def test_config_service_v2_client_create_channel_credentials_file(
patched.assert_called_once_with(
credentials=None,
credentials_file="credentials.json",
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
@@ -736,27 +1146,119 @@ def test_list_buckets(request_type, transport: str = "grpc"):
# 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()
+ request = logging_config.ListBucketsRequest()
+ assert args[0] == request
# 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_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.
+def test_list_buckets_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.ListBucketsRequest(
+ parent="parent_value",
+ page_token="page_token_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:
- client.list_buckets()
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_buckets(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.ListBucketsRequest()
+ assert args[0] == logging_config.ListBucketsRequest(
+ parent="parent_value",
+ page_token="page_token_value",
+ )
+
+
+def test_list_buckets_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.list_buckets in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.list_buckets] = mock_rpc
+ request = {}
+ client.list_buckets(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.list_buckets(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_list_buckets_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.list_buckets
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.list_buckets
+ ] = mock_rpc
+
+ request = {}
+ await client.list_buckets(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.list_buckets(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
@@ -764,7 +1266,7 @@ async def test_list_buckets_async(
transport: str = "grpc_asyncio", request_type=logging_config.ListBucketsRequest
):
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -785,7 +1287,8 @@ async def test_list_buckets_async(
# 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()
+ request = logging_config.ListBucketsRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListBucketsAsyncPager)
@@ -829,7 +1332,7 @@ def test_list_buckets_field_headers():
@pytest.mark.asyncio
async def test_list_buckets_field_headers_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -899,7 +1402,7 @@ def test_list_buckets_flattened_error():
@pytest.mark.asyncio
async def test_list_buckets_flattened_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -928,7 +1431,7 @@ async def test_list_buckets_flattened_async():
@pytest.mark.asyncio
async def test_list_buckets_flattened_error_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -942,7 +1445,7 @@ async def test_list_buckets_flattened_error_async():
def test_list_buckets_pager(transport_name: str = "grpc"):
client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport_name,
)
@@ -977,13 +1480,17 @@ def test_list_buckets_pager(transport_name: str = "grpc"):
RuntimeError,
)
- metadata = ()
- metadata = tuple(metadata) + (
+ expected_metadata = ()
+ retry = retries.Retry()
+ timeout = 5
+ expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_buckets(request={})
+ pager = client.list_buckets(request={}, retry=retry, timeout=timeout)
- assert pager._metadata == metadata
+ assert pager._metadata == expected_metadata
+ assert pager._retry == retry
+ assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -992,7 +1499,7 @@ def test_list_buckets_pager(transport_name: str = "grpc"):
def test_list_buckets_pages(transport_name: str = "grpc"):
client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport_name,
)
@@ -1034,7 +1541,7 @@ def test_list_buckets_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_buckets_async_pager():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1084,7 +1591,7 @@ async def test_list_buckets_async_pager():
@pytest.mark.asyncio
async def test_list_buckets_async_pages():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1120,9 +1627,11 @@ async def test_list_buckets_async_pages():
RuntimeError,
)
pages = []
- async for page_ in (
+ # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch`
+ # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372
+ async for page_ in ( # pragma: no branch
await client.list_buckets(request={})
- ).pages: # pragma: no branch
+ ).pages:
pages.append(page_)
for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
assert page_.raw_page.next_page_token == token
@@ -1154,6 +1663,7 @@ def test_get_bucket(request_type, transport: str = "grpc"):
retention_days=1512,
locked=True,
lifecycle_state=logging_config.LifecycleState.ACTIVE,
+ analytics_enabled=True,
restricted_fields=["restricted_fields_value"],
)
response = client.get_bucket(request)
@@ -1161,7 +1671,8 @@ def test_get_bucket(request_type, transport: str = "grpc"):
# 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()
+ request = logging_config.GetBucketRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, logging_config.LogBucket)
@@ -1170,48 +1681,137 @@ def test_get_bucket(request_type, transport: str = "grpc"):
assert response.retention_days == 1512
assert response.locked is True
assert response.lifecycle_state == logging_config.LifecycleState.ACTIVE
+ assert response.analytics_enabled is True
assert response.restricted_fields == ["restricted_fields_value"]
-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.
+def test_get_bucket_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.GetBucketRequest(
+ 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:
- client.get_bucket()
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_bucket(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.GetBucketRequest()
+ assert args[0] == logging_config.GetBucketRequest(
+ name="name_value",
+ )
-@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,
- )
+def test_get_bucket_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
- # 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()
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
- # 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,
+ # Ensure method has been cached
+ assert client._transport.get_bucket in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.get_bucket] = mock_rpc
+ request = {}
+ client.get_bucket(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_bucket(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_get_bucket_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.get_bucket
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.get_bucket
+ ] = mock_rpc
+
+ request = {}
+ await client.get_bucket(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.get_bucket(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_get_bucket_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.GetBucketRequest
+):
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ 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,
+ analytics_enabled=True,
restricted_fields=["restricted_fields_value"],
)
)
@@ -1220,7 +1820,8 @@ async def test_get_bucket_async(
# 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()
+ request = logging_config.GetBucketRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, logging_config.LogBucket)
@@ -1229,6 +1830,7 @@ async def test_get_bucket_async(
assert response.retention_days == 1512
assert response.locked is True
assert response.lifecycle_state == logging_config.LifecycleState.ACTIVE
+ assert response.analytics_enabled is True
assert response.restricted_fields == ["restricted_fields_value"]
@@ -1269,7 +1871,7 @@ def test_get_bucket_field_headers():
@pytest.mark.asyncio
async def test_get_bucket_field_headers_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1305,7 +1907,7 @@ async def test_get_bucket_field_headers_async():
dict,
],
)
-def test_create_bucket(request_type, transport: str = "grpc"):
+def test_create_bucket_async(request_type, transport: str = "grpc"):
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -1316,55 +1918,152 @@ def test_create_bucket(request_type, transport: str = "grpc"):
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:
+ with mock.patch.object(
+ type(client.transport.create_bucket_async), "__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,
- restricted_fields=["restricted_fields_value"],
- )
- response = client.create_bucket(request)
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+ response = client.create_bucket_async(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()
+ request = logging_config.CreateBucketRequest()
+ assert args[0] == request
# 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
- assert response.restricted_fields == ["restricted_fields_value"]
+ assert isinstance(response, future.Future)
-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.
+def test_create_bucket_async_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.CreateBucketRequest(
+ parent="parent_value",
+ bucket_id="bucket_id_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:
- client.create_bucket()
+ with mock.patch.object(
+ type(client.transport.create_bucket_async), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_bucket_async(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.CreateBucketRequest()
+ assert args[0] == logging_config.CreateBucketRequest(
+ parent="parent_value",
+ bucket_id="bucket_id_value",
+ )
+
+
+def test_create_bucket_async_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._transport.create_bucket_async in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.create_bucket_async
+ ] = mock_rpc
+ request = {}
+ client.create_bucket_async(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ # Operation methods call wrapper_fn to build a cached
+ # client._transport.operations_client instance on first rpc call.
+ # Subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ client.create_bucket_async(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
-async def test_create_bucket_async(
+async def test_create_bucket_async_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.create_bucket_async
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.create_bucket_async
+ ] = mock_rpc
+
+ request = {}
+ await client.create_bucket_async(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ # Operation methods call wrapper_fn to build a cached
+ # client._transport.operations_client instance on first rpc call.
+ # Subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ await client.create_bucket_async(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_create_bucket_async_async(
transport: str = "grpc_asyncio", request_type=logging_config.CreateBucketRequest
):
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -1373,41 +2072,31 @@ async def test_create_bucket_async(
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:
+ with mock.patch.object(
+ type(client.transport.create_bucket_async), "__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,
- restricted_fields=["restricted_fields_value"],
- )
+ operations_pb2.Operation(name="operations/spam")
)
- response = await client.create_bucket(request)
+ response = await client.create_bucket_async(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()
+ request = logging_config.CreateBucketRequest()
+ assert args[0] == request
# 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
- assert response.restricted_fields == ["restricted_fields_value"]
+ assert isinstance(response, future.Future)
@pytest.mark.asyncio
-async def test_create_bucket_async_from_dict():
- await test_create_bucket_async(request_type=dict)
+async def test_create_bucket_async_async_from_dict():
+ await test_create_bucket_async_async(request_type=dict)
-def test_create_bucket_field_headers():
+def test_create_bucket_async_field_headers():
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
)
@@ -1419,9 +2108,11 @@ def test_create_bucket_field_headers():
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)
+ with mock.patch.object(
+ type(client.transport.create_bucket_async), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+ client.create_bucket_async(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
@@ -1437,9 +2128,9 @@ def test_create_bucket_field_headers():
@pytest.mark.asyncio
-async def test_create_bucket_field_headers_async():
+async def test_create_bucket_async_field_headers_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1449,11 +2140,13 @@ async def test_create_bucket_field_headers_async():
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:
+ with mock.patch.object(
+ type(client.transport.create_bucket_async), "__call__"
+ ) as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- logging_config.LogBucket()
+ operations_pb2.Operation(name="operations/op")
)
- await client.create_bucket(request)
+ await client.create_bucket_async(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
@@ -1475,7 +2168,7 @@ async def test_create_bucket_field_headers_async():
dict,
],
)
-def test_update_bucket(request_type, transport: str = "grpc"):
+def test_update_bucket_async(request_type, transport: str = "grpc"):
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -1486,55 +2179,150 @@ def test_update_bucket(request_type, transport: str = "grpc"):
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:
+ with mock.patch.object(
+ type(client.transport.update_bucket_async), "__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,
- restricted_fields=["restricted_fields_value"],
- )
- response = client.update_bucket(request)
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+ response = client.update_bucket_async(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()
+ request = logging_config.UpdateBucketRequest()
+ assert args[0] == request
# 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
- assert response.restricted_fields == ["restricted_fields_value"]
+ assert isinstance(response, future.Future)
-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.
+def test_update_bucket_async_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.UpdateBucketRequest(
+ 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:
- client.update_bucket()
+ with mock.patch.object(
+ type(client.transport.update_bucket_async), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_bucket_async(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.UpdateBucketRequest()
+ assert args[0] == logging_config.UpdateBucketRequest(
+ name="name_value",
+ )
+
+
+def test_update_bucket_async_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._transport.update_bucket_async in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.update_bucket_async
+ ] = mock_rpc
+ request = {}
+ client.update_bucket_async(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ # Operation methods call wrapper_fn to build a cached
+ # client._transport.operations_client instance on first rpc call.
+ # Subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ client.update_bucket_async(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
-async def test_update_bucket_async(
+async def test_update_bucket_async_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.update_bucket_async
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.update_bucket_async
+ ] = mock_rpc
+
+ request = {}
+ await client.update_bucket_async(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ # Operation methods call wrapper_fn to build a cached
+ # client._transport.operations_client instance on first rpc call.
+ # Subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ await client.update_bucket_async(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_update_bucket_async_async(
transport: str = "grpc_asyncio", request_type=logging_config.UpdateBucketRequest
):
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -1543,41 +2331,31 @@ async def test_update_bucket_async(
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:
+ with mock.patch.object(
+ type(client.transport.update_bucket_async), "__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,
- restricted_fields=["restricted_fields_value"],
- )
+ operations_pb2.Operation(name="operations/spam")
)
- response = await client.update_bucket(request)
+ response = await client.update_bucket_async(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()
+ request = logging_config.UpdateBucketRequest()
+ assert args[0] == request
# 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
- assert response.restricted_fields == ["restricted_fields_value"]
+ assert isinstance(response, future.Future)
@pytest.mark.asyncio
-async def test_update_bucket_async_from_dict():
- await test_update_bucket_async(request_type=dict)
+async def test_update_bucket_async_async_from_dict():
+ await test_update_bucket_async_async(request_type=dict)
-def test_update_bucket_field_headers():
+def test_update_bucket_async_field_headers():
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
)
@@ -1589,9 +2367,11 @@ def test_update_bucket_field_headers():
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)
+ with mock.patch.object(
+ type(client.transport.update_bucket_async), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+ client.update_bucket_async(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
@@ -1607,9 +2387,9 @@ def test_update_bucket_field_headers():
@pytest.mark.asyncio
-async def test_update_bucket_field_headers_async():
+async def test_update_bucket_async_field_headers_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1619,11 +2399,13 @@ async def test_update_bucket_field_headers_async():
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:
+ with mock.patch.object(
+ type(client.transport.update_bucket_async), "__call__"
+ ) as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- logging_config.LogBucket()
+ operations_pb2.Operation(name="operations/op")
)
- await client.update_bucket(request)
+ await client.update_bucket_async(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
@@ -1641,11 +2423,11 @@ async def test_update_bucket_field_headers_async():
@pytest.mark.parametrize(
"request_type",
[
- logging_config.DeleteBucketRequest,
+ logging_config.CreateBucketRequest,
dict,
],
)
-def test_delete_bucket(request_type, transport: str = "grpc"):
+def test_create_bucket(request_type, transport: str = "grpc"):
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -1656,42 +2438,149 @@ def test_delete_bucket(request_type, transport: str = "grpc"):
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:
+ with mock.patch.object(type(client.transport.create_bucket), "__call__") as call:
# Designate an appropriate return value for the call.
- call.return_value = None
- response = client.delete_bucket(request)
+ call.return_value = logging_config.LogBucket(
+ name="name_value",
+ description="description_value",
+ retention_days=1512,
+ locked=True,
+ lifecycle_state=logging_config.LifecycleState.ACTIVE,
+ analytics_enabled=True,
+ restricted_fields=["restricted_fields_value"],
+ )
+ 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.DeleteBucketRequest()
+ request = logging_config.CreateBucketRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
- assert response is None
+ 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
+ assert response.analytics_enabled is True
+ assert response.restricted_fields == ["restricted_fields_value"]
-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.
+def test_create_bucket_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.CreateBucketRequest(
+ parent="parent_value",
+ bucket_id="bucket_id_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:
- client.delete_bucket()
+ with mock.patch.object(type(client.transport.create_bucket), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_bucket(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.DeleteBucketRequest()
+ assert args[0] == logging_config.CreateBucketRequest(
+ parent="parent_value",
+ bucket_id="bucket_id_value",
+ )
+
+
+def test_create_bucket_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.create_bucket in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.create_bucket] = mock_rpc
+ request = {}
+ client.create_bucket(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.create_bucket(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
-async def test_delete_bucket_async(
- transport: str = "grpc_asyncio", request_type=logging_config.DeleteBucketRequest
+async def test_create_bucket_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.create_bucket
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.create_bucket
+ ] = mock_rpc
+
+ request = {}
+ await client.create_bucket(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.create_bucket(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_create_bucket_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.CreateBucketRequest
):
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -1700,40 +2589,58 @@ async def test_delete_bucket_async(
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:
+ 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(None)
- response = await client.delete_bucket(request)
+ 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,
+ analytics_enabled=True,
+ restricted_fields=["restricted_fields_value"],
+ )
+ )
+ 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.DeleteBucketRequest()
+ request = logging_config.CreateBucketRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
- assert response is None
+ 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
+ assert response.analytics_enabled is True
+ assert response.restricted_fields == ["restricted_fields_value"]
@pytest.mark.asyncio
-async def test_delete_bucket_async_from_dict():
- await test_delete_bucket_async(request_type=dict)
+async def test_create_bucket_async_from_dict():
+ await test_create_bucket_async(request_type=dict)
-def test_delete_bucket_field_headers():
+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.DeleteBucketRequest()
+ request = logging_config.CreateBucketRequest()
- request.name = "name_value"
+ request.parent = "parent_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)
+ 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
@@ -1744,26 +2651,28 @@ def test_delete_bucket_field_headers():
_, _, kw = call.mock_calls[0]
assert (
"x-goog-request-params",
- "name=name_value",
+ "parent=parent_value",
) in kw["metadata"]
@pytest.mark.asyncio
-async def test_delete_bucket_field_headers_async():
+async def test_create_bucket_field_headers_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# 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 = logging_config.CreateBucketRequest()
- request.name = "name_value"
+ request.parent = "parent_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)
+ 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)
@@ -1774,18 +2683,18 @@ async def test_delete_bucket_field_headers_async():
_, _, kw = call.mock_calls[0]
assert (
"x-goog-request-params",
- "name=name_value",
+ "parent=parent_value",
) in kw["metadata"]
@pytest.mark.parametrize(
"request_type",
[
- logging_config.UndeleteBucketRequest,
+ logging_config.UpdateBucketRequest,
dict,
],
)
-def test_undelete_bucket(request_type, transport: str = "grpc"):
+def test_update_bucket(request_type, transport: str = "grpc"):
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -1796,42 +2705,147 @@ def test_undelete_bucket(request_type, transport: str = "grpc"):
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:
+ with mock.patch.object(type(client.transport.update_bucket), "__call__") as call:
# Designate an appropriate return value for the call.
- call.return_value = None
- response = client.undelete_bucket(request)
+ call.return_value = logging_config.LogBucket(
+ name="name_value",
+ description="description_value",
+ retention_days=1512,
+ locked=True,
+ lifecycle_state=logging_config.LifecycleState.ACTIVE,
+ analytics_enabled=True,
+ restricted_fields=["restricted_fields_value"],
+ )
+ 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.UndeleteBucketRequest()
+ request = logging_config.UpdateBucketRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
- assert response is None
+ 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
+ assert response.analytics_enabled is True
+ assert response.restricted_fields == ["restricted_fields_value"]
-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.
+def test_update_bucket_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.UpdateBucketRequest(
+ 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:
- client.undelete_bucket()
+ with mock.patch.object(type(client.transport.update_bucket), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_bucket(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.UndeleteBucketRequest()
+ assert args[0] == logging_config.UpdateBucketRequest(
+ name="name_value",
+ )
+
+
+def test_update_bucket_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.update_bucket in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.update_bucket] = mock_rpc
+ request = {}
+ client.update_bucket(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_bucket(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
-async def test_undelete_bucket_async(
- transport: str = "grpc_asyncio", request_type=logging_config.UndeleteBucketRequest
+async def test_update_bucket_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.update_bucket
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.update_bucket
+ ] = mock_rpc
+
+ request = {}
+ await client.update_bucket(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.update_bucket(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_update_bucket_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.UpdateBucketRequest
):
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -1840,40 +2854,58 @@ async def test_undelete_bucket_async(
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:
+ 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(None)
- response = await client.undelete_bucket(request)
+ 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,
+ analytics_enabled=True,
+ restricted_fields=["restricted_fields_value"],
+ )
+ )
+ 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.UndeleteBucketRequest()
+ request = logging_config.UpdateBucketRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
- assert response is None
+ 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
+ assert response.analytics_enabled is True
+ assert response.restricted_fields == ["restricted_fields_value"]
@pytest.mark.asyncio
-async def test_undelete_bucket_async_from_dict():
- await test_undelete_bucket_async(request_type=dict)
+async def test_update_bucket_async_from_dict():
+ await test_update_bucket_async(request_type=dict)
-def test_undelete_bucket_field_headers():
+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.UndeleteBucketRequest()
+ 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.undelete_bucket), "__call__") as call:
- call.return_value = None
- client.undelete_bucket(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
@@ -1889,21 +2921,23 @@ def test_undelete_bucket_field_headers():
@pytest.mark.asyncio
-async def test_undelete_bucket_field_headers_async():
+async def test_update_bucket_field_headers_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# 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 = 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.undelete_bucket), "__call__") as call:
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
- await client.undelete_bucket(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)
@@ -1921,11 +2955,11 @@ async def test_undelete_bucket_field_headers_async():
@pytest.mark.parametrize(
"request_type",
[
- logging_config.ListViewsRequest,
+ logging_config.DeleteBucketRequest,
dict,
],
)
-def test_list_views(request_type, transport: str = "grpc"):
+def test_delete_bucket(request_type, transport: str = "grpc"):
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -1936,45 +2970,132 @@ def test_list_views(request_type, transport: str = "grpc"):
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:
+ with mock.patch.object(type(client.transport.delete_bucket), "__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)
+ 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.ListViewsRequest()
+ request = logging_config.DeleteBucketRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListViewsPager)
- assert response.next_page_token == "next_page_token_value"
+ assert response is None
-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.
+def test_delete_bucket_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.DeleteBucketRequest(
+ name="name_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:
- client.list_views()
+ with mock.patch.object(type(client.transport.delete_bucket), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_bucket(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.ListViewsRequest()
+ assert args[0] == logging_config.DeleteBucketRequest(
+ name="name_value",
+ )
+
+
+def test_delete_bucket_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.delete_bucket in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.delete_bucket] = mock_rpc
+ request = {}
+ client.delete_bucket(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.delete_bucket(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
-async def test_list_views_async(
- transport: str = "grpc_asyncio", request_type=logging_config.ListViewsRequest
+async def test_delete_bucket_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.delete_bucket
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.delete_bucket
+ ] = mock_rpc
+
+ request = {}
+ await client.delete_bucket(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.delete_bucket(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_delete_bucket_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.DeleteBucketRequest
):
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -1983,45 +3104,41 @@ async def test_list_views_async(
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:
+ 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(
- logging_config.ListViewsResponse(
- next_page_token="next_page_token_value",
- )
- )
- response = await client.list_views(request)
+ 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.ListViewsRequest()
+ request = logging_config.DeleteBucketRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListViewsAsyncPager)
- assert response.next_page_token == "next_page_token_value"
+ assert response is None
@pytest.mark.asyncio
-async def test_list_views_async_from_dict():
- await test_list_views_async(request_type=dict)
+async def test_delete_bucket_async_from_dict():
+ await test_delete_bucket_async(request_type=dict)
-def test_list_views_field_headers():
+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.ListViewsRequest()
+ request = logging_config.DeleteBucketRequest()
- request.parent = "parent_value"
+ request.name = "name_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)
+ 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
@@ -2032,28 +3149,26 @@ def test_list_views_field_headers():
_, _, kw = call.mock_calls[0]
assert (
"x-goog-request-params",
- "parent=parent_value",
+ "name=name_value",
) in kw["metadata"]
@pytest.mark.asyncio
-async def test_list_views_field_headers_async():
+async def test_delete_bucket_field_headers_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# 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 = logging_config.DeleteBucketRequest()
- request.parent = "parent_value"
+ request.name = "name_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)
+ 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)
@@ -2064,392 +3179,197 @@ async def test_list_views_field_headers_async():
_, _, kw = call.mock_calls[0]
assert (
"x-goog-request-params",
- "parent=parent_value",
+ "name=name_value",
) in kw["metadata"]
-def test_list_views_flattened():
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ logging_config.UndeleteBucketRequest,
+ dict,
+ ],
+)
+def test_undelete_bucket(request_type, transport: str = "grpc"):
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:
+ with mock.patch.object(type(client.transport.undelete_bucket), "__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",
- )
+ call.return_value = None
+ response = client.undelete_bucket(request)
- # Establish that the underlying call was made with the expected
- # request object values.
+ # Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
- arg = args[0].parent
- mock_val = "parent_value"
- assert arg == mock_val
+ request = logging_config.UndeleteBucketRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert response is None
-def test_list_views_flattened_error():
+def test_undelete_bucket_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
)
- # 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(),
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.UndeleteBucketRequest(
+ name="name_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:
- # Designate an appropriate return value for the call.
- call.return_value = logging_config.ListViewsResponse()
-
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- logging_config.ListViewsResponse()
+ with mock.patch.object(type(client.transport.undelete_bucket), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
)
- # 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",
+ client.undelete_bucket(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == logging_config.UndeleteBucketRequest(
+ 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]
- arg = args[0].parent
- mock_val = "parent_value"
- assert arg == mock_val
+def test_undelete_bucket_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
-@pytest.mark.asyncio
-async def test_list_views_flattened_error_async():
- client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
- )
+ # Ensure method has been cached
+ assert client._transport.undelete_bucket in client._transport._wrapped_methods
- # 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",
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
)
+ client._transport._wrapped_methods[client._transport.undelete_bucket] = mock_rpc
+ request = {}
+ client.undelete_bucket(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
-def test_list_views_pager(transport_name: str = "grpc"):
- client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials,
- transport=transport_name,
- )
+ client.undelete_bucket(request)
- # 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,
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_undelete_bucket_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
)
- metadata = ()
- metadata = tuple(metadata) + (
- gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.undelete_bucket
+ in client._client._transport._wrapped_methods
)
- pager = client.list_views(request={})
- assert pager._metadata == metadata
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.undelete_bucket
+ ] = mock_rpc
- results = list(pager)
- assert len(results) == 6
- assert all(isinstance(i, logging_config.LogView) for i in results)
+ request = {}
+ await client.undelete_bucket(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
-def test_list_views_pages(transport_name: str = "grpc"):
- client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials,
- transport=transport_name,
+ await client.undelete_bucket(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_undelete_bucket_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.UndeleteBucketRequest
+):
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ 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:
- # 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: # pragma: no branch
- 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: # pragma: no branch
- pages.append(page_)
- for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
- assert page_.raw_page.next_page_token == token
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- logging_config.GetViewRequest,
- dict,
- ],
-)
-def test_get_view(request_type, transport: str = "grpc"):
- 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_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:
+ 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(
- logging_config.LogView(
- name="name_value",
- description="description_value",
- filter="filter_value",
- )
- )
- response = await client.get_view(request)
+ 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.GetViewRequest()
+ request = logging_config.UndeleteBucketRequest()
+ assert args[0] == request
# 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"
+ assert response is None
@pytest.mark.asyncio
-async def test_get_view_async_from_dict():
- await test_get_view_async(request_type=dict)
+async def test_undelete_bucket_async_from_dict():
+ await test_undelete_bucket_async(request_type=dict)
-def test_get_view_field_headers():
+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.GetViewRequest()
+ 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.get_view), "__call__") as call:
- call.return_value = logging_config.LogView()
- client.get_view(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
@@ -2465,23 +3385,21 @@ def test_get_view_field_headers():
@pytest.mark.asyncio
-async def test_get_view_field_headers_async():
+async def test_undelete_bucket_field_headers_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# 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 = 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.get_view), "__call__") as call:
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- logging_config.LogView()
- )
- await client.get_view(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)
@@ -2499,11 +3417,11 @@ async def test_get_view_field_headers_async():
@pytest.mark.parametrize(
"request_type",
[
- logging_config.CreateViewRequest,
+ logging_config.ListViewsRequest,
dict,
],
)
-def test_create_view(request_type, transport: str = "grpc"):
+def test_list_views(request_type, transport: str = "grpc"):
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -2514,49 +3432,135 @@ def test_create_view(request_type, transport: str = "grpc"):
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:
+ 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.LogView(
- name="name_value",
- description="description_value",
- filter="filter_value",
+ call.return_value = logging_config.ListViewsResponse(
+ next_page_token="next_page_token_value",
)
- response = client.create_view(request)
+ 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.CreateViewRequest()
+ request = logging_config.ListViewsRequest()
+ assert args[0] == request
# 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"
+ assert isinstance(response, pagers.ListViewsPager)
+ assert response.next_page_token == "next_page_token_value"
-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.
+def test_list_views_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.ListViewsRequest(
+ parent="parent_value",
+ page_token="page_token_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:
- client.create_view()
+ with mock.patch.object(type(client.transport.list_views), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_views(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.CreateViewRequest()
+ assert args[0] == logging_config.ListViewsRequest(
+ parent="parent_value",
+ page_token="page_token_value",
+ )
+
+
+def test_list_views_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.list_views in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.list_views] = mock_rpc
+ request = {}
+ client.list_views(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.list_views(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
-async def test_create_view_async(
- transport: str = "grpc_asyncio", request_type=logging_config.CreateViewRequest
+async def test_list_views_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.list_views
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.list_views
+ ] = mock_rpc
+
+ request = {}
+ await client.list_views(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.list_views(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_list_views_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.ListViewsRequest
):
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -2565,49 +3569,46 @@ async def test_create_view_async(
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:
+ 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.LogView(
- name="name_value",
- description="description_value",
- filter="filter_value",
+ logging_config.ListViewsResponse(
+ next_page_token="next_page_token_value",
)
)
- response = await client.create_view(request)
+ 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.CreateViewRequest()
+ request = logging_config.ListViewsRequest()
+ assert args[0] == request
# 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"
+ assert isinstance(response, pagers.ListViewsAsyncPager)
+ assert response.next_page_token == "next_page_token_value"
@pytest.mark.asyncio
-async def test_create_view_async_from_dict():
- await test_create_view_async(request_type=dict)
+async def test_list_views_async_from_dict():
+ await test_list_views_async(request_type=dict)
-def test_create_view_field_headers():
+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.CreateViewRequest()
+ 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.create_view), "__call__") as call:
- call.return_value = logging_config.LogView()
- client.create_view(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
@@ -2623,23 +3624,23 @@ def test_create_view_field_headers():
@pytest.mark.asyncio
-async def test_create_view_field_headers_async():
+async def test_list_views_field_headers_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# 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 = 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.create_view), "__call__") as call:
+ with mock.patch.object(type(client.transport.list_views), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- logging_config.LogView()
+ logging_config.ListViewsResponse()
)
- await client.create_view(request)
+ await client.list_views(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
@@ -2654,172 +3655,290 @@ async def test_create_view_field_headers_async():
) in kw["metadata"]
-@pytest.mark.parametrize(
- "request_type",
- [
- logging_config.UpdateViewRequest,
- dict,
- ],
-)
-def test_update_view(request_type, transport: str = "grpc"):
+def test_list_views_flattened():
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:
+ 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.LogView(
- name="name_value",
- description="description_value",
- filter="filter_value",
+ 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",
)
- response = client.update_view(request)
- # Establish that the underlying gRPC stub method was called.
+ # 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] == 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"
+ arg = args[0].parent
+ mock_val = "parent_value"
+ assert arg == mock_val
-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.
+def test_list_views_flattened_error():
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()
+ # 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_update_view_async(
- transport: str = "grpc_asyncio", request_type=logging_config.UpdateViewRequest
-):
+async def test_list_views_flattened_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+ credentials=async_anonymous_credentials(),
)
- # 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:
+ 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.LogView(
- name="name_value",
- description="description_value",
- filter="filter_value",
- )
+ 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",
)
- response = await client.update_view(request)
- # Establish that the underlying gRPC stub method was called.
+ # 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] == 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"
+ arg = args[0].parent
+ mock_val = "parent_value"
+ assert arg == mock_val
@pytest.mark.asyncio
-async def test_update_view_async_from_dict():
- await test_update_view_async(request_type=dict)
+async def test_list_views_flattened_error_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # 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_update_view_field_headers():
+def test_list_views_pager(transport_name: str = "grpc"):
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport_name,
)
- # 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)
+ 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,
+ )
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0] == request
+ expected_metadata = ()
+ retry = retries.Retry()
+ timeout = 5
+ expected_metadata = tuple(expected_metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.list_views(request={}, retry=retry, timeout=timeout)
- # Establish that the field header was sent.
- _, _, kw = call.mock_calls[0]
- assert (
- "x-goog-request-params",
- "name=name_value",
- ) in kw["metadata"]
+ assert pager._metadata == expected_metadata
+ assert pager._retry == retry
+ assert pager._timeout == timeout
+
+ results = list(pager)
+ assert len(results) == 6
+ assert all(isinstance(i, logging_config.LogView) for i in results)
-@pytest.mark.asyncio
-async def test_update_view_field_headers_async():
- client = ConfigServiceV2AsyncClient(
+def test_list_views_pages(transport_name: str = "grpc"):
+ client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport_name,
)
- # 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()
+ 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,
)
- await client.update_view(request)
+ pages = list(client.list_views(request={}).pages)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls)
- _, args, _ = call.mock_calls[0]
- assert args[0] == request
- # Establish that the field header was sent.
- _, _, kw = call.mock_calls[0]
- assert (
- "x-goog-request-params",
- "name=name_value",
- ) in kw["metadata"]
+@pytest.mark.asyncio
+async def test_list_views_async_pager():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # 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: # pragma: no branch
+ 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=async_anonymous_credentials(),
+ )
+
+ # 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 = []
+ # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch`
+ # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372
+ async for page_ in ( # pragma: no branch
+ 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
@pytest.mark.parametrize(
"request_type",
[
- logging_config.DeleteViewRequest,
+ logging_config.GetViewRequest,
dict,
],
)
-def test_delete_view(request_type, transport: str = "grpc"):
+def test_get_view(request_type, transport: str = "grpc"):
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -2830,42 +3949,137 @@ def test_delete_view(request_type, transport: str = "grpc"):
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:
+ with mock.patch.object(type(client.transport.get_view), "__call__") as call:
# Designate an appropriate return value for the call.
- call.return_value = None
- response = client.delete_view(request)
+ 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.DeleteViewRequest()
+ request = logging_config.GetViewRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
- assert response is None
+ assert isinstance(response, logging_config.LogView)
+ assert response.name == "name_value"
+ assert response.description == "description_value"
+ assert response.filter == "filter_value"
-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.
+def test_get_view_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.GetViewRequest(
+ 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:
- client.delete_view()
+ with mock.patch.object(type(client.transport.get_view), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_view(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.DeleteViewRequest()
+ assert args[0] == logging_config.GetViewRequest(
+ name="name_value",
+ )
+
+
+def test_get_view_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.get_view in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.get_view] = mock_rpc
+ request = {}
+ client.get_view(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_view(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
-async def test_delete_view_async(
- transport: str = "grpc_asyncio", request_type=logging_config.DeleteViewRequest
+async def test_get_view_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.get_view
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.get_view
+ ] = mock_rpc
+
+ request = {}
+ await client.get_view(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.get_view(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_get_view_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.GetViewRequest
):
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -2874,40 +4088,50 @@ async def test_delete_view_async(
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:
+ 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(None)
- response = await client.delete_view(request)
+ 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.DeleteViewRequest()
+ request = logging_config.GetViewRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
- assert response is None
+ 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_delete_view_async_from_dict():
- await test_delete_view_async(request_type=dict)
+async def test_get_view_async_from_dict():
+ await test_get_view_async(request_type=dict)
-def test_delete_view_field_headers():
+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.DeleteViewRequest()
+ 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.delete_view), "__call__") as call:
- call.return_value = None
- client.delete_view(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
@@ -2923,21 +4147,23 @@ def test_delete_view_field_headers():
@pytest.mark.asyncio
-async def test_delete_view_field_headers_async():
+async def test_get_view_field_headers_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# 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 = 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.delete_view), "__call__") as call:
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
- await client.delete_view(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)
@@ -2955,11 +4181,11 @@ async def test_delete_view_field_headers_async():
@pytest.mark.parametrize(
"request_type",
[
- logging_config.ListSinksRequest,
+ logging_config.CreateViewRequest,
dict,
],
)
-def test_list_sinks(request_type, transport: str = "grpc"):
+def test_create_view(request_type, transport: str = "grpc"):
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -2970,45 +4196,141 @@ def test_list_sinks(request_type, transport: str = "grpc"):
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:
+ 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.ListSinksResponse(
- next_page_token="next_page_token_value",
+ call.return_value = logging_config.LogView(
+ name="name_value",
+ description="description_value",
+ filter="filter_value",
)
- response = client.list_sinks(request)
+ 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.ListSinksRequest()
+ request = logging_config.CreateViewRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListSinksPager)
- assert response.next_page_token == "next_page_token_value"
+ assert isinstance(response, logging_config.LogView)
+ assert response.name == "name_value"
+ assert response.description == "description_value"
+ assert response.filter == "filter_value"
-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.
+def test_create_view_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.CreateViewRequest(
+ parent="parent_value",
+ view_id="view_id_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:
- client.list_sinks()
+ with mock.patch.object(type(client.transport.create_view), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_view(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.ListSinksRequest()
+ assert args[0] == logging_config.CreateViewRequest(
+ parent="parent_value",
+ view_id="view_id_value",
+ )
+
+
+def test_create_view_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.create_view in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.create_view] = mock_rpc
+ request = {}
+ client.create_view(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.create_view(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
-async def test_list_sinks_async(
- transport: str = "grpc_asyncio", request_type=logging_config.ListSinksRequest
+async def test_create_view_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.create_view
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.create_view
+ ] = mock_rpc
+
+ request = {}
+ await client.create_view(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.create_view(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_create_view_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.CreateViewRequest
):
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -3017,45 +4339,50 @@ async def test_list_sinks_async(
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:
+ 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.ListSinksResponse(
- next_page_token="next_page_token_value",
+ logging_config.LogView(
+ name="name_value",
+ description="description_value",
+ filter="filter_value",
)
)
- response = await client.list_sinks(request)
+ 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.ListSinksRequest()
+ request = logging_config.CreateViewRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListSinksAsyncPager)
- assert response.next_page_token == "next_page_token_value"
+ 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_list_sinks_async_from_dict():
- await test_list_sinks_async(request_type=dict)
+async def test_create_view_async_from_dict():
+ await test_create_view_async(request_type=dict)
-def test_list_sinks_field_headers():
+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.ListSinksRequest()
+ 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.list_sinks), "__call__") as call:
- call.return_value = logging_config.ListSinksResponse()
- client.list_sinks(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
@@ -3071,23 +4398,23 @@ def test_list_sinks_field_headers():
@pytest.mark.asyncio
-async def test_list_sinks_field_headers_async():
+async def test_create_view_field_headers_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# 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 = 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.list_sinks), "__call__") as call:
+ with mock.patch.object(type(client.transport.create_view), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- logging_config.ListSinksResponse()
+ logging_config.LogView()
)
- await client.list_sinks(request)
+ await client.create_view(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
@@ -3102,411 +4429,209 @@ async def test_list_sinks_field_headers_async():
) in kw["metadata"]
-def test_list_sinks_flattened():
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ logging_config.UpdateViewRequest,
+ dict,
+ ],
+)
+def test_update_view(request_type, transport: str = "grpc"):
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:
+ 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.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",
+ call.return_value = logging_config.LogView(
+ name="name_value",
+ description="description_value",
+ filter="filter_value",
)
+ response = client.update_view(request)
- # Establish that the underlying call was made with the expected
- # request object values.
+ # Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
- arg = args[0].parent
- mock_val = "parent_value"
- assert arg == mock_val
+ request = logging_config.UpdateViewRequest()
+ assert args[0] == request
+
+ # 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_list_sinks_flattened_error():
+def test_update_view_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
)
- # 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(),
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.UpdateViewRequest(
+ name="name_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:
- # Designate an appropriate return value for the call.
- call.return_value = logging_config.ListSinksResponse()
-
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- logging_config.ListSinksResponse()
+ with mock.patch.object(type(client.transport.update_view), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
)
- # 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",
+ client.update_view(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == logging_config.UpdateViewRequest(
+ 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]
- arg = args[0].parent
- mock_val = "parent_value"
- assert arg == mock_val
+def test_update_view_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
-@pytest.mark.asyncio
-async def test_list_sinks_flattened_error_async():
- client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
- )
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
- # 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",
+ # Ensure method has been cached
+ assert client._transport.update_view in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
)
+ client._transport._wrapped_methods[client._transport.update_view] = mock_rpc
+ request = {}
+ client.update_view(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
-def test_list_sinks_pager(transport_name: str = "grpc"):
- client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials,
- transport=transport_name,
- )
+ client.update_view(request)
- # 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,
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_update_view_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
)
- metadata = ()
- metadata = tuple(metadata) + (
- gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.update_view
+ in client._client._transport._wrapped_methods
)
- pager = client.list_sinks(request={})
- assert pager._metadata == metadata
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.update_view
+ ] = mock_rpc
- results = list(pager)
- assert len(results) == 6
- assert all(isinstance(i, logging_config.LogSink) for i in results)
+ request = {}
+ await client.update_view(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
-def test_list_sinks_pages(transport_name: str = "grpc"):
- client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials,
- transport=transport_name,
+ await client.update_view(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_update_view_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.UpdateViewRequest
+):
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ 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:
- # 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: # pragma: no branch
- 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: # pragma: no branch
- pages.append(page_)
- for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
- assert page_.raw_page.next_page_token == token
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- logging_config.GetSinkRequest,
- dict,
- ],
-)
-def test_get_sink(request_type, transport: str = "grpc"):
- 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_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:
+ 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.LogSink(
+ logging_config.LogView(
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,
+ filter="filter_value",
)
)
- response = await client.get_sink(request)
+ 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.GetSinkRequest()
+ request = logging_config.UpdateViewRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
- assert isinstance(response, logging_config.LogSink)
+ assert isinstance(response, logging_config.LogView)
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
+ assert response.filter == "filter_value"
@pytest.mark.asyncio
-async def test_get_sink_async_from_dict():
- await test_get_sink_async(request_type=dict)
+async def test_update_view_async_from_dict():
+ await test_update_view_async(request_type=dict)
-def test_get_sink_field_headers():
+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.GetSinkRequest()
+ request = logging_config.UpdateViewRequest()
- request.sink_name = "sink_name_value"
+ request.name = "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)
+ 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
@@ -3517,28 +4642,28 @@ def test_get_sink_field_headers():
_, _, kw = call.mock_calls[0]
assert (
"x-goog-request-params",
- "sink_name=sink_name_value",
+ "name=name_value",
) in kw["metadata"]
@pytest.mark.asyncio
-async def test_get_sink_field_headers_async():
+async def test_update_view_field_headers_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# 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 = logging_config.UpdateViewRequest()
- request.sink_name = "sink_name_value"
+ request.name = "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:
+ with mock.patch.object(type(client.transport.update_view), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- logging_config.LogSink()
+ logging_config.LogView()
)
- await client.get_sink(request)
+ await client.update_view(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
@@ -3549,100 +4674,18 @@ async def test_get_sink_field_headers_async():
_, _, kw = call.mock_calls[0]
assert (
"x-goog-request-params",
- "sink_name=sink_name_value",
+ "name=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]
- arg = args[0].sink_name
- mock_val = "sink_name_value"
- assert arg == mock_val
-
-
-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]
- arg = args[0].sink_name
- mock_val = "sink_name_value"
- assert arg == mock_val
-
-
-@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",
- )
-
-
@pytest.mark.parametrize(
"request_type",
[
- logging_config.CreateSinkRequest,
+ logging_config.DeleteViewRequest,
dict,
],
)
-def test_create_sink(request_type, transport: str = "grpc"):
+def test_delete_view(request_type, transport: str = "grpc"):
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -3653,62 +4696,132 @@ def test_create_sink(request_type, transport: str = "grpc"):
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:
+ with mock.patch.object(type(client.transport.delete_view), "__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)
+ 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.CreateSinkRequest()
+ request = logging_config.DeleteViewRequest()
+ assert args[0] == request
# 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
+ assert response is None
-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.
+def test_delete_view_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.DeleteViewRequest(
+ name="name_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:
- client.create_sink()
+ with mock.patch.object(type(client.transport.delete_view), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_view(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.CreateSinkRequest()
+ assert args[0] == logging_config.DeleteViewRequest(
+ name="name_value",
+ )
+
+
+def test_delete_view_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.delete_view in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.delete_view] = mock_rpc
+ request = {}
+ client.delete_view(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.delete_view(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
-async def test_create_sink_async(
- transport: str = "grpc_asyncio", request_type=logging_config.CreateSinkRequest
+async def test_delete_view_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.delete_view
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.delete_view
+ ] = mock_rpc
+
+ request = {}
+ await client.delete_view(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.delete_view(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_delete_view_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.DeleteViewRequest
):
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -3717,59 +4830,41 @@ async def test_create_sink_async(
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:
+ 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(
- 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)
+ 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.CreateSinkRequest()
+ request = logging_config.DeleteViewRequest()
+ assert args[0] == request
# 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
+ assert response is None
@pytest.mark.asyncio
-async def test_create_sink_async_from_dict():
- await test_create_sink_async(request_type=dict)
+async def test_delete_view_async_from_dict():
+ await test_delete_view_async(request_type=dict)
-def test_create_sink_field_headers():
+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.CreateSinkRequest()
+ request = logging_config.DeleteViewRequest()
- request.parent = "parent_value"
+ request.name = "name_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)
+ 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
@@ -3780,28 +4875,26 @@ def test_create_sink_field_headers():
_, _, kw = call.mock_calls[0]
assert (
"x-goog-request-params",
- "parent=parent_value",
+ "name=name_value",
) in kw["metadata"]
@pytest.mark.asyncio
-async def test_create_sink_field_headers_async():
+async def test_delete_view_field_headers_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# 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 = logging_config.DeleteViewRequest()
- request.parent = "parent_value"
+ request.name = "name_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)
+ 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)
@@ -3812,176 +4905,157 @@ async def test_create_sink_field_headers_async():
_, _, kw = call.mock_calls[0]
assert (
"x-goog-request-params",
- "parent=parent_value",
+ "name=name_value",
) in kw["metadata"]
-def test_create_sink_flattened():
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ logging_config.ListSinksRequest,
+ dict,
+ ],
+)
+def test_list_sinks(request_type, transport: str = "grpc"):
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:
+ 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.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"),
+ call.return_value = logging_config.ListSinksResponse(
+ next_page_token="next_page_token_value",
)
+ response = client.list_sinks(request)
- # Establish that the underlying call was made with the expected
- # request object values.
+ # Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
- arg = args[0].parent
- mock_val = "parent_value"
- assert arg == mock_val
- arg = args[0].sink
- mock_val = logging_config.LogSink(name="name_value")
- assert arg == mock_val
+ request = logging_config.ListSinksRequest()
+ assert args[0] == request
+
+ # 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_create_sink_flattened_error():
+def test_list_sinks_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
)
- # 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(),
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.ListSinksRequest(
+ parent="parent_value",
+ page_token="page_token_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:
- # Designate an appropriate return value for the call.
- call.return_value = logging_config.LogSink()
-
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- logging_config.LogSink()
+ with mock.patch.object(type(client.transport.list_sinks), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
)
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = await client.create_sink(
+ client.list_sinks(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == logging_config.ListSinksRequest(
parent="parent_value",
- sink=logging_config.LogSink(name="name_value"),
+ page_token="page_token_value",
)
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls)
- _, args, _ = call.mock_calls[0]
- arg = args[0].parent
- mock_val = "parent_value"
- assert arg == mock_val
- arg = args[0].sink
- mock_val = logging_config.LogSink(name="name_value")
- assert arg == mock_val
+def test_list_sinks_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
-@pytest.mark.asyncio
-async def test_create_sink_flattened_error_async():
- client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
- )
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
- # 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"),
+ # Ensure method has been cached
+ assert client._transport.list_sinks in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
)
+ client._transport._wrapped_methods[client._transport.list_sinks] = mock_rpc
+ request = {}
+ client.list_sinks(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
-@pytest.mark.parametrize(
- "request_type",
- [
- logging_config.UpdateSinkRequest,
- dict,
- ],
-)
-def test_update_sink(request_type, transport: str = "grpc"):
- client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
+ client.list_sinks(request)
- # 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()
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
- # 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
- ),
+
+@pytest.mark.asyncio
+async def test_list_sinks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
)
- 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()
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
- # 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
+ # Ensure method has been cached
+ assert (
+ client._client._transport.list_sinks
+ in client._client._transport._wrapped_methods
+ )
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.list_sinks
+ ] = mock_rpc
-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",
- )
+ request = {}
+ await client.list_sinks(request)
- # 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()
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.list_sinks(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
-async def test_update_sink_async(
- transport: str = "grpc_asyncio", request_type=logging_config.UpdateSinkRequest
+async def test_list_sinks_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.ListSinksRequest
):
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -3990,59 +5064,46 @@ async def test_update_sink_async(
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:
+ 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.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,
+ logging_config.ListSinksResponse(
+ next_page_token="next_page_token_value",
)
)
- response = await client.update_sink(request)
+ 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.UpdateSinkRequest()
+ request = logging_config.ListSinksRequest()
+ assert args[0] == request
# 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
+ assert isinstance(response, pagers.ListSinksAsyncPager)
+ assert response.next_page_token == "next_page_token_value"
@pytest.mark.asyncio
-async def test_update_sink_async_from_dict():
- await test_update_sink_async(request_type=dict)
+async def test_list_sinks_async_from_dict():
+ await test_list_sinks_async(request_type=dict)
-def test_update_sink_field_headers():
+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.UpdateSinkRequest()
+ request = logging_config.ListSinksRequest()
- request.sink_name = "sink_name_value"
+ request.parent = "parent_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)
+ 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
@@ -4053,28 +5114,28 @@ def test_update_sink_field_headers():
_, _, kw = call.mock_calls[0]
assert (
"x-goog-request-params",
- "sink_name=sink_name_value",
+ "parent=parent_value",
) in kw["metadata"]
@pytest.mark.asyncio
-async def test_update_sink_field_headers_async():
+async def test_list_sinks_field_headers_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# 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 = logging_config.ListSinksRequest()
- request.sink_name = "sink_name_value"
+ request.parent = "parent_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:
+ with mock.patch.object(type(client.transport.list_sinks), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- logging_config.LogSink()
+ logging_config.ListSinksResponse()
)
- await client.update_sink(request)
+ await client.list_sinks(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
@@ -4085,43 +5146,35 @@ async def test_update_sink_field_headers_async():
_, _, kw = call.mock_calls[0]
assert (
"x-goog-request-params",
- "sink_name=sink_name_value",
+ "parent=parent_value",
) in kw["metadata"]
-def test_update_sink_flattened():
+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.update_sink), "__call__") as call:
+ 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.LogSink()
+ 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.update_sink(
- sink_name="sink_name_value",
- sink=logging_config.LogSink(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ 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]
- arg = args[0].sink_name
- mock_val = "sink_name_value"
- assert arg == mock_val
- arg = args[0].sink
- mock_val = logging_config.LogSink(name="name_value")
- assert arg == mock_val
- arg = args[0].update_mask
- mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
+ arg = args[0].parent
+ mock_val = "parent_value"
assert arg == mock_val
-def test_update_sink_flattened_error():
+def test_list_sinks_flattened_error():
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
)
@@ -4129,75 +5182,1338 @@ def test_update_sink_flattened_error():
# 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"]),
+ client.list_sinks(
+ logging_config.ListSinksRequest(),
+ parent="parent_value",
)
@pytest.mark.asyncio
-async def test_update_sink_flattened_async():
+async def test_list_sinks_flattened_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client.transport.update_sink), "__call__") as call:
+ 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.LogSink()
+ call.return_value = logging_config.ListSinksResponse()
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- logging_config.LogSink()
+ logging_config.ListSinksResponse()
)
# 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"]),
+ 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]
- arg = args[0].sink_name
- mock_val = "sink_name_value"
- assert arg == mock_val
- arg = args[0].sink
- mock_val = logging_config.LogSink(name="name_value")
- assert arg == mock_val
- arg = args[0].update_mask
- mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
+ arg = args[0].parent
+ mock_val = "parent_value"
assert arg == mock_val
@pytest.mark.asyncio
-async def test_update_sink_flattened_error_async():
+async def test_list_sinks_flattened_error_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# 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"]),
+ await client.list_sinks(
+ logging_config.ListSinksRequest(),
+ parent="parent_value",
)
-@pytest.mark.parametrize(
- "request_type",
- [
- logging_config.DeleteSinkRequest,
- dict,
- ],
-)
+def test_list_sinks_pager(transport_name: str = "grpc"):
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport_name,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_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,
+ )
+
+ expected_metadata = ()
+ retry = retries.Retry()
+ timeout = 5
+ expected_metadata = tuple(expected_metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.list_sinks(request={}, retry=retry, timeout=timeout)
+
+ assert pager._metadata == expected_metadata
+ assert pager._retry == retry
+ assert pager._timeout == timeout
+
+ results = list(pager)
+ assert len(results) == 6
+ assert all(isinstance(i, logging_config.LogSink) for i in results)
+
+
+def test_list_sinks_pages(transport_name: str = "grpc"):
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport_name,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_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=async_anonymous_credentials(),
+ )
+
+ # 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: # pragma: no branch
+ 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=async_anonymous_credentials(),
+ )
+
+ # 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 = []
+ # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch`
+ # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372
+ async for page_ in ( # pragma: no branch
+ 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
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ logging_config.GetSinkRequest,
+ dict,
+ ],
+)
+def test_get_sink(request_type, transport: str = "grpc"):
+ 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,
+ )
+ 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]
+ request = logging_config.GetSinkRequest()
+ assert args[0] == request
+
+ # 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_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.GetSinkRequest(
+ 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.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_sink(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == logging_config.GetSinkRequest(
+ sink_name="sink_name_value",
+ )
+
+
+def test_get_sink_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.get_sink in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.get_sink] = mock_rpc
+ request = {}
+ client.get_sink(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_sink(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_get_sink_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.get_sink
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.get_sink
+ ] = mock_rpc
+
+ request = {}
+ await client.get_sink(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.get_sink(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_get_sink_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.GetSinkRequest
+):
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ 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]
+ request = logging_config.GetSinkRequest()
+ assert args[0] == request
+
+ # 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=async_anonymous_credentials(),
+ )
+
+ # 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]
+ arg = args[0].sink_name
+ mock_val = "sink_name_value"
+ assert arg == mock_val
+
+
+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=async_anonymous_credentials(),
+ )
+
+ # 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]
+ arg = args[0].sink_name
+ mock_val = "sink_name_value"
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_get_sink_flattened_error_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # 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",
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ logging_config.CreateSinkRequest,
+ dict,
+ ],
+)
+def test_create_sink(request_type, transport: str = "grpc"):
+ 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,
+ )
+ 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]
+ request = logging_config.CreateSinkRequest()
+ assert args[0] == request
+
+ # 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_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.CreateSinkRequest(
+ 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.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_sink(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == logging_config.CreateSinkRequest(
+ parent="parent_value",
+ )
+
+
+def test_create_sink_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.create_sink in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.create_sink] = mock_rpc
+ request = {}
+ client.create_sink(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.create_sink(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_create_sink_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.create_sink
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.create_sink
+ ] = mock_rpc
+
+ request = {}
+ await client.create_sink(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.create_sink(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_create_sink_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.CreateSinkRequest
+):
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ 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]
+ request = logging_config.CreateSinkRequest()
+ assert args[0] == request
+
+ # 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=async_anonymous_credentials(),
+ )
+
+ # 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]
+ arg = args[0].parent
+ mock_val = "parent_value"
+ assert arg == mock_val
+ arg = args[0].sink
+ mock_val = logging_config.LogSink(name="name_value")
+ assert arg == mock_val
+
+
+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=async_anonymous_credentials(),
+ )
+
+ # 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]
+ arg = args[0].parent
+ mock_val = "parent_value"
+ assert arg == mock_val
+ arg = args[0].sink
+ mock_val = logging_config.LogSink(name="name_value")
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_create_sink_flattened_error_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # 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"),
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ logging_config.UpdateSinkRequest,
+ dict,
+ ],
+)
+def test_update_sink(request_type, transport: str = "grpc"):
+ 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,
+ )
+ 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]
+ request = logging_config.UpdateSinkRequest()
+ assert args[0] == request
+
+ # 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_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.UpdateSinkRequest(
+ 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.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_sink(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == logging_config.UpdateSinkRequest(
+ sink_name="sink_name_value",
+ )
+
+
+def test_update_sink_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.update_sink in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.update_sink] = mock_rpc
+ request = {}
+ client.update_sink(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_sink(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_update_sink_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.update_sink
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.update_sink
+ ] = mock_rpc
+
+ request = {}
+ await client.update_sink(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.update_sink(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_update_sink_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.UpdateSinkRequest
+):
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ 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]
+ request = logging_config.UpdateSinkRequest()
+ assert args[0] == request
+
+ # 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=async_anonymous_credentials(),
+ )
+
+ # 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]
+ arg = args[0].sink_name
+ mock_val = "sink_name_value"
+ assert arg == mock_val
+ arg = args[0].sink
+ mock_val = logging_config.LogSink(name="name_value")
+ assert arg == mock_val
+ arg = args[0].update_mask
+ mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
+ assert arg == mock_val
+
+
+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=async_anonymous_credentials(),
+ )
+
+ # 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]
+ arg = args[0].sink_name
+ mock_val = "sink_name_value"
+ assert arg == mock_val
+ arg = args[0].sink
+ mock_val = logging_config.LogSink(name="name_value")
+ assert arg == mock_val
+ arg = args[0].update_mask
+ mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_update_sink_flattened_error_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # 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"]),
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ logging_config.DeleteSinkRequest,
+ dict,
+ ],
+)
def test_delete_sink(request_type, transport: str = "grpc"):
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
@@ -4209,42 +6525,4115 @@ def test_delete_sink(request_type, transport: str = "grpc"):
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:
+ 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]
+ request = logging_config.DeleteSinkRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_delete_sink_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.DeleteSinkRequest(
+ 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.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_sink(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == logging_config.DeleteSinkRequest(
+ sink_name="sink_name_value",
+ )
+
+
+def test_delete_sink_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.delete_sink in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.delete_sink] = mock_rpc
+ request = {}
+ client.delete_sink(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.delete_sink(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_delete_sink_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.delete_sink
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.delete_sink
+ ] = mock_rpc
+
+ request = {}
+ await client.delete_sink(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.delete_sink(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_delete_sink_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.DeleteSinkRequest
+):
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ 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]
+ request = logging_config.DeleteSinkRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+@pytest.mark.asyncio
+async def test_delete_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=async_anonymous_credentials(),
+ )
+
+ # 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]
+ arg = args[0].sink_name
+ mock_val = "sink_name_value"
+ assert arg == mock_val
+
+
+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=async_anonymous_credentials(),
+ )
+
+ # 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]
+ arg = args[0].sink_name
+ mock_val = "sink_name_value"
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_delete_sink_flattened_error_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # 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",
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ logging_config.CreateLinkRequest,
+ dict,
+ ],
+)
+def test_create_link(request_type, transport: str = "grpc"):
+ 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_link), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+ response = client.create_link(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = logging_config.CreateLinkRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_create_link_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.CreateLinkRequest(
+ parent="parent_value",
+ link_id="link_id_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_link), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_link(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == logging_config.CreateLinkRequest(
+ parent="parent_value",
+ link_id="link_id_value",
+ )
+
+
+def test_create_link_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.create_link in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.create_link] = mock_rpc
+ request = {}
+ client.create_link(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ # Operation methods call wrapper_fn to build a cached
+ # client._transport.operations_client instance on first rpc call.
+ # Subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ client.create_link(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_create_link_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.create_link
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.create_link
+ ] = mock_rpc
+
+ request = {}
+ await client.create_link(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ # Operation methods call wrapper_fn to build a cached
+ # client._transport.operations_client instance on first rpc call.
+ # Subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ await client.create_link(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_create_link_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.CreateLinkRequest
+):
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ 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_link), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/spam")
+ )
+ response = await client.create_link(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = logging_config.CreateLinkRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_create_link_async_from_dict():
+ await test_create_link_async(request_type=dict)
+
+
+def test_create_link_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.CreateLinkRequest()
+
+ request.parent = "parent_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_link), "__call__") as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+ client.create_link(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_link_field_headers_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # 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.CreateLinkRequest()
+
+ request.parent = "parent_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_link), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+ await client.create_link(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_link_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_link), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/op")
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.create_link(
+ parent="parent_value",
+ link=logging_config.Link(name="name_value"),
+ link_id="link_id_value",
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ arg = args[0].parent
+ mock_val = "parent_value"
+ assert arg == mock_val
+ arg = args[0].link
+ mock_val = logging_config.Link(name="name_value")
+ assert arg == mock_val
+ arg = args[0].link_id
+ mock_val = "link_id_value"
+ assert arg == mock_val
+
+
+def test_create_link_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_link(
+ logging_config.CreateLinkRequest(),
+ parent="parent_value",
+ link=logging_config.Link(name="name_value"),
+ link_id="link_id_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_create_link_flattened_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_link), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/spam")
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.create_link(
+ parent="parent_value",
+ link=logging_config.Link(name="name_value"),
+ link_id="link_id_value",
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ arg = args[0].parent
+ mock_val = "parent_value"
+ assert arg == mock_val
+ arg = args[0].link
+ mock_val = logging_config.Link(name="name_value")
+ assert arg == mock_val
+ arg = args[0].link_id
+ mock_val = "link_id_value"
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_create_link_flattened_error_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ await client.create_link(
+ logging_config.CreateLinkRequest(),
+ parent="parent_value",
+ link=logging_config.Link(name="name_value"),
+ link_id="link_id_value",
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ logging_config.DeleteLinkRequest,
+ dict,
+ ],
+)
+def test_delete_link(request_type, transport: str = "grpc"):
+ 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_link), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+ response = client.delete_link(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = logging_config.DeleteLinkRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_delete_link_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.DeleteLinkRequest(
+ name="name_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_link), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_link(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == logging_config.DeleteLinkRequest(
+ name="name_value",
+ )
+
+
+def test_delete_link_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.delete_link in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.delete_link] = mock_rpc
+ request = {}
+ client.delete_link(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ # Operation methods call wrapper_fn to build a cached
+ # client._transport.operations_client instance on first rpc call.
+ # Subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ client.delete_link(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_delete_link_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.delete_link
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.delete_link
+ ] = mock_rpc
+
+ request = {}
+ await client.delete_link(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ # Operation methods call wrapper_fn to build a cached
+ # client._transport.operations_client instance on first rpc call.
+ # Subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ await client.delete_link(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_delete_link_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.DeleteLinkRequest
+):
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ 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_link), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/spam")
+ )
+ response = await client.delete_link(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = logging_config.DeleteLinkRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_delete_link_async_from_dict():
+ await test_delete_link_async(request_type=dict)
+
+
+def test_delete_link_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.DeleteLinkRequest()
+
+ request.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_link), "__call__") as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+ client.delete_link(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_link_field_headers_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # 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.DeleteLinkRequest()
+
+ request.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_link), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+ await client.delete_link(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_link_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_link), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/op")
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.delete_link(
+ 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]
+ arg = args[0].name
+ mock_val = "name_value"
+ assert arg == mock_val
+
+
+def test_delete_link_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_link(
+ logging_config.DeleteLinkRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_delete_link_flattened_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_link), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/spam")
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.delete_link(
+ 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]
+ arg = args[0].name
+ mock_val = "name_value"
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_delete_link_flattened_error_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ await client.delete_link(
+ logging_config.DeleteLinkRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ logging_config.ListLinksRequest,
+ dict,
+ ],
+)
+def test_list_links(request_type, transport: str = "grpc"):
+ 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_links), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = logging_config.ListLinksResponse(
+ next_page_token="next_page_token_value",
+ )
+ response = client.list_links(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = logging_config.ListLinksRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListLinksPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_links_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.ListLinksRequest(
+ parent="parent_value",
+ page_token="page_token_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_links), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_links(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == logging_config.ListLinksRequest(
+ parent="parent_value",
+ page_token="page_token_value",
+ )
+
+
+def test_list_links_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.list_links in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.list_links] = mock_rpc
+ request = {}
+ client.list_links(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.list_links(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_list_links_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.list_links
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.list_links
+ ] = mock_rpc
+
+ request = {}
+ await client.list_links(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.list_links(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_list_links_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.ListLinksRequest
+):
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ 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_links), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ logging_config.ListLinksResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_links(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = logging_config.ListLinksRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListLinksAsyncPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
+@pytest.mark.asyncio
+async def test_list_links_async_from_dict():
+ await test_list_links_async(request_type=dict)
+
+
+def test_list_links_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.ListLinksRequest()
+
+ request.parent = "parent_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_links), "__call__") as call:
+ call.return_value = logging_config.ListLinksResponse()
+ client.list_links(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_links_field_headers_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # 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.ListLinksRequest()
+
+ request.parent = "parent_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_links), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ logging_config.ListLinksResponse()
+ )
+ await client.list_links(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_links_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_links), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = logging_config.ListLinksResponse()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.list_links(
+ parent="parent_value",
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ arg = args[0].parent
+ mock_val = "parent_value"
+ assert arg == mock_val
+
+
+def test_list_links_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_links(
+ logging_config.ListLinksRequest(),
+ parent="parent_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_list_links_flattened_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_links), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = logging_config.ListLinksResponse()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ logging_config.ListLinksResponse()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.list_links(
+ parent="parent_value",
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ arg = args[0].parent
+ mock_val = "parent_value"
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_list_links_flattened_error_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ await client.list_links(
+ logging_config.ListLinksRequest(),
+ parent="parent_value",
+ )
+
+
+def test_list_links_pager(transport_name: str = "grpc"):
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport_name,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_links), "__call__") as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ logging_config.ListLinksResponse(
+ links=[
+ logging_config.Link(),
+ logging_config.Link(),
+ logging_config.Link(),
+ ],
+ next_page_token="abc",
+ ),
+ logging_config.ListLinksResponse(
+ links=[],
+ next_page_token="def",
+ ),
+ logging_config.ListLinksResponse(
+ links=[
+ logging_config.Link(),
+ ],
+ next_page_token="ghi",
+ ),
+ logging_config.ListLinksResponse(
+ links=[
+ logging_config.Link(),
+ logging_config.Link(),
+ ],
+ ),
+ RuntimeError,
+ )
+
+ expected_metadata = ()
+ retry = retries.Retry()
+ timeout = 5
+ expected_metadata = tuple(expected_metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.list_links(request={}, retry=retry, timeout=timeout)
+
+ assert pager._metadata == expected_metadata
+ assert pager._retry == retry
+ assert pager._timeout == timeout
+
+ results = list(pager)
+ assert len(results) == 6
+ assert all(isinstance(i, logging_config.Link) for i in results)
+
+
+def test_list_links_pages(transport_name: str = "grpc"):
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport_name,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_links), "__call__") as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ logging_config.ListLinksResponse(
+ links=[
+ logging_config.Link(),
+ logging_config.Link(),
+ logging_config.Link(),
+ ],
+ next_page_token="abc",
+ ),
+ logging_config.ListLinksResponse(
+ links=[],
+ next_page_token="def",
+ ),
+ logging_config.ListLinksResponse(
+ links=[
+ logging_config.Link(),
+ ],
+ next_page_token="ghi",
+ ),
+ logging_config.ListLinksResponse(
+ links=[
+ logging_config.Link(),
+ logging_config.Link(),
+ ],
+ ),
+ RuntimeError,
+ )
+ pages = list(client.list_links(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_links_async_pager():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_links), "__call__", new_callable=mock.AsyncMock
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ logging_config.ListLinksResponse(
+ links=[
+ logging_config.Link(),
+ logging_config.Link(),
+ logging_config.Link(),
+ ],
+ next_page_token="abc",
+ ),
+ logging_config.ListLinksResponse(
+ links=[],
+ next_page_token="def",
+ ),
+ logging_config.ListLinksResponse(
+ links=[
+ logging_config.Link(),
+ ],
+ next_page_token="ghi",
+ ),
+ logging_config.ListLinksResponse(
+ links=[
+ logging_config.Link(),
+ logging_config.Link(),
+ ],
+ ),
+ RuntimeError,
+ )
+ async_pager = await client.list_links(
+ request={},
+ )
+ assert async_pager.next_page_token == "abc"
+ responses = []
+ async for response in async_pager: # pragma: no branch
+ responses.append(response)
+
+ assert len(responses) == 6
+ assert all(isinstance(i, logging_config.Link) for i in responses)
+
+
+@pytest.mark.asyncio
+async def test_list_links_async_pages():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_links), "__call__", new_callable=mock.AsyncMock
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ logging_config.ListLinksResponse(
+ links=[
+ logging_config.Link(),
+ logging_config.Link(),
+ logging_config.Link(),
+ ],
+ next_page_token="abc",
+ ),
+ logging_config.ListLinksResponse(
+ links=[],
+ next_page_token="def",
+ ),
+ logging_config.ListLinksResponse(
+ links=[
+ logging_config.Link(),
+ ],
+ next_page_token="ghi",
+ ),
+ logging_config.ListLinksResponse(
+ links=[
+ logging_config.Link(),
+ logging_config.Link(),
+ ],
+ ),
+ RuntimeError,
+ )
+ pages = []
+ # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch`
+ # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372
+ async for page_ in ( # pragma: no branch
+ await client.list_links(request={})
+ ).pages:
+ pages.append(page_)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ logging_config.GetLinkRequest,
+ dict,
+ ],
+)
+def test_get_link(request_type, transport: str = "grpc"):
+ 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_link), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = logging_config.Link(
+ name="name_value",
+ description="description_value",
+ lifecycle_state=logging_config.LifecycleState.ACTIVE,
+ )
+ response = client.get_link(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = logging_config.GetLinkRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, logging_config.Link)
+ assert response.name == "name_value"
+ assert response.description == "description_value"
+ assert response.lifecycle_state == logging_config.LifecycleState.ACTIVE
+
+
+def test_get_link_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.GetLinkRequest(
+ name="name_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_link), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_link(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == logging_config.GetLinkRequest(
+ name="name_value",
+ )
+
+
+def test_get_link_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.get_link in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.get_link] = mock_rpc
+ request = {}
+ client.get_link(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_link(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_get_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.get_link
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.get_link
+ ] = mock_rpc
+
+ request = {}
+ await client.get_link(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.get_link(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_get_link_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.GetLinkRequest
+):
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ 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_link), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ logging_config.Link(
+ name="name_value",
+ description="description_value",
+ lifecycle_state=logging_config.LifecycleState.ACTIVE,
+ )
+ )
+ response = await client.get_link(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = logging_config.GetLinkRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, logging_config.Link)
+ assert response.name == "name_value"
+ assert response.description == "description_value"
+ assert response.lifecycle_state == logging_config.LifecycleState.ACTIVE
+
+
+@pytest.mark.asyncio
+async def test_get_link_async_from_dict():
+ await test_get_link_async(request_type=dict)
+
+
+def test_get_link_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.GetLinkRequest()
+
+ request.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_link), "__call__") as call:
+ call.return_value = logging_config.Link()
+ client.get_link(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_link_field_headers_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # 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.GetLinkRequest()
+
+ request.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_link), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.Link())
+ await client.get_link(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_link_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_link), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = logging_config.Link()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_link(
+ 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]
+ arg = args[0].name
+ mock_val = "name_value"
+ assert arg == mock_val
+
+
+def test_get_link_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_link(
+ logging_config.GetLinkRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_get_link_flattened_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_link), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = logging_config.Link()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(logging_config.Link())
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_link(
+ 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]
+ arg = args[0].name
+ mock_val = "name_value"
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_get_link_flattened_error_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ await client.get_link(
+ logging_config.GetLinkRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ logging_config.ListExclusionsRequest,
+ dict,
+ ],
+)
+def test_list_exclusions(request_type, transport: str = "grpc"):
+ 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]
+ request = logging_config.ListExclusionsRequest()
+ assert args[0] == request
+
+ # 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_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.ListExclusionsRequest(
+ parent="parent_value",
+ page_token="page_token_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.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_exclusions(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == logging_config.ListExclusionsRequest(
+ parent="parent_value",
+ page_token="page_token_value",
+ )
+
+
+def test_list_exclusions_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.list_exclusions in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.list_exclusions] = mock_rpc
+ request = {}
+ client.list_exclusions(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.list_exclusions(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_list_exclusions_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.list_exclusions
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.list_exclusions
+ ] = mock_rpc
+
+ request = {}
+ await client.list_exclusions(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.list_exclusions(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_list_exclusions_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.ListExclusionsRequest
+):
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ 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]
+ request = logging_config.ListExclusionsRequest()
+ assert args[0] == request
+
+ # 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=async_anonymous_credentials(),
+ )
+
+ # 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]
+ arg = args[0].parent
+ mock_val = "parent_value"
+ assert arg == mock_val
+
+
+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=async_anonymous_credentials(),
+ )
+
+ # 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]
+ arg = args[0].parent
+ mock_val = "parent_value"
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_list_exclusions_flattened_error_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # 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(transport_name: str = "grpc"):
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport_name,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_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,
+ )
+
+ expected_metadata = ()
+ retry = retries.Retry()
+ timeout = 5
+ expected_metadata = tuple(expected_metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.list_exclusions(request={}, retry=retry, timeout=timeout)
+
+ assert pager._metadata == expected_metadata
+ assert pager._retry == retry
+ assert pager._timeout == timeout
+
+ results = list(pager)
+ assert len(results) == 6
+ assert all(isinstance(i, logging_config.LogExclusion) for i in results)
+
+
+def test_list_exclusions_pages(transport_name: str = "grpc"):
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport_name,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_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=async_anonymous_credentials(),
+ )
+
+ # 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: # pragma: no branch
+ 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=async_anonymous_credentials(),
+ )
+
+ # 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 = []
+ # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch`
+ # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372
+ async for page_ in ( # pragma: no branch
+ 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
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ logging_config.GetExclusionRequest,
+ dict,
+ ],
+)
+def test_get_exclusion(request_type, transport: str = "grpc"):
+ 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]
+ request = logging_config.GetExclusionRequest()
+ assert args[0] == request
+
+ # 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_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.GetExclusionRequest(
+ 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.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_exclusion(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == logging_config.GetExclusionRequest(
+ name="name_value",
+ )
+
+
+def test_get_exclusion_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.get_exclusion in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.get_exclusion] = mock_rpc
+ request = {}
+ client.get_exclusion(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_exclusion(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_get_exclusion_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.get_exclusion
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.get_exclusion
+ ] = mock_rpc
+
+ request = {}
+ await client.get_exclusion(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.get_exclusion(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_get_exclusion_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.GetExclusionRequest
+):
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ 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]
+ request = logging_config.GetExclusionRequest()
+ assert args[0] == request
+
+ # 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=async_anonymous_credentials(),
+ )
+
+ # 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]
+ arg = args[0].name
+ mock_val = "name_value"
+ assert arg == mock_val
+
+
+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=async_anonymous_credentials(),
+ )
+
+ # 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]
+ arg = args[0].name
+ mock_val = "name_value"
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_get_exclusion_flattened_error_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # 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",
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ logging_config.CreateExclusionRequest,
+ dict,
+ ],
+)
+def test_create_exclusion(request_type, transport: str = "grpc"):
+ 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]
+ request = logging_config.CreateExclusionRequest()
+ assert args[0] == request
+
+ # 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_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.CreateExclusionRequest(
+ 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.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_exclusion(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == logging_config.CreateExclusionRequest(
+ parent="parent_value",
+ )
+
+
+def test_create_exclusion_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.create_exclusion in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.create_exclusion
+ ] = mock_rpc
+ request = {}
+ client.create_exclusion(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.create_exclusion(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_create_exclusion_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.create_exclusion
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.create_exclusion
+ ] = mock_rpc
+
+ request = {}
+ await client.create_exclusion(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.create_exclusion(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_create_exclusion_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.CreateExclusionRequest
+):
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ 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]
+ request = logging_config.CreateExclusionRequest()
+ assert args[0] == request
+
+ # 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=async_anonymous_credentials(),
+ )
+
+ # 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]
+ arg = args[0].parent
+ mock_val = "parent_value"
+ assert arg == mock_val
+ arg = args[0].exclusion
+ mock_val = logging_config.LogExclusion(name="name_value")
+ assert arg == mock_val
+
+
+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=async_anonymous_credentials(),
+ )
+
+ # 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]
+ arg = args[0].parent
+ mock_val = "parent_value"
+ assert arg == mock_val
+ arg = args[0].exclusion
+ mock_val = logging_config.LogExclusion(name="name_value")
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_create_exclusion_flattened_error_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # 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"),
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ logging_config.UpdateExclusionRequest,
+ dict,
+ ],
+)
+def test_update_exclusion(request_type, transport: str = "grpc"):
+ 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]
+ request = logging_config.UpdateExclusionRequest()
+ assert args[0] == request
+
+ # 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_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.UpdateExclusionRequest(
+ 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.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_exclusion(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == logging_config.UpdateExclusionRequest(
+ name="name_value",
+ )
+
+
+def test_update_exclusion_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.update_exclusion in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.update_exclusion
+ ] = mock_rpc
+ request = {}
+ client.update_exclusion(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_exclusion(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_update_exclusion_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.update_exclusion
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.update_exclusion
+ ] = mock_rpc
+
+ request = {}
+ await client.update_exclusion(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.update_exclusion(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_update_exclusion_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.UpdateExclusionRequest
+):
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ 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]
+ request = logging_config.UpdateExclusionRequest()
+ assert args[0] == request
+
+ # 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=async_anonymous_credentials(),
+ )
+
+ # 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]
+ arg = args[0].name
+ mock_val = "name_value"
+ assert arg == mock_val
+ arg = args[0].exclusion
+ mock_val = logging_config.LogExclusion(name="name_value")
+ assert arg == mock_val
+ arg = args[0].update_mask
+ mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
+ assert arg == mock_val
+
+
+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=async_anonymous_credentials(),
+ )
+
+ # 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]
+ arg = args[0].name
+ mock_val = "name_value"
+ assert arg == mock_val
+ arg = args[0].exclusion
+ mock_val = logging_config.LogExclusion(name="name_value")
+ assert arg == mock_val
+ arg = args[0].update_mask
+ mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_update_exclusion_flattened_error_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # 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"]),
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ logging_config.DeleteExclusionRequest,
+ dict,
+ ],
+)
+def test_delete_exclusion(request_type, transport: str = "grpc"):
+ 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]
+ request = logging_config.DeleteExclusionRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_delete_exclusion_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.DeleteExclusionRequest(
+ 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.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_exclusion(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == logging_config.DeleteExclusionRequest(
+ name="name_value",
+ )
+
+
+def test_delete_exclusion_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.delete_exclusion in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.delete_exclusion
+ ] = mock_rpc
+ request = {}
+ client.delete_exclusion(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.delete_exclusion(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_delete_exclusion_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.delete_exclusion
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.delete_exclusion
+ ] = mock_rpc
+
+ request = {}
+ await client.delete_exclusion(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.delete_exclusion(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_delete_exclusion_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.DeleteExclusionRequest
+):
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ 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]
+ request = logging_config.DeleteExclusionRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+@pytest.mark.asyncio
+async def test_delete_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=async_anonymous_credentials(),
+ )
+
+ # 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]
+ arg = args[0].name
+ mock_val = "name_value"
+ assert arg == mock_val
+
+
+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=async_anonymous_credentials(),
+ )
+
+ # 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]
+ arg = args[0].name
+ mock_val = "name_value"
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_delete_exclusion_flattened_error_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # 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",
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ logging_config.GetCmekSettingsRequest,
+ dict,
+ ],
+)
+def test_get_cmek_settings(request_type, transport: str = "grpc"):
+ 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",
+ kms_key_version_name="kms_key_version_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]
+ request = logging_config.GetCmekSettingsRequest()
+ assert args[0] == request
+
+ # 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.kms_key_version_name == "kms_key_version_name_value"
+ assert response.service_account_id == "service_account_id_value"
+
+
+def test_get_cmek_settings_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.GetCmekSettingsRequest(
+ 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.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_cmek_settings(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == logging_config.GetCmekSettingsRequest(
+ name="name_value",
+ )
+
+
+def test_get_cmek_settings_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.get_cmek_settings in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.get_cmek_settings
+ ] = mock_rpc
+ request = {}
+ client.get_cmek_settings(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_cmek_settings(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_get_cmek_settings_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.get_cmek_settings
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.get_cmek_settings
+ ] = mock_rpc
+
+ request = {}
+ await client.get_cmek_settings(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.get_cmek_settings(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_get_cmek_settings_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.GetCmekSettingsRequest
+):
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ 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",
+ kms_key_version_name="kms_key_version_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]
+ request = logging_config.GetCmekSettingsRequest()
+ assert args[0] == request
+
+ # 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.kms_key_version_name == "kms_key_version_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=async_anonymous_credentials(),
+ )
+
+ # 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"]
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ logging_config.UpdateCmekSettingsRequest,
+ dict,
+ ],
+)
+def test_update_cmek_settings(request_type, transport: str = "grpc"):
+ 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 = None
- response = client.delete_sink(request)
+ call.return_value = logging_config.CmekSettings(
+ name="name_value",
+ kms_key_name="kms_key_name_value",
+ kms_key_version_name="kms_key_version_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.DeleteSinkRequest()
+ request = logging_config.UpdateCmekSettingsRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
- assert response is None
+ assert isinstance(response, logging_config.CmekSettings)
+ assert response.name == "name_value"
+ assert response.kms_key_name == "kms_key_name_value"
+ assert response.kms_key_version_name == "kms_key_version_name_value"
+ assert response.service_account_id == "service_account_id_value"
-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.
+def test_update_cmek_settings_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.UpdateCmekSettingsRequest(
+ name="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:
- client.delete_sink()
+ with mock.patch.object(
+ type(client.transport.update_cmek_settings), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_cmek_settings(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.DeleteSinkRequest()
+ assert args[0] == logging_config.UpdateCmekSettingsRequest(
+ name="name_value",
+ )
+
+
+def test_update_cmek_settings_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._transport.update_cmek_settings in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.update_cmek_settings
+ ] = mock_rpc
+ request = {}
+ client.update_cmek_settings(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_cmek_settings(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
-async def test_delete_sink_async(
- transport: str = "grpc_asyncio", request_type=logging_config.DeleteSinkRequest
+async def test_update_cmek_settings_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.update_cmek_settings
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.update_cmek_settings
+ ] = mock_rpc
+
+ request = {}
+ await client.update_cmek_settings(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.update_cmek_settings(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@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(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -4253,40 +10642,56 @@ async def test_delete_sink_async(
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:
+ 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(None)
- response = await client.delete_sink(request)
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ logging_config.CmekSettings(
+ name="name_value",
+ kms_key_name="kms_key_name_value",
+ kms_key_version_name="kms_key_version_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.DeleteSinkRequest()
+ request = logging_config.UpdateCmekSettingsRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
- assert response is None
+ assert isinstance(response, logging_config.CmekSettings)
+ assert response.name == "name_value"
+ assert response.kms_key_name == "kms_key_name_value"
+ assert response.kms_key_version_name == "kms_key_version_name_value"
+ assert response.service_account_id == "service_account_id_value"
@pytest.mark.asyncio
-async def test_delete_sink_async_from_dict():
- await test_delete_sink_async(request_type=dict)
+async def test_update_cmek_settings_async_from_dict():
+ await test_update_cmek_settings_async(request_type=dict)
-def test_delete_sink_field_headers():
+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.DeleteSinkRequest()
+ request = logging_config.UpdateCmekSettingsRequest()
- request.sink_name = "sink_name_value"
+ request.name = "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)
+ 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
@@ -4297,26 +10702,30 @@ def test_delete_sink_field_headers():
_, _, kw = call.mock_calls[0]
assert (
"x-goog-request-params",
- "sink_name=sink_name_value",
+ "name=name_value",
) in kw["metadata"]
@pytest.mark.asyncio
-async def test_delete_sink_field_headers_async():
+async def test_update_cmek_settings_field_headers_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# 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 = logging_config.UpdateCmekSettingsRequest()
- request.sink_name = "sink_name_value"
+ request.name = "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)
+ 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)
@@ -4327,147 +10736,165 @@ async def test_delete_sink_field_headers_async():
_, _, kw = call.mock_calls[0]
assert (
"x-goog-request-params",
- "sink_name=sink_name_value",
+ "name=name_value",
) in kw["metadata"]
-def test_delete_sink_flattened():
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ logging_config.GetSettingsRequest,
+ dict,
+ ],
+)
+def test_get_settings(request_type, transport: str = "grpc"):
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:
+ with mock.patch.object(type(client.transport.get_settings), "__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",
+ call.return_value = logging_config.Settings(
+ name="name_value",
+ kms_key_name="kms_key_name_value",
+ kms_service_account_id="kms_service_account_id_value",
+ storage_location="storage_location_value",
+ disable_default_sink=True,
)
+ response = client.get_settings(request)
- # Establish that the underlying call was made with the expected
- # request object values.
+ # Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
- arg = args[0].sink_name
- mock_val = "sink_name_value"
- assert arg == mock_val
+ request = logging_config.GetSettingsRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, logging_config.Settings)
+ assert response.name == "name_value"
+ assert response.kms_key_name == "kms_key_name_value"
+ assert response.kms_service_account_id == "kms_service_account_id_value"
+ assert response.storage_location == "storage_location_value"
+ assert response.disable_default_sink is True
-def test_delete_sink_flattened_error():
+def test_get_settings_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
)
- # 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(),
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.GetSettingsRequest(
+ name="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:
- # 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",
+ with mock.patch.object(type(client.transport.get_settings), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls)
+ client.get_settings(request=request)
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- arg = args[0].sink_name
- mock_val = "sink_name_value"
- assert arg == mock_val
-
+ assert args[0] == logging_config.GetSettingsRequest(
+ name="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_get_settings_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
)
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
-@pytest.mark.parametrize(
- "request_type",
- [
- logging_config.ListExclusionsRequest,
- dict,
- ],
-)
-def test_list_exclusions(request_type, transport: str = "grpc"):
- client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
+ # Ensure method has been cached
+ assert client._transport.get_settings in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.get_settings] = mock_rpc
+ request = {}
+ client.get_settings(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
- # 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()
+ client.get_settings(request)
- # 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",
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_get_settings_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
)
- 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()
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListExclusionsPager)
- assert response.next_page_token == "next_page_token_value"
+ # Ensure method has been cached
+ assert (
+ client._client._transport.get_settings
+ in client._client._transport._wrapped_methods
+ )
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.get_settings
+ ] = mock_rpc
-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",
- )
+ request = {}
+ await client.get_settings(request)
- # 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()
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.get_settings(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
-async def test_list_exclusions_async(
- transport: str = "grpc_asyncio", request_type=logging_config.ListExclusionsRequest
+async def test_get_settings_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.GetSettingsRequest
):
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -4476,45 +10903,54 @@ async def test_list_exclusions_async(
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:
+ with mock.patch.object(type(client.transport.get_settings), "__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",
+ logging_config.Settings(
+ name="name_value",
+ kms_key_name="kms_key_name_value",
+ kms_service_account_id="kms_service_account_id_value",
+ storage_location="storage_location_value",
+ disable_default_sink=True,
)
)
- response = await client.list_exclusions(request)
+ response = await client.get_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.ListExclusionsRequest()
+ request = logging_config.GetSettingsRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListExclusionsAsyncPager)
- assert response.next_page_token == "next_page_token_value"
+ assert isinstance(response, logging_config.Settings)
+ assert response.name == "name_value"
+ assert response.kms_key_name == "kms_key_name_value"
+ assert response.kms_service_account_id == "kms_service_account_id_value"
+ assert response.storage_location == "storage_location_value"
+ assert response.disable_default_sink is True
@pytest.mark.asyncio
-async def test_list_exclusions_async_from_dict():
- await test_list_exclusions_async(request_type=dict)
+async def test_get_settings_async_from_dict():
+ await test_get_settings_async(request_type=dict)
-def test_list_exclusions_field_headers():
+def test_get_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.ListExclusionsRequest()
+ request = logging_config.GetSettingsRequest()
- request.parent = "parent_value"
+ request.name = "name_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)
+ with mock.patch.object(type(client.transport.get_settings), "__call__") as call:
+ call.return_value = logging_config.Settings()
+ client.get_settings(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
@@ -4525,28 +10961,28 @@ def test_list_exclusions_field_headers():
_, _, kw = call.mock_calls[0]
assert (
"x-goog-request-params",
- "parent=parent_value",
+ "name=name_value",
) in kw["metadata"]
@pytest.mark.asyncio
-async def test_list_exclusions_field_headers_async():
+async def test_get_settings_field_headers_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# 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 = logging_config.GetSettingsRequest()
- request.parent = "parent_value"
+ request.name = "name_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:
+ with mock.patch.object(type(client.transport.get_settings), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- logging_config.ListExclusionsResponse()
+ logging_config.Settings()
)
- await client.list_exclusions(request)
+ await client.get_settings(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
@@ -4557,288 +10993,100 @@ async def test_list_exclusions_field_headers_async():
_, _, kw = call.mock_calls[0]
assert (
"x-goog-request-params",
- "parent=parent_value",
+ "name=name_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]
- arg = args[0].parent
- mock_val = "parent_value"
- assert arg == mock_val
-
-
-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]
- arg = args[0].parent
- mock_val = "parent_value"
- assert arg == mock_val
-
-
-@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(transport_name: str = "grpc"):
- client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials,
- transport=transport_name,
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client.transport.list_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 = list(pager)
- assert len(results) == 6
- assert all(isinstance(i, logging_config.LogExclusion) for i in results)
-
-
-def test_list_exclusions_pages(transport_name: str = "grpc"):
+def test_get_settings_flattened():
client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials,
- transport=transport_name,
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client.transport.list_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,
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_settings), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = logging_config.Settings()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_settings(
+ 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]
+ arg = args[0].name
+ mock_val = "name_value"
+ assert arg == mock_val
+
+
+def test_get_settings_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_settings(
+ logging_config.GetSettingsRequest(),
+ name="name_value",
)
- 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():
+async def test_get_settings_flattened_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=async_anonymous_credentials(),
)
# 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,
+ with mock.patch.object(type(client.transport.get_settings), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = logging_config.Settings()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ logging_config.Settings()
)
- async_pager = await client.list_exclusions(
- request={},
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_settings(
+ name="name_value",
)
- assert async_pager.next_page_token == "abc"
- responses = []
- async for response in async_pager: # pragma: no branch
- responses.append(response)
- assert len(responses) == 6
- assert all(isinstance(i, logging_config.LogExclusion) for i in responses)
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ arg = args[0].name
+ mock_val = "name_value"
+ assert arg == mock_val
@pytest.mark.asyncio
-async def test_list_exclusions_async_pages():
+async def test_get_settings_flattened_error_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=async_anonymous_credentials(),
)
- # 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,
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ await client.get_settings(
+ logging_config.GetSettingsRequest(),
+ name="name_value",
)
- pages = []
- async for page_ in (
- await client.list_exclusions(request={})
- ).pages: # pragma: no branch
- pages.append(page_)
- for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
- assert page_.raw_page.next_page_token == token
@pytest.mark.parametrize(
"request_type",
[
- logging_config.GetExclusionRequest,
+ logging_config.UpdateSettingsRequest,
dict,
],
)
-def test_get_exclusion(request_type, transport: str = "grpc"):
+def test_update_settings(request_type, transport: str = "grpc"):
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -4849,51 +11097,143 @@ def test_get_exclusion(request_type, transport: str = "grpc"):
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:
+ with mock.patch.object(type(client.transport.update_settings), "__call__") as call:
# Designate an appropriate return value for the call.
- call.return_value = logging_config.LogExclusion(
+ call.return_value = logging_config.Settings(
name="name_value",
- description="description_value",
- filter="filter_value",
- disabled=True,
+ kms_key_name="kms_key_name_value",
+ kms_service_account_id="kms_service_account_id_value",
+ storage_location="storage_location_value",
+ disable_default_sink=True,
)
- response = client.get_exclusion(request)
+ response = client.update_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.GetExclusionRequest()
+ request = logging_config.UpdateSettingsRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
- assert isinstance(response, logging_config.LogExclusion)
+ assert isinstance(response, logging_config.Settings)
assert response.name == "name_value"
- assert response.description == "description_value"
- assert response.filter == "filter_value"
- assert response.disabled is True
+ assert response.kms_key_name == "kms_key_name_value"
+ assert response.kms_service_account_id == "kms_service_account_id_value"
+ assert response.storage_location == "storage_location_value"
+ assert response.disable_default_sink is True
-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.
+def test_update_settings_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.UpdateSettingsRequest(
+ 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:
- client.get_exclusion()
+ with mock.patch.object(type(client.transport.update_settings), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_settings(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.GetExclusionRequest()
+ assert args[0] == logging_config.UpdateSettingsRequest(
+ name="name_value",
+ )
+
+
+def test_update_settings_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.update_settings in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.update_settings] = mock_rpc
+ request = {}
+ client.update_settings(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_settings(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
-async def test_get_exclusion_async(
- transport: str = "grpc_asyncio", request_type=logging_config.GetExclusionRequest
+async def test_update_settings_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.update_settings
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.update_settings
+ ] = mock_rpc
+
+ request = {}
+ await client.update_settings(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.update_settings(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_update_settings_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.UpdateSettingsRequest
):
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -4902,51 +11242,54 @@ async def test_get_exclusion_async(
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:
+ with mock.patch.object(type(client.transport.update_settings), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- logging_config.LogExclusion(
+ logging_config.Settings(
name="name_value",
- description="description_value",
- filter="filter_value",
- disabled=True,
+ kms_key_name="kms_key_name_value",
+ kms_service_account_id="kms_service_account_id_value",
+ storage_location="storage_location_value",
+ disable_default_sink=True,
)
)
- response = await client.get_exclusion(request)
+ response = await client.update_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.GetExclusionRequest()
+ request = logging_config.UpdateSettingsRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
- assert isinstance(response, logging_config.LogExclusion)
+ assert isinstance(response, logging_config.Settings)
assert response.name == "name_value"
- assert response.description == "description_value"
- assert response.filter == "filter_value"
- assert response.disabled is True
+ assert response.kms_key_name == "kms_key_name_value"
+ assert response.kms_service_account_id == "kms_service_account_id_value"
+ assert response.storage_location == "storage_location_value"
+ assert response.disable_default_sink is True
@pytest.mark.asyncio
-async def test_get_exclusion_async_from_dict():
- await test_get_exclusion_async(request_type=dict)
+async def test_update_settings_async_from_dict():
+ await test_update_settings_async(request_type=dict)
-def test_get_exclusion_field_headers():
+def test_update_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.GetExclusionRequest()
+ request = logging_config.UpdateSettingsRequest()
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)
+ with mock.patch.object(type(client.transport.update_settings), "__call__") as call:
+ call.return_value = logging_config.Settings()
+ client.update_settings(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
@@ -4962,23 +11305,23 @@ def test_get_exclusion_field_headers():
@pytest.mark.asyncio
-async def test_get_exclusion_field_headers_async():
+async def test_update_settings_field_headers_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# 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 = logging_config.UpdateSettingsRequest()
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:
+ with mock.patch.object(type(client.transport.update_settings), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- logging_config.LogExclusion()
+ logging_config.Settings()
)
- await client.get_exclusion(request)
+ await client.update_settings(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
@@ -4993,31 +11336,35 @@ async def test_get_exclusion_field_headers_async():
) in kw["metadata"]
-def test_get_exclusion_flattened():
+def test_update_settings_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:
+ with mock.patch.object(type(client.transport.update_settings), "__call__") as call:
# Designate an appropriate return value for the call.
- call.return_value = logging_config.LogExclusion()
+ call.return_value = logging_config.Settings()
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
- client.get_exclusion(
- name="name_value",
+ client.update_settings(
+ settings=logging_config.Settings(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]
- arg = args[0].name
- mock_val = "name_value"
+ arg = args[0].settings
+ mock_val = logging_config.Settings(name="name_value")
+ assert arg == mock_val
+ arg = args[0].update_mask
+ mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
assert arg == mock_val
-def test_get_exclusion_flattened_error():
+def test_update_settings_flattened_error():
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
)
@@ -5025,64 +11372,70 @@ def test_get_exclusion_flattened_error():
# 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",
+ client.update_settings(
+ logging_config.UpdateSettingsRequest(),
+ settings=logging_config.Settings(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
@pytest.mark.asyncio
-async def test_get_exclusion_flattened_async():
+async def test_update_settings_flattened_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client.transport.get_exclusion), "__call__") as call:
+ with mock.patch.object(type(client.transport.update_settings), "__call__") as call:
# Designate an appropriate return value for the call.
- call.return_value = logging_config.LogExclusion()
+ call.return_value = logging_config.Settings()
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- logging_config.LogExclusion()
+ logging_config.Settings()
)
# 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",
+ response = await client.update_settings(
+ settings=logging_config.Settings(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]
- arg = args[0].name
- mock_val = "name_value"
+ arg = args[0].settings
+ mock_val = logging_config.Settings(name="name_value")
+ assert arg == mock_val
+ arg = args[0].update_mask
+ mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
assert arg == mock_val
@pytest.mark.asyncio
-async def test_get_exclusion_flattened_error_async():
+async def test_update_settings_flattened_error_async():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# 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",
+ await client.update_settings(
+ logging_config.UpdateSettingsRequest(),
+ settings=logging_config.Settings(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
@pytest.mark.parametrize(
"request_type",
[
- logging_config.CreateExclusionRequest,
+ logging_config.CopyLogEntriesRequest,
dict,
],
)
-def test_create_exclusion(request_type, transport: str = "grpc"):
+def test_copy_log_entries(request_type, transport: str = "grpc"):
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -5093,51 +11446,148 @@ def test_create_exclusion(request_type, transport: str = "grpc"):
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:
+ with mock.patch.object(type(client.transport.copy_log_entries), "__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)
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+ response = client.copy_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_config.CreateExclusionRequest()
+ request = logging_config.CopyLogEntriesRequest()
+ assert args[0] == request
# 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
+ assert isinstance(response, future.Future)
-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.
+def test_copy_log_entries_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_config.CopyLogEntriesRequest(
+ name="name_value",
+ filter="filter_value",
+ destination="destination_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:
- client.create_exclusion()
+ with mock.patch.object(type(client.transport.copy_log_entries), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.copy_log_entries(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.CreateExclusionRequest()
+ assert args[0] == logging_config.CopyLogEntriesRequest(
+ name="name_value",
+ filter="filter_value",
+ destination="destination_value",
+ )
+
+
+def test_copy_log_entries_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.copy_log_entries in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.copy_log_entries
+ ] = mock_rpc
+ request = {}
+ client.copy_log_entries(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ # Operation methods call wrapper_fn to build a cached
+ # client._transport.operations_client instance on first rpc call.
+ # Subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ client.copy_log_entries(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
-async def test_create_exclusion_async(
- transport: str = "grpc_asyncio", request_type=logging_config.CreateExclusionRequest
+async def test_copy_log_entries_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.copy_log_entries
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.copy_log_entries
+ ] = mock_rpc
+
+ request = {}
+ await client.copy_log_entries(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ # Operation methods call wrapper_fn to build a cached
+ # client._transport.operations_client instance on first rpc call.
+ # Subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ await client.copy_log_entries(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_copy_log_entries_async(
+ transport: str = "grpc_asyncio", request_type=logging_config.CopyLogEntriesRequest
):
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -5146,1701 +11596,1737 @@ async def test_create_exclusion_async(
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:
+ with mock.patch.object(type(client.transport.copy_log_entries), "__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,
- )
+ operations_pb2.Operation(name="operations/spam")
)
- response = await client.create_exclusion(request)
+ response = await client.copy_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_config.CreateExclusionRequest()
+ request = logging_config.CopyLogEntriesRequest()
+ assert args[0] == request
# 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
+ assert isinstance(response, future.Future)
@pytest.mark.asyncio
-async def test_create_exclusion_async_from_dict():
- await test_create_exclusion_async(request_type=dict)
+async def test_copy_log_entries_async_from_dict():
+ await test_copy_log_entries_async(request_type=dict)
-def test_create_exclusion_field_headers():
- client = ConfigServiceV2Client(
+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,
+ )
- # 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()
+ # 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,
+ )
- request.parent = "parent_value"
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.ConfigServiceV2GrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = ConfigServiceV2Client(
+ client_options=options,
+ transport=transport,
+ )
- # 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)
+ # It is an error to provide an api_key and a credential.
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = ConfigServiceV2Client(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0] == request
+ # 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,
+ )
- # 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_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
-@pytest.mark.asyncio
-async def test_create_exclusion_field_headers_async():
- client = ConfigServiceV2AsyncClient(
+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_kind_grpc():
+ transport = ConfigServiceV2Client.get_transport_class("grpc")(
+ credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert transport.kind == "grpc"
+
+
+def test_initialize_client_w_grpc():
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
+ )
+ assert client is not None
- # 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"
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_list_buckets_empty_call_grpc():
+ 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:
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- logging_config.LogExclusion()
- )
- await client.create_exclusion(request)
+ # Mock the actual call, 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=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == request
+ request_msg = logging_config.ListBucketsRequest()
- # Establish that the field header was sent.
- _, _, kw = call.mock_calls[0]
- assert (
- "x-goog-request-params",
- "parent=parent_value",
- ) in kw["metadata"]
+ assert args[0] == request_msg
-def test_create_exclusion_flattened():
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_get_bucket_empty_call_grpc():
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:
- # 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"),
- )
+ # Mock the actual call, 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=None)
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- arg = args[0].parent
- mock_val = "parent_value"
- assert arg == mock_val
- arg = args[0].exclusion
- mock_val = logging_config.LogExclusion(name="name_value")
- assert arg == mock_val
+ request_msg = logging_config.GetBucketRequest()
+ assert args[0] == request_msg
-def test_create_exclusion_flattened_error():
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_create_bucket_async_empty_call_grpc():
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
)
- # 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"),
- )
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_bucket_async), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+ client.create_bucket_async(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_config.CreateBucketRequest()
+ assert args[0] == request_msg
-@pytest.mark.asyncio
-async def test_create_exclusion_flattened_async():
- client = ConfigServiceV2AsyncClient(
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_update_bucket_async_empty_call_grpc():
+ 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:
- # 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"),
- )
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_bucket_async), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+ client.update_bucket_async(request=None)
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- arg = args[0].parent
- mock_val = "parent_value"
- assert arg == mock_val
- arg = args[0].exclusion
- mock_val = logging_config.LogExclusion(name="name_value")
- assert arg == mock_val
+ request_msg = logging_config.UpdateBucketRequest()
+ assert args[0] == request_msg
-@pytest.mark.asyncio
-async def test_create_exclusion_flattened_error_async():
- client = ConfigServiceV2AsyncClient(
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_create_bucket_empty_call_grpc():
+ client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
)
- # 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"),
- )
+ # Mock the actual call, 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=None)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_config.CreateBucketRequest()
-@pytest.mark.parametrize(
- "request_type",
- [
- logging_config.UpdateExclusionRequest,
- dict,
- ],
-)
-def test_update_exclusion(request_type, transport: str = "grpc"):
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_update_bucket_empty_call_grpc():
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+ transport="grpc",
)
- # 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)
+ # Mock the actual call, 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=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.UpdateExclusionRequest()
+ request_msg = logging_config.UpdateBucketRequest()
- # 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
+ assert args[0] == request_msg
-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.
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_delete_bucket_empty_call_grpc():
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()
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.delete_bucket), "__call__") as call:
+ call.return_value = None
+ client.delete_bucket(request=None)
+
+ # Establish that the underlying stub method was called.
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.UpdateExclusionRequest()
+ request_msg = logging_config.DeleteBucketRequest()
+ assert args[0] == request_msg
-@pytest.mark.asyncio
-async def test_update_exclusion_async(
- transport: str = "grpc_asyncio", request_type=logging_config.UpdateExclusionRequest
-):
- client = ConfigServiceV2AsyncClient(
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_undelete_bucket_empty_call_grpc():
+ client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+ transport="grpc",
)
- # 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)
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.undelete_bucket), "__call__") as call:
+ call.return_value = None
+ client.undelete_bucket(request=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.UpdateExclusionRequest()
+ request_msg = logging_config.UndeleteBucketRequest()
- # 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
+ assert args[0] == request_msg
-@pytest.mark.asyncio
-async def test_update_exclusion_async_from_dict():
- await test_update_exclusion_async(request_type=dict)
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_list_views_empty_call_grpc():
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+ # Mock the actual call, 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=None)
-def test_update_exclusion_field_headers():
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_config.ListViewsRequest()
+
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_get_view_empty_call_grpc():
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
)
- # 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()
+ # Mock the actual call, 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=None)
- request.name = "name_value"
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_config.GetViewRequest()
- # 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)
+ assert args[0] == request_msg
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_create_view_empty_call_grpc():
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, 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=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == request
+ request_msg = logging_config.CreateViewRequest()
- # Establish that the field header was sent.
- _, _, kw = call.mock_calls[0]
- assert (
- "x-goog-request-params",
- "name=name_value",
- ) in kw["metadata"]
+ assert args[0] == request_msg
-@pytest.mark.asyncio
-async def test_update_exclusion_field_headers_async():
- client = ConfigServiceV2AsyncClient(
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_update_view_empty_call_grpc():
+ client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
)
- # 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()
+ # Mock the actual call, 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=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_config.UpdateViewRequest()
+
+ assert args[0] == request_msg
+
- request.name = "name_value"
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_delete_view_empty_call_grpc():
+ 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:
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- logging_config.LogExclusion()
- )
- await client.update_exclusion(request)
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.delete_view), "__call__") as call:
+ call.return_value = None
+ client.delete_view(request=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == request
+ request_msg = logging_config.DeleteViewRequest()
- # Establish that the field header was sent.
- _, _, kw = call.mock_calls[0]
- assert (
- "x-goog-request-params",
- "name=name_value",
- ) in kw["metadata"]
+ assert args[0] == request_msg
-def test_update_exclusion_flattened():
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_list_sinks_empty_call_grpc():
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:
- # 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"]),
- )
+ # Mock the actual call, 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=None)
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- arg = args[0].name
- mock_val = "name_value"
- assert arg == mock_val
- arg = args[0].exclusion
- mock_val = logging_config.LogExclusion(name="name_value")
- assert arg == mock_val
- arg = args[0].update_mask
- mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
- assert arg == mock_val
+ request_msg = logging_config.ListSinksRequest()
+ assert args[0] == request_msg
-def test_update_exclusion_flattened_error():
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_get_sink_empty_call_grpc():
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
)
- # 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"]),
- )
+ # Mock the actual call, 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=None)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_config.GetSinkRequest()
-@pytest.mark.asyncio
-async def test_update_exclusion_flattened_async():
- client = ConfigServiceV2AsyncClient(
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_create_sink_empty_call_grpc():
+ 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:
- # 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"]),
- )
+ # Mock the actual call, 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=None)
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- arg = args[0].name
- mock_val = "name_value"
- assert arg == mock_val
- arg = args[0].exclusion
- mock_val = logging_config.LogExclusion(name="name_value")
- assert arg == mock_val
- arg = args[0].update_mask
- mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
- assert arg == mock_val
+ request_msg = logging_config.CreateSinkRequest()
+ assert args[0] == request_msg
-@pytest.mark.asyncio
-async def test_update_exclusion_flattened_error_async():
- client = ConfigServiceV2AsyncClient(
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_update_sink_empty_call_grpc():
+ client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
)
- # 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"]),
- )
+ # Mock the actual call, 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=None)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_config.UpdateSinkRequest()
-@pytest.mark.parametrize(
- "request_type",
- [
- logging_config.DeleteExclusionRequest,
- dict,
- ],
-)
-def test_delete_exclusion(request_type, transport: str = "grpc"):
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_delete_sink_empty_call_grpc():
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+ transport="grpc",
)
- # 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.
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.delete_sink), "__call__") as call:
call.return_value = None
- response = client.delete_exclusion(request)
+ client.delete_sink(request=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.DeleteExclusionRequest()
+ request_msg = logging_config.DeleteSinkRequest()
- # Establish that the response is the type that we expect.
- assert response is None
+ assert args[0] == request_msg
-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.
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_create_link_empty_call_grpc():
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()
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.create_link), "__call__") as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+ client.create_link(request=None)
+
+ # Establish that the underlying stub method was called.
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.DeleteExclusionRequest()
+ request_msg = logging_config.CreateLinkRequest()
+ assert args[0] == request_msg
-@pytest.mark.asyncio
-async def test_delete_exclusion_async(
- transport: str = "grpc_asyncio", request_type=logging_config.DeleteExclusionRequest
-):
- client = ConfigServiceV2AsyncClient(
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_delete_link_empty_call_grpc():
+ client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+ transport="grpc",
)
- # 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)
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.delete_link), "__call__") as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+ client.delete_link(request=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, 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
+ request_msg = logging_config.DeleteLinkRequest()
-
-@pytest.mark.asyncio
-async def test_delete_exclusion_async_from_dict():
- await test_delete_exclusion_async(request_type=dict)
+ assert args[0] == request_msg
-def test_delete_exclusion_field_headers():
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_list_links_empty_call_grpc():
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
)
- # 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)
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.list_links), "__call__") as call:
+ call.return_value = logging_config.ListLinksResponse()
+ client.list_links(request=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == request
+ request_msg = logging_config.ListLinksRequest()
- # Establish that the field header was sent.
- _, _, kw = call.mock_calls[0]
- assert (
- "x-goog-request-params",
- "name=name_value",
- ) in kw["metadata"]
+ assert args[0] == request_msg
-@pytest.mark.asyncio
-async def test_delete_exclusion_field_headers_async():
- client = ConfigServiceV2AsyncClient(
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_get_link_empty_call_grpc():
+ client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
)
- # 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()
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_link), "__call__") as call:
+ call.return_value = logging_config.Link()
+ client.get_link(request=None)
- request.name = "name_value"
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_config.GetLinkRequest()
- # 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)
+ assert args[0] == request_msg
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls)
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_list_exclusions_empty_call_grpc():
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, 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=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == request
+ request_msg = logging_config.ListExclusionsRequest()
- # Establish that the field header was sent.
- _, _, kw = call.mock_calls[0]
- assert (
- "x-goog-request-params",
- "name=name_value",
- ) in kw["metadata"]
+ assert args[0] == request_msg
-def test_delete_exclusion_flattened():
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_get_exclusion_empty_call_grpc():
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:
- # 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",
- )
+ # Mock the actual call, 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=None)
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- arg = args[0].name
- mock_val = "name_value"
- assert arg == mock_val
+ request_msg = logging_config.GetExclusionRequest()
+ assert args[0] == request_msg
-def test_delete_exclusion_flattened_error():
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_create_exclusion_empty_call_grpc():
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
)
- # 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",
- )
+ # Mock the actual call, 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=None)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_config.CreateExclusionRequest()
-@pytest.mark.asyncio
-async def test_delete_exclusion_flattened_async():
- client = ConfigServiceV2AsyncClient(
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_update_exclusion_empty_call_grpc():
+ 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:
- # 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",
- )
+ # Mock the actual call, 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=None)
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- arg = args[0].name
- mock_val = "name_value"
- assert arg == mock_val
+ request_msg = logging_config.UpdateExclusionRequest()
+ assert args[0] == request_msg
-@pytest.mark.asyncio
-async def test_delete_exclusion_flattened_error_async():
- client = ConfigServiceV2AsyncClient(
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_delete_exclusion_empty_call_grpc():
+ client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
)
- # 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",
- )
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.delete_exclusion), "__call__") as call:
+ call.return_value = None
+ client.delete_exclusion(request=None)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_config.DeleteExclusionRequest()
-@pytest.mark.parametrize(
- "request_type",
- [
- logging_config.GetCmekSettingsRequest,
- dict,
- ],
-)
-def test_get_cmek_settings(request_type, transport: str = "grpc"):
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_get_cmek_settings_empty_call_grpc():
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+ transport="grpc",
)
- # 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.
+ # Mock the actual call, 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)
+ call.return_value = logging_config.CmekSettings()
+ client.get_cmek_settings(request=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.GetCmekSettingsRequest()
+ request_msg = 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"
+ assert args[0] == request_msg
-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.
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_update_cmek_settings_empty_call_grpc():
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
- # Mock the actual call within the gRPC stub, and fake the request.
+ # Mock the actual call, and fake the request.
with mock.patch.object(
- type(client.transport.get_cmek_settings), "__call__"
+ type(client.transport.update_cmek_settings), "__call__"
) as call:
- client.get_cmek_settings()
+ call.return_value = logging_config.CmekSettings()
+ client.update_cmek_settings(request=None)
+
+ # Establish that the underlying stub method was called.
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.GetCmekSettingsRequest()
+ request_msg = logging_config.UpdateCmekSettingsRequest()
+ assert args[0] == request_msg
-@pytest.mark.asyncio
-async def test_get_cmek_settings_async(
- transport: str = "grpc_asyncio", request_type=logging_config.GetCmekSettingsRequest
-):
- client = ConfigServiceV2AsyncClient(
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_get_settings_empty_call_grpc():
+ client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+ transport="grpc",
)
- # 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)
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_settings), "__call__") as call:
+ call.return_value = logging_config.Settings()
+ client.get_settings(request=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.GetCmekSettingsRequest()
+ request_msg = logging_config.GetSettingsRequest()
- # 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"
+ assert args[0] == request_msg
-@pytest.mark.asyncio
-async def test_get_cmek_settings_async_from_dict():
- await test_get_cmek_settings_async(request_type=dict)
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_update_settings_empty_call_grpc():
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.update_settings), "__call__") as call:
+ call.return_value = logging_config.Settings()
+ client.update_settings(request=None)
-def test_get_cmek_settings_field_headers():
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_config.UpdateSettingsRequest()
+
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_copy_log_entries_empty_call_grpc():
client = ConfigServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
)
- # 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()
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.copy_log_entries), "__call__") as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+ client.copy_log_entries(request=None)
- request.name = "name_value"
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_config.CopyLogEntriesRequest()
- # 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)
+ assert args[0] == request_msg
- # 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"]
+def test_transport_kind_grpc_asyncio():
+ transport = ConfigServiceV2AsyncClient.get_transport_class("grpc_asyncio")(
+ credentials=async_anonymous_credentials()
+ )
+ assert transport.kind == "grpc_asyncio"
-@pytest.mark.asyncio
-async def test_get_cmek_settings_field_headers_async():
+def test_initialize_client_w_grpc_asyncio():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(), transport="grpc_asyncio"
)
+ assert client is not None
- # 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"
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_list_buckets_empty_call_grpc_asyncio():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
- # 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:
+ # Mock the actual call, 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.CmekSettings()
+ logging_config.ListBucketsResponse(
+ next_page_token="next_page_token_value",
+ )
)
- await client.get_cmek_settings(request)
+ await client.list_buckets(request=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == request
+ request_msg = logging_config.ListBucketsRequest()
- # Establish that the field header was sent.
- _, _, kw = call.mock_calls[0]
- assert (
- "x-goog-request-params",
- "name=name_value",
- ) in kw["metadata"]
+ assert args[0] == request_msg
-@pytest.mark.parametrize(
- "request_type",
- [
- logging_config.UpdateCmekSettingsRequest,
- dict,
- ],
-)
-def test_update_cmek_settings(request_type, transport: str = "grpc"):
- client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_get_bucket_empty_call_grpc_asyncio():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # 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:
+ # Mock the actual call, 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.CmekSettings(
- name="name_value",
- kms_key_name="kms_key_name_value",
- service_account_id="service_account_id_value",
+ 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,
+ analytics_enabled=True,
+ restricted_fields=["restricted_fields_value"],
+ )
)
- response = client.update_cmek_settings(request)
+ await client.get_bucket(request=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.UpdateCmekSettingsRequest()
+ request_msg = logging_config.GetBucketRequest()
- # 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"
+ assert args[0] == request_msg
-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",
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_create_bucket_async_empty_call_grpc_asyncio():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # Mock the actual call within the gRPC stub, and fake the request.
+ # Mock the actual call, and fake the request.
with mock.patch.object(
- type(client.transport.update_cmek_settings), "__call__"
+ type(client.transport.create_bucket_async), "__call__"
) as call:
- client.update_cmek_settings()
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/spam")
+ )
+ await client.create_bucket_async(request=None)
+
+ # Establish that the underlying stub method was called.
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.UpdateCmekSettingsRequest()
+ request_msg = logging_config.CreateBucketRequest()
+ assert args[0] == request_msg
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
@pytest.mark.asyncio
-async def test_update_cmek_settings_async(
- transport: str = "grpc_asyncio",
- request_type=logging_config.UpdateCmekSettingsRequest,
-):
+async def test_update_bucket_async_empty_call_grpc_asyncio():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # 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.
+ # Mock the actual call, and fake the request.
with mock.patch.object(
- type(client.transport.update_cmek_settings), "__call__"
+ type(client.transport.update_bucket_async), "__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",
- )
+ operations_pb2.Operation(name="operations/spam")
)
- response = await client.update_cmek_settings(request)
+ await client.update_bucket_async(request=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.UpdateCmekSettingsRequest()
+ request_msg = logging_config.UpdateBucketRequest()
- # 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"
+ assert args[0] == request_msg
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
@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(),
+async def test_create_bucket_empty_call_grpc_asyncio():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # 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)
+ # Mock the actual call, 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,
+ analytics_enabled=True,
+ restricted_fields=["restricted_fields_value"],
+ )
+ )
+ await client.create_bucket(request=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == request
+ request_msg = logging_config.CreateBucketRequest()
- # Establish that the field header was sent.
- _, _, kw = call.mock_calls[0]
- assert (
- "x-goog-request-params",
- "name=name_value",
- ) in kw["metadata"]
+ assert args[0] == request_msg
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
@pytest.mark.asyncio
-async def test_update_cmek_settings_field_headers_async():
+async def test_update_bucket_empty_call_grpc_asyncio():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # 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:
+ # Mock the actual call, 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.CmekSettings()
+ logging_config.LogBucket(
+ name="name_value",
+ description="description_value",
+ retention_days=1512,
+ locked=True,
+ lifecycle_state=logging_config.LifecycleState.ACTIVE,
+ analytics_enabled=True,
+ restricted_fields=["restricted_fields_value"],
+ )
)
- await client.update_cmek_settings(request)
+ await client.update_bucket(request=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == request
+ request_msg = logging_config.UpdateBucketRequest()
- # Establish that the field header was sent.
- _, _, kw = call.mock_calls[0]
- assert (
- "x-goog-request-params",
- "name=name_value",
- ) in kw["metadata"]
+ assert args[0] == request_msg
-@pytest.mark.parametrize(
- "request_type",
- [
- logging_config.GetSettingsRequest,
- dict,
- ],
-)
-def test_get_settings(request_type, transport: str = "grpc"):
- client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_delete_bucket_empty_call_grpc_asyncio():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # 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_settings), "__call__") as call:
+ # Mock the actual call, 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 = logging_config.Settings(
- name="name_value",
- kms_key_name="kms_key_name_value",
- kms_service_account_id="kms_service_account_id_value",
- storage_location="storage_location_value",
- disable_default_sink=True,
- )
- response = client.get_settings(request)
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ await client.delete_bucket(request=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.GetSettingsRequest()
+ request_msg = logging_config.DeleteBucketRequest()
- # Establish that the response is the type that we expect.
- assert isinstance(response, logging_config.Settings)
- assert response.name == "name_value"
- assert response.kms_key_name == "kms_key_name_value"
- assert response.kms_service_account_id == "kms_service_account_id_value"
- assert response.storage_location == "storage_location_value"
- assert response.disable_default_sink is True
+ assert args[0] == request_msg
-def test_get_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",
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_undelete_bucket_empty_call_grpc_asyncio():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client.transport.get_settings), "__call__") as call:
- client.get_settings()
+ # Mock the actual call, 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)
+ await client.undelete_bucket(request=None)
+
+ # Establish that the underlying stub method was called.
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.GetSettingsRequest()
+ request_msg = logging_config.UndeleteBucketRequest()
+
+ assert args[0] == request_msg
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
@pytest.mark.asyncio
-async def test_get_settings_async(
- transport: str = "grpc_asyncio", request_type=logging_config.GetSettingsRequest
-):
+async def test_list_views_empty_call_grpc_asyncio():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # 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_settings), "__call__") as call:
+ # Mock the actual call, 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.Settings(
- name="name_value",
- kms_key_name="kms_key_name_value",
- kms_service_account_id="kms_service_account_id_value",
- storage_location="storage_location_value",
- disable_default_sink=True,
+ logging_config.ListViewsResponse(
+ next_page_token="next_page_token_value",
)
)
- response = await client.get_settings(request)
+ await client.list_views(request=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.GetSettingsRequest()
+ request_msg = logging_config.ListViewsRequest()
- # Establish that the response is the type that we expect.
- assert isinstance(response, logging_config.Settings)
- assert response.name == "name_value"
- assert response.kms_key_name == "kms_key_name_value"
- assert response.kms_service_account_id == "kms_service_account_id_value"
- assert response.storage_location == "storage_location_value"
- assert response.disable_default_sink is True
+ assert args[0] == request_msg
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
@pytest.mark.asyncio
-async def test_get_settings_async_from_dict():
- await test_get_settings_async(request_type=dict)
-
-
-def test_get_settings_field_headers():
- client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials(),
+async def test_get_view_empty_call_grpc_asyncio():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # 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.GetSettingsRequest()
-
- request.name = "name_value"
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client.transport.get_settings), "__call__") as call:
- call.return_value = logging_config.Settings()
- client.get_settings(request)
+ # Mock the actual call, 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",
+ )
+ )
+ await client.get_view(request=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == request
+ request_msg = logging_config.GetViewRequest()
- # Establish that the field header was sent.
- _, _, kw = call.mock_calls[0]
- assert (
- "x-goog-request-params",
- "name=name_value",
- ) in kw["metadata"]
+ assert args[0] == request_msg
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
@pytest.mark.asyncio
-async def test_get_settings_field_headers_async():
+async def test_create_view_empty_call_grpc_asyncio():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # 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.GetSettingsRequest()
-
- request.name = "name_value"
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client.transport.get_settings), "__call__") as call:
+ # Mock the actual call, 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.Settings()
+ logging_config.LogView(
+ name="name_value",
+ description="description_value",
+ filter="filter_value",
+ )
)
- await client.get_settings(request)
+ await client.create_view(request=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == request
+ request_msg = logging_config.CreateViewRequest()
- # Establish that the field header was sent.
- _, _, kw = call.mock_calls[0]
- assert (
- "x-goog-request-params",
- "name=name_value",
- ) in kw["metadata"]
+ assert args[0] == request_msg
-def test_get_settings_flattened():
- client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials(),
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_update_view_empty_call_grpc_asyncio():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client.transport.get_settings), "__call__") as call:
+ # Mock the actual call, 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.Settings()
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- client.get_settings(
- name="name_value",
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ logging_config.LogView(
+ name="name_value",
+ description="description_value",
+ filter="filter_value",
+ )
)
+ await client.update_view(request=None)
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- arg = args[0].name
- mock_val = "name_value"
- assert arg == mock_val
-
-
-def test_get_settings_flattened_error():
- client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials(),
- )
+ request_msg = logging_config.UpdateViewRequest()
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.get_settings(
- logging_config.GetSettingsRequest(),
- name="name_value",
- )
+ assert args[0] == request_msg
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
@pytest.mark.asyncio
-async def test_get_settings_flattened_async():
+async def test_delete_view_empty_call_grpc_asyncio():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client.transport.get_settings), "__call__") as call:
+ # Mock the actual call, 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 = logging_config.Settings()
-
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- logging_config.Settings()
- )
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = await client.get_settings(
- name="name_value",
- )
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ await client.delete_view(request=None)
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- arg = args[0].name
- mock_val = "name_value"
- assert arg == mock_val
+ request_msg = logging_config.DeleteViewRequest()
+ assert args[0] == request_msg
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
@pytest.mark.asyncio
-async def test_get_settings_flattened_error_async():
+async def test_list_sinks_empty_call_grpc_asyncio():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- await client.get_settings(
- logging_config.GetSettingsRequest(),
- name="name_value",
+ # Mock the actual call, 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",
+ )
)
+ await client.list_sinks(request=None)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_config.ListSinksRequest()
-@pytest.mark.parametrize(
- "request_type",
- [
- logging_config.UpdateSettingsRequest,
- dict,
- ],
-)
-def test_update_settings(request_type, transport: str = "grpc"):
- client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
+ assert args[0] == request_msg
- # 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_settings), "__call__") as call:
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_get_sink_empty_call_grpc_asyncio():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, 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.Settings(
- name="name_value",
- kms_key_name="kms_key_name_value",
- kms_service_account_id="kms_service_account_id_value",
- storage_location="storage_location_value",
- disable_default_sink=True,
+ 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 = client.update_settings(request)
+ await client.get_sink(request=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.UpdateSettingsRequest()
+ request_msg = logging_config.GetSinkRequest()
- # Establish that the response is the type that we expect.
- assert isinstance(response, logging_config.Settings)
- assert response.name == "name_value"
- assert response.kms_key_name == "kms_key_name_value"
- assert response.kms_service_account_id == "kms_service_account_id_value"
- assert response.storage_location == "storage_location_value"
- assert response.disable_default_sink is True
+ assert args[0] == request_msg
-def test_update_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",
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_create_sink_empty_call_grpc_asyncio():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client.transport.update_settings), "__call__") as call:
- client.update_settings()
+ # Mock the actual call, 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,
+ )
+ )
+ await client.create_sink(request=None)
+
+ # Establish that the underlying stub method was called.
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.UpdateSettingsRequest()
+ request_msg = logging_config.CreateSinkRequest()
+ assert args[0] == request_msg
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
@pytest.mark.asyncio
-async def test_update_settings_async(
- transport: str = "grpc_asyncio", request_type=logging_config.UpdateSettingsRequest
-):
+async def test_update_sink_empty_call_grpc_asyncio():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # 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_settings), "__call__") as call:
+ # Mock the actual call, 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.Settings(
+ logging_config.LogSink(
name="name_value",
- kms_key_name="kms_key_name_value",
- kms_service_account_id="kms_service_account_id_value",
- storage_location="storage_location_value",
- disable_default_sink=True,
+ 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_settings(request)
+ await client.update_sink(request=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.UpdateSettingsRequest()
+ request_msg = logging_config.UpdateSinkRequest()
- # Establish that the response is the type that we expect.
- assert isinstance(response, logging_config.Settings)
- assert response.name == "name_value"
- assert response.kms_key_name == "kms_key_name_value"
- assert response.kms_service_account_id == "kms_service_account_id_value"
- assert response.storage_location == "storage_location_value"
- assert response.disable_default_sink is True
+ assert args[0] == request_msg
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
@pytest.mark.asyncio
-async def test_update_settings_async_from_dict():
- await test_update_settings_async(request_type=dict)
+async def test_delete_sink_empty_call_grpc_asyncio():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+ # Mock the actual call, 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)
+ await client.delete_sink(request=None)
-def test_update_settings_field_headers():
- client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials(),
- )
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_config.DeleteSinkRequest()
- # 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.UpdateSettingsRequest()
+ assert args[0] == request_msg
- request.name = "name_value"
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client.transport.update_settings), "__call__") as call:
- call.return_value = logging_config.Settings()
- client.update_settings(request)
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_create_link_empty_call_grpc_asyncio():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.create_link), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/spam")
+ )
+ await client.create_link(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == request
+ request_msg = logging_config.CreateLinkRequest()
- # Establish that the field header was sent.
- _, _, kw = call.mock_calls[0]
- assert (
- "x-goog-request-params",
- "name=name_value",
- ) in kw["metadata"]
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_delete_link_empty_call_grpc_asyncio():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.delete_link), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/spam")
+ )
+ await client.delete_link(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_config.DeleteLinkRequest()
+
+ assert args[0] == request_msg
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
@pytest.mark.asyncio
-async def test_update_settings_field_headers_async():
+async def test_list_links_empty_call_grpc_asyncio():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # 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.UpdateSettingsRequest()
-
- request.name = "name_value"
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client.transport.update_settings), "__call__") as call:
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.list_links), "__call__") as call:
+ # Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- logging_config.Settings()
+ logging_config.ListLinksResponse(
+ next_page_token="next_page_token_value",
+ )
)
- await client.update_settings(request)
+ await client.list_links(request=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == request
+ request_msg = logging_config.ListLinksRequest()
- # Establish that the field header was sent.
- _, _, kw = call.mock_calls[0]
- assert (
- "x-goog-request-params",
- "name=name_value",
- ) in kw["metadata"]
+ assert args[0] == request_msg
-def test_update_settings_flattened():
- client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials(),
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_get_link_empty_call_grpc_asyncio():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client.transport.update_settings), "__call__") as call:
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_link), "__call__") as call:
# Designate an appropriate return value for the call.
- call.return_value = logging_config.Settings()
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- client.update_settings(
- settings=logging_config.Settings(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ logging_config.Link(
+ name="name_value",
+ description="description_value",
+ lifecycle_state=logging_config.LifecycleState.ACTIVE,
+ )
)
+ await client.get_link(request=None)
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- arg = args[0].settings
- mock_val = logging_config.Settings(name="name_value")
- assert arg == mock_val
- arg = args[0].update_mask
- mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
- assert arg == mock_val
+ request_msg = logging_config.GetLinkRequest()
+ assert args[0] == request_msg
-def test_update_settings_flattened_error():
- client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials(),
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_list_exclusions_empty_call_grpc_asyncio():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.update_settings(
- logging_config.UpdateSettingsRequest(),
- settings=logging_config.Settings(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ # Mock the actual call, 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",
+ )
)
+ await client.list_exclusions(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_config.ListExclusionsRequest()
+ assert args[0] == request_msg
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
@pytest.mark.asyncio
-async def test_update_settings_flattened_async():
+async def test_get_exclusion_empty_call_grpc_asyncio():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client.transport.update_settings), "__call__") as call:
+ # Mock the actual call, 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.Settings()
-
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- logging_config.Settings()
- )
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = await client.update_settings(
- settings=logging_config.Settings(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ logging_config.LogExclusion(
+ name="name_value",
+ description="description_value",
+ filter="filter_value",
+ disabled=True,
+ )
)
+ await client.get_exclusion(request=None)
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- arg = args[0].settings
- mock_val = logging_config.Settings(name="name_value")
- assert arg == mock_val
- arg = args[0].update_mask
- mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
- assert arg == mock_val
+ request_msg = logging_config.GetExclusionRequest()
+ assert args[0] == request_msg
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
@pytest.mark.asyncio
-async def test_update_settings_flattened_error_async():
+async def test_create_exclusion_empty_call_grpc_asyncio():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- await client.update_settings(
- logging_config.UpdateSettingsRequest(),
- settings=logging_config.Settings(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ # Mock the actual call, 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,
+ )
)
+ await client.create_exclusion(request=None)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_config.CreateExclusionRequest()
-@pytest.mark.parametrize(
- "request_type",
- [
- logging_config.CopyLogEntriesRequest,
- dict,
- ],
-)
-def test_copy_log_entries(request_type, transport: str = "grpc"):
- client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
+ assert args[0] == request_msg
- # 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.copy_log_entries), "__call__") as call:
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_update_exclusion_empty_call_grpc_asyncio():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, 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 = operations_pb2.Operation(name="operations/spam")
- response = client.copy_log_entries(request)
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ logging_config.LogExclusion(
+ name="name_value",
+ description="description_value",
+ filter="filter_value",
+ disabled=True,
+ )
+ )
+ await client.update_exclusion(request=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.CopyLogEntriesRequest()
+ request_msg = logging_config.UpdateExclusionRequest()
- # Establish that the response is the type that we expect.
- assert isinstance(response, future.Future)
+ assert args[0] == request_msg
-def test_copy_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 = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_delete_exclusion_empty_call_grpc_asyncio():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client.transport.copy_log_entries), "__call__") as call:
- client.copy_log_entries()
+ # Mock the actual call, 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)
+ await client.delete_exclusion(request=None)
+
+ # Establish that the underlying stub method was called.
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.CopyLogEntriesRequest()
+ request_msg = logging_config.DeleteExclusionRequest()
+ assert args[0] == request_msg
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
@pytest.mark.asyncio
-async def test_copy_log_entries_async(
- transport: str = "grpc_asyncio", request_type=logging_config.CopyLogEntriesRequest
-):
+async def test_get_cmek_settings_empty_call_grpc_asyncio():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- # 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.copy_log_entries), "__call__") as call:
+ # Mock the actual call, 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(
- operations_pb2.Operation(name="operations/spam")
+ logging_config.CmekSettings(
+ name="name_value",
+ kms_key_name="kms_key_name_value",
+ kms_key_version_name="kms_key_version_name_value",
+ service_account_id="service_account_id_value",
+ )
)
- response = await client.copy_log_entries(request)
+ await client.get_cmek_settings(request=None)
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_config.CopyLogEntriesRequest()
+ request_msg = logging_config.GetCmekSettingsRequest()
- # Establish that the response is the type that we expect.
- assert isinstance(response, future.Future)
+ assert args[0] == request_msg
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
@pytest.mark.asyncio
-async def test_copy_log_entries_async_from_dict():
- await test_copy_log_entries_async(request_type=dict)
-
-
-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(),
+async def test_update_cmek_settings_empty_call_grpc_asyncio():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- with pytest.raises(ValueError):
- client = ConfigServiceV2Client(
- client_options={"credentials_file": "credentials.json"},
- transport=transport,
- )
- # It is an error to provide an api_key and a transport instance.
- transport = transports.ConfigServiceV2GrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = ConfigServiceV2Client(
- client_options=options,
- transport=transport,
+ # Mock the actual call, 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",
+ kms_key_version_name="kms_key_version_name_value",
+ service_account_id="service_account_id_value",
+ )
)
+ await client.update_cmek_settings(request=None)
- # It is an error to provide an api_key and a credential.
- options = mock.Mock()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = ConfigServiceV2Client(
- client_options=options, credentials=ga_credentials.AnonymousCredentials()
- )
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_config.UpdateCmekSettingsRequest()
- # It is an error to provide scopes and a transport instance.
- transport = transports.ConfigServiceV2GrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_get_settings_empty_call_grpc_asyncio():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- with pytest.raises(ValueError):
- client = ConfigServiceV2Client(
- client_options={"scopes": ["1", "2"]},
- transport=transport,
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_settings), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ logging_config.Settings(
+ name="name_value",
+ kms_key_name="kms_key_name_value",
+ kms_service_account_id="kms_service_account_id_value",
+ storage_location="storage_location_value",
+ disable_default_sink=True,
+ )
)
+ await client.get_settings(request=None)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_config.GetSettingsRequest()
-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
+ assert args[0] == request_msg
-def test_transport_get_channel():
- # A client may be instantiated with a custom transport instance.
- transport = transports.ConfigServiceV2GrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_update_settings_empty_call_grpc_asyncio():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- channel = transport.grpc_channel
- assert channel
- transport = transports.ConfigServiceV2GrpcAsyncIOTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.update_settings), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ logging_config.Settings(
+ name="name_value",
+ kms_key_name="kms_key_name_value",
+ kms_service_account_id="kms_service_account_id_value",
+ storage_location="storage_location_value",
+ disable_default_sink=True,
+ )
+ )
+ await client.update_settings(request=None)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_config.UpdateSettingsRequest()
-@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()
+ assert args[0] == request_msg
-@pytest.mark.parametrize(
- "transport_name",
- [
- "grpc",
- ],
-)
-def test_transport_kind(transport_name):
- transport = ConfigServiceV2Client.get_transport_class(transport_name)(
- credentials=ga_credentials.AnonymousCredentials(),
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_copy_log_entries_empty_call_grpc_asyncio():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
)
- assert transport.kind == transport_name
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.copy_log_entries), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/spam")
+ )
+ await client.copy_log_entries(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_config.CopyLogEntriesRequest()
+
+ assert args[0] == request_msg
def test_transport_grpc_default():
@@ -6878,6 +13364,8 @@ def test_config_service_v2_base_transport():
methods = (
"list_buckets",
"get_bucket",
+ "create_bucket_async",
+ "update_bucket_async",
"create_bucket",
"update_bucket",
"delete_bucket",
@@ -6892,6 +13380,10 @@ def test_config_service_v2_base_transport():
"create_sink",
"update_sink",
"delete_sink",
+ "create_link",
+ "delete_link",
+ "list_links",
+ "get_link",
"list_exclusions",
"get_exclusion",
"create_exclusion",
@@ -6902,6 +13394,9 @@ def test_config_service_v2_base_transport():
"get_settings",
"update_settings",
"copy_log_entries",
+ "get_operation",
+ "cancel_operation",
+ "list_operations",
)
for method in methods:
with pytest.raises(NotImplementedError):
@@ -7296,316 +13791,770 @@ def test_config_service_v2_grpc_lro_async_client():
)
transport = client.transport
- # Ensure that we have a api-core operations client.
- assert isinstance(
- transport.operations_client,
- operations_v1.OperationsAsyncClient,
+ # Ensure that we have a api-core operations client.
+ assert isinstance(
+ transport.operations_client,
+ operations_v1.OperationsAsyncClient,
+ )
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_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_link_path():
+ project = "whelk"
+ location = "octopus"
+ bucket = "oyster"
+ link = "nudibranch"
+ expected = (
+ "projects/{project}/locations/{location}/buckets/{bucket}/links/{link}".format(
+ project=project,
+ location=location,
+ bucket=bucket,
+ link=link,
+ )
+ )
+ actual = ConfigServiceV2Client.link_path(project, location, bucket, link)
+ assert expected == actual
+
+
+def test_parse_link_path():
+ expected = {
+ "project": "cuttlefish",
+ "location": "mussel",
+ "bucket": "winkle",
+ "link": "nautilus",
+ }
+ path = ConfigServiceV2Client.link_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ConfigServiceV2Client.parse_link_path(path)
+ assert expected == actual
+
+
+def test_log_bucket_path():
+ project = "scallop"
+ location = "abalone"
+ bucket = "squid"
+ 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": "clam",
+ "location": "whelk",
+ "bucket": "octopus",
+ }
+ 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 = "oyster"
+ exclusion = "nudibranch"
+ 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": "cuttlefish",
+ "exclusion": "mussel",
+ }
+ 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 = "winkle"
+ sink = "nautilus"
+ 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": "scallop",
+ "sink": "abalone",
+ }
+ 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 = "squid"
+ location = "clam"
+ bucket = "whelk"
+ view = "octopus"
+ 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": "oyster",
+ "location": "nudibranch",
+ "bucket": "cuttlefish",
+ "view": "mussel",
+ }
+ 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_settings_path():
+ project = "winkle"
+ expected = "projects/{project}/settings".format(
+ project=project,
+ )
+ actual = ConfigServiceV2Client.settings_path(project)
+ assert expected == actual
+
+
+def test_parse_settings_path():
+ expected = {
+ "project": "nautilus",
+ }
+ path = ConfigServiceV2Client.settings_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ConfigServiceV2Client.parse_settings_path(path)
+ assert expected == actual
+
+
+def test_common_billing_account_path():
+ billing_account = "scallop"
+ expected = "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
)
+ actual = ConfigServiceV2Client.common_billing_account_path(billing_account)
+ assert expected == actual
- # Ensure that subsequent calls to the property send the exact same object.
- assert transport.operations_client is transport.operations_client
+def test_parse_common_billing_account_path():
+ expected = {
+ "billing_account": "abalone",
+ }
+ 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_cmek_settings_path():
- project = "squid"
- expected = "projects/{project}/cmekSettings".format(
- project=project,
+
+def test_common_folder_path():
+ folder = "squid"
+ expected = "folders/{folder}".format(
+ folder=folder,
)
- actual = ConfigServiceV2Client.cmek_settings_path(project)
+ actual = ConfigServiceV2Client.common_folder_path(folder)
assert expected == actual
-def test_parse_cmek_settings_path():
+def test_parse_common_folder_path():
expected = {
- "project": "clam",
+ "folder": "clam",
}
- path = ConfigServiceV2Client.cmek_settings_path(**expected)
+ path = ConfigServiceV2Client.common_folder_path(**expected)
# Check that the path construction is reversible.
- actual = ConfigServiceV2Client.parse_cmek_settings_path(path)
+ actual = ConfigServiceV2Client.parse_common_folder_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,
+def test_common_organization_path():
+ organization = "whelk"
+ expected = "organizations/{organization}".format(
+ organization=organization,
)
- actual = ConfigServiceV2Client.log_bucket_path(project, location, bucket)
+ actual = ConfigServiceV2Client.common_organization_path(organization)
assert expected == actual
-def test_parse_log_bucket_path():
+def test_parse_common_organization_path():
expected = {
- "project": "nudibranch",
- "location": "cuttlefish",
- "bucket": "mussel",
+ "organization": "octopus",
}
- path = ConfigServiceV2Client.log_bucket_path(**expected)
+ path = ConfigServiceV2Client.common_organization_path(**expected)
# Check that the path construction is reversible.
- actual = ConfigServiceV2Client.parse_log_bucket_path(path)
+ actual = ConfigServiceV2Client.parse_common_organization_path(path)
assert expected == actual
-def test_log_exclusion_path():
- project = "winkle"
- exclusion = "nautilus"
- expected = "projects/{project}/exclusions/{exclusion}".format(
+def test_common_project_path():
+ project = "oyster"
+ expected = "projects/{project}".format(
project=project,
- exclusion=exclusion,
)
- actual = ConfigServiceV2Client.log_exclusion_path(project, exclusion)
+ actual = ConfigServiceV2Client.common_project_path(project)
assert expected == actual
-def test_parse_log_exclusion_path():
+def test_parse_common_project_path():
expected = {
- "project": "scallop",
- "exclusion": "abalone",
+ "project": "nudibranch",
}
- path = ConfigServiceV2Client.log_exclusion_path(**expected)
+ path = ConfigServiceV2Client.common_project_path(**expected)
# Check that the path construction is reversible.
- actual = ConfigServiceV2Client.parse_log_exclusion_path(path)
+ actual = ConfigServiceV2Client.parse_common_project_path(path)
assert expected == actual
-def test_log_sink_path():
- project = "squid"
- sink = "clam"
- expected = "projects/{project}/sinks/{sink}".format(
+def test_common_location_path():
+ project = "cuttlefish"
+ location = "mussel"
+ expected = "projects/{project}/locations/{location}".format(
project=project,
- sink=sink,
+ location=location,
)
- actual = ConfigServiceV2Client.log_sink_path(project, sink)
+ actual = ConfigServiceV2Client.common_location_path(project, location)
assert expected == actual
-def test_parse_log_sink_path():
+def test_parse_common_location_path():
expected = {
- "project": "whelk",
- "sink": "octopus",
+ "project": "winkle",
+ "location": "nautilus",
}
- path = ConfigServiceV2Client.log_sink_path(**expected)
+ path = ConfigServiceV2Client.common_location_path(**expected)
# Check that the path construction is reversible.
- actual = ConfigServiceV2Client.parse_log_sink_path(path)
+ actual = ConfigServiceV2Client.parse_common_location_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,
- )
+def test_client_with_default_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)
+
+
+def test_cancel_operation(transport: str = "grpc"):
+ 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 = operations_pb2.CancelOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+ response = client.cancel_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = operations_pb2.CancelOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.cancel_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_cancel_operation_field_headers():
+ client = 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 = operations_pb2.CancelOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ call.return_value = None
+
+ client.cancel_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "name=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_field_headers_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = operations_pb2.CancelOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ await client.cancel_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "name=locations",
+ ) in kw["metadata"]
+
+
+def test_cancel_operation_from_dict():
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ response = client.cancel_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_from_dict_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.cancel_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_get_operation(transport: str = "grpc"):
+ client = 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 = operations_pb2.GetOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+ response = client.get_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+@pytest.mark.asyncio
+async def test_get_operation_async(transport: str = "grpc_asyncio"):
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = operations_pb2.GetOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ response = await client.get_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+def test_get_operation_field_headers():
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
)
- actual = ConfigServiceV2Client.log_view_path(project, location, bucket, view)
- assert expected == actual
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = operations_pb2.GetOperationRequest()
+ request.name = "locations"
-def test_parse_log_view_path():
- expected = {
- "project": "winkle",
- "location": "nautilus",
- "bucket": "scallop",
- "view": "abalone",
- }
- path = ConfigServiceV2Client.log_view_path(**expected)
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ call.return_value = operations_pb2.Operation()
- # Check that the path construction is reversible.
- actual = ConfigServiceV2Client.parse_log_view_path(path)
- assert expected == actual
+ client.get_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "name=locations",
+ ) in kw["metadata"]
-def test_settings_path():
- project = "squid"
- expected = "projects/{project}/settings".format(
- project=project,
+
+@pytest.mark.asyncio
+async def test_get_operation_field_headers_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
)
- actual = ConfigServiceV2Client.settings_path(project)
- assert expected == actual
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = operations_pb2.GetOperationRequest()
+ request.name = "locations"
-def test_parse_settings_path():
- expected = {
- "project": "clam",
- }
- path = ConfigServiceV2Client.settings_path(**expected)
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ await client.get_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
- # Check that the path construction is reversible.
- actual = ConfigServiceV2Client.parse_settings_path(path)
- assert expected == actual
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "name=locations",
+ ) in kw["metadata"]
-def test_common_billing_account_path():
- billing_account = "whelk"
- expected = "billingAccounts/{billing_account}".format(
- billing_account=billing_account,
+def test_get_operation_from_dict():
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
)
- actual = ConfigServiceV2Client.common_billing_account_path(billing_account)
- assert expected == actual
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+ response = client.get_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
-def test_parse_common_billing_account_path():
- expected = {
- "billing_account": "octopus",
- }
- 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
+@pytest.mark.asyncio
+async def test_get_operation_from_dict_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ response = await client.get_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
-def test_common_folder_path():
- folder = "oyster"
- expected = "folders/{folder}".format(
- folder=folder,
+def test_list_operations(transport: str = "grpc"):
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- actual = ConfigServiceV2Client.common_folder_path(folder)
- assert expected == actual
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = operations_pb2.ListOperationsRequest()
-def test_parse_common_folder_path():
- expected = {
- "folder": "nudibranch",
- }
- path = ConfigServiceV2Client.common_folder_path(**expected)
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+ response = client.list_operations(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
- # Check that the path construction is reversible.
- actual = ConfigServiceV2Client.parse_common_folder_path(path)
- assert expected == actual
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
-def test_common_organization_path():
- organization = "cuttlefish"
- expected = "organizations/{organization}".format(
- organization=organization,
+@pytest.mark.asyncio
+async def test_list_operations_async(transport: str = "grpc_asyncio"):
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
)
- actual = ConfigServiceV2Client.common_organization_path(organization)
- assert expected == actual
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = operations_pb2.ListOperationsRequest()
-def test_parse_common_organization_path():
- expected = {
- "organization": "mussel",
- }
- path = ConfigServiceV2Client.common_organization_path(**expected)
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ response = await client.list_operations(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
- # Check that the path construction is reversible.
- actual = ConfigServiceV2Client.parse_common_organization_path(path)
- assert expected == actual
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
-def test_common_project_path():
- project = "winkle"
- expected = "projects/{project}".format(
- project=project,
+def test_list_operations_field_headers():
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
)
- actual = ConfigServiceV2Client.common_project_path(project)
- assert expected == actual
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = operations_pb2.ListOperationsRequest()
+ request.name = "locations"
-def test_parse_common_project_path():
- expected = {
- "project": "nautilus",
- }
- path = ConfigServiceV2Client.common_project_path(**expected)
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ call.return_value = operations_pb2.ListOperationsResponse()
- # Check that the path construction is reversible.
- actual = ConfigServiceV2Client.parse_common_project_path(path)
- assert expected == actual
+ client.list_operations(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "name=locations",
+ ) in kw["metadata"]
-def test_common_location_path():
- project = "scallop"
- location = "abalone"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
+
+@pytest.mark.asyncio
+async def test_list_operations_field_headers_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
)
- actual = ConfigServiceV2Client.common_location_path(project, location)
- assert expected == actual
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = operations_pb2.ListOperationsRequest()
+ request.name = "locations"
-def test_parse_common_location_path():
- expected = {
- "project": "squid",
- "location": "clam",
- }
- path = ConfigServiceV2Client.common_location_path(**expected)
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ await client.list_operations(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
- # Check that the path construction is reversible.
- actual = ConfigServiceV2Client.parse_common_location_path(path)
- assert expected == actual
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "name=locations",
+ ) in kw["metadata"]
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
+def test_list_operations_from_dict():
+ 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_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
- with mock.patch.object(
- transports.ConfigServiceV2Transport, "_prep_wrapped_messages"
- ) as prep:
- client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
+ response = client.list_operations(
+ request={
+ "name": "locations",
+ }
)
- prep.assert_called_once_with(client_info)
+ call.assert_called()
- 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,
+
+@pytest.mark.asyncio
+async def test_list_operations_from_dict_async():
+ client = ConfigServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
)
- prep.assert_called_once_with(client_info)
+ response = await client.list_operations(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_transport_close_grpc():
+ client = ConfigServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_grpc_channel")), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
@pytest.mark.asyncio
-async def test_transport_close_async():
+async def test_transport_close_grpc_asyncio():
client = ConfigServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc_asyncio",
+ credentials=async_anonymous_credentials(), transport="grpc_asyncio"
)
with mock.patch.object(
- type(getattr(client.transport, "grpc_channel")), "close"
+ type(getattr(client.transport, "_grpc_channel")), "close"
) as close:
async with client:
close.assert_not_called()
close.assert_called_once()
-def test_transport_close():
- transports = {
- "grpc": "_grpc_channel",
- }
-
- for transport, close_name in transports.items():
- client = ConfigServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials(), transport=transport
- )
- with mock.patch.object(
- type(getattr(client.transport, close_name)), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
-
-
def test_client_ctx():
transports = [
"grpc",
@@ -7643,7 +14592,9 @@ def test_api_key_credentials(client_class, transport_class):
patched.assert_called_once_with(
credentials=mock_cred,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
diff --git a/tests/unit/gapic/logging_v2/test_logging_service_v2.py b/tests/unit/gapic/logging_v2/test_logging_service_v2.py
index d8bbd5b73..ef3833740 100644
--- a/tests/unit/gapic/logging_v2/test_logging_service_v2.py
+++ b/tests/unit/gapic/logging_v2/test_logging_service_v2.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -24,11 +24,20 @@
import grpc
from grpc.experimental import aio
+import json
import math
import pytest
+from google.api_core import api_core_version
from proto.marshal.rules.dates import DurationRule, TimestampRule
from proto.marshal.rules import wrappers
+try:
+ from google.auth.aio import credentials as ga_credentials_async
+
+ HAS_GOOGLE_AUTH_AIO = True
+except ImportError: # pragma: NO COVER
+ HAS_GOOGLE_AUTH_AIO = False
+
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
@@ -36,6 +45,7 @@
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
from google.api_core import path_template
+from google.api_core import retry as retries
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.logging_v2.services.logging_service_v2 import (
@@ -48,6 +58,7 @@
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.longrunning import operations_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
@@ -56,10 +67,32 @@
import google.auth
+CRED_INFO_JSON = {
+ "credential_source": "/path/to/file",
+ "credential_type": "service account credentials",
+ "principal": "service-account@example.com",
+}
+CRED_INFO_STRING = json.dumps(CRED_INFO_JSON)
+
+
+async def mock_async_gen(data, chunk_size=1):
+ for i in range(0, len(data)): # pragma: NO COVER
+ chunk = data[i : i + chunk_size]
+ yield chunk.encode("utf-8")
+
+
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
+# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
+# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
+def async_anonymous_credentials():
+ if HAS_GOOGLE_AUTH_AIO:
+ return ga_credentials_async.AnonymousCredentials()
+ return ga_credentials.AnonymousCredentials()
+
+
# 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.
@@ -71,6 +104,17 @@ def modify_default_endpoint(client):
)
+# If default endpoint template is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint template so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint_template(client):
+ return (
+ "test.{UNIVERSE_DOMAIN}"
+ if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE)
+ else client._DEFAULT_ENDPOINT_TEMPLATE
+ )
+
+
def test__get_default_mtls_endpoint():
api_endpoint = "example.googleapis.com"
api_mtls_endpoint = "example.mtls.googleapis.com"
@@ -101,6 +145,237 @@ def test__get_default_mtls_endpoint():
)
+def test__read_environment_variables():
+ assert LoggingServiceV2Client._read_environment_variables() == (False, "auto", None)
+
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ assert LoggingServiceV2Client._read_environment_variables() == (
+ True,
+ "auto",
+ None,
+ )
+
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}):
+ assert LoggingServiceV2Client._read_environment_variables() == (
+ False,
+ "auto",
+ None,
+ )
+
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}
+ ):
+ with pytest.raises(ValueError) as excinfo:
+ LoggingServiceV2Client._read_environment_variables()
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
+ )
+
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ assert LoggingServiceV2Client._read_environment_variables() == (
+ False,
+ "never",
+ None,
+ )
+
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ assert LoggingServiceV2Client._read_environment_variables() == (
+ False,
+ "always",
+ None,
+ )
+
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}):
+ assert LoggingServiceV2Client._read_environment_variables() == (
+ False,
+ "auto",
+ None,
+ )
+
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
+ with pytest.raises(MutualTLSChannelError) as excinfo:
+ LoggingServiceV2Client._read_environment_variables()
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
+ )
+
+ with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}):
+ assert LoggingServiceV2Client._read_environment_variables() == (
+ False,
+ "auto",
+ "foo.com",
+ )
+
+
+def test__get_client_cert_source():
+ mock_provided_cert_source = mock.Mock()
+ mock_default_cert_source = mock.Mock()
+
+ assert LoggingServiceV2Client._get_client_cert_source(None, False) is None
+ assert (
+ LoggingServiceV2Client._get_client_cert_source(mock_provided_cert_source, False)
+ is None
+ )
+ assert (
+ LoggingServiceV2Client._get_client_cert_source(mock_provided_cert_source, True)
+ == mock_provided_cert_source
+ )
+
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source", return_value=True
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=mock_default_cert_source,
+ ):
+ assert (
+ LoggingServiceV2Client._get_client_cert_source(None, True)
+ is mock_default_cert_source
+ )
+ assert (
+ LoggingServiceV2Client._get_client_cert_source(
+ mock_provided_cert_source, "true"
+ )
+ is mock_provided_cert_source
+ )
+
+
+@mock.patch.object(
+ LoggingServiceV2Client,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(LoggingServiceV2Client),
+)
+@mock.patch.object(
+ LoggingServiceV2AsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(LoggingServiceV2AsyncClient),
+)
+def test__get_api_endpoint():
+ api_override = "foo.com"
+ mock_client_cert_source = mock.Mock()
+ default_universe = LoggingServiceV2Client._DEFAULT_UNIVERSE
+ default_endpoint = LoggingServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=default_universe
+ )
+ mock_universe = "bar.com"
+ mock_endpoint = LoggingServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=mock_universe
+ )
+
+ assert (
+ LoggingServiceV2Client._get_api_endpoint(
+ api_override, mock_client_cert_source, default_universe, "always"
+ )
+ == api_override
+ )
+ assert (
+ LoggingServiceV2Client._get_api_endpoint(
+ None, mock_client_cert_source, default_universe, "auto"
+ )
+ == LoggingServiceV2Client.DEFAULT_MTLS_ENDPOINT
+ )
+ assert (
+ LoggingServiceV2Client._get_api_endpoint(None, None, default_universe, "auto")
+ == default_endpoint
+ )
+ assert (
+ LoggingServiceV2Client._get_api_endpoint(None, None, default_universe, "always")
+ == LoggingServiceV2Client.DEFAULT_MTLS_ENDPOINT
+ )
+ assert (
+ LoggingServiceV2Client._get_api_endpoint(
+ None, mock_client_cert_source, default_universe, "always"
+ )
+ == LoggingServiceV2Client.DEFAULT_MTLS_ENDPOINT
+ )
+ assert (
+ LoggingServiceV2Client._get_api_endpoint(None, None, mock_universe, "never")
+ == mock_endpoint
+ )
+ assert (
+ LoggingServiceV2Client._get_api_endpoint(None, None, default_universe, "never")
+ == default_endpoint
+ )
+
+ with pytest.raises(MutualTLSChannelError) as excinfo:
+ LoggingServiceV2Client._get_api_endpoint(
+ None, mock_client_cert_source, mock_universe, "auto"
+ )
+ assert (
+ str(excinfo.value)
+ == "mTLS is not supported in any universe other than googleapis.com."
+ )
+
+
+def test__get_universe_domain():
+ client_universe_domain = "foo.com"
+ universe_domain_env = "bar.com"
+
+ assert (
+ LoggingServiceV2Client._get_universe_domain(
+ client_universe_domain, universe_domain_env
+ )
+ == client_universe_domain
+ )
+ assert (
+ LoggingServiceV2Client._get_universe_domain(None, universe_domain_env)
+ == universe_domain_env
+ )
+ assert (
+ LoggingServiceV2Client._get_universe_domain(None, None)
+ == LoggingServiceV2Client._DEFAULT_UNIVERSE
+ )
+
+ with pytest.raises(ValueError) as excinfo:
+ LoggingServiceV2Client._get_universe_domain("", None)
+ assert str(excinfo.value) == "Universe Domain cannot be an empty string."
+
+
+@pytest.mark.parametrize(
+ "error_code,cred_info_json,show_cred_info",
+ [
+ (401, CRED_INFO_JSON, True),
+ (403, CRED_INFO_JSON, True),
+ (404, CRED_INFO_JSON, True),
+ (500, CRED_INFO_JSON, False),
+ (401, None, False),
+ (403, None, False),
+ (404, None, False),
+ (500, None, False),
+ ],
+)
+def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info):
+ cred = mock.Mock(["get_cred_info"])
+ cred.get_cred_info = mock.Mock(return_value=cred_info_json)
+ client = LoggingServiceV2Client(credentials=cred)
+ client._transport._credentials = cred
+
+ error = core_exceptions.GoogleAPICallError("message", details=["foo"])
+ error.code = error_code
+
+ client._add_cred_info_for_auth_errors(error)
+ if show_cred_info:
+ assert error.details == ["foo", CRED_INFO_STRING]
+ else:
+ assert error.details == ["foo"]
+
+
+@pytest.mark.parametrize("error_code", [401, 403, 404, 500])
+def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code):
+ cred = mock.Mock([])
+ assert not hasattr(cred, "get_cred_info")
+ client = LoggingServiceV2Client(credentials=cred)
+ client._transport._credentials = cred
+
+ error = core_exceptions.GoogleAPICallError("message", details=[])
+ error.code = error_code
+
+ client._add_cred_info_for_auth_errors(error)
+ assert error.details == []
+
+
@pytest.mark.parametrize(
"client_class,transport_name",
[
@@ -203,13 +478,13 @@ def test_logging_service_v2_client_get_transport_class():
)
@mock.patch.object(
LoggingServiceV2Client,
- "DEFAULT_ENDPOINT",
- modify_default_endpoint(LoggingServiceV2Client),
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(LoggingServiceV2Client),
)
@mock.patch.object(
LoggingServiceV2AsyncClient,
- "DEFAULT_ENDPOINT",
- modify_default_endpoint(LoggingServiceV2AsyncClient),
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(LoggingServiceV2AsyncClient),
)
def test_logging_service_v2_client_client_options(
client_class, transport_class, transport_name
@@ -251,7 +526,9 @@ def test_logging_service_v2_client_client_options(
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
@@ -281,15 +558,23 @@ def test_logging_service_v2_client_client_options(
# 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):
+ with pytest.raises(MutualTLSChannelError) as excinfo:
client = client_class(transport=transport_name)
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
+ )
# 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):
+ with pytest.raises(ValueError) as excinfo:
client = client_class(transport=transport_name)
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
+ )
# Check the case quota_project_id is provided
options = client_options.ClientOptions(quota_project_id="octopus")
@@ -299,7 +584,9 @@ def test_logging_service_v2_client_client_options(
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id="octopus",
@@ -317,7 +604,9 @@ def test_logging_service_v2_client_client_options(
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
@@ -358,13 +647,13 @@ def test_logging_service_v2_client_client_options(
)
@mock.patch.object(
LoggingServiceV2Client,
- "DEFAULT_ENDPOINT",
- modify_default_endpoint(LoggingServiceV2Client),
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(LoggingServiceV2Client),
)
@mock.patch.object(
LoggingServiceV2AsyncClient,
- "DEFAULT_ENDPOINT",
- modify_default_endpoint(LoggingServiceV2AsyncClient),
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(LoggingServiceV2AsyncClient),
)
@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
def test_logging_service_v2_client_mtls_env_auto(
@@ -387,7 +676,9 @@ def test_logging_service_v2_client_mtls_env_auto(
if use_client_cert_env == "false":
expected_client_cert_source = None
- expected_host = client.DEFAULT_ENDPOINT
+ expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ )
else:
expected_client_cert_source = client_cert_source_callback
expected_host = client.DEFAULT_MTLS_ENDPOINT
@@ -419,7 +710,9 @@ def test_logging_service_v2_client_mtls_env_auto(
return_value=client_cert_source_callback,
):
if use_client_cert_env == "false":
- expected_host = client.DEFAULT_ENDPOINT
+ expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ )
expected_client_cert_source = None
else:
expected_host = client.DEFAULT_MTLS_ENDPOINT
@@ -453,7 +746,9 @@ def test_logging_service_v2_client_mtls_env_auto(
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
@@ -543,6 +838,115 @@ def test_logging_service_v2_client_get_mtls_endpoint_and_cert_source(client_clas
assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
assert cert_source == mock_client_cert_source
+ # 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) as excinfo:
+ client_class.get_mtls_endpoint_and_cert_source()
+
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
+ )
+
+ # 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) as excinfo:
+ client_class.get_mtls_endpoint_and_cert_source()
+
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class", [LoggingServiceV2Client, LoggingServiceV2AsyncClient]
+)
+@mock.patch.object(
+ LoggingServiceV2Client,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(LoggingServiceV2Client),
+)
+@mock.patch.object(
+ LoggingServiceV2AsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(LoggingServiceV2AsyncClient),
+)
+def test_logging_service_v2_client_client_api_endpoint(client_class):
+ mock_client_cert_source = client_cert_source_callback
+ api_override = "foo.com"
+ default_universe = LoggingServiceV2Client._DEFAULT_UNIVERSE
+ default_endpoint = LoggingServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=default_universe
+ )
+ mock_universe = "bar.com"
+ mock_endpoint = LoggingServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=mock_universe
+ )
+
+ # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true",
+ # use ClientOptions.api_endpoint as the api endpoint regardless.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ with mock.patch(
+ "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source, api_endpoint=api_override
+ )
+ client = client_class(
+ client_options=options,
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert client.api_endpoint == api_override
+
+ # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ client = client_class(credentials=ga_credentials.AnonymousCredentials())
+ assert client.api_endpoint == default_endpoint
+
+ # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always",
+ # use the DEFAULT_MTLS_ENDPOINT as the api endpoint.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ client = client_class(credentials=ga_credentials.AnonymousCredentials())
+ assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
+
+ # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default),
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist,
+ # and ClientOptions.universe_domain="bar.com",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint.
+ options = client_options.ClientOptions()
+ universe_exists = hasattr(options, "universe_domain")
+ if universe_exists:
+ options = client_options.ClientOptions(universe_domain=mock_universe)
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ else:
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert client.api_endpoint == (
+ mock_endpoint if universe_exists else default_endpoint
+ )
+ assert client.universe_domain == (
+ mock_universe if universe_exists else default_universe
+ )
+
+ # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint.
+ options = client_options.ClientOptions()
+ if hasattr(options, "universe_domain"):
+ delattr(options, "universe_domain")
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert client.api_endpoint == default_endpoint
+
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
@@ -568,7 +972,9 @@ def test_logging_service_v2_client_client_options_scopes(
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=["1", "2"],
client_cert_source_for_mtls=None,
quota_project_id=None,
@@ -607,7 +1013,9 @@ def test_logging_service_v2_client_client_options_credentials_file(
patched.assert_called_once_with(
credentials=None,
credentials_file="credentials.json",
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
@@ -667,7 +1075,9 @@ def test_logging_service_v2_client_create_channel_credentials_file(
patched.assert_called_once_with(
credentials=None,
credentials_file="credentials.json",
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
@@ -737,26 +1147,114 @@ def test_delete_log(request_type, transport: str = "grpc"):
# 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()
+ request = logging.DeleteLogRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
assert response is None
-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.
+def test_delete_log_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = LoggingServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging.DeleteLogRequest(
+ 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:
- client.delete_log()
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_log(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging.DeleteLogRequest()
+ assert args[0] == logging.DeleteLogRequest(
+ log_name="log_name_value",
+ )
+
+
+def test_delete_log_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = LoggingServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.delete_log in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.delete_log] = mock_rpc
+ request = {}
+ client.delete_log(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.delete_log(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_delete_log_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.delete_log
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.delete_log
+ ] = mock_rpc
+
+ request = {}
+ await client.delete_log(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.delete_log(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
@@ -764,7 +1262,7 @@ async def test_delete_log_async(
transport: str = "grpc_asyncio", request_type=logging.DeleteLogRequest
):
client = LoggingServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -781,7 +1279,8 @@ async def test_delete_log_async(
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
- assert args[0] == logging.DeleteLogRequest()
+ request = logging.DeleteLogRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
assert response is None
@@ -824,7 +1323,7 @@ def test_delete_log_field_headers():
@pytest.mark.asyncio
async def test_delete_log_field_headers_async():
client = LoggingServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -892,7 +1391,7 @@ def test_delete_log_flattened_error():
@pytest.mark.asyncio
async def test_delete_log_flattened_async():
client = LoggingServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -919,7 +1418,7 @@ async def test_delete_log_flattened_async():
@pytest.mark.asyncio
async def test_delete_log_flattened_error_async():
client = LoggingServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -959,60 +1458,153 @@ def test_write_log_entries(request_type, transport: str = "grpc"):
# 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()
+ request = logging.WriteLogEntriesRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, logging.WriteLogEntriesResponse)
-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.
+def test_write_log_entries_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = LoggingServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging.WriteLogEntriesRequest(
+ log_name="log_name_value",
+ )
+
# 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.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.write_log_entries(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging.WriteLogEntriesRequest()
+ assert args[0] == logging.WriteLogEntriesRequest(
+ log_name="log_name_value",
+ )
-@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,
- )
+def test_write_log_entries_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = LoggingServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
- # 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()
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
- # 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()
+ # Ensure method has been cached
+ assert client._transport.write_log_entries in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
)
- response = await client.write_log_entries(request)
+ client._transport._wrapped_methods[
+ client._transport.write_log_entries
+ ] = mock_rpc
+ request = {}
+ 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()
+ assert mock_rpc.call_count == 1
- # Establish that the response is the type that we expect.
- assert isinstance(response, logging.WriteLogEntriesResponse)
+ client.write_log_entries(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_write_log_entries_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.write_log_entries
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.write_log_entries
+ ] = mock_rpc
+
+ request = {}
+ await client.write_log_entries(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.write_log_entries(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_write_log_entries_async(
+ transport: str = "grpc_asyncio", request_type=logging.WriteLogEntriesRequest
+):
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ 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]
+ request = logging.WriteLogEntriesRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, logging.WriteLogEntriesResponse)
@pytest.mark.asyncio
@@ -1078,7 +1670,7 @@ def test_write_log_entries_flattened_error():
@pytest.mark.asyncio
async def test_write_log_entries_flattened_async():
client = LoggingServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1121,7 +1713,7 @@ async def test_write_log_entries_flattened_async():
@pytest.mark.asyncio
async def test_write_log_entries_flattened_error_async():
client = LoggingServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1164,27 +1756,123 @@ def test_list_log_entries(request_type, transport: str = "grpc"):
# 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()
+ request = logging.ListLogEntriesRequest()
+ assert args[0] == request
# 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_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.
+def test_list_log_entries_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = LoggingServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging.ListLogEntriesRequest(
+ filter="filter_value",
+ order_by="order_by_value",
+ page_token="page_token_value",
+ )
+
# 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.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_log_entries(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging.ListLogEntriesRequest()
+ assert args[0] == logging.ListLogEntriesRequest(
+ filter="filter_value",
+ order_by="order_by_value",
+ page_token="page_token_value",
+ )
+
+
+def test_list_log_entries_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = LoggingServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.list_log_entries in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.list_log_entries
+ ] = mock_rpc
+ request = {}
+ client.list_log_entries(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.list_log_entries(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_list_log_entries_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.list_log_entries
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.list_log_entries
+ ] = mock_rpc
+
+ request = {}
+ await client.list_log_entries(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.list_log_entries(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
@@ -1192,7 +1880,7 @@ async def test_list_log_entries_async(
transport: str = "grpc_asyncio", request_type=logging.ListLogEntriesRequest
):
client = LoggingServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -1213,7 +1901,8 @@ async def test_list_log_entries_async(
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
- assert args[0] == logging.ListLogEntriesRequest()
+ request = logging.ListLogEntriesRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListLogEntriesAsyncPager)
@@ -1276,7 +1965,7 @@ def test_list_log_entries_flattened_error():
@pytest.mark.asyncio
async def test_list_log_entries_flattened_async():
client = LoggingServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1313,7 +2002,7 @@ async def test_list_log_entries_flattened_async():
@pytest.mark.asyncio
async def test_list_log_entries_flattened_error_async():
client = LoggingServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1329,7 +2018,7 @@ async def test_list_log_entries_flattened_error_async():
def test_list_log_entries_pager(transport_name: str = "grpc"):
client = LoggingServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport_name,
)
@@ -1364,10 +2053,14 @@ def test_list_log_entries_pager(transport_name: str = "grpc"):
RuntimeError,
)
- metadata = ()
- pager = client.list_log_entries(request={})
+ expected_metadata = ()
+ retry = retries.Retry()
+ timeout = 5
+ pager = client.list_log_entries(request={}, retry=retry, timeout=timeout)
- assert pager._metadata == metadata
+ assert pager._metadata == expected_metadata
+ assert pager._retry == retry
+ assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -1376,7 +2069,7 @@ def test_list_log_entries_pager(transport_name: str = "grpc"):
def test_list_log_entries_pages(transport_name: str = "grpc"):
client = LoggingServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport_name,
)
@@ -1418,7 +2111,7 @@ def test_list_log_entries_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_log_entries_async_pager():
client = LoggingServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1468,7 +2161,7 @@ async def test_list_log_entries_async_pager():
@pytest.mark.asyncio
async def test_list_log_entries_async_pages():
client = LoggingServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1504,9 +2197,11 @@ async def test_list_log_entries_async_pages():
RuntimeError,
)
pages = []
- async for page_ in (
+ # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch`
+ # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372
+ async for page_ in ( # pragma: no branch
await client.list_log_entries(request={})
- ).pages: # pragma: no branch
+ ).pages:
pages.append(page_)
for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
assert page_.raw_page.next_page_token == token
@@ -1542,29 +2237,124 @@ def test_list_monitored_resource_descriptors(request_type, transport: str = "grp
# 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()
+ request = logging.ListMonitoredResourceDescriptorsRequest()
+ assert args[0] == request
# 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_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.
+def test_list_monitored_resource_descriptors_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = LoggingServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging.ListMonitoredResourceDescriptorsRequest(
+ page_token="page_token_value",
+ )
+
# 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.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_monitored_resource_descriptors(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging.ListMonitoredResourceDescriptorsRequest()
+ assert args[0] == logging.ListMonitoredResourceDescriptorsRequest(
+ page_token="page_token_value",
+ )
+
+
+def test_list_monitored_resource_descriptors_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = LoggingServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._transport.list_monitored_resource_descriptors
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.list_monitored_resource_descriptors
+ ] = mock_rpc
+ request = {}
+ client.list_monitored_resource_descriptors(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.list_monitored_resource_descriptors(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_list_monitored_resource_descriptors_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.list_monitored_resource_descriptors
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.list_monitored_resource_descriptors
+ ] = mock_rpc
+
+ request = {}
+ await client.list_monitored_resource_descriptors(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.list_monitored_resource_descriptors(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
@@ -1573,7 +2363,7 @@ async def test_list_monitored_resource_descriptors_async(
request_type=logging.ListMonitoredResourceDescriptorsRequest,
):
client = LoggingServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -1596,7 +2386,8 @@ async def test_list_monitored_resource_descriptors_async(
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
- assert args[0] == logging.ListMonitoredResourceDescriptorsRequest()
+ request = logging.ListMonitoredResourceDescriptorsRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListMonitoredResourceDescriptorsAsyncPager)
@@ -1610,7 +2401,7 @@ async def test_list_monitored_resource_descriptors_async_from_dict():
def test_list_monitored_resource_descriptors_pager(transport_name: str = "grpc"):
client = LoggingServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport_name,
)
@@ -1647,10 +2438,16 @@ def test_list_monitored_resource_descriptors_pager(transport_name: str = "grpc")
RuntimeError,
)
- metadata = ()
- pager = client.list_monitored_resource_descriptors(request={})
+ expected_metadata = ()
+ retry = retries.Retry()
+ timeout = 5
+ pager = client.list_monitored_resource_descriptors(
+ request={}, retry=retry, timeout=timeout
+ )
- assert pager._metadata == metadata
+ assert pager._metadata == expected_metadata
+ assert pager._retry == retry
+ assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -1662,7 +2459,7 @@ def test_list_monitored_resource_descriptors_pager(transport_name: str = "grpc")
def test_list_monitored_resource_descriptors_pages(transport_name: str = "grpc"):
client = LoggingServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport_name,
)
@@ -1706,7 +2503,7 @@ def test_list_monitored_resource_descriptors_pages(transport_name: str = "grpc")
@pytest.mark.asyncio
async def test_list_monitored_resource_descriptors_async_pager():
client = LoggingServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1761,7 +2558,7 @@ async def test_list_monitored_resource_descriptors_async_pager():
@pytest.mark.asyncio
async def test_list_monitored_resource_descriptors_async_pages():
client = LoggingServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1799,9 +2596,11 @@ async def test_list_monitored_resource_descriptors_async_pages():
RuntimeError,
)
pages = []
- async for page_ in (
+ # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch`
+ # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372
+ async for page_ in ( # pragma: no branch
await client.list_monitored_resource_descriptors(request={})
- ).pages: # pragma: no branch
+ ).pages:
pages.append(page_)
for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
assert page_.raw_page.next_page_token == token
@@ -1836,7 +2635,8 @@ def test_list_logs(request_type, transport: str = "grpc"):
# 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()
+ request = logging.ListLogsRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListLogsPager)
@@ -1844,20 +2644,109 @@ def test_list_logs(request_type, transport: str = "grpc"):
assert response.next_page_token == "next_page_token_value"
-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.
+def test_list_logs_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = LoggingServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging.ListLogsRequest(
+ parent="parent_value",
+ page_token="page_token_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:
- client.list_logs()
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_logs(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging.ListLogsRequest()
+ assert args[0] == logging.ListLogsRequest(
+ parent="parent_value",
+ page_token="page_token_value",
+ )
+
+
+def test_list_logs_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = LoggingServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.list_logs in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.list_logs] = mock_rpc
+ request = {}
+ client.list_logs(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.list_logs(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_list_logs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.list_logs
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.list_logs
+ ] = mock_rpc
+
+ request = {}
+ await client.list_logs(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.list_logs(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
@@ -1865,7 +2754,7 @@ async def test_list_logs_async(
transport: str = "grpc_asyncio", request_type=logging.ListLogsRequest
):
client = LoggingServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -1887,7 +2776,8 @@ async def test_list_logs_async(
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
- assert args[0] == logging.ListLogsRequest()
+ request = logging.ListLogsRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListLogsAsyncPager)
@@ -1932,7 +2822,7 @@ def test_list_logs_field_headers():
@pytest.mark.asyncio
async def test_list_logs_field_headers_async():
client = LoggingServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2002,7 +2892,7 @@ def test_list_logs_flattened_error():
@pytest.mark.asyncio
async def test_list_logs_flattened_async():
client = LoggingServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2031,7 +2921,7 @@ async def test_list_logs_flattened_async():
@pytest.mark.asyncio
async def test_list_logs_flattened_error_async():
client = LoggingServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2045,7 +2935,7 @@ async def test_list_logs_flattened_error_async():
def test_list_logs_pager(transport_name: str = "grpc"):
client = LoggingServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport_name,
)
@@ -2080,13 +2970,17 @@ def test_list_logs_pager(transport_name: str = "grpc"):
RuntimeError,
)
- metadata = ()
- metadata = tuple(metadata) + (
+ expected_metadata = ()
+ retry = retries.Retry()
+ timeout = 5
+ expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_logs(request={})
+ pager = client.list_logs(request={}, retry=retry, timeout=timeout)
- assert pager._metadata == metadata
+ assert pager._metadata == expected_metadata
+ assert pager._retry == retry
+ assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -2095,7 +2989,7 @@ def test_list_logs_pager(transport_name: str = "grpc"):
def test_list_logs_pages(transport_name: str = "grpc"):
client = LoggingServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport_name,
)
@@ -2137,7 +3031,7 @@ def test_list_logs_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_logs_async_pager():
client = LoggingServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2187,7 +3081,7 @@ async def test_list_logs_async_pager():
@pytest.mark.asyncio
async def test_list_logs_async_pages():
client = LoggingServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2223,9 +3117,11 @@ async def test_list_logs_async_pages():
RuntimeError,
)
pages = []
- async for page_ in (
+ # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch`
+ # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372
+ async for page_ in ( # pragma: no branch
await client.list_logs(request={})
- ).pages: # pragma: no branch
+ ).pages:
pages.append(page_)
for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
assert page_.raw_page.next_page_token == token
@@ -2265,12 +3161,91 @@ def test_tail_log_entries(request_type, transport: str = "grpc"):
assert isinstance(message, logging.TailLogEntriesResponse)
+def test_tail_log_entries_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = LoggingServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.tail_log_entries in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.tail_log_entries
+ ] = mock_rpc
+ request = [{}]
+ client.tail_log_entries(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.tail_log_entries(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_tail_log_entries_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.tail_log_entries
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.tail_log_entries
+ ] = mock_rpc
+
+ request = [{}]
+ await client.tail_log_entries(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.tail_log_entries(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
@pytest.mark.asyncio
async def test_tail_log_entries_async(
transport: str = "grpc_asyncio", request_type=logging.TailLogEntriesRequest
):
client = LoggingServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -2337,7 +3312,7 @@ def test_credentials_transport_error():
)
# It is an error to provide an api_key and a credential.
- options = mock.Mock()
+ options = client_options.ClientOptions()
options.api_key = "api_key"
with pytest.raises(ValueError):
client = LoggingServiceV2Client(
@@ -2394,60 +3369,321 @@ def test_transport_adc(transport_class):
adc.assert_called_once()
-@pytest.mark.parametrize(
- "transport_name",
- [
- "grpc",
- ],
-)
-def test_transport_kind(transport_name):
- transport = LoggingServiceV2Client.get_transport_class(transport_name)(
- credentials=ga_credentials.AnonymousCredentials(),
+def test_transport_kind_grpc():
+ transport = LoggingServiceV2Client.get_transport_class("grpc")(
+ credentials=ga_credentials.AnonymousCredentials()
)
- assert transport.kind == transport_name
+ assert transport.kind == "grpc"
-def test_transport_grpc_default():
- # A client should use the gRPC transport by default.
+def test_initialize_client_w_grpc():
client = LoggingServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
)
- assert isinstance(
- client.transport,
- transports.LoggingServiceV2GrpcTransport,
+ assert client is not None
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_delete_log_empty_call_grpc():
+ client = LoggingServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
)
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.delete_log), "__call__") as call:
+ call.return_value = None
+ client.delete_log(request=None)
-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",
- )
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging.DeleteLogRequest()
+ assert args[0] == request_msg
-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:
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_write_log_entries_empty_call_grpc():
+ client = LoggingServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.write_log_entries), "__call__"
+ ) as call:
+ call.return_value = logging.WriteLogEntriesResponse()
+ client.write_log_entries(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging.WriteLogEntriesRequest()
+
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_list_log_entries_empty_call_grpc():
+ client = LoggingServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.list_log_entries), "__call__") as call:
+ call.return_value = logging.ListLogEntriesResponse()
+ client.list_log_entries(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging.ListLogEntriesRequest()
+
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_list_monitored_resource_descriptors_empty_call_grpc():
+ client = LoggingServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_monitored_resource_descriptors), "__call__"
+ ) as call:
+ call.return_value = logging.ListMonitoredResourceDescriptorsResponse()
+ client.list_monitored_resource_descriptors(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging.ListMonitoredResourceDescriptorsRequest()
+
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_list_logs_empty_call_grpc():
+ client = LoggingServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, 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=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging.ListLogsRequest()
+
+ assert args[0] == request_msg
+
+
+def test_transport_kind_grpc_asyncio():
+ transport = LoggingServiceV2AsyncClient.get_transport_class("grpc_asyncio")(
+ credentials=async_anonymous_credentials()
+ )
+ assert transport.kind == "grpc_asyncio"
+
+
+def test_initialize_client_w_grpc_asyncio():
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(), transport="grpc_asyncio"
+ )
+ assert client is not None
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_delete_log_empty_call_grpc_asyncio():
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, 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)
+ await client.delete_log(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging.DeleteLogRequest()
+
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_write_log_entries_empty_call_grpc_asyncio():
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, 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()
+ )
+ await client.write_log_entries(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging.WriteLogEntriesRequest()
+
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_list_log_entries_empty_call_grpc_asyncio():
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, 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",
+ )
+ )
+ await client.list_log_entries(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging.ListLogEntriesRequest()
+
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_list_monitored_resource_descriptors_empty_call_grpc_asyncio():
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, 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",
+ )
+ )
+ await client.list_monitored_resource_descriptors(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging.ListMonitoredResourceDescriptorsRequest()
+
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_list_logs_empty_call_grpc_asyncio():
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, 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",
+ )
+ )
+ await client.list_logs(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging.ListLogsRequest()
+
+ assert args[0] == request_msg
+
+
+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",
+ "get_operation",
+ "cancel_operation",
+ "list_operations",
+ )
+ for method in methods:
with pytest.raises(NotImplementedError):
getattr(transport, method)(request=object())
@@ -2964,35 +4200,458 @@ def test_client_with_default_client_info():
prep.assert_called_once_with(client_info)
+def test_cancel_operation(transport: str = "grpc"):
+ 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 = operations_pb2.CancelOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+ response = client.cancel_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
@pytest.mark.asyncio
-async def test_transport_close_async():
+async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = operations_pb2.CancelOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.cancel_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_cancel_operation_field_headers():
+ client = LoggingServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc_asyncio",
)
- with mock.patch.object(
- type(getattr(client.transport, "grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = operations_pb2.CancelOperationRequest()
+ request.name = "locations"
-def test_transport_close():
- transports = {
- "grpc": "_grpc_channel",
- }
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ call.return_value = None
- for transport, close_name in transports.items():
- client = LoggingServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials(), transport=transport
- )
- with mock.patch.object(
- type(getattr(client.transport, close_name)), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ client.cancel_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "name=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_field_headers_async():
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = operations_pb2.CancelOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ await client.cancel_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "name=locations",
+ ) in kw["metadata"]
+
+
+def test_cancel_operation_from_dict():
+ client = LoggingServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ response = client.cancel_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_from_dict_async():
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.cancel_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_get_operation(transport: str = "grpc"):
+ client = 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 = operations_pb2.GetOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+ response = client.get_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+@pytest.mark.asyncio
+async def test_get_operation_async(transport: str = "grpc_asyncio"):
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = operations_pb2.GetOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ response = await client.get_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+def test_get_operation_field_headers():
+ client = 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 = operations_pb2.GetOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ call.return_value = operations_pb2.Operation()
+
+ client.get_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "name=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_get_operation_field_headers_async():
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = operations_pb2.GetOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ await client.get_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "name=locations",
+ ) in kw["metadata"]
+
+
+def test_get_operation_from_dict():
+ client = LoggingServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+
+ response = client.get_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_get_operation_from_dict_async():
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ response = await client.get_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_list_operations(transport: str = "grpc"):
+ client = 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 = operations_pb2.ListOperationsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+ response = client.list_operations(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+@pytest.mark.asyncio
+async def test_list_operations_async(transport: str = "grpc_asyncio"):
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = operations_pb2.ListOperationsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ response = await client.list_operations(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+def test_list_operations_field_headers():
+ client = 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 = operations_pb2.ListOperationsRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ client.list_operations(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "name=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_list_operations_field_headers_async():
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = operations_pb2.ListOperationsRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ await client.list_operations(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "name=locations",
+ ) in kw["metadata"]
+
+
+def test_list_operations_from_dict():
+ client = 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_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ response = client.list_operations(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_list_operations_from_dict_async():
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ response = await client.list_operations(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_transport_close_grpc():
+ client = LoggingServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_grpc_channel")), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+@pytest.mark.asyncio
+async def test_transport_close_grpc_asyncio():
+ client = LoggingServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(), transport="grpc_asyncio"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
@@ -3032,7 +4691,9 @@ def test_api_key_credentials(client_class, transport_class):
patched.assert_called_once_with(
credentials=mock_cred,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
diff --git a/tests/unit/gapic/logging_v2/test_metrics_service_v2.py b/tests/unit/gapic/logging_v2/test_metrics_service_v2.py
index 39a005c97..7c59a09f1 100644
--- a/tests/unit/gapic/logging_v2/test_metrics_service_v2.py
+++ b/tests/unit/gapic/logging_v2/test_metrics_service_v2.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# Copyright 2022 Google LLC
+# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -24,11 +24,20 @@
import grpc
from grpc.experimental import aio
+import json
import math
import pytest
+from google.api_core import api_core_version
from proto.marshal.rules.dates import DurationRule, TimestampRule
from proto.marshal.rules import wrappers
+try:
+ from google.auth.aio import credentials as ga_credentials_async
+
+ HAS_GOOGLE_AUTH_AIO = True
+except ImportError: # pragma: NO COVER
+ HAS_GOOGLE_AUTH_AIO = False
+
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
@@ -39,6 +48,7 @@
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
from google.api_core import path_template
+from google.api_core import retry as retries
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.logging_v2.services.metrics_service_v2 import (
@@ -48,16 +58,39 @@
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.types import logging_metrics
+from google.longrunning import operations_pb2 # type: ignore
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
+CRED_INFO_JSON = {
+ "credential_source": "/path/to/file",
+ "credential_type": "service account credentials",
+ "principal": "service-account@example.com",
+}
+CRED_INFO_STRING = json.dumps(CRED_INFO_JSON)
+
+
+async def mock_async_gen(data, chunk_size=1):
+ for i in range(0, len(data)): # pragma: NO COVER
+ chunk = data[i : i + chunk_size]
+ yield chunk.encode("utf-8")
+
+
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
+# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
+# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
+def async_anonymous_credentials():
+ if HAS_GOOGLE_AUTH_AIO:
+ return ga_credentials_async.AnonymousCredentials()
+ return ga_credentials.AnonymousCredentials()
+
+
# 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.
@@ -69,6 +102,17 @@ def modify_default_endpoint(client):
)
+# If default endpoint template is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint template so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint_template(client):
+ return (
+ "test.{UNIVERSE_DOMAIN}"
+ if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE)
+ else client._DEFAULT_ENDPOINT_TEMPLATE
+ )
+
+
def test__get_default_mtls_endpoint():
api_endpoint = "example.googleapis.com"
api_mtls_endpoint = "example.mtls.googleapis.com"
@@ -99,6 +143,237 @@ def test__get_default_mtls_endpoint():
)
+def test__read_environment_variables():
+ assert MetricsServiceV2Client._read_environment_variables() == (False, "auto", None)
+
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ assert MetricsServiceV2Client._read_environment_variables() == (
+ True,
+ "auto",
+ None,
+ )
+
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}):
+ assert MetricsServiceV2Client._read_environment_variables() == (
+ False,
+ "auto",
+ None,
+ )
+
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}
+ ):
+ with pytest.raises(ValueError) as excinfo:
+ MetricsServiceV2Client._read_environment_variables()
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
+ )
+
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ assert MetricsServiceV2Client._read_environment_variables() == (
+ False,
+ "never",
+ None,
+ )
+
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ assert MetricsServiceV2Client._read_environment_variables() == (
+ False,
+ "always",
+ None,
+ )
+
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}):
+ assert MetricsServiceV2Client._read_environment_variables() == (
+ False,
+ "auto",
+ None,
+ )
+
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
+ with pytest.raises(MutualTLSChannelError) as excinfo:
+ MetricsServiceV2Client._read_environment_variables()
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
+ )
+
+ with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}):
+ assert MetricsServiceV2Client._read_environment_variables() == (
+ False,
+ "auto",
+ "foo.com",
+ )
+
+
+def test__get_client_cert_source():
+ mock_provided_cert_source = mock.Mock()
+ mock_default_cert_source = mock.Mock()
+
+ assert MetricsServiceV2Client._get_client_cert_source(None, False) is None
+ assert (
+ MetricsServiceV2Client._get_client_cert_source(mock_provided_cert_source, False)
+ is None
+ )
+ assert (
+ MetricsServiceV2Client._get_client_cert_source(mock_provided_cert_source, True)
+ == mock_provided_cert_source
+ )
+
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source", return_value=True
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=mock_default_cert_source,
+ ):
+ assert (
+ MetricsServiceV2Client._get_client_cert_source(None, True)
+ is mock_default_cert_source
+ )
+ assert (
+ MetricsServiceV2Client._get_client_cert_source(
+ mock_provided_cert_source, "true"
+ )
+ is mock_provided_cert_source
+ )
+
+
+@mock.patch.object(
+ MetricsServiceV2Client,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(MetricsServiceV2Client),
+)
+@mock.patch.object(
+ MetricsServiceV2AsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(MetricsServiceV2AsyncClient),
+)
+def test__get_api_endpoint():
+ api_override = "foo.com"
+ mock_client_cert_source = mock.Mock()
+ default_universe = MetricsServiceV2Client._DEFAULT_UNIVERSE
+ default_endpoint = MetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=default_universe
+ )
+ mock_universe = "bar.com"
+ mock_endpoint = MetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=mock_universe
+ )
+
+ assert (
+ MetricsServiceV2Client._get_api_endpoint(
+ api_override, mock_client_cert_source, default_universe, "always"
+ )
+ == api_override
+ )
+ assert (
+ MetricsServiceV2Client._get_api_endpoint(
+ None, mock_client_cert_source, default_universe, "auto"
+ )
+ == MetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT
+ )
+ assert (
+ MetricsServiceV2Client._get_api_endpoint(None, None, default_universe, "auto")
+ == default_endpoint
+ )
+ assert (
+ MetricsServiceV2Client._get_api_endpoint(None, None, default_universe, "always")
+ == MetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT
+ )
+ assert (
+ MetricsServiceV2Client._get_api_endpoint(
+ None, mock_client_cert_source, default_universe, "always"
+ )
+ == MetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT
+ )
+ assert (
+ MetricsServiceV2Client._get_api_endpoint(None, None, mock_universe, "never")
+ == mock_endpoint
+ )
+ assert (
+ MetricsServiceV2Client._get_api_endpoint(None, None, default_universe, "never")
+ == default_endpoint
+ )
+
+ with pytest.raises(MutualTLSChannelError) as excinfo:
+ MetricsServiceV2Client._get_api_endpoint(
+ None, mock_client_cert_source, mock_universe, "auto"
+ )
+ assert (
+ str(excinfo.value)
+ == "mTLS is not supported in any universe other than googleapis.com."
+ )
+
+
+def test__get_universe_domain():
+ client_universe_domain = "foo.com"
+ universe_domain_env = "bar.com"
+
+ assert (
+ MetricsServiceV2Client._get_universe_domain(
+ client_universe_domain, universe_domain_env
+ )
+ == client_universe_domain
+ )
+ assert (
+ MetricsServiceV2Client._get_universe_domain(None, universe_domain_env)
+ == universe_domain_env
+ )
+ assert (
+ MetricsServiceV2Client._get_universe_domain(None, None)
+ == MetricsServiceV2Client._DEFAULT_UNIVERSE
+ )
+
+ with pytest.raises(ValueError) as excinfo:
+ MetricsServiceV2Client._get_universe_domain("", None)
+ assert str(excinfo.value) == "Universe Domain cannot be an empty string."
+
+
+@pytest.mark.parametrize(
+ "error_code,cred_info_json,show_cred_info",
+ [
+ (401, CRED_INFO_JSON, True),
+ (403, CRED_INFO_JSON, True),
+ (404, CRED_INFO_JSON, True),
+ (500, CRED_INFO_JSON, False),
+ (401, None, False),
+ (403, None, False),
+ (404, None, False),
+ (500, None, False),
+ ],
+)
+def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info):
+ cred = mock.Mock(["get_cred_info"])
+ cred.get_cred_info = mock.Mock(return_value=cred_info_json)
+ client = MetricsServiceV2Client(credentials=cred)
+ client._transport._credentials = cred
+
+ error = core_exceptions.GoogleAPICallError("message", details=["foo"])
+ error.code = error_code
+
+ client._add_cred_info_for_auth_errors(error)
+ if show_cred_info:
+ assert error.details == ["foo", CRED_INFO_STRING]
+ else:
+ assert error.details == ["foo"]
+
+
+@pytest.mark.parametrize("error_code", [401, 403, 404, 500])
+def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code):
+ cred = mock.Mock([])
+ assert not hasattr(cred, "get_cred_info")
+ client = MetricsServiceV2Client(credentials=cred)
+ client._transport._credentials = cred
+
+ error = core_exceptions.GoogleAPICallError("message", details=[])
+ error.code = error_code
+
+ client._add_cred_info_for_auth_errors(error)
+ assert error.details == []
+
+
@pytest.mark.parametrize(
"client_class,transport_name",
[
@@ -216,13 +491,13 @@ def test_metrics_service_v2_client_get_transport_class():
)
@mock.patch.object(
MetricsServiceV2Client,
- "DEFAULT_ENDPOINT",
- modify_default_endpoint(MetricsServiceV2Client),
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(MetricsServiceV2Client),
)
@mock.patch.object(
MetricsServiceV2AsyncClient,
- "DEFAULT_ENDPOINT",
- modify_default_endpoint(MetricsServiceV2AsyncClient),
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(MetricsServiceV2AsyncClient),
)
def test_metrics_service_v2_client_client_options(
client_class, transport_class, transport_name
@@ -264,7 +539,9 @@ def test_metrics_service_v2_client_client_options(
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
@@ -294,15 +571,23 @@ def test_metrics_service_v2_client_client_options(
# 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):
+ with pytest.raises(MutualTLSChannelError) as excinfo:
client = client_class(transport=transport_name)
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
+ )
# 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):
+ with pytest.raises(ValueError) as excinfo:
client = client_class(transport=transport_name)
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
+ )
# Check the case quota_project_id is provided
options = client_options.ClientOptions(quota_project_id="octopus")
@@ -312,7 +597,9 @@ def test_metrics_service_v2_client_client_options(
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id="octopus",
@@ -330,7 +617,9 @@ def test_metrics_service_v2_client_client_options(
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
@@ -371,13 +660,13 @@ def test_metrics_service_v2_client_client_options(
)
@mock.patch.object(
MetricsServiceV2Client,
- "DEFAULT_ENDPOINT",
- modify_default_endpoint(MetricsServiceV2Client),
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(MetricsServiceV2Client),
)
@mock.patch.object(
MetricsServiceV2AsyncClient,
- "DEFAULT_ENDPOINT",
- modify_default_endpoint(MetricsServiceV2AsyncClient),
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(MetricsServiceV2AsyncClient),
)
@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
def test_metrics_service_v2_client_mtls_env_auto(
@@ -400,7 +689,9 @@ def test_metrics_service_v2_client_mtls_env_auto(
if use_client_cert_env == "false":
expected_client_cert_source = None
- expected_host = client.DEFAULT_ENDPOINT
+ expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ )
else:
expected_client_cert_source = client_cert_source_callback
expected_host = client.DEFAULT_MTLS_ENDPOINT
@@ -432,7 +723,9 @@ def test_metrics_service_v2_client_mtls_env_auto(
return_value=client_cert_source_callback,
):
if use_client_cert_env == "false":
- expected_host = client.DEFAULT_ENDPOINT
+ expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ )
expected_client_cert_source = None
else:
expected_host = client.DEFAULT_MTLS_ENDPOINT
@@ -466,7 +759,9 @@ def test_metrics_service_v2_client_mtls_env_auto(
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
@@ -556,6 +851,115 @@ def test_metrics_service_v2_client_get_mtls_endpoint_and_cert_source(client_clas
assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
assert cert_source == mock_client_cert_source
+ # 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) as excinfo:
+ client_class.get_mtls_endpoint_and_cert_source()
+
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
+ )
+
+ # 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) as excinfo:
+ client_class.get_mtls_endpoint_and_cert_source()
+
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class", [MetricsServiceV2Client, MetricsServiceV2AsyncClient]
+)
+@mock.patch.object(
+ MetricsServiceV2Client,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(MetricsServiceV2Client),
+)
+@mock.patch.object(
+ MetricsServiceV2AsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(MetricsServiceV2AsyncClient),
+)
+def test_metrics_service_v2_client_client_api_endpoint(client_class):
+ mock_client_cert_source = client_cert_source_callback
+ api_override = "foo.com"
+ default_universe = MetricsServiceV2Client._DEFAULT_UNIVERSE
+ default_endpoint = MetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=default_universe
+ )
+ mock_universe = "bar.com"
+ mock_endpoint = MetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=mock_universe
+ )
+
+ # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true",
+ # use ClientOptions.api_endpoint as the api endpoint regardless.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ with mock.patch(
+ "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source, api_endpoint=api_override
+ )
+ client = client_class(
+ client_options=options,
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert client.api_endpoint == api_override
+
+ # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ client = client_class(credentials=ga_credentials.AnonymousCredentials())
+ assert client.api_endpoint == default_endpoint
+
+ # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always",
+ # use the DEFAULT_MTLS_ENDPOINT as the api endpoint.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ client = client_class(credentials=ga_credentials.AnonymousCredentials())
+ assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
+
+ # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default),
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist,
+ # and ClientOptions.universe_domain="bar.com",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint.
+ options = client_options.ClientOptions()
+ universe_exists = hasattr(options, "universe_domain")
+ if universe_exists:
+ options = client_options.ClientOptions(universe_domain=mock_universe)
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ else:
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert client.api_endpoint == (
+ mock_endpoint if universe_exists else default_endpoint
+ )
+ assert client.universe_domain == (
+ mock_universe if universe_exists else default_universe
+ )
+
+ # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint.
+ options = client_options.ClientOptions()
+ if hasattr(options, "universe_domain"):
+ delattr(options, "universe_domain")
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert client.api_endpoint == default_endpoint
+
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
@@ -581,7 +985,9 @@ def test_metrics_service_v2_client_client_options_scopes(
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=["1", "2"],
client_cert_source_for_mtls=None,
quota_project_id=None,
@@ -620,7 +1026,9 @@ def test_metrics_service_v2_client_client_options_credentials_file(
patched.assert_called_once_with(
credentials=None,
credentials_file="credentials.json",
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
@@ -680,7 +1088,9 @@ def test_metrics_service_v2_client_create_channel_credentials_file(
patched.assert_called_once_with(
credentials=None,
credentials_file="credentials.json",
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
@@ -752,27 +1162,121 @@ def test_list_log_metrics(request_type, transport: str = "grpc"):
# 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()
+ request = logging_metrics.ListLogMetricsRequest()
+ assert args[0] == request
# 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_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.
+def test_list_log_metrics_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = MetricsServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_metrics.ListLogMetricsRequest(
+ parent="parent_value",
+ page_token="page_token_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:
- client.list_log_metrics()
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_log_metrics(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_metrics.ListLogMetricsRequest()
+ assert args[0] == logging_metrics.ListLogMetricsRequest(
+ parent="parent_value",
+ page_token="page_token_value",
+ )
+
+
+def test_list_log_metrics_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = MetricsServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.list_log_metrics in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.list_log_metrics
+ ] = mock_rpc
+ request = {}
+ client.list_log_metrics(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.list_log_metrics(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_list_log_metrics_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.list_log_metrics
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.list_log_metrics
+ ] = mock_rpc
+
+ request = {}
+ await client.list_log_metrics(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.list_log_metrics(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
@@ -780,7 +1284,7 @@ async def test_list_log_metrics_async(
transport: str = "grpc_asyncio", request_type=logging_metrics.ListLogMetricsRequest
):
client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -801,7 +1305,8 @@ async def test_list_log_metrics_async(
# 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()
+ request = logging_metrics.ListLogMetricsRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListLogMetricsAsyncPager)
@@ -845,7 +1350,7 @@ def test_list_log_metrics_field_headers():
@pytest.mark.asyncio
async def test_list_log_metrics_field_headers_async():
client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -915,7 +1420,7 @@ def test_list_log_metrics_flattened_error():
@pytest.mark.asyncio
async def test_list_log_metrics_flattened_async():
client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -944,7 +1449,7 @@ async def test_list_log_metrics_flattened_async():
@pytest.mark.asyncio
async def test_list_log_metrics_flattened_error_async():
client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -958,7 +1463,7 @@ async def test_list_log_metrics_flattened_error_async():
def test_list_log_metrics_pager(transport_name: str = "grpc"):
client = MetricsServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport_name,
)
@@ -993,13 +1498,17 @@ def test_list_log_metrics_pager(transport_name: str = "grpc"):
RuntimeError,
)
- metadata = ()
- metadata = tuple(metadata) + (
+ expected_metadata = ()
+ retry = retries.Retry()
+ timeout = 5
+ expected_metadata = tuple(expected_metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
)
- pager = client.list_log_metrics(request={})
+ pager = client.list_log_metrics(request={}, retry=retry, timeout=timeout)
- assert pager._metadata == metadata
+ assert pager._metadata == expected_metadata
+ assert pager._retry == retry
+ assert pager._timeout == timeout
results = list(pager)
assert len(results) == 6
@@ -1008,7 +1517,7 @@ def test_list_log_metrics_pager(transport_name: str = "grpc"):
def test_list_log_metrics_pages(transport_name: str = "grpc"):
client = MetricsServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=ga_credentials.AnonymousCredentials(),
transport=transport_name,
)
@@ -1050,7 +1559,7 @@ def test_list_log_metrics_pages(transport_name: str = "grpc"):
@pytest.mark.asyncio
async def test_list_log_metrics_async_pager():
client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1100,7 +1609,7 @@ async def test_list_log_metrics_async_pager():
@pytest.mark.asyncio
async def test_list_log_metrics_async_pages():
client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials,
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1136,9 +1645,11 @@ async def test_list_log_metrics_async_pages():
RuntimeError,
)
pages = []
- async for page_ in (
+ # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch`
+ # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372
+ async for page_ in ( # pragma: no branch
await client.list_log_metrics(request={})
- ).pages: # pragma: no branch
+ ).pages:
pages.append(page_)
for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
assert page_.raw_page.next_page_token == token
@@ -1168,6 +1679,7 @@ def test_get_log_metric(request_type, transport: str = "grpc"):
name="name_value",
description="description_value",
filter="filter_value",
+ bucket_name="bucket_name_value",
disabled=True,
value_extractor="value_extractor_value",
version=logging_metrics.LogMetric.ApiVersion.V1,
@@ -1177,44 +1689,135 @@ def test_get_log_metric(request_type, transport: str = "grpc"):
# 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()
+ request = logging_metrics.GetLogMetricRequest()
+ assert args[0] == request
# 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.bucket_name == "bucket_name_value"
assert response.disabled is True
assert response.value_extractor == "value_extractor_value"
assert response.version == logging_metrics.LogMetric.ApiVersion.V1
-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.
+def test_get_log_metric_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = MetricsServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_metrics.GetLogMetricRequest(
+ 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:
- client.get_log_metric()
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_log_metric(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_metrics.GetLogMetricRequest()
+ assert args[0] == logging_metrics.GetLogMetricRequest(
+ metric_name="metric_name_value",
+ )
+
+
+def test_get_log_metric_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = MetricsServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.get_log_metric in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.get_log_metric] = mock_rpc
+ request = {}
+ client.get_log_metric(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_log_metric(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
-async def test_get_log_metric_async(
- transport: str = "grpc_asyncio", request_type=logging_metrics.GetLogMetricRequest
+async def test_get_log_metric_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
):
- client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
- # Everything is optional in proto3 as far as the runtime is concerned,
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.get_log_metric
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.get_log_metric
+ ] = mock_rpc
+
+ request = {}
+ await client.get_log_metric(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.get_log_metric(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_get_log_metric_async(
+ transport: str = "grpc_asyncio", request_type=logging_metrics.GetLogMetricRequest
+):
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ 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()
@@ -1226,6 +1829,7 @@ async def test_get_log_metric_async(
name="name_value",
description="description_value",
filter="filter_value",
+ bucket_name="bucket_name_value",
disabled=True,
value_extractor="value_extractor_value",
version=logging_metrics.LogMetric.ApiVersion.V1,
@@ -1236,13 +1840,15 @@ async def test_get_log_metric_async(
# 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()
+ request = logging_metrics.GetLogMetricRequest()
+ assert args[0] == request
# 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.bucket_name == "bucket_name_value"
assert response.disabled is True
assert response.value_extractor == "value_extractor_value"
assert response.version == logging_metrics.LogMetric.ApiVersion.V1
@@ -1285,7 +1891,7 @@ def test_get_log_metric_field_headers():
@pytest.mark.asyncio
async def test_get_log_metric_field_headers_async():
client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1355,7 +1961,7 @@ def test_get_log_metric_flattened_error():
@pytest.mark.asyncio
async def test_get_log_metric_flattened_async():
client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1384,7 +1990,7 @@ async def test_get_log_metric_flattened_async():
@pytest.mark.asyncio
async def test_get_log_metric_flattened_error_async():
client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1422,6 +2028,7 @@ def test_create_log_metric(request_type, transport: str = "grpc"):
name="name_value",
description="description_value",
filter="filter_value",
+ bucket_name="bucket_name_value",
disabled=True,
value_extractor="value_extractor_value",
version=logging_metrics.LogMetric.ApiVersion.V1,
@@ -1431,34 +2038,127 @@ def test_create_log_metric(request_type, transport: str = "grpc"):
# 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()
+ request = logging_metrics.CreateLogMetricRequest()
+ assert args[0] == request
# 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.bucket_name == "bucket_name_value"
assert response.disabled is True
assert response.value_extractor == "value_extractor_value"
assert response.version == logging_metrics.LogMetric.ApiVersion.V1
-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.
+def test_create_log_metric_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = MetricsServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_metrics.CreateLogMetricRequest(
+ 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:
- client.create_log_metric()
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_log_metric(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_metrics.CreateLogMetricRequest()
+ assert args[0] == logging_metrics.CreateLogMetricRequest(
+ parent="parent_value",
+ )
+
+
+def test_create_log_metric_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = MetricsServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.create_log_metric in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.create_log_metric
+ ] = mock_rpc
+ request = {}
+ client.create_log_metric(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.create_log_metric(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_create_log_metric_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.create_log_metric
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.create_log_metric
+ ] = mock_rpc
+
+ request = {}
+ await client.create_log_metric(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.create_log_metric(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
@@ -1466,7 +2166,7 @@ async def test_create_log_metric_async(
transport: str = "grpc_asyncio", request_type=logging_metrics.CreateLogMetricRequest
):
client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -1484,6 +2184,7 @@ async def test_create_log_metric_async(
name="name_value",
description="description_value",
filter="filter_value",
+ bucket_name="bucket_name_value",
disabled=True,
value_extractor="value_extractor_value",
version=logging_metrics.LogMetric.ApiVersion.V1,
@@ -1494,13 +2195,15 @@ async def test_create_log_metric_async(
# 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()
+ request = logging_metrics.CreateLogMetricRequest()
+ assert args[0] == request
# 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.bucket_name == "bucket_name_value"
assert response.disabled is True
assert response.value_extractor == "value_extractor_value"
assert response.version == logging_metrics.LogMetric.ApiVersion.V1
@@ -1545,7 +2248,7 @@ def test_create_log_metric_field_headers():
@pytest.mark.asyncio
async def test_create_log_metric_field_headers_async():
client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1624,7 +2327,7 @@ def test_create_log_metric_flattened_error():
@pytest.mark.asyncio
async def test_create_log_metric_flattened_async():
client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1659,7 +2362,7 @@ async def test_create_log_metric_flattened_async():
@pytest.mark.asyncio
async def test_create_log_metric_flattened_error_async():
client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1698,6 +2401,7 @@ def test_update_log_metric(request_type, transport: str = "grpc"):
name="name_value",
description="description_value",
filter="filter_value",
+ bucket_name="bucket_name_value",
disabled=True,
value_extractor="value_extractor_value",
version=logging_metrics.LogMetric.ApiVersion.V1,
@@ -1707,34 +2411,127 @@ def test_update_log_metric(request_type, transport: str = "grpc"):
# 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()
+ request = logging_metrics.UpdateLogMetricRequest()
+ assert args[0] == request
# 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.bucket_name == "bucket_name_value"
assert response.disabled is True
assert response.value_extractor == "value_extractor_value"
assert response.version == logging_metrics.LogMetric.ApiVersion.V1
-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.
+def test_update_log_metric_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = MetricsServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_metrics.UpdateLogMetricRequest(
+ 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:
- client.update_log_metric()
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_log_metric(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_metrics.UpdateLogMetricRequest()
+ assert args[0] == logging_metrics.UpdateLogMetricRequest(
+ metric_name="metric_name_value",
+ )
+
+
+def test_update_log_metric_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = MetricsServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.update_log_metric in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.update_log_metric
+ ] = mock_rpc
+ request = {}
+ client.update_log_metric(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_log_metric(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_update_log_metric_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.update_log_metric
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.update_log_metric
+ ] = mock_rpc
+
+ request = {}
+ await client.update_log_metric(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.update_log_metric(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
@@ -1742,7 +2539,7 @@ async def test_update_log_metric_async(
transport: str = "grpc_asyncio", request_type=logging_metrics.UpdateLogMetricRequest
):
client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -1760,6 +2557,7 @@ async def test_update_log_metric_async(
name="name_value",
description="description_value",
filter="filter_value",
+ bucket_name="bucket_name_value",
disabled=True,
value_extractor="value_extractor_value",
version=logging_metrics.LogMetric.ApiVersion.V1,
@@ -1770,13 +2568,15 @@ async def test_update_log_metric_async(
# 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()
+ request = logging_metrics.UpdateLogMetricRequest()
+ assert args[0] == request
# 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.bucket_name == "bucket_name_value"
assert response.disabled is True
assert response.value_extractor == "value_extractor_value"
assert response.version == logging_metrics.LogMetric.ApiVersion.V1
@@ -1821,7 +2621,7 @@ def test_update_log_metric_field_headers():
@pytest.mark.asyncio
async def test_update_log_metric_field_headers_async():
client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -1900,7 +2700,7 @@ def test_update_log_metric_flattened_error():
@pytest.mark.asyncio
async def test_update_log_metric_flattened_async():
client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1935,7 +2735,7 @@ async def test_update_log_metric_flattened_async():
@pytest.mark.asyncio
async def test_update_log_metric_flattened_error_async():
client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1976,28 +2776,120 @@ def test_delete_log_metric(request_type, transport: str = "grpc"):
# 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()
+ request = logging_metrics.DeleteLogMetricRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
assert response is None
-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.
+def test_delete_log_metric_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
client = MetricsServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = logging_metrics.DeleteLogMetricRequest(
+ 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:
- client.delete_log_metric()
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_log_metric(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- assert args[0] == logging_metrics.DeleteLogMetricRequest()
+ assert args[0] == logging_metrics.DeleteLogMetricRequest(
+ metric_name="metric_name_value",
+ )
+
+
+def test_delete_log_metric_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = MetricsServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.delete_log_metric in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.delete_log_metric
+ ] = mock_rpc
+ request = {}
+ client.delete_log_metric(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.delete_log_metric(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_delete_log_metric_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.delete_log_metric
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.delete_log_metric
+ ] = mock_rpc
+
+ request = {}
+ await client.delete_log_metric(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.delete_log_metric(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
@pytest.mark.asyncio
@@ -2005,7 +2897,7 @@ async def test_delete_log_metric_async(
transport: str = "grpc_asyncio", request_type=logging_metrics.DeleteLogMetricRequest
):
client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
transport=transport,
)
@@ -2024,7 +2916,8 @@ async def test_delete_log_metric_async(
# 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()
+ request = logging_metrics.DeleteLogMetricRequest()
+ assert args[0] == request
# Establish that the response is the type that we expect.
assert response is None
@@ -2069,7 +2962,7 @@ def test_delete_log_metric_field_headers():
@pytest.mark.asyncio
async def test_delete_log_metric_field_headers_async():
client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
@@ -2141,7 +3034,7 @@ def test_delete_log_metric_flattened_error():
@pytest.mark.asyncio
async def test_delete_log_metric_flattened_async():
client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2170,7 +3063,7 @@ async def test_delete_log_metric_flattened_async():
@pytest.mark.asyncio
async def test_delete_log_metric_flattened_error_async():
client = MetricsServiceV2AsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=async_anonymous_credentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -2216,7 +3109,7 @@ def test_credentials_transport_error():
)
# It is an error to provide an api_key and a credential.
- options = mock.Mock()
+ options = client_options.ClientOptions()
options.api_key = "api_key"
with pytest.raises(ValueError):
client = MetricsServiceV2Client(
@@ -2273,102 +3166,386 @@ def test_transport_adc(transport_class):
adc.assert_called_once()
-@pytest.mark.parametrize(
- "transport_name",
- [
- "grpc",
- ],
-)
-def test_transport_kind(transport_name):
- transport = MetricsServiceV2Client.get_transport_class(transport_name)(
- credentials=ga_credentials.AnonymousCredentials(),
+def test_transport_kind_grpc():
+ transport = MetricsServiceV2Client.get_transport_class("grpc")(
+ credentials=ga_credentials.AnonymousCredentials()
)
- assert transport.kind == transport_name
+ assert transport.kind == "grpc"
-def test_transport_grpc_default():
- # A client should use the gRPC transport by default.
+def test_initialize_client_w_grpc():
client = MetricsServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
)
- assert isinstance(
- client.transport,
- transports.MetricsServiceV2GrpcTransport,
+ assert client is not None
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_list_log_metrics_empty_call_grpc():
+ client = MetricsServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
)
+ # Mock the actual call, 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=None)
-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",
- )
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_metrics.ListLogMetricsRequest()
+ assert args[0] == request_msg
-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",
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_get_log_metric_empty_call_grpc():
+ client = MetricsServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
)
- for method in methods:
- with pytest.raises(NotImplementedError):
- getattr(transport, method)(request=object())
- with pytest.raises(NotImplementedError):
- transport.close()
+ # Mock the actual call, 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=None)
- # Catch all for all remaining methods and properties
- remainder = [
- "kind",
- ]
- for r in remainder:
- with pytest.raises(NotImplementedError):
- getattr(transport, r)()
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_metrics.GetLogMetricRequest()
+ assert args[0] == request_msg
-def test_metrics_service_v2_base_transport_with_credentials_file():
- # Instantiate the base transport with a credentials file
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_create_log_metric_empty_call_grpc():
+ client = MetricsServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
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",
- )
+ type(client.transport.create_log_metric), "__call__"
+ ) as call:
+ call.return_value = logging_metrics.LogMetric()
+ client.create_log_metric(request=None)
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_metrics.CreateLogMetricRequest()
-def test_metrics_service_v2_base_transport_with_adc():
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_update_log_metric_empty_call_grpc():
+ client = MetricsServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, 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=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_metrics.UpdateLogMetricRequest()
+
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_delete_log_metric_empty_call_grpc():
+ client = MetricsServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, 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=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_metrics.DeleteLogMetricRequest()
+
+ assert args[0] == request_msg
+
+
+def test_transport_kind_grpc_asyncio():
+ transport = MetricsServiceV2AsyncClient.get_transport_class("grpc_asyncio")(
+ credentials=async_anonymous_credentials()
+ )
+ assert transport.kind == "grpc_asyncio"
+
+
+def test_initialize_client_w_grpc_asyncio():
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(), transport="grpc_asyncio"
+ )
+ assert client is not None
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_list_log_metrics_empty_call_grpc_asyncio():
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, 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",
+ )
+ )
+ await client.list_log_metrics(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_metrics.ListLogMetricsRequest()
+
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_get_log_metric_empty_call_grpc_asyncio():
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, 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",
+ bucket_name="bucket_name_value",
+ disabled=True,
+ value_extractor="value_extractor_value",
+ version=logging_metrics.LogMetric.ApiVersion.V1,
+ )
+ )
+ await client.get_log_metric(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_metrics.GetLogMetricRequest()
+
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_create_log_metric_empty_call_grpc_asyncio():
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, 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",
+ bucket_name="bucket_name_value",
+ disabled=True,
+ value_extractor="value_extractor_value",
+ version=logging_metrics.LogMetric.ApiVersion.V1,
+ )
+ )
+ await client.create_log_metric(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_metrics.CreateLogMetricRequest()
+
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_update_log_metric_empty_call_grpc_asyncio():
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, 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",
+ bucket_name="bucket_name_value",
+ disabled=True,
+ value_extractor="value_extractor_value",
+ version=logging_metrics.LogMetric.ApiVersion.V1,
+ )
+ )
+ await client.update_log_metric(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_metrics.UpdateLogMetricRequest()
+
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+@pytest.mark.asyncio
+async def test_delete_log_metric_empty_call_grpc_asyncio():
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, 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)
+ await client.delete_log_metric(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = logging_metrics.DeleteLogMetricRequest()
+
+ assert args[0] == request_msg
+
+
+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",
+ "get_operation",
+ "cancel_operation",
+ "list_operations",
+ )
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
+
+ with pytest.raises(NotImplementedError):
+ transport.close()
+
+ # Catch all for all remaining methods and properties
+ remainder = [
+ "kind",
+ ]
+ for r in remainder:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, r)()
+
+
+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",
+ )
+
+
+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"
@@ -2842,35 +4019,458 @@ def test_client_with_default_client_info():
prep.assert_called_once_with(client_info)
-@pytest.mark.asyncio
-async def test_transport_close_async():
- client = MetricsServiceV2AsyncClient(
+def test_cancel_operation(transport: str = "grpc"):
+ client = MetricsServiceV2Client(
credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc_asyncio",
+ transport=transport,
)
- with mock.patch.object(
- type(getattr(client.transport, "grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = operations_pb2.CancelOperationRequest()
-def test_transport_close():
- transports = {
- "grpc": "_grpc_channel",
- }
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+ response = client.cancel_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
- for transport, close_name in transports.items():
- client = MetricsServiceV2Client(
- credentials=ga_credentials.AnonymousCredentials(), transport=transport
- )
- with mock.patch.object(
- type(getattr(client.transport, close_name)), "close"
- ) as close:
- with client:
- close.assert_not_called()
- close.assert_called_once()
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = operations_pb2.CancelOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.cancel_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_cancel_operation_field_headers():
+ client = 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 = operations_pb2.CancelOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ call.return_value = None
+
+ client.cancel_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "name=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_field_headers_async():
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = operations_pb2.CancelOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ await client.cancel_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "name=locations",
+ ) in kw["metadata"]
+
+
+def test_cancel_operation_from_dict():
+ client = MetricsServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ response = client.cancel_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_from_dict_async():
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.cancel_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_get_operation(transport: str = "grpc"):
+ client = 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 = operations_pb2.GetOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+ response = client.get_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+@pytest.mark.asyncio
+async def test_get_operation_async(transport: str = "grpc_asyncio"):
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = operations_pb2.GetOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ response = await client.get_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+def test_get_operation_field_headers():
+ client = 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 = operations_pb2.GetOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ call.return_value = operations_pb2.Operation()
+
+ client.get_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "name=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_get_operation_field_headers_async():
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = operations_pb2.GetOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ await client.get_operation(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "name=locations",
+ ) in kw["metadata"]
+
+
+def test_get_operation_from_dict():
+ client = 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_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+
+ response = client.get_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_get_operation_from_dict_async():
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ response = await client.get_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_list_operations(transport: str = "grpc"):
+ client = 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 = operations_pb2.ListOperationsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+ response = client.list_operations(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+@pytest.mark.asyncio
+async def test_list_operations_async(transport: str = "grpc_asyncio"):
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = operations_pb2.ListOperationsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ response = await client.list_operations(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+def test_list_operations_field_headers():
+ client = 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 = operations_pb2.ListOperationsRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ client.list_operations(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "name=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_list_operations_field_headers_async():
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = operations_pb2.ListOperationsRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ await client.list_operations(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "name=locations",
+ ) in kw["metadata"]
+
+
+def test_list_operations_from_dict():
+ client = 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_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ response = client.list_operations(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_list_operations_from_dict_async():
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ response = await client.list_operations(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_transport_close_grpc():
+ client = MetricsServiceV2Client(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_grpc_channel")), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+@pytest.mark.asyncio
+async def test_transport_close_grpc_asyncio():
+ client = MetricsServiceV2AsyncClient(
+ credentials=async_anonymous_credentials(), transport="grpc_asyncio"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_client_ctx():
@@ -2910,7 +4510,9 @@ def test_api_key_credentials(client_class, transport_class):
patched.assert_called_once_with(
credentials=mock_cred,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
diff --git a/tests/unit/handlers/__init__.py b/tests/unit/handlers/__init__.py
index df379f1e9..32eba185f 100644
--- a/tests/unit/handlers/__init__.py
+++ b/tests/unit/handlers/__init__.py
@@ -11,3 +11,44 @@
# 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.
+
+
+# Utility functions to setup mock OpenTelemetry spans, needed by multiple test
+# suites.
+
+import contextlib
+
+import opentelemetry.context
+import opentelemetry.trace
+
+from opentelemetry.trace import NonRecordingSpan
+from opentelemetry.trace.span import TraceFlags
+
+_OTEL_SPAN_CONTEXT_TRACE_ID = 0x123456789123456789
+_OTEL_SPAN_CONTEXT_SPAN_ID = 0x123456789
+_OTEL_SPAN_CONTEXT_TRACEFLAGS = TraceFlags(TraceFlags.SAMPLED)
+
+_EXPECTED_OTEL_TRACE_ID = "00000000000000123456789123456789"
+_EXPECTED_OTEL_SPAN_ID = "0000000123456789"
+_EXPECTED_OTEL_TRACESAMPLED = True
+
+
+@contextlib.contextmanager
+def _setup_otel_span_context():
+ """Sets up a nonrecording OpenTelemetry span with a mock span context that gets returned
+ by opentelemetry.trace.get_current_span, and returns it as a contextmanager
+ """
+ span_context = opentelemetry.trace.SpanContext(
+ _OTEL_SPAN_CONTEXT_TRACE_ID,
+ _OTEL_SPAN_CONTEXT_SPAN_ID,
+ False,
+ trace_flags=_OTEL_SPAN_CONTEXT_TRACEFLAGS,
+ )
+ ctx = opentelemetry.trace.set_span_in_context(NonRecordingSpan(span_context))
+ tracer = opentelemetry.trace.NoOpTracer()
+ token = opentelemetry.context.attach(ctx)
+ try:
+ with tracer.start_as_current_span("test-span", context=ctx):
+ yield
+ finally:
+ opentelemetry.context.detach(token)
diff --git a/tests/unit/handlers/test__helpers.py b/tests/unit/handlers/test__helpers.py
index 6a7ff245f..d0577cf22 100644
--- a/tests/unit/handlers/test__helpers.py
+++ b/tests/unit/handlers/test__helpers.py
@@ -16,11 +16,22 @@
import mock
+from tests.unit.handlers import (
+ _setup_otel_span_context,
+ _EXPECTED_OTEL_TRACE_ID,
+ _EXPECTED_OTEL_SPAN_ID,
+ _EXPECTED_OTEL_TRACESAMPLED,
+)
+
_FLASK_TRACE_ID = "flask0id"
_FLASK_SPAN_ID = "span0flask"
+_FLASK_SPAN_ID_XCTC_DEC = "12345"
+_FLASK_SPAN_ID_XCTC_HEX = "3039".zfill(16)
_FLASK_HTTP_REQUEST = {"requestUrl": "https://flask.palletsprojects.com/en/1.1.x/"}
_DJANGO_TRACE_ID = "django0id"
_DJANGO_SPAN_ID = "span0django"
+_DJANGO_SPAN_ID_XCTC_DEC = "54321"
+_DJANGO_SPAN_ID_XCTC_HEX = "d431".zfill(16)
_DJANGO_HTTP_REQUEST = {"requestUrl": "https://www.djangoproject.com/"}
@@ -57,8 +68,9 @@ def test_no_context_header(self):
def test_xcloud_header(self):
flask_trace_header = "X_CLOUD_TRACE_CONTEXT"
expected_trace_id = _FLASK_TRACE_ID
- expected_span_id = _FLASK_SPAN_ID
- flask_trace_id = f"{expected_trace_id}/{expected_span_id};o=1"
+ input_span_id = _FLASK_SPAN_ID_XCTC_DEC
+ expected_span_id = _FLASK_SPAN_ID_XCTC_HEX
+ flask_trace_id = f"{expected_trace_id}/{input_span_id};o=1"
app = self.create_app()
context = app.test_request_context(
@@ -166,9 +178,10 @@ def test_xcloud_header(self):
from google.cloud.logging_v2.handlers.middleware import request
django_trace_header = "HTTP_X_CLOUD_TRACE_CONTEXT"
- expected_span_id = _DJANGO_SPAN_ID
+ input_span_id = _DJANGO_SPAN_ID_XCTC_DEC
+ expected_span_id = _DJANGO_SPAN_ID_XCTC_HEX
expected_trace_id = _DJANGO_TRACE_ID
- django_trace_id = f"{expected_trace_id}/{expected_span_id};o=1"
+ django_trace_id = f"{expected_trace_id}/{input_span_id};o=1"
django_request = RequestFactory().get(
"/", **{django_trace_header: django_trace_id}
@@ -242,6 +255,19 @@ def test_http_request_sparse(self):
self.assertEqual(http_request["requestUrl"], expected_path)
self.assertEqual(http_request["protocol"], "HTTP/1.1")
+ def test_invalid_host_header(self):
+ from django.test import RequestFactory
+ from google.cloud.logging_v2.handlers.middleware import request
+
+ invalid_http_host = "testserver%7d"
+ django_request = RequestFactory().put("/", HTTP_HOST=invalid_http_host)
+ middleware = request.RequestMiddleware(None)
+ middleware(django_request)
+ http_request, *_ = self._call_fut()
+ self.assertEqual(http_request["requestMethod"], "PUT")
+ self.assertIsNone(http_request["requestUrl"])
+ self.assertEqual(http_request["protocol"], "HTTP/1.1")
+
class Test_get_request_data(unittest.TestCase):
@staticmethod
@@ -343,6 +369,120 @@ def test_wo_libraries(self):
output = self._call_fut()
self.assertEqual(output, (None, None, None, False))
+ def test_otel_span_exists_no_request(self):
+ flask_expected = (None, None, None, False)
+ django_expected = (None, None, None, False)
+
+ with _setup_otel_span_context():
+ _, _, output = self._helper(django_expected, flask_expected)
+ self.assertEqual(
+ output,
+ (
+ None,
+ _EXPECTED_OTEL_TRACE_ID,
+ _EXPECTED_OTEL_SPAN_ID,
+ _EXPECTED_OTEL_TRACESAMPLED,
+ ),
+ )
+
+ def test_otel_span_exists_django_request(self):
+ django_expected = (
+ _DJANGO_HTTP_REQUEST,
+ _DJANGO_TRACE_ID,
+ _DJANGO_SPAN_ID,
+ False,
+ )
+ flask_expected = (None, None, None, False)
+
+ with _setup_otel_span_context():
+ _, _, output = self._helper(django_expected, flask_expected)
+ self.assertEqual(
+ output,
+ (
+ _DJANGO_HTTP_REQUEST,
+ _EXPECTED_OTEL_TRACE_ID,
+ _EXPECTED_OTEL_SPAN_ID,
+ _EXPECTED_OTEL_TRACESAMPLED,
+ ),
+ )
+
+ def test_otel_span_exists_flask_request(self):
+ django_expected = (None, None, None, False)
+ flask_expected = (_FLASK_HTTP_REQUEST, _FLASK_TRACE_ID, _FLASK_SPAN_ID, False)
+
+ with _setup_otel_span_context():
+ _, _, output = self._helper(django_expected, flask_expected)
+ self.assertEqual(
+ output,
+ (
+ _FLASK_HTTP_REQUEST,
+ _EXPECTED_OTEL_TRACE_ID,
+ _EXPECTED_OTEL_SPAN_ID,
+ _EXPECTED_OTEL_TRACESAMPLED,
+ ),
+ )
+
+ def test_otel_span_exists_both_django_and_flask(self):
+ django_expected = (
+ _DJANGO_HTTP_REQUEST,
+ _DJANGO_TRACE_ID,
+ _DJANGO_SPAN_ID,
+ False,
+ )
+ flask_expected = (_FLASK_HTTP_REQUEST, _FLASK_TRACE_ID, _FLASK_SPAN_ID, False)
+
+ with _setup_otel_span_context():
+ _, _, output = self._helper(django_expected, flask_expected)
+
+ # Django wins
+ self.assertEqual(
+ output,
+ (
+ _DJANGO_HTTP_REQUEST,
+ _EXPECTED_OTEL_TRACE_ID,
+ _EXPECTED_OTEL_SPAN_ID,
+ _EXPECTED_OTEL_TRACESAMPLED,
+ ),
+ )
+
+ def test_no_otel_span_no_requests(self):
+ flask_expected = (None, None, None, False)
+ django_expected = (None, None, None, False)
+ _, _, output = self._helper(django_expected, flask_expected)
+ self.assertEqual(output, (None, None, None, False))
+
+ def test_no_otel_span_django_request(self):
+ django_expected = (
+ _DJANGO_HTTP_REQUEST,
+ _DJANGO_TRACE_ID,
+ _DJANGO_SPAN_ID,
+ False,
+ )
+ flask_expected = (None, None, None, False)
+ _, _, output = self._helper(django_expected, flask_expected)
+ self.assertEqual(output, django_expected)
+
+ def test_no_otel_span_flask_request(self):
+ django_expected = (None, None, None, False)
+ flask_expected = (_FLASK_HTTP_REQUEST, _FLASK_TRACE_ID, _FLASK_SPAN_ID, False)
+ _, _, output = self._helper(django_expected, flask_expected)
+
+ # Django wins
+ self.assertEqual(output, flask_expected)
+
+ def test_no_otel_span_both_django_and_flask(self):
+ django_expected = (
+ _DJANGO_HTTP_REQUEST,
+ _DJANGO_TRACE_ID,
+ _DJANGO_SPAN_ID,
+ False,
+ )
+ flask_expected = (_FLASK_HTTP_REQUEST, _FLASK_TRACE_ID, _FLASK_SPAN_ID, False)
+ _, _, output = self._helper(django_expected, flask_expected)
+
+ # Django wins
+ self.assertEqual(output, django_expected)
+
class Test__parse_xcloud_trace(unittest.TestCase):
@staticmethod
@@ -367,25 +507,40 @@ def test_no_span(self):
self.assertEqual(sampled, False)
def test_no_trace(self):
- header = "/12345"
+ input_span = "12345"
+ expected_span = "3039".zfill(16)
+ header = f"/{input_span}"
trace_id, span_id, sampled = self._call_fut(header)
self.assertIsNone(trace_id)
- self.assertEqual(span_id, "12345")
+ self.assertEqual(span_id, expected_span)
self.assertEqual(sampled, False)
def test_with_span(self):
expected_trace = "12345"
- expected_span = "67890"
- header = f"{expected_trace}/{expected_span}"
+ input_span = "67890"
+ expected_span = "10932".zfill(16)
+ header = f"{expected_trace}/{input_span}"
trace_id, span_id, sampled = self._call_fut(header)
self.assertEqual(trace_id, expected_trace)
self.assertEqual(span_id, expected_span)
self.assertEqual(sampled, False)
+ def test_with_span_decimal_not_in_bounds(self):
+ input_spans = ["0", "9" * 100]
+
+ for input_span in input_spans:
+ expected_trace = "12345"
+ header = f"{expected_trace}/{input_span}"
+ trace_id, span_id, sampled = self._call_fut(header)
+ self.assertEqual(trace_id, expected_trace)
+ self.assertIsNone(span_id)
+ self.assertEqual(sampled, False)
+
def test_with_extra_characters(self):
expected_trace = "12345"
- expected_span = "67890"
- header = f"{expected_trace}/{expected_span};abc"
+ input_span = "67890"
+ expected_span = "10932".zfill(16)
+ header = f"{expected_trace}/{input_span};abc"
trace_id, span_id, sampled = self._call_fut(header)
self.assertEqual(trace_id, expected_trace)
self.assertEqual(span_id, expected_span)
@@ -393,8 +548,9 @@ def test_with_extra_characters(self):
def test_with_explicit_no_sampled(self):
expected_trace = "12345"
- expected_span = "67890"
- header = f"{expected_trace}/{expected_span};o=0"
+ input_span = "67890"
+ expected_span = "10932".zfill(16)
+ header = f"{expected_trace}/{input_span};o=0"
trace_id, span_id, sampled = self._call_fut(header)
self.assertEqual(trace_id, expected_trace)
self.assertEqual(span_id, expected_span)
@@ -402,8 +558,9 @@ def test_with_explicit_no_sampled(self):
def test_with__sampled(self):
expected_trace = "12345"
- expected_span = "67890"
- header = f"{expected_trace}/{expected_span};o=1"
+ input_span = "67890"
+ expected_span = "10932".zfill(16)
+ header = f"{expected_trace}/{input_span};o=1"
trace_id, span_id, sampled = self._call_fut(header)
self.assertEqual(trace_id, expected_trace)
self.assertEqual(span_id, expected_span)
@@ -464,3 +621,25 @@ def test_invalid_headers(self):
self.assertIsNone(trace_id)
self.assertIsNone(span_id)
self.assertEqual(sampled, False)
+
+
+class Test__parse_open_telemetry_data(unittest.TestCase):
+ @staticmethod
+ def _call_fut():
+ from google.cloud.logging_v2.handlers import _helpers
+
+ trace, span, sampled = _helpers._retrieve_current_open_telemetry_span()
+ return trace, span, sampled
+
+ def test_no_op(self):
+ trace_id, span_id, sampled = self._call_fut()
+ self.assertIsNone(trace_id)
+ self.assertIsNone(span_id)
+ self.assertEqual(sampled, False)
+
+ def test_span_exists(self):
+ with _setup_otel_span_context():
+ trace_id, span_id, sampled = self._call_fut()
+ self.assertEqual(trace_id, _EXPECTED_OTEL_TRACE_ID)
+ self.assertEqual(span_id, _EXPECTED_OTEL_SPAN_ID)
+ self.assertEqual(sampled, _EXPECTED_OTEL_TRACESAMPLED)
diff --git a/tests/unit/handlers/test__monitored_resources.py b/tests/unit/handlers/test__monitored_resources.py
index 3c62cba88..28f064b7b 100644
--- a/tests/unit/handlers/test__monitored_resources.py
+++ b/tests/unit/handlers/test__monitored_resources.py
@@ -12,37 +12,30 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+import pytest
import unittest
+import logging
import mock
import os
import functools
-from google.cloud.logging_v2.handlers._monitored_resources import (
- _create_functions_resource,
-)
from google.cloud.logging_v2.handlers._monitored_resources import (
_create_app_engine_resource,
-)
-from google.cloud.logging_v2.handlers._monitored_resources import (
+ _create_functions_resource,
_create_kubernetes_resource,
-)
-from google.cloud.logging_v2.handlers._monitored_resources import (
- _create_cloud_run_resource,
-)
-from google.cloud.logging_v2.handlers._monitored_resources import (
+ _create_cloud_run_service_resource,
+ _create_cloud_run_job_resource,
_create_compute_resource,
-)
-from google.cloud.logging_v2.handlers._monitored_resources import (
_create_global_resource,
+ detect_resource,
+ add_resource_labels,
)
-from google.cloud.logging_v2.handlers._monitored_resources import detect_resource
from google.cloud.logging_v2.handlers import _monitored_resources
from google.cloud.logging_v2.resource import Resource
class Test_Create_Resources(unittest.TestCase):
-
PROJECT = "test-project"
LOCATION = "test-location"
NAME = "test-name"
@@ -54,6 +47,7 @@ def _mock_metadata(self, endpoint):
if (
endpoint == _monitored_resources._ZONE_ID
or endpoint == _monitored_resources._REGION_ID
+ or endpoint == _monitored_resources._GKE_CLUSTER_LOCATION
):
return self.LOCATION
elif (
@@ -132,7 +126,6 @@ def test_functions_resource_no_name(self):
self.assertEqual(func_resource.labels["function_name"], "")
def test_create_kubernetes_resource(self):
-
patch = mock.patch(
"google.cloud.logging_v2.handlers._monitored_resources.retrieve_metadata_server",
wraps=self._mock_metadata,
@@ -160,7 +153,7 @@ def test_compute_resource(self):
self.assertEqual(resource.labels["instance_id"], self.NAME)
self.assertEqual(resource.labels["zone"], self.LOCATION)
- def test_cloud_run_resource(self):
+ def test_cloud_run_service_resource(self):
patch = mock.patch(
"google.cloud.logging_v2.handlers._monitored_resources.retrieve_metadata_server",
wraps=self._mock_metadata,
@@ -169,7 +162,7 @@ def test_cloud_run_resource(self):
os.environ[_monitored_resources._CLOUD_RUN_REVISION_ID] = self.VERSION
os.environ[_monitored_resources._CLOUD_RUN_CONFIGURATION_ID] = self.CONFIG
with patch:
- resource = _create_cloud_run_resource()
+ resource = _create_cloud_run_service_resource()
self.assertIsInstance(resource, Resource)
self.assertEqual(resource.type, "cloud_run_revision")
self.assertEqual(resource.labels["project_id"], self.PROJECT)
@@ -178,6 +171,23 @@ def test_cloud_run_resource(self):
self.assertEqual(resource.labels["configuration_name"], self.CONFIG)
self.assertEqual(resource.labels["location"], self.LOCATION)
+ def test_cloud_run_job_resource(self):
+ patch = mock.patch(
+ "google.cloud.logging_v2.handlers._monitored_resources.retrieve_metadata_server",
+ wraps=self._mock_metadata,
+ )
+ os.environ[_monitored_resources._CLOUD_RUN_JOB_ID] = self.NAME
+ os.environ[_monitored_resources._CLOUD_RUN_EXECUTION_ID] = self.VERSION
+ os.environ[_monitored_resources._CLOUD_RUN_TASK_INDEX] = self.CONFIG
+ os.environ[_monitored_resources._CLOUD_RUN_TASK_ATTEMPT] = self.CLUSTER
+ with patch:
+ resource = _create_cloud_run_job_resource()
+ self.assertIsInstance(resource, Resource)
+ self.assertEqual(resource.type, "cloud_run_job")
+ self.assertEqual(resource.labels["project_id"], self.PROJECT)
+ self.assertEqual(resource.labels["job_name"], self.NAME)
+ self.assertEqual(resource.labels["location"], self.LOCATION)
+
def test_app_engine_resource(self):
patch = mock.patch(
"google.cloud.logging_v2.handlers._monitored_resources.retrieve_metadata_server",
@@ -214,7 +224,8 @@ def test_with_no_project_from_server(self):
resource_fns = [
_global_resource_patched,
_create_app_engine_resource,
- _create_cloud_run_resource,
+ _create_cloud_run_service_resource,
+ _create_cloud_run_job_resource,
_create_compute_resource,
_create_kubernetes_resource,
_create_functions_resource,
@@ -225,7 +236,6 @@ def test_with_no_project_from_server(self):
class Test_Resource_Detection(unittest.TestCase):
-
PROJECT = "test-project"
def _mock_k8s_metadata(self, endpoint):
@@ -285,13 +295,20 @@ def test_detect_legacy_functions(self):
self.assertIsInstance(resource, Resource)
self.assertEqual(resource.type, "cloud_function")
- def test_detect_cloud_run(self):
- for env in _monitored_resources._CLOUD_RUN_ENV_VARS:
+ def test_detect_cloud_run_service(self):
+ for env in _monitored_resources._CLOUD_RUN_SERVICE_ENV_VARS:
os.environ[env] = "TRUE"
resource = detect_resource(self.PROJECT)
self.assertIsInstance(resource, Resource)
self.assertEqual(resource.type, "cloud_run_revision")
+ def test_detect_cloud_run_job(self):
+ for env in _monitored_resources._CLOUD_RUN_JOB_ENV_VARS:
+ os.environ[env] = "TRUE"
+ resource = detect_resource(self.PROJECT)
+ self.assertIsInstance(resource, Resource)
+ self.assertEqual(resource.type, "cloud_run_job")
+
def test_detect_compute_engine(self):
patch = mock.patch(
"google.cloud.logging_v2.handlers._monitored_resources.retrieve_metadata_server",
@@ -327,3 +344,45 @@ def test_detect_partial_data(self):
# project id not returned from metadata serve
# should be empty string
self.assertEqual(resource.labels["project_id"], "")
+
+
+@pytest.mark.parametrize(
+ "resource_type,os_environ,record_attrs,expected_labels",
+ [
+ (
+ _monitored_resources._GAE_RESOURCE_TYPE,
+ {},
+ {"_trace": "trace_id"},
+ {_monitored_resources._GAE_TRACE_ID_LABEL: "trace_id"},
+ ),
+ (
+ _monitored_resources._CLOUD_RUN_JOB_RESOURCE_TYPE,
+ {
+ _monitored_resources._CLOUD_RUN_EXECUTION_ID: "test_job_12345",
+ _monitored_resources._CLOUD_RUN_TASK_INDEX: "1",
+ _monitored_resources._CLOUD_RUN_TASK_ATTEMPT: "12",
+ },
+ {},
+ {
+ _monitored_resources._CLOUD_RUN_JOBS_EXECUTION_NAME_LABEL: "test_job_12345",
+ _monitored_resources._CLOUD_RUN_JOBS_TASK_INDEX_LABEL: "1",
+ _monitored_resources._CLOUD_RUN_JOBS_TASK_ATTEMPT_LABEL: "12",
+ },
+ ),
+ ("global", {}, {}, {}),
+ ],
+)
+def test_add_resource_labels(resource_type, os_environ, record_attrs, expected_labels):
+ os.environ.clear()
+ record = logging.LogRecord("logname", None, None, None, "test", None, None)
+
+ resource = Resource(type=resource_type, labels={})
+
+ for attr, val in record_attrs.items():
+ setattr(record, attr, val)
+
+ os.environ.update(os_environ)
+
+ labels = add_resource_labels(resource, record)
+
+ assert expected_labels == labels
diff --git a/tests/unit/handlers/test_app_engine.py b/tests/unit/handlers/test_app_engine.py
index 8eedfad9b..38d607e99 100644
--- a/tests/unit/handlers/test_app_engine.py
+++ b/tests/unit/handlers/test_app_engine.py
@@ -13,6 +13,7 @@
# limitations under the License.
import logging
+import pytest
import unittest
import mock
@@ -46,6 +47,9 @@ def test_constructor_w_gae_standard_env(self):
), mock.patch(
"google.cloud.logging_v2.handlers._monitored_resources.retrieve_metadata_server",
return_value=self.PROJECT,
+ ), pytest.warns(
+ DeprecationWarning,
+ match="AppEngineHandler is deprecated. Use CloudLoggingHandler instead",
):
handler = self._make_one(client, transport=_Transport)
@@ -78,6 +82,9 @@ def test_constructor_w_gae_flex_env(self):
), mock.patch(
"google.cloud.logging_v2.handlers._monitored_resources.retrieve_metadata_server",
return_value=self.PROJECT,
+ ), pytest.warns(
+ DeprecationWarning,
+ match="AppEngineHandler is deprecated. Use CloudLoggingHandler instead",
):
handler = self._make_one(
client, name=name, transport=_Transport, stream=stream
@@ -99,7 +106,10 @@ def test_emit(self):
"google.cloud.logging_v2.handlers.app_engine.get_request_data",
return_value=(expected_http_request, trace_id, None, None),
)
- with get_request_patch:
+ with get_request_patch, pytest.warns(
+ DeprecationWarning,
+ match="AppEngineHandler is deprecated. Use CloudLoggingHandler instead",
+ ):
# library integrations mocked to return test data
client = mock.Mock(project=self.PROJECT, spec=["project"])
handler = self._make_one(client, transport=_Transport)
@@ -137,7 +147,10 @@ def test_emit_manual_field_override(self):
"google.cloud.logging_v2.handlers.app_engine.get_request_data",
return_value=(inferred_http_request, inferred_trace_id, None, None),
)
- with get_request_patch:
+ with get_request_patch, pytest.warns(
+ DeprecationWarning,
+ match="AppEngineHandler is deprecated. Use CloudLoggingHandler instead",
+ ):
# library integrations mocked to return test data
client = mock.Mock(project=self.PROJECT, spec=["project"])
handler = self._make_one(client, transport=_Transport)
@@ -153,7 +166,7 @@ def test_emit_manual_field_override(self):
setattr(record, "trace", expected_trace)
expected_span = "456"
setattr(record, "span_id", expected_span)
- expected_http = {"reuqest_url": "manual"}
+ expected_http = {"request_url": "manual"}
setattr(record, "http_request", expected_http)
expected_resource = Resource(type="test", labels={})
setattr(record, "resource", expected_resource)
@@ -197,12 +210,20 @@ def test_get_gae_labels_with_label(self):
from google.cloud.logging_v2.handlers import app_engine
trace_id = "test-gae-trace-id"
- gae_labels = self._get_gae_labels_helper(trace_id)
+ with pytest.warns(
+ DeprecationWarning,
+ match="AppEngineHandler is deprecated. Use CloudLoggingHandler instead",
+ ):
+ gae_labels = self._get_gae_labels_helper(trace_id)
expected_labels = {app_engine._TRACE_ID_LABEL: trace_id}
self.assertEqual(gae_labels, expected_labels)
def test_get_gae_labels_without_label(self):
- gae_labels = self._get_gae_labels_helper(None)
+ with pytest.warns(
+ DeprecationWarning,
+ match="AppEngineHandler is deprecated. Use CloudLoggingHandler instead",
+ ):
+ gae_labels = self._get_gae_labels_helper(None)
self.assertEqual(gae_labels, {})
diff --git a/tests/unit/handlers/test_container_engine.py b/tests/unit/handlers/test_container_engine.py
index 280ab9cf0..5c814c53d 100644
--- a/tests/unit/handlers/test_container_engine.py
+++ b/tests/unit/handlers/test_container_engine.py
@@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+import pytest
import unittest
@@ -27,18 +28,30 @@ def _make_one(self, *args, **kw):
return self._get_target_class()(*args, **kw)
def test_ctor_defaults(self):
- handler = self._make_one()
+ with pytest.warns(
+ DeprecationWarning,
+ match="ContainerEngineHandler is deprecated. Use StructuredLogHandler instead",
+ ):
+ handler = self._make_one()
self.assertIsNone(handler.name)
def test_ctor_w_name(self):
- handler = self._make_one(name="foo")
+ with pytest.warns(
+ DeprecationWarning,
+ match="ContainerEngineHandler is deprecated. Use StructuredLogHandler instead",
+ ):
+ handler = self._make_one(name="foo")
self.assertEqual(handler.name, "foo")
def test_format(self):
import logging
import json
- handler = self._make_one()
+ with pytest.warns(
+ DeprecationWarning,
+ match="ContainerEngineHandler is deprecated. Use StructuredLogHandler instead",
+ ):
+ handler = self._make_one()
logname = "loggername"
message = "hello world,嗨 世界"
record = logging.LogRecord(
@@ -51,6 +64,10 @@ def test_format(self):
"thread": record.thread,
"severity": record.levelname,
}
- payload = handler.format(record)
+ with pytest.warns(
+ DeprecationWarning,
+ match="format_stackdriver_json is deprecated. Use StructuredLogHandler instead",
+ ):
+ payload = handler.format(record)
self.assertEqual(payload, json.dumps(expected_payload, ensure_ascii=False))
diff --git a/tests/unit/handlers/test_handlers.py b/tests/unit/handlers/test_handlers.py
index 1e431f1aa..3f25929e2 100644
--- a/tests/unit/handlers/test_handlers.py
+++ b/tests/unit/handlers/test_handlers.py
@@ -18,14 +18,25 @@
import mock
import json
+from google.cloud.logging_v2.handlers.handlers import (
+ _INTERNAL_LOGGERS,
+ EXCLUDED_LOGGER_DEFAULTS,
+)
+
from google.cloud.logging_v2.handlers._monitored_resources import (
_FUNCTION_ENV_VARS,
_GAE_ENV_VARS,
)
+from tests.unit.handlers import (
+ _setup_otel_span_context,
+ _EXPECTED_OTEL_TRACE_ID,
+ _EXPECTED_OTEL_SPAN_ID,
+ _EXPECTED_OTEL_TRACESAMPLED,
+)
-class TestCloudLoggingFilter(unittest.TestCase):
+class TestCloudLoggingFilter(unittest.TestCase):
PROJECT = "PROJECT"
@staticmethod
@@ -129,7 +140,7 @@ def test_minimal_record(self):
self.assertIsNone(record._labels)
self.assertEqual(record._labels_str, "{}")
- def test_record_with_request(self):
+ def test_record_with_xctc_request(self):
"""
test filter adds http request data when available
"""
@@ -150,8 +161,9 @@ def test_record_with_request(self):
expected_path = "http://testserver/123"
expected_agent = "Mozilla/5.0"
expected_trace = "123"
- expected_span = "456"
- combined_trace = f"{expected_trace}/{expected_span};o=1"
+ input_span = "456"
+ expected_span = "1c8".zfill(16)
+ combined_trace = f"{expected_trace}/{input_span};o=1"
expected_request = {
"requestMethod": "GET",
"requestUrl": expected_path,
@@ -226,6 +238,136 @@ def test_record_with_traceparent_request(self):
self.assertEqual(record._http_request, expected_request)
self.assertEqual(record._http_request_str, json.dumps(expected_request))
+ def test_record_with_opentelemetry_span_no_request(self):
+ filter_obj = self._make_one()
+ record = logging.LogRecord(
+ None,
+ logging.INFO,
+ None,
+ None,
+ None,
+ None,
+ None,
+ )
+ record.created = None
+
+ with _setup_otel_span_context():
+ success = filter_obj.filter(record)
+ self.assertTrue(success)
+
+ self.assertEqual(record._trace, _EXPECTED_OTEL_TRACE_ID)
+ self.assertEqual(record._trace_str, _EXPECTED_OTEL_TRACE_ID)
+ self.assertEqual(record._span_id, _EXPECTED_OTEL_SPAN_ID)
+ self.assertEqual(record._span_id_str, _EXPECTED_OTEL_SPAN_ID)
+ self.assertEqual(record._trace_sampled, _EXPECTED_OTEL_TRACESAMPLED)
+ self.assertEqual(record._trace_sampled_str, "true")
+ self.assertIsNone(record._http_request)
+ self.assertEqual(record._http_request_str, "{}")
+
+ def test_record_with_opentelemetry_span_and_request(self):
+ filter_obj = self._make_one()
+ record = logging.LogRecord(
+ None,
+ logging.INFO,
+ None,
+ None,
+ None,
+ None,
+ None,
+ )
+ record.created = None
+ http_path = "http://testserver/123"
+ http_agent = "Mozilla/5.0"
+ http_trace = "123"
+ http_span = "456"
+ combined_trace = f"{http_trace}/{http_span};o=1"
+ expected_request = {
+ "requestMethod": "GET",
+ "requestUrl": http_path,
+ "userAgent": http_agent,
+ "protocol": "HTTP/1.1",
+ }
+
+ app = self.create_app()
+ with app.test_request_context(
+ http_path,
+ headers={
+ "User-Agent": http_agent,
+ "X_CLOUD_TRACE_CONTEXT": combined_trace,
+ },
+ ):
+ with _setup_otel_span_context():
+ success = filter_obj.filter(record)
+ self.assertTrue(success)
+
+ self.assertEqual(record._trace, _EXPECTED_OTEL_TRACE_ID)
+ self.assertEqual(record._trace_str, _EXPECTED_OTEL_TRACE_ID)
+ self.assertEqual(record._span_id, _EXPECTED_OTEL_SPAN_ID)
+ self.assertEqual(record._span_id_str, _EXPECTED_OTEL_SPAN_ID)
+ self.assertEqual(record._trace_sampled, _EXPECTED_OTEL_TRACESAMPLED)
+ self.assertEqual(record._trace_sampled_str, "true")
+
+ self.assertEqual(record._http_request, expected_request)
+ self.assertEqual(record._http_request_str, json.dumps(expected_request))
+
+ def test_record_with_opentelemetry_span_and_request_with_overrides(self):
+ """
+ sort of does what the test after this one does, but more in the context of OTel precedence
+ """
+ filter_obj = self._make_one()
+ record = logging.LogRecord(
+ None,
+ logging.INFO,
+ None,
+ None,
+ None,
+ None,
+ None,
+ )
+ record.created = None
+ http_path = "http://testserver/123"
+ http_agent = "Mozilla/5.0"
+ http_trace = "123"
+ http_span = "456"
+ combined_trace = f"{http_trace}/{http_span};o=1"
+ expected_request = {
+ "requestMethod": "GET",
+ "requestUrl": http_path,
+ "userAgent": http_agent,
+ "protocol": "HTTP/1.1",
+ }
+
+ overwritten_trace = "01234"
+ overwritten_span = "43210"
+ overwritten_tracesampled = False
+ record.trace = overwritten_trace
+ record.span_id = overwritten_span
+ record.trace_sampled = overwritten_tracesampled
+
+ app = self.create_app()
+ with app.test_request_context(
+ http_path,
+ headers={
+ "User-Agent": http_agent,
+ "X_CLOUD_TRACE_CONTEXT": combined_trace,
+ },
+ ):
+ with _setup_otel_span_context():
+ success = filter_obj.filter(record)
+ self.assertTrue(success)
+
+ self.assertEqual(record._trace, overwritten_trace)
+ self.assertEqual(record._trace_str, overwritten_trace)
+ self.assertEqual(record._span_id, overwritten_span)
+ self.assertEqual(record._span_id_str, overwritten_span)
+ self.assertFalse(record._trace_sampled)
+ self.assertEqual(
+ record._trace_sampled_str, json.dumps(overwritten_tracesampled)
+ )
+
+ self.assertEqual(record._http_request, expected_request)
+ self.assertEqual(record._http_request_str, json.dumps(expected_request))
+
def test_user_overrides(self):
"""
ensure user can override fields
@@ -291,7 +433,6 @@ def test_user_overrides(self):
class TestCloudLoggingHandler(unittest.TestCase):
-
PROJECT = "PROJECT"
@staticmethod
@@ -320,6 +461,7 @@ def test_ctor_defaults(self):
self.assertEqual(handler.name, DEFAULT_LOGGER_NAME)
self.assertIs(handler.client, client)
self.assertIsInstance(handler.transport, _Transport)
+ self.assertTrue(handler._transport_open)
self.assertIs(handler.transport.client, client)
self.assertEqual(handler.transport.name, DEFAULT_LOGGER_NAME)
global_resource = _create_global_resource(self.PROJECT)
@@ -327,6 +469,17 @@ def test_ctor_defaults(self):
self.assertIsNone(handler.labels)
self.assertIs(handler.stream, sys.stderr)
+ def test_add_handler_to_client_handlers(self):
+ from google.cloud.logging_v2.logger import _GLOBAL_RESOURCE
+
+ client = _Client(self.PROJECT)
+ handler = self._make_one(
+ client,
+ transport=_Transport,
+ resource=_GLOBAL_RESOURCE,
+ )
+ self.assertIn(handler, client._handlers)
+
def test_ctor_explicit(self):
import io
from google.cloud.logging import Resource
@@ -432,7 +585,7 @@ def test_emit_manual_field_override(self):
setattr(record, "span_id", expected_span)
expected_sampled = True
setattr(record, "trace_sampled", expected_sampled)
- expected_http = {"reuqest_url": "manual"}
+ expected_http = {"request_url": "manual"}
setattr(record, "http_request", expected_http)
expected_source = {"file": "test-file"}
setattr(record, "source_location", expected_source)
@@ -649,6 +802,56 @@ def test_emit_with_encoded_json(self):
),
)
+ def test_emit_after_close(self):
+ from google.cloud.logging_v2.logger import _GLOBAL_RESOURCE
+
+ client = _Client(self.PROJECT)
+ handler = self._make_one(
+ client, transport=_Transport, resource=_GLOBAL_RESOURCE
+ )
+ logname = "loggername"
+ message = "hello world"
+ record = logging.LogRecord(
+ logname, logging.INFO, None, None, message, None, None
+ )
+ handler.handle(record)
+ old_transport = handler.transport
+ self.assertEqual(
+ handler.transport.send_called_with,
+ (
+ record,
+ message,
+ _GLOBAL_RESOURCE,
+ {"python_logger": logname},
+ None,
+ None,
+ False,
+ None,
+ None,
+ ),
+ )
+
+ handler.close()
+ self.assertFalse(handler._transport_open)
+
+ handler.handle(record)
+ self.assertTrue(handler._transport_open)
+ self.assertNotEqual(handler.transport, old_transport)
+ self.assertEqual(
+ handler.transport.send_called_with,
+ (
+ record,
+ message,
+ _GLOBAL_RESOURCE,
+ {"python_logger": logname},
+ None,
+ None,
+ False,
+ None,
+ None,
+ ),
+ )
+
def test_format_with_arguments(self):
"""
Handler should support format string arguments
@@ -684,6 +887,24 @@ def test_format_with_arguments(self):
),
)
+ def test_close(self):
+ from google.cloud.logging_v2.logger import _GLOBAL_RESOURCE
+
+ client = _Client(self.PROJECT)
+ handler = self._make_one(
+ client,
+ transport=_Transport,
+ resource=_GLOBAL_RESOURCE,
+ )
+ old_transport = handler.transport
+ handler.close()
+ self.assertFalse(handler._transport_open)
+ self.assertTrue(old_transport.close_called)
+
+ # second call to close shouldn't throw an exception
+ handler.close()
+ self.assertFalse(handler._transport_open)
+
class TestFormatAndParseMessage(unittest.TestCase):
def test_none(self):
@@ -859,7 +1080,7 @@ def test_json_fields_input_unmodified(self):
_format_and_parse_message(record, handler)
# ensure json_fields has no side-effects
self.assertEqual(set(json_fields.keys()), set(json_fields_orig.keys()))
- for (key, value) in json_fields_orig.items():
+ for key, value in json_fields_orig.items():
self.assertEqual(
value, json_fields[key], f"expected_payload[{key}] != result[{key}]"
)
@@ -869,7 +1090,7 @@ class TestSetupLogging(unittest.TestCase):
def _call_fut(self, handler, excludes=None):
from google.cloud.logging.handlers import setup_logging
- if excludes:
+ if excludes is not None:
return setup_logging(handler, excluded_loggers=excludes)
else:
return setup_logging(handler)
@@ -895,6 +1116,24 @@ def test_setup_logging_excludes(self):
self.assertNotIn(handler, excluded_logger.handlers)
self.assertFalse(excluded_logger.propagate)
+ def test_setup_logging_internal_loggers_no_excludes(self):
+ handler = _Handler(logging.INFO)
+ self._call_fut(handler, excludes=())
+
+ # Test that excluded logger defaults can be included, but internal
+ # loggers can't be.
+ for logger_name in _INTERNAL_LOGGERS:
+ logger = logging.getLogger(logger_name)
+ self.assertNotIn(handler, logger.handlers)
+ self.assertFalse(logger.propagate)
+
+ logger = logging.getLogger("logging")
+ self.assertTrue(logger.propagate)
+
+ for logger_name in EXCLUDED_LOGGER_DEFAULTS:
+ logger = logging.getLogger(logger_name)
+ self.assertTrue(logger.propagate)
+
@patch.dict("os.environ", {envar: "1" for envar in _FUNCTION_ENV_VARS})
def test_remove_handlers_gcf(self):
logger = logging.getLogger()
@@ -941,10 +1180,18 @@ def test_keep_handlers_others(self):
def setUp(self):
self._handlers_cache = logging.getLogger().handlers[:]
+ # reset the logging manager every time so that we're not reusing loggers
+ # across different test cases.
+ self._logger_manager = logging.Logger.manager
+ logging.Logger.manager = logging.Manager(logging.Logger.root)
+
def tearDown(self):
# cleanup handlers
logging.getLogger().handlers = self._handlers_cache[:]
+ # restore the old logging manager.
+ logging.Logger.manager = self._logger_manager
+
class _Handler(object):
def __init__(self, level):
@@ -960,12 +1207,14 @@ def release(self):
class _Client(object):
def __init__(self, project):
self.project = project
+ self._handlers = set()
class _Transport(object):
def __init__(self, client, name, resource=None):
self.client = client
self.name = name
+ self.close_called = False
def send(
self,
@@ -990,3 +1239,6 @@ def send(
http_request,
source_location,
)
+
+ def close(self):
+ self.close_called = True
diff --git a/tests/unit/handlers/test_structured_log.py b/tests/unit/handlers/test_structured_log.py
index 353530ed1..908758749 100644
--- a/tests/unit/handlers/test_structured_log.py
+++ b/tests/unit/handlers/test_structured_log.py
@@ -86,7 +86,7 @@ def test_format(self):
}
handler.filter(record)
result = json.loads(handler.format(record))
- for (key, value) in expected_payload.items():
+ for key, value in expected_payload.items():
self.assertEqual(value, result[key])
self.assertEqual(
len(expected_payload.keys()),
@@ -121,7 +121,7 @@ def test_format_minimal(self):
handler.filter(record)
result = json.loads(handler.format(record))
self.assertEqual(set(expected_payload.keys()), set(result.keys()))
- for (key, value) in expected_payload.items():
+ for key, value in expected_payload.items():
self.assertEqual(
value, result[key], f"expected_payload[{key}] != result[{key}]"
)
@@ -304,7 +304,7 @@ def test_format_with_reserved_json_field(self):
handler.filter(record)
result = json.loads(handler.format(record))
self.assertEqual(set(expected_payload.keys()), set(result.keys()))
- for (key, value) in expected_payload.items():
+ for key, value in expected_payload.items():
self.assertEqual(
value, result[key], f"expected_payload[{key}] != result[{key}]"
)
@@ -382,7 +382,7 @@ def test_format_with_arguments(self):
result = handler.format(record)
self.assertIn(expected_result, result)
- def test_format_with_request(self):
+ def test_format_with_xctc_request(self):
import logging
import json
@@ -393,8 +393,9 @@ def test_format_with_request(self):
expected_path = "http://testserver/123"
expected_agent = "Mozilla/5.0"
expected_trace = "123"
- expected_span = "456"
- trace_header = f"{expected_trace}/{expected_span};o=1"
+ input_span = "456"
+ expected_span = "1c8".zfill(16)
+ trace_header = f"{expected_trace}/{input_span};o=1"
expected_payload = {
"logging.googleapis.com/trace": expected_trace,
"logging.googleapis.com/spanId": expected_span,
@@ -417,7 +418,7 @@ def test_format_with_request(self):
):
handler.filter(record)
result = json.loads(handler.format(record))
- for (key, value) in expected_payload.items():
+ for key, value in expected_payload.items():
self.assertEqual(value, result[key])
def test_format_with_traceparent(self):
@@ -452,14 +453,14 @@ def test_format_with_traceparent(self):
):
handler.filter(record)
result = json.loads(handler.format(record))
- for (key, value) in expected_payload.items():
+ for key, value in expected_payload.items():
self.assertEqual(value, result[key])
def test_format_overrides(self):
"""
Allow users to override log fields using `logging.info("", extra={})`
- If supported fields were overriden by the user, those choices should
+ If supported fields were overridden by the user, those choices should
take precedence.
"""
import logging
@@ -509,7 +510,108 @@ def test_format_overrides(self):
)
handler.filter(record)
result = json.loads(handler.format(record))
- for (key, value) in expected_payload.items():
+ for key, value in expected_payload.items():
+ self.assertEqual(value, result[key])
+
+ def test_format_with_opentelemetry_span(self):
+ import logging
+ import json
+
+ from tests.unit.handlers import (
+ _setup_otel_span_context,
+ _EXPECTED_OTEL_TRACE_ID,
+ _EXPECTED_OTEL_SPAN_ID,
+ _EXPECTED_OTEL_TRACESAMPLED,
+ )
+
+ handler = self._make_one()
+ logname = "loggername"
+ message = "hello world,嗨 世界"
+ record = logging.LogRecord(logname, logging.INFO, "", 0, message, None, None)
+ expected_payload = {
+ "logging.googleapis.com/trace": _EXPECTED_OTEL_TRACE_ID,
+ "logging.googleapis.com/spanId": _EXPECTED_OTEL_SPAN_ID,
+ "logging.googleapis.com/trace_sampled": _EXPECTED_OTEL_TRACESAMPLED,
+ }
+
+ with _setup_otel_span_context():
+ handler.filter(record)
+ result = json.loads(handler.format(record))
+ for key, value in expected_payload.items():
+ self.assertEqual(value, result[key])
+
+ def test_format_with_opentelemetry_span_and_request(self):
+ import logging
+ import json
+
+ from tests.unit.handlers import (
+ _setup_otel_span_context,
+ _EXPECTED_OTEL_TRACE_ID,
+ _EXPECTED_OTEL_SPAN_ID,
+ _EXPECTED_OTEL_TRACESAMPLED,
+ )
+
+ handler = self._make_one()
+ logname = "loggername"
+ message = "hello world,嗨 世界"
+ record = logging.LogRecord(logname, logging.INFO, "", 0, message, None, None)
+ expected_path = "http://testserver/123"
+ expected_agent = "Mozilla/5.0"
+ http_trace = "123"
+ http_span = "456"
+ trace_header = f"{http_trace}/{http_span};o=1"
+ expected_payload = {
+ "logging.googleapis.com/trace": _EXPECTED_OTEL_TRACE_ID,
+ "logging.googleapis.com/spanId": _EXPECTED_OTEL_SPAN_ID,
+ "logging.googleapis.com/trace_sampled": _EXPECTED_OTEL_TRACESAMPLED,
+ "httpRequest": {
+ "requestMethod": "GET",
+ "requestUrl": expected_path,
+ "userAgent": expected_agent,
+ "protocol": "HTTP/1.1",
+ },
+ }
+
+ app = self.create_app()
+ with app.test_request_context(
+ expected_path,
+ headers={
+ "User-Agent": expected_agent,
+ "X_CLOUD_TRACE_CONTEXT": trace_header,
+ },
+ ):
+ with _setup_otel_span_context():
+ handler.filter(record)
+ result = json.loads(handler.format(record))
+ for key, value in expected_payload.items():
+ self.assertEqual(value, result[key])
+
+ def test_format_with_opentelemetry_span_and_overrides(self):
+ import logging
+ import json
+
+ from tests.unit.handlers import _setup_otel_span_context
+
+ handler = self._make_one()
+ logname = "loggername"
+ message = "hello world,嗨 世界"
+ record = logging.LogRecord(logname, logging.INFO, "", 0, message, None, None)
+ overwrite_trace = "abc"
+ overwrite_span = "123"
+ overwrite_tracesampled = False
+ record.trace = overwrite_trace
+ record.span_id = overwrite_span
+ record.trace_sampled = overwrite_tracesampled
+ expected_payload = {
+ "logging.googleapis.com/trace": overwrite_trace,
+ "logging.googleapis.com/spanId": overwrite_span,
+ "logging.googleapis.com/trace_sampled": overwrite_tracesampled,
+ }
+
+ with _setup_otel_span_context():
+ handler.filter(record)
+ result = json.loads(handler.format(record))
+ for key, value in expected_payload.items():
self.assertEqual(value, result[key])
def test_format_with_json_fields(self):
@@ -590,7 +692,7 @@ def test_json_fields_input_unmodified(self):
handler.format(record)
# ensure json_fields has no side-effects
self.assertEqual(set(json_fields.keys()), set(json_fields_orig.keys()))
- for (key, value) in json_fields_orig.items():
+ for key, value in json_fields_orig.items():
self.assertEqual(
value, json_fields[key], f"expected_payload[{key}] != result[{key}]"
)
diff --git a/tests/unit/handlers/transports/test_background_thread.py b/tests/unit/handlers/transports/test_background_thread.py
index d4954ff7b..9fdccb172 100644
--- a/tests/unit/handlers/transports/test_background_thread.py
+++ b/tests/unit/handlers/transports/test_background_thread.py
@@ -12,13 +12,17 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+import contextlib
import time
import logging
import queue
+import re
import unittest
import mock
+from io import StringIO
+
class TestBackgroundThreadHandler(unittest.TestCase):
PROJECT = "PROJECT"
@@ -176,6 +180,11 @@ def test_worker(self):
class Test_Worker(unittest.TestCase):
NAME = "python_logger"
+ def setUp(self):
+ import sys
+
+ print("In method", self._testMethodName, file=sys.stderr)
+
@staticmethod
def _get_target_class():
from google.cloud.logging_v2.handlers.transports import background_thread
@@ -187,9 +196,26 @@ def _make_one(self, *args, **kw):
def _start_with_thread_patch(self, worker):
with mock.patch("threading.Thread", new=_Thread) as thread_mock:
- with mock.patch("atexit.register") as atexit_mock:
- worker.start()
- return thread_mock, atexit_mock
+ worker.start()
+ return thread_mock
+
+ @staticmethod
+ @contextlib.contextmanager
+ def _init_atexit_mock():
+ atexit_mock = _AtexitMock()
+ with mock.patch.multiple(
+ "atexit", register=atexit_mock.register, unregister=atexit_mock.unregister
+ ):
+ yield atexit_mock
+
+ @staticmethod
+ @contextlib.contextmanager
+ def _init_main_thread_is_alive_mock(is_alive):
+ with mock.patch("threading.main_thread") as main_thread_func_mock:
+ main_thread_obj_mock = mock.Mock()
+ main_thread_func_mock.return_value = main_thread_obj_mock
+ main_thread_obj_mock.is_alive = mock.Mock(return_value=is_alive)
+ yield
def test_constructor(self):
logger = _Logger(self.NAME)
@@ -216,14 +242,15 @@ def test_start(self):
worker = self._make_one(_Logger(self.NAME))
- _, atexit_mock = self._start_with_thread_patch(worker)
+ with self._init_atexit_mock() as atexit_mock:
+ self._start_with_thread_patch(worker)
self.assertTrue(worker.is_alive)
self.assertIsNotNone(worker._thread)
self.assertTrue(worker._thread.daemon)
self.assertEqual(worker._thread._target, worker._thread_main)
self.assertEqual(worker._thread._name, background_thread._WORKER_THREAD_NAME)
- atexit_mock.assert_called_once_with(worker._main_thread_terminated)
+ self.assertIn(worker._handle_exit, atexit_mock.registered_funcs)
# Calling start again should not start a new thread.
current_thread = worker._thread
@@ -260,29 +287,33 @@ def test_stop_no_grace(self):
self.assertEqual(thread._timeout, None)
- def test__main_thread_terminated(self):
+ def test__close(self):
worker = self._make_one(_Logger(self.NAME))
self._start_with_thread_patch(worker)
- worker._main_thread_terminated()
+ worker._close("")
self.assertFalse(worker.is_alive)
# Calling twice should not be an error
- worker._main_thread_terminated()
+ worker._close("")
- def test__main_thread_terminated_non_empty_queue(self):
+ def test__close_non_empty_queue(self):
worker = self._make_one(_Logger(self.NAME))
+ msg = "My Message"
self._start_with_thread_patch(worker)
record = mock.Mock()
record.created = time.time()
worker.enqueue(record, "")
- worker._main_thread_terminated()
+
+ with mock.patch("sys.stderr", new_callable=StringIO) as stderr_mock:
+ worker._close(msg)
+ self.assertIn(msg, stderr_mock.getvalue())
self.assertFalse(worker.is_alive)
- def test__main_thread_terminated_did_not_join(self):
+ def test__close_did_not_join(self):
worker = self._make_one(_Logger(self.NAME))
self._start_with_thread_patch(worker)
@@ -290,7 +321,65 @@ def test__main_thread_terminated_did_not_join(self):
record = mock.Mock()
record.created = time.time()
worker.enqueue(record, "")
- worker._main_thread_terminated()
+ worker._close("")
+
+ self.assertFalse(worker.is_alive)
+
+ def test__handle_exit(self):
+ from google.cloud.logging_v2.handlers.transports.background_thread import (
+ _CLOSE_THREAD_SHUTDOWN_ERROR_MSG,
+ )
+
+ worker = self._make_one(_Logger(self.NAME))
+
+ with mock.patch("sys.stderr", new_callable=StringIO) as stderr_mock:
+ with self._init_main_thread_is_alive_mock(False):
+ with self._init_atexit_mock():
+ self._start_with_thread_patch(worker)
+ self._enqueue_record(worker, "test")
+ worker._handle_exit()
+
+ self.assertRegex(
+ stderr_mock.getvalue(),
+ re.compile("^%s$" % _CLOSE_THREAD_SHUTDOWN_ERROR_MSG, re.MULTILINE),
+ )
+
+ self.assertRegex(
+ stderr_mock.getvalue(),
+ re.compile(
+ r"^Failed to send %d pending logs\.$" % worker._queue.qsize(),
+ re.MULTILINE,
+ ),
+ )
+
+ def test__handle_exit_no_items(self):
+ worker = self._make_one(_Logger(self.NAME))
+
+ with mock.patch("sys.stderr", new_callable=StringIO) as stderr_mock:
+ with self._init_main_thread_is_alive_mock(False):
+ with self._init_atexit_mock():
+ self._start_with_thread_patch(worker)
+ worker._handle_exit()
+
+ self.assertEqual(stderr_mock.getvalue(), "")
+
+ def test_close_unregister_atexit(self):
+ worker = self._make_one(_Logger(self.NAME))
+
+ with mock.patch("sys.stderr", new_callable=StringIO) as stderr_mock:
+ with self._init_atexit_mock() as atexit_mock:
+ self._start_with_thread_patch(worker)
+ self.assertIn(worker._handle_exit, atexit_mock.registered_funcs)
+ worker.close()
+ self.assertNotIn(worker._handle_exit, atexit_mock.registered_funcs)
+
+ self.assertNotRegex(
+ stderr_mock.getvalue(),
+ re.compile(
+ r"^Failed to send %d pending logs\.$" % worker._queue.qsize(),
+ re.MULTILINE,
+ ),
+ )
self.assertFalse(worker.is_alive)
@@ -402,6 +491,23 @@ def test__thread_main_batches(self):
self.assertFalse(worker._cloud_logger._batch.commit_called)
self.assertEqual(worker._queue.qsize(), 0)
+ def test__thread_main_main_thread_terminated(self):
+ from google.cloud.logging_v2.handlers.transports import background_thread
+
+ worker = self._make_one(_Logger(self.NAME))
+ self._enqueue_record(worker, "1")
+ worker._queue.put_nowait(background_thread._WORKER_TERMINATOR)
+
+ with mock.patch("threading.main_thread") as main_thread_func_mock:
+ main_thread_obj_mock = mock.Mock()
+ main_thread_func_mock.return_value = main_thread_obj_mock
+ main_thread_obj_mock.is_alive = mock.Mock(return_value=False)
+ self._enqueue_record(worker, "1")
+ self._enqueue_record(worker, "2")
+ worker._thread_main()
+
+ self.assertFalse(worker._cloud_logger._batch.commit_called)
+
@mock.patch("time.time", autospec=True, return_value=1)
def test__thread_main_max_latency(self, time):
# Note: this test is a bit brittle as it assumes the operation of
@@ -565,3 +671,16 @@ def __init__(self, project, _http=None, credentials=None):
def logger(self, name, resource=None): # pylint: disable=unused-argument
self._logger = _Logger(name, resource=resource)
return self._logger
+
+
+class _AtexitMock(object):
+ """_AtexitMock is a simulation of registering/unregistering functions in atexit using a dummy set."""
+
+ def __init__(self):
+ self.registered_funcs = set()
+
+ def register(self, func):
+ self.registered_funcs.add(func)
+
+ def unregister(self, func):
+ self.registered_funcs.remove(func)
diff --git a/tests/unit/handlers/transports/test_base.py b/tests/unit/handlers/transports/test_base.py
index 71ef1366a..b723db87b 100644
--- a/tests/unit/handlers/transports/test_base.py
+++ b/tests/unit/handlers/transports/test_base.py
@@ -16,7 +16,6 @@
class TestBaseHandler(unittest.TestCase):
-
PROJECT = "PROJECT"
@staticmethod
@@ -39,3 +38,7 @@ def test_resource_is_valid_argunent(self):
def test_flush_is_abstract_and_optional(self):
target = self._make_one("client", "name")
target.flush()
+
+ def test_close_is_abstract_and_optional(self):
+ target = self._make_one("client", "name")
+ target.close()
diff --git a/tests/unit/handlers/transports/test_sync.py b/tests/unit/handlers/transports/test_sync.py
index 752a96d9f..01a949d24 100644
--- a/tests/unit/handlers/transports/test_sync.py
+++ b/tests/unit/handlers/transports/test_sync.py
@@ -17,7 +17,6 @@
class TestSyncHandler(unittest.TestCase):
-
PROJECT = "PROJECT"
@staticmethod
diff --git a/tests/unit/test__gapic.py b/tests/unit/test__gapic.py
index 8bf25870a..58e230129 100644
--- a/tests/unit/test__gapic.py
+++ b/tests/unit/test__gapic.py
@@ -17,6 +17,8 @@
import google.auth.credentials
import mock
+from datetime import datetime
+
import google.cloud.logging
from google.cloud import logging_v2
from google.cloud.logging_v2 import _gapic
@@ -173,6 +175,21 @@ def test_write_entries_single(self):
assert request.entries[0].resource.type == entry["resource"]["type"]
assert request.entries[0].text_payload == "text"
+ def test_write_entries_parse_error(self):
+ client = self.make_logging_api()
+ with self.assertRaises(ValueError):
+ with mock.patch.object(
+ type(client._gapic_api.transport.write_log_entries), "__call__"
+ ) as call:
+ entry = {
+ "logName": self.LOG_PATH,
+ "resource": {"type": "global"},
+ "jsonPayload": {"time": datetime.now()},
+ }
+ client.write_entries([entry])
+
+ call.assert_not_called()
+
def test_logger_delete(self):
client = self.make_logging_api()
@@ -595,7 +612,6 @@ def test_non_registry_failure(self, msg_to_dict_mock):
msg_to_dict_mock.assert_called_once_with(
entry_pb,
preserving_proto_field_name=False,
- including_default_value_fields=False,
)
def test_unregistered_type(self):
diff --git a/tests/unit/test__http.py b/tests/unit/test__http.py
index f9b60cfa6..5709a50a6 100644
--- a/tests/unit/test__http.py
+++ b/tests/unit/test__http.py
@@ -24,7 +24,6 @@ def _make_credentials():
class TestConnection(unittest.TestCase):
-
PROJECT = "project"
FILTER = "logName:syslog AND severity>=ERROR"
@@ -96,7 +95,6 @@ def test_extra_headers(self):
class Test_LoggingAPI(unittest.TestCase):
-
PROJECT = "project"
PROJECT_PATH = "projects/project"
LIST_ENTRIES_PATH = "entries:list"
@@ -124,9 +122,9 @@ def test_ctor(self):
@staticmethod
def _make_timestamp():
import datetime
- from google.cloud._helpers import UTC
+ from datetime import timezone
- NOW = datetime.datetime.utcnow().replace(tzinfo=UTC)
+ NOW = datetime.datetime.now(timezone.utc)
return NOW, _datetime_to_rfc3339_w_nanos(NOW)
def test_list_entries_with_limits(self):
@@ -354,7 +352,6 @@ def test_logger_delete(self):
class Test_SinksAPI(unittest.TestCase):
-
PROJECT = "project"
PROJECT_PATH = "projects/project"
FILTER = "logName:syslog AND severity>=ERROR"
@@ -636,7 +633,6 @@ def test_sink_delete_hit(self):
class Test_MetricsAPI(unittest.TestCase):
-
PROJECT = "project"
FILTER = "logName:syslog AND severity>=ERROR"
LIST_METRICS_PATH = "projects/%s/metrics" % (PROJECT,)
@@ -865,7 +861,6 @@ def test_metric_delete_hit(self):
class _Connection(object):
-
_called_with = None
_raise_conflict = False
diff --git a/tests/unit/test__instrumentation.py b/tests/unit/test__instrumentation.py
index dc330b0ca..97473ee61 100644
--- a/tests/unit/test__instrumentation.py
+++ b/tests/unit/test__instrumentation.py
@@ -17,7 +17,6 @@
class TestInstrumentation(unittest.TestCase):
-
TEST_NAME = "python"
# LONG_NAME > 14 characters
LONG_NAME = TEST_NAME + "789ABCDEF"
@@ -26,7 +25,7 @@ class TestInstrumentation(unittest.TestCase):
# LONG_VERSION > 16 characters
LONG_VERSION = TEST_VERSION + "6789ABCDEF12"
- def _get_diagonstic_value(self, entry, key):
+ def _get_diagnostic_value(self, entry, key):
return entry.payload[i._DIAGNOSTIC_INFO_KEY][i._INSTRUMENTATION_SOURCE_KEY][-1][
key
]
@@ -35,10 +34,10 @@ def test_default_diagnostic_info(self):
entry = i._create_diagnostic_entry()
self.assertEqual(
i._PYTHON_LIBRARY_NAME,
- self._get_diagonstic_value(entry, "name"),
+ self._get_diagnostic_value(entry, "name"),
)
self.assertEqual(
- i._LIBRARY_VERSION, self._get_diagonstic_value(entry, "version")
+ i._LIBRARY_VERSION, self._get_diagnostic_value(entry, "version")
)
def test_custom_diagnostic_info(self):
@@ -47,10 +46,10 @@ def test_custom_diagnostic_info(self):
)
self.assertEqual(
self.TEST_NAME,
- self._get_diagonstic_value(entry, "name"),
+ self._get_diagnostic_value(entry, "name"),
)
self.assertEqual(
- self.TEST_VERSION, self._get_diagonstic_value(entry, "version")
+ self.TEST_VERSION, self._get_diagnostic_value(entry, "version")
)
def test_truncate_long_values(self):
@@ -61,8 +60,8 @@ def test_truncate_long_values(self):
expected_name = self.LONG_NAME[: i._MAX_NAME_LENGTH] + "*"
expected_version = self.LONG_VERSION[: i._MAX_VERSION_LENGTH] + "*"
- self.assertEqual(expected_name, self._get_diagonstic_value(entry, "name"))
- self.assertEqual(expected_version, self._get_diagonstic_value(entry, "version"))
+ self.assertEqual(expected_name, self._get_diagnostic_value(entry, "name"))
+ self.assertEqual(expected_version, self._get_diagnostic_value(entry, "version"))
def test_drop_labels(self):
"""Labels should not be copied in instrumentation log"""
diff --git a/tests/unit/test_client.py b/tests/unit/test_client.py
index 1c47a343b..6a9a7fd84 100644
--- a/tests/unit/test_client.py
+++ b/tests/unit/test_client.py
@@ -34,7 +34,6 @@ def _make_credentials():
class TestClient(unittest.TestCase):
-
PROJECT = "PROJECT"
PROJECT_PATH = f"projects/{PROJECT}"
LOGGER_NAME = "LOGGER_NAME"
@@ -843,14 +842,12 @@ def test_setup_logging(self):
(handler,) = args
self.assertIsInstance(handler, CloudLoggingHandler)
+ self.assertIn(handler, client._handlers)
handler.transport.worker.stop()
expected_kwargs = {
"excluded_loggers": (
- "google.cloud",
- "google.auth",
- "google_auth_httplib2",
"google.api_core.bidi",
"werkzeug",
),
@@ -886,14 +883,12 @@ def test_setup_logging_w_extra_kwargs(self):
self.assertEqual(handler.name, name)
self.assertEqual(handler.resource, resource)
self.assertEqual(handler.labels, labels)
+ self.assertIn(handler, client._handlers)
handler.transport.worker.stop()
expected_kwargs = {
"excluded_loggers": (
- "google.cloud",
- "google.auth",
- "google_auth_httplib2",
"google.api_core.bidi",
"werkzeug",
),
@@ -901,9 +896,206 @@ def test_setup_logging_w_extra_kwargs(self):
}
self.assertEqual(kwargs, expected_kwargs)
+ def test_setup_logging_w_extra_kwargs_structured_log(self):
+ import io
+ from google.cloud.logging.handlers import StructuredLogHandler
+ from google.cloud.logging import Resource
+ from google.cloud.logging_v2.client import _GKE_RESOURCE_TYPE
-class _Connection(object):
+ name = "test-logger"
+ resource = Resource(_GKE_RESOURCE_TYPE, {"resource_label": "value"})
+ labels = {"handler_label": "value"}
+ stream = io.BytesIO()
+
+ credentials = _make_credentials()
+ client = self._make_one(
+ project=self.PROJECT, credentials=credentials, _use_grpc=False
+ )
+
+ with mock.patch("google.cloud.logging_v2.client.setup_logging") as mocked:
+ client.setup_logging(
+ name=name, resource=resource, labels=labels, stream=stream
+ )
+
+ self.assertEqual(len(mocked.mock_calls), 1)
+ _, args, kwargs = mocked.mock_calls[0]
+
+ (handler,) = args
+ self.assertIsInstance(handler, StructuredLogHandler)
+
+ expected_kwargs = {
+ "excluded_loggers": (
+ "google.api_core.bidi",
+ "werkzeug",
+ ),
+ "log_level": 20,
+ }
+ self.assertEqual(kwargs, expected_kwargs)
+ self.assertIn(handler, client._handlers)
+
+ def test_flush_handlers_cloud_logging_handler(self):
+ import io
+ from google.cloud.logging.handlers import CloudLoggingHandler
+ from google.cloud.logging import Resource
+
+ name = "test-logger"
+ resource = Resource("resource_type", {"resource_label": "value"})
+ labels = {"handler_label": "value"}
+ stream = io.BytesIO()
+
+ credentials = _make_credentials()
+ client = self._make_one(
+ project=self.PROJECT, credentials=credentials, _use_grpc=False
+ )
+
+ with mock.patch("google.cloud.logging_v2.client.setup_logging") as mocked:
+ client.setup_logging(
+ name=name, resource=resource, labels=labels, stream=stream
+ )
+
+ self.assertEqual(len(mocked.mock_calls), 1)
+ _, args, kwargs = mocked.mock_calls[0]
+
+ (handler,) = args
+ self.assertIsInstance(handler, CloudLoggingHandler)
+
+ handler.flush = mock.Mock()
+ client.flush_handlers()
+ handler.flush.assert_called_once_with()
+
+ def test_flush_handlers_cloud_logging_handler_no_setup_logging(self):
+ from google.cloud.logging.handlers import CloudLoggingHandler
+
+ credentials = _make_credentials()
+ client = self._make_one(
+ project=self.PROJECT, credentials=credentials, _use_grpc=False
+ )
+
+ handler = CloudLoggingHandler(client)
+ self.assertIn(handler, client._handlers)
+
+ handler.flush = mock.Mock()
+ client.flush_handlers()
+ handler.flush.assert_called_once_with()
+
+ def test_flush_handlers_structured_log(self):
+ import io
+ from google.cloud.logging.handlers import StructuredLogHandler
+ from google.cloud.logging import Resource
+ from google.cloud.logging_v2.client import _GKE_RESOURCE_TYPE
+
+ name = "test-logger"
+ resource = Resource(_GKE_RESOURCE_TYPE, {"resource_label": "value"})
+ labels = {"handler_label": "value"}
+ stream = io.BytesIO()
+
+ credentials = _make_credentials()
+ client = self._make_one(
+ project=self.PROJECT, credentials=credentials, _use_grpc=False
+ )
+
+ with mock.patch("google.cloud.logging_v2.client.setup_logging") as mocked:
+ client.setup_logging(
+ name=name, resource=resource, labels=labels, stream=stream
+ )
+
+ self.assertEqual(len(mocked.mock_calls), 1)
+ _, args, kwargs = mocked.mock_calls[0]
+
+ (handler,) = args
+ self.assertIsInstance(handler, StructuredLogHandler)
+
+ handler.flush = mock.Mock()
+ client.flush_handlers()
+ handler.flush.assert_called_once_with()
+
+ def test_close_cloud_logging_handler(self):
+ import contextlib
+ import io
+ from google.cloud.logging.handlers import CloudLoggingHandler
+ from google.cloud.logging import Resource
+
+ name = "test-logger"
+ resource = Resource("resource_type", {"resource_label": "value"})
+ labels = {"handler_label": "value"}
+ stream = io.BytesIO()
+
+ credentials = _make_credentials()
+ client = self._make_one(
+ project=self.PROJECT, credentials=credentials, _use_grpc=False
+ )
+
+ with mock.patch("google.cloud.logging_v2.client.setup_logging") as mocked:
+ client.setup_logging(
+ name=name, resource=resource, labels=labels, stream=stream
+ )
+
+ self.assertEqual(len(mocked.mock_calls), 1)
+ _, args, kwargs = mocked.mock_calls[0]
+
+ (handler,) = args
+ self.assertIsInstance(handler, CloudLoggingHandler)
+
+ handler.close = mock.Mock()
+ with contextlib.closing(client):
+ pass
+ handler.close.assert_called_once_with()
+
+ def test_close_cloud_logging_handler_no_setup_logging(self):
+ import contextlib
+ from google.cloud.logging.handlers import CloudLoggingHandler
+
+ credentials = _make_credentials()
+ client = self._make_one(
+ project=self.PROJECT, credentials=credentials, _use_grpc=False
+ )
+
+ handler = CloudLoggingHandler(client)
+ self.assertIn(handler, client._handlers)
+
+ handler.close = mock.Mock()
+ with contextlib.closing(client):
+ pass
+
+ handler.close.assert_called_once_with()
+
+ def test_close_structured_log_handler(self):
+ import contextlib
+ import io
+ from google.cloud.logging.handlers import StructuredLogHandler
+ from google.cloud.logging import Resource
+ from google.cloud.logging_v2.client import _GKE_RESOURCE_TYPE
+
+ name = "test-logger"
+ resource = Resource(_GKE_RESOURCE_TYPE, {"resource_label": "value"})
+ labels = {"handler_label": "value"}
+ stream = io.BytesIO()
+
+ credentials = _make_credentials()
+ client = self._make_one(
+ project=self.PROJECT, credentials=credentials, _use_grpc=False
+ )
+
+ with mock.patch("google.cloud.logging_v2.client.setup_logging") as mocked:
+ client.setup_logging(
+ name=name, resource=resource, labels=labels, stream=stream
+ )
+
+ self.assertEqual(len(mocked.mock_calls), 1)
+ _, args, kwargs = mocked.mock_calls[0]
+
+ (handler,) = args
+ self.assertIsInstance(handler, StructuredLogHandler)
+
+ handler.close = mock.Mock()
+ with contextlib.closing(client):
+ pass
+
+ handler.close.assert_called_once_with()
+
+
+class _Connection(object):
_called_with = None
def __init__(self, *responses):
diff --git a/tests/unit/test_entries.py b/tests/unit/test_entries.py
index 6f3af684f..382674ebd 100644
--- a/tests/unit/test_entries.py
+++ b/tests/unit/test_entries.py
@@ -79,7 +79,6 @@ def test_w_str(self):
class TestLogEntry(unittest.TestCase):
-
PROJECT = "PROJECT"
LOGGER_NAME = "LOGGER_NAME"
@@ -201,14 +200,14 @@ def test_from_api_repr_missing_data_no_loggers(self):
def test_from_api_repr_w_loggers_no_logger_match(self):
from datetime import datetime
- from google.cloud._helpers import UTC
+ from datetime import timezone
from google.cloud.logging import Resource
klass = self._get_target_class()
client = _Client(self.PROJECT)
SEVERITY = "CRITICAL"
IID = "IID"
- NOW = datetime.utcnow().replace(tzinfo=UTC)
+ NOW = datetime.now(timezone.utc)
TIMESTAMP = _datetime_to_rfc3339_w_nanos(NOW)
LOG_NAME = "projects/%s/logs/%s" % (self.PROJECT, self.LOGGER_NAME)
LABELS = {"foo": "bar", "baz": "qux"}
@@ -284,11 +283,11 @@ def test_from_api_repr_w_loggers_no_logger_match(self):
def test_from_api_repr_w_loggers_w_logger_match(self):
from datetime import datetime
from datetime import timedelta
- from google.cloud._helpers import UTC
+ from datetime import timezone
client = _Client(self.PROJECT)
IID = "IID"
- NOW = datetime.utcnow().replace(tzinfo=UTC)
+ NOW = datetime.now(timezone.utc)
LATER = NOW + timedelta(seconds=1)
TIMESTAMP = _datetime_to_rfc3339_w_nanos(NOW)
RECEIVED = _datetime_to_rfc3339_w_nanos(LATER)
@@ -342,11 +341,11 @@ def test_from_api_repr_w_loggers_w_logger_match(self):
def test_from_api_repr_w_folder_path(self):
from datetime import datetime
from datetime import timedelta
- from google.cloud._helpers import UTC
+ from datetime import timezone
client = _Client(self.PROJECT)
IID = "IID"
- NOW = datetime.utcnow().replace(tzinfo=UTC)
+ NOW = datetime.now(timezone.utc)
LATER = NOW + timedelta(seconds=1)
TIMESTAMP = _datetime_to_rfc3339_w_nanos(NOW)
RECEIVED = _datetime_to_rfc3339_w_nanos(LATER)
@@ -469,7 +468,6 @@ def test_to_api_repr_explicit(self):
class TestTextEntry(unittest.TestCase):
-
PROJECT = "PROJECT"
LOGGER_NAME = "LOGGER_NAME"
@@ -557,7 +555,6 @@ def test_to_api_repr_explicit(self):
class TestStructEntry(unittest.TestCase):
-
PROJECT = "PROJECT"
LOGGER_NAME = "LOGGER_NAME"
@@ -659,7 +656,6 @@ def test_to_api_repr_explicit(self):
class TestProtobufEntry(unittest.TestCase):
-
PROJECT = "PROJECT"
LOGGER_NAME = "LOGGER_NAME"
@@ -743,6 +739,45 @@ def test_to_api_repr_proto_defaults(self):
}
self.assertEqual(entry.to_api_repr(), expected)
+ def test_to_api_repr_proto_inner_struct_field(self):
+ from google.protobuf.json_format import MessageToDict
+ from google.cloud.logging_v2.logger import _GLOBAL_RESOURCE
+ from google.protobuf.struct_pb2 import Struct
+ from google.protobuf.struct_pb2 import Value
+
+ LOG_NAME = "test.log"
+ inner_struct = Struct(fields={"foo": Value(string_value="bar")})
+ message = Struct(fields={"inner": Value(struct_value=inner_struct)})
+
+ entry = self._make_one(log_name=LOG_NAME, payload=message)
+ expected = {
+ "logName": LOG_NAME,
+ "protoPayload": MessageToDict(message),
+ "resource": _GLOBAL_RESOURCE._to_dict(),
+ }
+ self.assertEqual(entry.to_api_repr(), expected)
+
+ def test_to_api_repr_proto_inner_list_field(self):
+ from google.protobuf.json_format import MessageToDict
+ from google.cloud.logging_v2.logger import _GLOBAL_RESOURCE
+ from google.protobuf.struct_pb2 import ListValue
+ from google.protobuf.struct_pb2 import Struct
+ from google.protobuf.struct_pb2 import Value
+
+ LOG_NAME = "test.log"
+ lines = ListValue(
+ values=[Value(string_value="line1"), Value(string_value="line2")]
+ )
+ message = Struct(fields={"lines": Value(list_value=lines)})
+
+ entry = self._make_one(log_name=LOG_NAME, payload=message)
+ expected = {
+ "logName": LOG_NAME,
+ "protoPayload": MessageToDict(message),
+ "resource": _GLOBAL_RESOURCE._to_dict(),
+ }
+ self.assertEqual(entry.to_api_repr(), expected)
+
def test_to_api_repr_proto_explicit(self):
import datetime
from google.protobuf.json_format import MessageToDict
diff --git a/tests/unit/test_logger.py b/tests/unit/test_logger.py
index 16c89959b..cdb56747d 100644
--- a/tests/unit/test_logger.py
+++ b/tests/unit/test_logger.py
@@ -28,7 +28,6 @@ def _make_credentials():
class TestLogger(unittest.TestCase):
-
PROJECT = "test-project"
LOGGER_NAME = "logger-name"
TIME_FORMAT = '"%Y-%m-%dT%H:%M:%S.%f%z"'
@@ -1086,7 +1085,6 @@ def test_first_log_emits_instrumentation(self):
class TestBatch(unittest.TestCase):
-
PROJECT = "test-project"
@staticmethod
@@ -1847,7 +1845,6 @@ def test_batch_error_gets_context(self):
class _Logger(object):
-
labels = None
def __init__(self, name="NAME", project="PROJECT"):
@@ -1855,7 +1852,6 @@ def __init__(self, name="NAME", project="PROJECT"):
class _DummyLoggingAPI(object):
-
_write_entries_called_with = None
def write_entries(
@@ -1909,7 +1905,6 @@ class _Bugout(Exception):
class _Connection(object):
-
_called_with = None
def __init__(self, *responses):
diff --git a/tests/unit/test_metric.py b/tests/unit/test_metric.py
index 83b49d02d..f36ae3b2a 100644
--- a/tests/unit/test_metric.py
+++ b/tests/unit/test_metric.py
@@ -16,7 +16,6 @@
class TestMetric(unittest.TestCase):
-
PROJECT = "test-project"
METRIC_NAME = "metric-name"
FULL_METRIC_NAME = f"projects/{PROJECT}/metrics/{METRIC_NAME}"
diff --git a/tests/unit/test_packaging.py b/tests/unit/test_packaging.py
new file mode 100644
index 000000000..4369ca2c1
--- /dev/null
+++ b/tests/unit/test_packaging.py
@@ -0,0 +1,56 @@
+# Copyright 2023 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 subprocess
+import sys
+
+
+def test_namespace_package_compat(tmp_path):
+ # The ``google`` namespace package should not be masked
+ # by the presence of ``google-cloud-logging``.
+
+ google = tmp_path / "google"
+ google.mkdir()
+ google.joinpath("othermod.py").write_text("")
+
+ google_otherpkg = tmp_path / "google" / "otherpkg"
+ google_otherpkg.mkdir()
+ google_otherpkg.joinpath("__init__.py").write_text("")
+
+ # The ``google.cloud`` namespace package should not be masked
+ # by the presence of ``google-cloud-logging``.
+ google_cloud = tmp_path / "google" / "cloud"
+ google_cloud.mkdir()
+ google_cloud.joinpath("othermod.py").write_text("")
+
+ google_cloud_otherpkg = tmp_path / "google" / "cloud" / "otherpkg"
+ google_cloud_otherpkg.mkdir()
+ google_cloud_otherpkg.joinpath("__init__.py").write_text("")
+
+ env = dict(os.environ, PYTHONPATH=str(tmp_path))
+
+ for pkg in [
+ "google.othermod",
+ "google.cloud.othermod",
+ "google.otherpkg",
+ "google.cloud.otherpkg",
+ "google.cloud.logging",
+ ]:
+ cmd = [sys.executable, "-c", f"import {pkg}"]
+ subprocess.check_output(cmd, env=env)
+
+ for module in ["google.othermod", "google.cloud.othermod"]:
+ cmd = [sys.executable, "-m", module]
+ subprocess.check_output(cmd, env=env)
diff --git a/tests/unit/test_sink.py b/tests/unit/test_sink.py
index 1e4852ab5..b5005b057 100644
--- a/tests/unit/test_sink.py
+++ b/tests/unit/test_sink.py
@@ -16,7 +16,6 @@
class TestSink(unittest.TestCase):
-
PROJECT = "test-project"
PROJECT_PATH = f"projects/{PROJECT}"
SINK_NAME = "sink-name"
pFad - Phonifier reborn
Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies:
Alternative Proxy
pFad Proxy
pFad v3 Proxy
pFad v4 Proxy